p2party 0.14.2 → 0.14.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.
package/lib/session.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e="undefined"!=typeof document?document.currentScript:null;function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var r,n={exports:{}};var i=(r||(r=1,function(e){var t,r=(t=globalThis.document?.currentScript?.src,async function(e={}){var r=e,n=!!globalThis.window,i=!!globalThis.WorkerGlobalScope;globalThis.process?.versions?.node&&globalThis.process,i&&(t=self.location.href);var a,o,s="";if(n||i){try{s=new URL(".",t).href}catch{}i&&(o=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),a=async e=>{var t=await fetch(e,{credentials:"same-origin"});if(t.ok)return t.arrayBuffer();throw new Error(t.status+" : "+t.url)}}console.log.bind(console);var c,l=console.error.bind(console),d=!1;function h(e,t,r){const n=e.BYTES_PER_ELEMENT,i=t*n;if(t<=0&&k(`segmentation fault ${r} ${n} bytes at address ${i}`),v){var a=O(0);i+n>a&&k(`segmentation fault, exceeded the top of the available dynamic heap when ${r} ${n} bytes at address ${i}. DYNAMICTOP=${a}`),a<B()&&k(`brk >= _emscripten_stack_get_base() (brk=${a}, _emscripten_stack_get_base()=${B()})`),a>w.buffer.byteLength&&k(`brk <= wasmMemory.buffer.byteLength (brk=${a}, wasmMemory.buffer.byteLength=${w.buffer.byteLength})`)}return t}var u,f,y,p,m,b,g,w,v=!1;function A(){if(!p?.buffer?.resizable){var e=w.buffer;p=new Int8Array(e),g=new Uint8Array(e),f=new Int32Array(e),b=new Uint32Array(e),m=new Float64Array(e),y=new BigInt64Array(e),new BigUint64Array(e)}}function k(e){throw l(e=`Aborted(${e})`),d=!0,e+=". Build with -sASSERTIONS for more info.",new WebAssembly.RuntimeError(e)}function E(){return s+"libcrypto.wasm"}async function K(e){if(!c)try{var t=await a(e);return new Uint8Array(t)}catch{}return function(e){if(e==u&&c)return new Uint8Array(c);if(o)return o(e);throw"both async and sync fetching of the wasm failed"}(e)}async function _(e,t,r){if(!e)try{var n=fetch(t,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(n,r)}catch(e){l(`wasm streaming compile failed: ${e}`),l("falling back to ArrayBuffer instantiation")}return async function(e,t){try{var r=await K(e);return await WebAssembly.instantiate(r,t)}catch(e){l(`failed to asynchronously prepare wasm: ${e}`),k(e)}}(t,r)}var U=globalThis.TextDecoder&&new TextDecoder,x=(e,t,r)=>e?((e,t=0,r)=>{var n=((e,t,r)=>{for(var n=t+r;e[t]&&!(t>=n);)++t;return t})(e,t,r);if(n-t>16&&e.buffer&&U)return U.decode(e.subarray(t,n));for(var i="";t<n;){var a=e[t++];if(128&a){var o=63&e[t++];if(192!=(224&a)){var s=63&e[t++];if((a=224==(240&a)?(15&a)<<12|o<<6|s:(7&a)<<18|o<<12|s<<6|63&e[t++])<65536)i+=String.fromCharCode(a);else{var c=a-65536;i+=String.fromCharCode(55296|c>>10,56320|1023&c)}}else i+=String.fromCharCode((31&a)<<6|o)}else i+=String.fromCharCode(a)}return i})(g,e,t):"",S=[],M=(e,t,r)=>{var n=((e,t)=>{var r;for(S.length=0;r=g[h(g,e++,"loading")];){var n=105!=r;t+=(n&=112!=r)&&t%8?4:0,S.push(112==r?b[h(b,t>>2,"loading")]:106==r?y[h(y,t>>3,"loading")]:105==r?f[h(f,t>>2,"loading")]:m[h(m,t>>3,"loading")]),t+=n?8:4}return S})(t,r);return N[e](...n)},C=e=>{k("OOM")},P=(e,t)=>Math.ceil(e/t)*t,R=e=>{var t=(e-w.buffer.byteLength+65535)/65536|0;try{return w.grow(t),A(),1}catch(e){}};!function(){if(r.wasmMemory)w=r.wasmMemory;else{var e=r.INITIAL_MEMORY||2097152;w=new WebAssembly.Memory({initial:e/65536,maximum:16384})}A()}(),r.wasmBinary&&(c=r.wasmBinary);var O,B,I,N={38164:()=>r.getRandomValue(),38200:()=>{if(void 0===r.getRandomValue)try{var e="object"==typeof window?window:self,t=void 0!==e.crypto?e.crypto:e.msCrypto;t=void 0===t?i:t;var n=function(){var e=new Uint32Array(1);return t.getRandomValues(e),e[0]>>>0};n(),r.getRandomValue=n}catch(e){try{var i=require("crypto"),a=function(){var e=i.randomBytes(4);return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0};a(),r.getRandomValue=a}catch(e){throw"No secure random number generator found"}}}},F={e:(e,t,r,n)=>k(`Assertion failed: ${x(e)}, at: `+[t?x(t):"unknown filename",r,n?x(n):"unknown function"]),g:()=>k(""),c:function(){k("alignment fault")},d:(e,t,r)=>M(e,t,r),f:e=>{var t=g.length,r=1073741824;(e>>>=0)>r&&C();for(var n=1;n<=4;n*=2){var i=t*(1+.2/n);i=Math.min(i,e+100663296);var a=Math.min(r,P(Math.max(e,i),65536));if(R(a))return!0}C()},a:w,b:function(){k("segmentation fault")}};return I=await async function(){function e(e){return function(e){r._crypto_init=e.i,r._argon2=e.j,r._keypair_from_seed=e.k,r._keypair_from_secret_key=e.l,r._sign=e.m,r._verify=e.n,r._get_merkle_root=e.o,r._get_merkle_proof=e.p,r._get_merkle_root_from_proof=e.q,r._verify_merkle_proof=e.r,r._cpace_ristretto255_from_hash=e.s,r._cpace_ristretto255_scalarmult=e.t,r._cpace_ristretto255_scalar_random=e.u,r._x25519_keypair=e.v,r._x25519_dh=e.w,r._hkdf_sha512_extract=e.x,r._hkdf_sha512_expand=e.y,r._encrypt_chachapoly_symmetric=e.z,r._decrypt_chachapoly_symmetric=e.A,r._receive_message_with_key=e.B,r._sha512_init=e.C,r._sha512_update=e.D,r._sha512_final=e.E,r._mlkem512_keypair=e.F,r._mlkem512_encaps=e.G,r._mlkem512_decaps=e.H,r._mlkem768_keypair=e.I,r._mlkem768_encaps=e.J,r._mlkem768_decaps=e.K,r._mlkem1024_keypair=e.L,r._mlkem1024_encaps=e.M,r._mlkem1024_decaps=e.N,r._free=e.O,r._malloc=e.P,O=e.Q,B=e.R,e.__indirect_function_table}(I=e.exports),I}var t={a:F};u??=E();var n=function(t){return e(t.instance)}(await _(c,u,t));return n}(),await async function(){d||(v=!0,I.h())}(),r});e.exports=r,e.exports.default=r}(n)),n.exports),a=t(i);const o=new Uint32Array(1),s=()=>{const e=globalThis.crypto;if("function"!=typeof e?.getRandomValues)throw new Error("Web Crypto secure randomness is unavailable");try{return e.getRandomValues(o),o[0]>>>0}finally{o[0]=0}},c=(e,t=e=>{const t=globalThis.crypto;if("function"!=typeof t?.getRandomValues)throw new Error("Web Crypto secure randomness is unavailable");t.getRandomValues(e)})=>{if(!(e instanceof Uint8Array))throw new TypeError("random: destination must be a Uint8Array");const r=new Uint8Array(e.byteLength);try{t(r),e.set(r)}finally{r.fill(0)}};if("object"!=typeof WebAssembly)throw new Error("no native wasm support detected");const l="0.14.2";let d=new URL(`https://cdn.p2party.com/@${l}/libcrypto.wasm`);const h={integrity:"sha384-pBMyUqQ3KBztxgeJMgDFZeohfj9QlAFNwt4/gRlqT0vlZ2kbkKxv+q5DwbZOBuUP"},u=async t=>{const r=("undefined"!=typeof process&&Boolean(process.versions?.node)?await(async()=>{try{const[{readFile:t},{createHash:r}]=await Promise.all([import("node:fs/promises"),import("node:crypto")]),n=await t(new URL("./libcrypto.wasm","undefined"==typeof document?require("url").pathToFileURL(__filename).href:e&&"SCRIPT"===e.tagName.toUpperCase()&&e.src||new URL("session.js",document.baseURI).href));return`sha384-${r("sha384").update(n).digest("base64")}`!==h.integrity?null:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}catch{return null}})():null)??await(async()=>{const e=await fetch(d,h);if(!e.ok)throw new Error(`Unable to load p2party ${l} WASM: HTTP ${String(e.status)}`);return await e.arrayBuffer()})();return await a({wasmBinary:r,wasmMemory:t,getRandomValue:s})},f=64*Uint8Array.BYTES_PER_ELEMENT,y=64*Uint8Array.BYTES_PER_ELEMENT,p=208,m=64*Uint8Array.BYTES_PER_ELEMENT,b=32*Uint8Array.BYTES_PER_ELEMENT,g=32*Uint8Array.BYTES_PER_ELEMENT,w=64*Uint8Array.BYTES_PER_ELEMENT,v=32*Uint8Array.BYTES_PER_ELEMENT,A=12*Uint8Array.BYTES_PER_ELEMENT,k=16*Uint8Array.BYTES_PER_ELEMENT,E=(Uint8Array.BYTES_PER_ELEMENT,32*Uint8Array.BYTES_PER_ELEMENT),K=64*Uint8Array.BYTES_PER_ELEMENT,_=32*Uint8Array.BYTES_PER_ELEMENT,U=32*Uint8Array.BYTES_PER_ELEMENT,x=32*Uint8Array.BYTES_PER_ELEMENT,S=(e,t,r)=>{t=t??32,r=r??16384;const n=65536,i=Math.ceil((e+1048576)/n);if(i>r)throw new Error(`Memory required is ${String(i*n)} bytes while declared maximum is ${String(r*n)} bytes`);return i<t?t:i};var M=()=>{const e=(g+w)*Uint8Array.BYTES_PER_ELEMENT,t=S(e);return new WebAssembly.Memory({initial:t,maximum:t})},C=()=>{const e=(U+x)*Uint8Array.BYTES_PER_ELEMENT,t=S(e);return new WebAssembly.Memory({initial:t,maximum:t})},P=e=>{const t=(e+m+w+y)*Uint8Array.BYTES_PER_ELEMENT,r=S(t);return new WebAssembly.Memory({initial:r,maximum:r})},R=e=>{const t=(e+m+g)*Uint8Array.BYTES_PER_ELEMENT,r=S(t);return new WebAssembly.Memory({initial:r,maximum:r})},O=e=>{const t=S((2*e+3)*y);return new WebAssembly.Memory({initial:t,maximum:t})},B=e=>{const t=S(e*y+e*(y+1)+3*y);return new WebAssembly.Memory({initial:t,maximum:t})};const I=(e,t)=>{t.fill(0),e._free(t.byteOffset)},N=e=>{const t=e._malloc(U),r=e._malloc(x);if(0!==e._x25519_keypair(t,r))throw e._free(t),I(e,new Uint8Array(e.wasmMemory.buffer,r,x)),new Error("x25519_keypair failed");const n=Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,t,U)),i=Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,r,x));return e._free(t),I(e,new Uint8Array(e.wasmMemory.buffer,r,x)),{publicKey:n,secretKey:i}},F=(e,t,r)=>{const n=r._malloc(U),i=r._malloc(x),a=r._malloc(U);new Uint8Array(r.wasmMemory.buffer,i,x).set(e),new Uint8Array(r.wasmMemory.buffer,a,U).set(t);const o=0===r._x25519_dh(n,i,a)?Uint8Array.from(new Uint8Array(r.wasmMemory.buffer,n,U)):null;if(I(r,new Uint8Array(r.wasmMemory.buffer,n,U)),I(r,new Uint8Array(r.wasmMemory.buffer,i,x)),r._free(a),!o)throw new Error("x25519_dh failed (identity point)");return o},L=65536,T=9+y+8+8+256+8+8+8,D=4+48*(y+1),q=65405-(T+D),V=65405,$=new Uint8Array([1]),H=32,z=65474+k,Q=(new TextEncoder).encode("p2party-x25519-idsig-v1"),j="hybrid-3dh-mlkem512-cpace21-v4",Y="hybrid-3dh-mlkem768-cpace21-v4",W="hybrid-3dh-mlkem1024-cpace21-v4",X=[j,Y,W],G=Y,Z=2e3,J=e=>{const t=new Uint8Array(Q.length+e.length);return t.set(Q,0),t.set(e,Q.length),t},ee=async(e,t,r)=>(async(e,t,r)=>{if(t.length!==w)throw new Error(`Ed25519 secret key must be ${String(w)} bytes`);const n=e.length,i=r?r.wasmMemory:P(n),a=r??await u(i),o=a._malloc(Math.max(n*Uint8Array.BYTES_PER_ELEMENT,1)),s=new Uint8Array(i.buffer,o,n*Uint8Array.BYTES_PER_ELEMENT);s.set(e);const c=a._malloc(m),l=new Uint8Array(i.buffer,c,m),d=a._malloc(w),h=new Uint8Array(i.buffer,d,w);h.set(t);try{if(0!==a._sign(n,s.byteOffset,h.byteOffset,l.byteOffset))throw new Error("Could not sign with Ed25519");return Uint8Array.from(l)}finally{a._free(o),a._free(c),I(a,h)}})(J(e),t,r),te=async(e,t,r,n)=>(async(e,t,r,n)=>{const i=e.length,a=n?n.wasmMemory:R(i),o=n??await u(a),s=o._malloc(i*Uint8Array.BYTES_PER_ELEMENT),c=new Uint8Array(a.buffer,s,i*Uint8Array.BYTES_PER_ELEMENT);c.set(e);const l=o._malloc(m),d=new Uint8Array(a.buffer,l,m);d.set(t);const h=o._malloc(g),f=new Uint8Array(a.buffer,h,g);f.set(r);const y=o._verify(i,c.byteOffset,f.byteOffset,d.byteOffset);return o._free(s),o._free(l),o._free(h),0===y})(J(e),t,r,n),re=(e,t,r)=>{const n=Math.max(e.length,1),i=Math.max(t.length,1),a=r._malloc(f),o=r._malloc(n),s=r._malloc(i);try{new Uint8Array(r.wasmMemory.buffer,o,e.length).set(e),new Uint8Array(r.wasmMemory.buffer,s,t.length).set(t);if(0!==r._hkdf_sha512_extract(a,o,e.length,s,t.length))throw new Error("hkdf_sha512_extract failed");return Uint8Array.from(new Uint8Array(r.wasmMemory.buffer,a,f))}finally{I(r,new Uint8Array(r.wasmMemory.buffer,a,f)),I(r,new Uint8Array(r.wasmMemory.buffer,o,n)),I(r,new Uint8Array(r.wasmMemory.buffer,s,i))}},ne=(e,t,r,n)=>{const i=n._malloc(r),a=n._malloc(f),o=n._malloc(Math.max(t.length,1));try{new Uint8Array(n.wasmMemory.buffer,a,f).set(e),new Uint8Array(n.wasmMemory.buffer,o,t.length).set(t);if(0!==n._hkdf_sha512_expand(i,r,a,o,t.length))throw new Error("hkdf_sha512_expand failed");return Uint8Array.from(new Uint8Array(n.wasmMemory.buffer,i,r))}finally{I(n,new Uint8Array(n.wasmMemory.buffer,i,r)),I(n,new Uint8Array(n.wasmMemory.buffer,a,f)),n._free(o)}},ie=(new TextEncoder).encode("p2party-rk-v1"),ae=(new TextEncoder).encode("p2party-ck-v1"),oe=(new TextEncoder).encode("p2party-mk-v1"),se=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),ce=e=>{const t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r++)t[r]=parseInt(e.slice(2*r,2*r+2),16);return t},le=(e,t,r)=>{const n=re(e,t,r),i=ne(n,ie,64,r);n.fill(0);const a=i.slice(0,32),o=i.slice(32,64);return i.fill(0),{rootKey:a,chainKey:o}},de=(e,t)=>{const r=re(e,oe,t),n=re(e,ae,t),i=r.slice(0,32),a=n.slice(0,32);return r.fill(0),n.fill(0),{chainKey:a,messageKey:i}},he=(e,t,r,n,i=G)=>{const a=N(n),o={rootSuite:i,rootKey:Uint8Array.from(e),sendingChainKey:null,receivingChainKey:null,dhSelfPub:a.publicKey,dhSelfSec:a.secretKey,dhRemotePub:null,Ns:0,Nr:0,PN:0,skipped:new Map};if(t){if(!r)throw new Error("ratchet: initiator requires remoteDhPub");o.dhRemotePub=Uint8Array.from(r);const e=F(o.dhSelfSec,o.dhRemotePub,n),t=le(o.rootKey,e,n);e.fill(0),o.rootKey.fill(0),o.rootKey=t.rootKey,o.sendingChainKey=t.chainKey}return o},ue=(e,t,r)=>{if(e.Nr+512<t)throw new Error("ratchet: MAX_SKIP exceeded");if(e.receivingChainKey){for(;e.Nr<t;){const{chainKey:t,messageKey:n}=de(e.receivingChainKey,r);e.receivingChainKey.fill(0),e.receivingChainKey=t,e.skipped.set(`${se(e.dhRemotePub)}:${e.Nr}`,n),e.Nr+=1}if(e.skipped.size>Z)for(const t of e.skipped.keys()){if(e.skipped.size<=Z)break;e.skipped.get(t)?.fill(0),e.skipped.delete(t)}}},fe=(e,t,r)=>{e.PN=e.Ns,e.Ns=0,e.Nr=0,e.dhRemotePub=Uint8Array.from(t.dhPub);let n=F(e.dhSelfSec,e.dhRemotePub,r),i=le(e.rootKey,n,r);n.fill(0),e.rootKey.fill(0),e.rootKey=i.rootKey,e.receivingChainKey?.fill(0),e.receivingChainKey=i.chainKey;const a=e.dhSelfSec,o=N(r);e.dhSelfPub=o.publicKey,e.dhSelfSec=o.secretKey,a.fill(0),n=F(e.dhSelfSec,e.dhRemotePub,r),i=le(e.rootKey,n,r),n.fill(0),e.rootKey.fill(0),e.rootKey=i.rootKey,e.sendingChainKey?.fill(0),e.sendingChainKey=i.chainKey},ye=(e,t,r)=>{if(!Number.isInteger(t.N)||t.N<0||!Number.isInteger(t.PN)||t.PN<0)throw new Error("invalid ratchet header");const n=((e,t)=>{const r=`${se(t.dhPub)}:${t.N}`,n=e.skipped.get(r);return n?(e.skipped.delete(r),n):null})(e,t);if(n)return n;if((!e.dhRemotePub||!((e,t)=>{if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r})(t.dhPub,e.dhRemotePub))&&(ue(e,t.PN,r),fe(e,t,r)),t.N<e.Nr)throw new Error("ratchet: message key already consumed");ue(e,t.N,r);const{chainKey:i,messageKey:a}=de(e.receivingChainKey,r);return e.receivingChainKey.fill(0),e.receivingChainKey=i,e.Nr+=1,a},pe=e=>e.slice().buffer,me=e=>e?e.slice().buffer:null,be=e=>({rootSuite:e.rootSuite,rootKey:pe(e.rootKey),sendingChainKey:me(e.sendingChainKey),receivingChainKey:me(e.receivingChainKey),dhSelfPub:pe(e.dhSelfPub),dhSelfSec:pe(e.dhSelfSec),dhRemotePub:me(e.dhRemotePub),Ns:e.Ns,Nr:e.Nr,PN:e.PN,skippedMessageKeys:Array.from(e.skipped.entries()).map(([e,t])=>{const r=e.lastIndexOf(":");return{dhPub:ce(e.slice(0,r)).slice().buffer,n:Number(e.slice(r+1)),messageKey:t.slice().buffer}})}),ge=e=>{const t=new Map;for(const r of e.skippedMessageKeys){const e=new Uint8Array(r.dhPub);t.set(`${se(e)}:${r.n}`,new Uint8Array(r.messageKey))}return{rootSuite:e.rootSuite,rootKey:new Uint8Array(e.rootKey),sendingChainKey:e.sendingChainKey?new Uint8Array(e.sendingChainKey):null,receivingChainKey:e.receivingChainKey?new Uint8Array(e.receivingChainKey):null,dhSelfPub:new Uint8Array(e.dhSelfPub),dhSelfSec:new Uint8Array(e.dhSelfSec),dhRemotePub:e.dhRemotePub?new Uint8Array(e.dhRemotePub):null,Ns:e.Ns,Nr:e.Nr,PN:e.PN,skipped:t}},we=e=>ge(be(e)),ve=e=>{e.rootKey.fill(0),e.sendingChainKey?.fill(0),e.receivingChainKey?.fill(0),e.dhSelfSec.fill(0);for(const t of e.skipped.values())t.fill(0)},Ae=(e,t)=>{if(e.rootSuite!==t.rootSuite)throw new Error("ratchet: cannot adopt a different root suite");ve(e),e.rootSuite=t.rootSuite,e.rootKey=t.rootKey,e.sendingChainKey=t.sendingChainKey,e.receivingChainKey=t.receivingChainKey,e.dhSelfPub=t.dhSelfPub,e.dhSelfSec=t.dhSelfSec,e.dhRemotePub=t.dhRemotePub,e.Ns=t.Ns,e.Nr=t.Nr,e.PN=t.PN,e.skipped=t.skipped},ke=(e,t)=>{const r=t._malloc(p),n=t._malloc(1+e.length),i=t._malloc(y);try{const a=new Uint8Array(t.wasmMemory.buffer,n,1+e.length);if(a[0]=0,a.set(e,1),0!==t._sha512_init(r))throw new Error("hashMerkleLeafWasm: sha512_init failed");if(0!==t._sha512_update(r,n,1+e.length))throw new Error("hashMerkleLeafWasm: sha512_update failed");if(0!==t._sha512_final(r,i))throw new Error("hashMerkleLeafWasm: sha512_final failed");return Uint8Array.from(new Uint8Array(t.wasmMemory.buffer,i,y))}finally{t._free(r),t._free(n),t._free(i)}},Ee=async(e,t,r,n)=>{if(e.length%y!==0)throw new Error("Hashes were not passed");const i=e.length/y;if(0===i)throw new Error("Cannot calculate Merkle proof of element of empty tree.");if(1===i){const e=new Uint8Array(y+1);if(e.set(t),n){const t=y+1,r=globalThis.crypto.getRandomValues(new Uint8Array(n));let i=0;const a=4;return new DataView(r.buffer,i,a).setUint32(0,t,!1),i+=a,r.set(e,i),r}return e}const a=r?.wasmMemory??B(i),o=r??await u(a),s=o._malloc(i*y),c=new Uint8Array(a.buffer,s,i*y);c.set(e);const l=o._malloc(y),d=new Uint8Array(a.buffer,l,y);d.set(t);const h=i*(y+1),f=o._malloc(h),p=new Uint8Array(a.buffer,f,h),m=o._get_merkle_proof(i,c.byteOffset,d.byteOffset,p.byteOffset);switch(o._free(s),o._free(l),m){case-1:throw o._free(f),new Error("Element not in tree.");case-2:throw o._free(f),new Error("Could not allocate memory for hash concatenation helper array.");case-3:throw o._free(f),new Error("Could not calculate hash.");default:if(m>0){if(n&&n>=m){const e=globalThis.crypto.getRandomValues(new Uint8Array(n));let t=0;const r=4;return new DataView(e.buffer,t,r).setUint32(0,m,!1),t+=r,e.set(p.slice(0,m),t),o._free(f),e}{const e=Uint8Array.from([...p.slice(0,m)]);return o._free(f),e}}throw o._free(f),new Error("An unexpected error occured")}},Ke=new TextEncoder,_e=Ke.encode("CPaceRistretto255"),Ue=Ke.encode("CPaceRistretto255_ISK"),xe=new Uint8Array(0),Se=(e,t,r)=>{if(t.length!==r)throw new Error(`cpace: ${e} must be ${r} bytes`)},Me=e=>{if(!Number.isSafeInteger(e)||e<0)throw new Error("cpace: invalid transcript field length");const t=[];let r=e;do{let e=r%128;r=Math.floor(r/128),0!==r&&(e|=128),t.push(e)}while(0!==r);return Uint8Array.from(t)},Ce=(e,t,r,n=!1)=>{if(0===r.length)return;const i=e._malloc(r.length),a=new Uint8Array(e.wasmMemory.buffer,i,r.length);try{if(a.set(r),0!==e._sha512_update(t,i,r.length))throw new Error("sha512_update failed")}finally{n?I(e,a):e._free(i)}},Pe=(e,t,r)=>{Ce(e,t,Me(r.data.length)),Ce(e,t,r.data,r.secret)},Re=(e,t,r,n)=>{const i=Math.max(0,127-(Me(_e.length).length+_e.length)-(Me(e.length).length+e.length)),a=((e,t)=>{const r=e._malloc(p),n=e._malloc(y),i=new Uint8Array(e.wasmMemory.buffer,r,p),a=new Uint8Array(e.wasmMemory.buffer,n,y);try{if(i.fill(0),a.fill(0),0!==e._sha512_init(r))throw new Error("sha512_init failed");for(const n of t)Pe(e,r,n);if(0!==e._sha512_final(r,n))throw new Error("sha512_final failed");return Uint8Array.from(a)}finally{I(e,i),I(e,a)}})(n,[{data:_e},{data:e,secret:!0},{data:new Uint8Array(i)},{data:r},{data:t}]),o=n._malloc(K),s=n._malloc(E),c=new Uint8Array(n.wasmMemory.buffer,o,K),l=new Uint8Array(n.wasmMemory.buffer,s,E);try{return c.set(a),l.fill(0),n._cpace_ristretto255_from_hash(s,o),Uint8Array.from(l)}finally{a.fill(0),I(n,c),n._free(s)}},Oe=(new TextEncoder).encode("p2party-interactive-3dh-v2"),Be=new Uint8Array(64),Ie=e=>Object.freeze({...e,wasmExports:Object.freeze({...e.wasmExports})}),Ne=Ie({parameterSet:512,standardName:"ML-KEM-512",publicKeyBytes:800,secretKeyBytes:1632,ciphertextBytes:768,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem512_keypair",encaps:"_mlkem512_encaps",decaps:"_mlkem512_decaps"}}),Fe=Ie({parameterSet:768,standardName:"ML-KEM-768",publicKeyBytes:1184,secretKeyBytes:2400,ciphertextBytes:1088,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem768_keypair",encaps:"_mlkem768_encaps",decaps:"_mlkem768_decaps"}}),Le=Ie({parameterSet:1024,standardName:"ML-KEM-1024",publicKeyBytes:1568,secretKeyBytes:3168,ciphertextBytes:1568,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem1024_keypair",encaps:"_mlkem1024_encaps",decaps:"_mlkem1024_decaps"}}),Te=Object.freeze({512:Ne,768:Fe,1024:Le}),De=e=>{const t=Te[e];if(void 0===t)throw new RangeError(`unsupported ML-KEM parameter set: ${String(e)}`);return t},qe=(e,t,r)=>{if(!(e instanceof Uint8Array))throw new TypeError(`${t} must be a Uint8Array`);if(e.length!==r)throw new RangeError(`${t} must be exactly ${String(r)} bytes`)},Ve=(e,t,r,n)=>{const i=e._malloc(r);if(0===i)throw new Error(`${t.standardName}: failed to allocate ${n}`);return i},$e=(e,t,r)=>new Uint8Array(e.wasmMemory.buffer,t,r),He=(e,t)=>{void 0!==t&&e._free(t)},ze=(e,t,r)=>{void 0!==t&&I(e,$e(e,t,r))};class Qe{#e;#t;suite;constructor(e,t){this.#e=e,this.suite=t,this.#t=((e,t)=>{const r=e,n=t.wasmExports,i=[n.keypair,n.encaps,n.decaps].filter(e=>"function"!=typeof r[e]);if(0!==i.length)throw new Error(`${t.standardName} WASM exports are unavailable; rebuild libcrypto.wasm (missing ${i.join(", ")})`);return{keypair:r[n.keypair].bind(e),encaps:r[n.encaps].bind(e),decaps:r[n.decaps].bind(e)}})(e,t)}async generateKeyPair(){await Promise.resolve();const e=this.#e,t=this.suite;let r,n,i;try{r=Ve(e,t,t.publicKeyBytes,"public key"),n=Ve(e,t,t.secretKeyBytes,"secret key"),i=Ve(e,t,t.keyPairRandomBytes,"key-generation randomness");const a=$e(e,i,t.keyPairRandomBytes);c(a);const o=this.#t.keypair(r,n,i);if(0!==o)throw new Error(`${t.standardName} key generation failed (${String(o)})`);return((e,t)=>{let r=!1;return{publicKey:e,secretKey:t,get destroyed(){return r},destroy(){r||(t.fill(0),r=!0)}}})(Uint8Array.from($e(e,r,t.publicKeyBytes)),Uint8Array.from($e(e,n,t.secretKeyBytes)))}finally{He(e,r),ze(e,n,t.secretKeyBytes),ze(e,i,t.keyPairRandomBytes)}}async encapsulate(e){await Promise.resolve();const t=this.#e,r=this.suite;let n,i,a,o;qe(e,`${r.standardName} public key`,r.publicKeyBytes);try{n=Ve(t,r,r.ciphertextBytes,"ciphertext"),i=Ve(t,r,r.sharedSecretBytes,"shared secret"),a=Ve(t,r,r.publicKeyBytes,"public key"),o=Ve(t,r,r.encapsRandomBytes,"encapsulation randomness"),$e(t,a,r.publicKeyBytes).set(e);const s=$e(t,o,r.encapsRandomBytes);c(s);const l=this.#t.encaps(n,i,a,o);if(0!==l)throw new Error(`${r.standardName} encapsulation failed (${String(l)})`);return((e,t)=>{let r=!1;return{ciphertext:e,sharedSecret:t,get destroyed(){return r},destroy(){r||(t.fill(0),r=!0)}}})(Uint8Array.from($e(t,n,r.ciphertextBytes)),Uint8Array.from($e(t,i,r.sharedSecretBytes)))}finally{He(t,n),ze(t,i,r.sharedSecretBytes),He(t,a),ze(t,o,r.encapsRandomBytes)}}async decapsulate(e,t){await Promise.resolve();const r=this.#e,n=this.suite;let i,a,o;qe(e,`${n.standardName} ciphertext`,n.ciphertextBytes),qe(t,`${n.standardName} secret key`,n.secretKeyBytes);try{i=Ve(r,n,n.sharedSecretBytes,"shared secret"),a=Ve(r,n,n.ciphertextBytes,"ciphertext"),o=Ve(r,n,n.secretKeyBytes,"secret key"),$e(r,a,n.ciphertextBytes).set(e),$e(r,o,n.secretKeyBytes).set(t);const s=this.#t.decaps(i,a,o);if(0!==s)throw new Error(`${n.standardName} decapsulation failed (${String(s)})`);return(e=>{let t=!1;return{sharedSecret:e,get destroyed(){return t},destroy(){t||(e.fill(0),t=!0)}}})(Uint8Array.from($e(r,i,n.sharedSecretBytes)))}finally{ze(r,i,n.sharedSecretBytes),He(r,a),ze(r,o,n.secretKeyBytes)}}}const je=(e,t)=>{const r=De(t.parameterSet);if(t!==r)throw new TypeError("ML-KEM suite descriptor must be one of the exported canonical suites");return new Qe(e,r)},Ye=e=>{if("hybrid-mlkem512"===e)return 512;if("hybrid-mlkem768"===e)return 768;if("hybrid-mlkem1024"===e)return 1024;throw new Error("roomPolicy: unsupported PQ mode")},We=e=>{if("hybrid-mlkem512"===e)return j;if("hybrid-mlkem768"===e)return Y;if("hybrid-mlkem1024"===e)return W;throw new Error("roomPolicy: unsupported PQ mode")},Xe=e=>{if(e===j)return"hybrid-mlkem512";if(e===Y)return"hybrid-mlkem768";if(e===W)return"hybrid-mlkem1024";throw new Error("roomPolicy: unsupported ratchet root suite")};(new TextEncoder).encode("p2party/room-policy/v1\0"),new Array(64),new Array(128);const Ge=e=>new Promise(t=>{let r=0;const n=e.length;for(let t=0;t<n;t++)r+=e[t].length;const i=new Uint8Array(r);let a=0;for(const t of e)i.set(t,a),a+=t.length;t(i)}),Ze=(e,t)=>new Promise(r=>{const n=e.length;if(n!==t.length)return void r(!1);let i=0;for(let r=0;r<n;r++)i|=e[r]^t[r];r(0===i)}),Je=e=>{const t=(e=>{if("hybrid-mlkem768"===e)return $;if("hybrid-mlkem512"===e)return new Uint8Array([2]);if("hybrid-mlkem1024"===e)return new Uint8Array([3]);throw new Error("handshake: unsupported room PQ mode")})(e.pqMode??"hybrid-mlkem768"),r=[e.channelId,e.ikInitiator,e.ikResponder,e.fpInitiator,e.fpResponder,t];let n=0;for(const e of r)n+=e.length;const i=new Uint8Array(n);let a=0;for(const e of r)i.set(e,a),a+=e.length;return i},et=(new TextEncoder).encode("p2party-v4-hs-kc-transcript-v4"),tt=(new TextEncoder).encode("p2party-v4-hs-kc-responder-v4"),rt=(new TextEncoder).encode("p2party-v4-hs-kc-initiator-ratchet-dh-v4"),nt=(new TextEncoder).encode("p2party-v4-hs-kc-responder-finish-v4"),it=new Uint8Array(64),at=(new TextEncoder).encode("p2party-v4-pq-healing-extract-v1"),ot=(new TextEncoder).encode("p2party-v4-pq-healing-root-v1"),st=(new TextEncoder).encode("p2party-v4-pq-healing-binding-v1\0"),ct=64,lt=129,dt=(e,t,r)=>{const n=r._malloc(e.length),i=r._malloc(t.length),a=r._malloc(ct);try{new Uint8Array(r.wasmMemory.buffer,n,e.length).set(e),new Uint8Array(r.wasmMemory.buffer,i,t.length).set(t);if(0!==r._hkdf_sha512_extract(a,n,e.length,i,t.length))throw new Error("handshake hmac_sha512 failed");return Uint8Array.from(new Uint8Array(r.wasmMemory.buffer,a,ct))}finally{I(r,new Uint8Array(r.wasmMemory.buffer,n,e.length)),r._free(i),r._free(a)}},ht=e=>{let t=0;for(const r of e)t|=r;return 0===t},ut=(e,t)=>{const r=new Uint8Array(97);return r[0]=2,r.set(e,1),r.set(t,33),r},ft=async(e,t,r)=>{const{mode:n,pqMode:i="hybrid-mlkem768",pin:a,channelInput:o,amInitiator:s,idSelfSec:c,selfIdentityX25519Pub:l,selfIdentityCrossSignature:d,peerIdentityEd25519Pub:h}=t,u=(e=>{const t=De(Ye(e)),r=193+t.publicKeyBytes;return{suite:t,publicKeyOffset:193,ciphertextOffset:r,length:r+t.ciphertextBytes}})(i),f=je(r,u.suite),m=We(i),b=crypto.getRandomValues(new Uint8Array(32)),g=N(r);let w=new Uint8Array(32),v=null;const A=new Uint8Array(u.suite.publicKeyBytes),k=new Uint8Array(u.suite.ciphertextBytes);let K,U,x,S,M,C,P,R,O=null,B=null,L=null;const T=e=>{if("pin"!==n)return null;if(!a)throw new Error("PIN mode requires a PIN");const t=Re(a,e,o,r),i=((e,t)=>{Se("generator",e,E);const r=t._malloc(_),n=t._malloc(E),i=t._malloc(E),a=new Uint8Array(t.wasmMemory.buffer,r,_),o=new Uint8Array(t.wasmMemory.buffer,n,E),s=new Uint8Array(t.wasmMemory.buffer,i,E);try{if(a.fill(0),s.fill(0),o.set(e),t._cpace_ristretto255_scalar_random(r),0!==t._cpace_ristretto255_scalarmult(i,r,n))throw new Error("cpace: public share is the identity");return{y:Uint8Array.from(a),Y:Uint8Array.from(s)}}finally{I(t,a),t._free(n),t._free(i)}})(t,r);return t.fill(0),i},D=()=>((e,t,r,n,i,a,o,s)=>{const c=new Uint8Array(e.length);return c[0]=1,c.set(t,1),c.set(r,33),c.set(n,65),c.set(i,97),c.set(a,lt),c.set(o,e.publicKeyOffset),c.set(s,e.ciphertextOffset),c})(u,b,g.publicKey,w,l,d,A,k);try{let t;if(s){O=await f.generateKeyPair(),A.set(O.publicKey);const r=T(b);r&&(v=r.y,w=r.Y),await e.send(D()),t=await e.recv()}else t=await e.recv();if(t.length!==u.length||1!==t[0])throw new Error("Malformed handshake HELLO");const i=t.subarray(1,33),a=t.subarray(33,65),N=t.subarray(65,97),q=t.subarray(97,129),V=t.subarray(lt,193),$=t.subarray(u.publicKeyOffset,u.publicKeyOffset+u.suite.publicKeyBytes),z=t.subarray(u.ciphertextOffset,u.ciphertextOffset+u.suite.ciphertextBytes);if(s){if(!ht($))throw new Error("Malformed handshake HELLO: responder ML-KEM public-key field must be zero");if(ht(z))throw new Error("Malformed handshake HELLO: responder ML-KEM ciphertext is required")}else{if(ht($))throw new Error("Malformed handshake HELLO: initiator ML-KEM public key is required");if(!ht(z))throw new Error("Malformed handshake HELLO: initiator ML-KEM ciphertext field must be zero")}if(!await te(q,V,h,r))throw new Error("Handshake peer X25519 identity cross-signature invalid");if(s){if(!O)throw new Error("Handshake ML-KEM initiator keypair is unavailable");B=await f.decapsulate(z,O.secretKey),O.destroy()}else{const t=await f.encapsulate($);B=t,k.set(t.ciphertext);const r=T(i);r&&(v=r.y,w=r.Y),await e.send(D())}K=((e,t,r,n,i,a)=>{let o,s;const c=F(r,n,a);i?(o=F(e,n,a),s=F(r,t,a)):(o=F(r,t,a),s=F(e,n,a));const l=new Uint8Array(96);l.set(o,0),l.set(s,32),l.set(c,64);const d=re(Be,l,a),h=ne(d,Oe,32,a);return l.fill(0),o.fill(0),s.fill(0),c.fill(0),d.fill(0),h})(c,q,g.secretKey,a,s,r);const Q=s?b:i,j=s?i:b,Y=s?g.publicKey:a,W=s?a:g.publicKey,X=s?w:N,G=s?N:w,Z=s?l:q,J=s?d:V,ee=s?q:l,ie=s?V:d,ae=s?A:$,oe=s?k:z,se=s?$:A,ce=s?z:k;if("pin"===n){if(!v)throw new Error("Handshake CPace scalar is unavailable");U=((e,t)=>{const{y:r,peerShare:n,sid:i,initiatorShare:a,responderShare:o,initiatorAssociatedData:s=xe,responderAssociatedData:c=xe}=e;Se("private scalar",r,_),Se("peer share",n,E),Se("initiator share",a,E),Se("responder share",o,E);const l=t._malloc(_),d=t._malloc(E),h=t._malloc(E),u=t._malloc(p),f=t._malloc(y),m=new Uint8Array(t.wasmMemory.buffer,l,_),b=new Uint8Array(t.wasmMemory.buffer,d,E),g=new Uint8Array(t.wasmMemory.buffer,h,E),w=new Uint8Array(t.wasmMemory.buffer,u,p),v=new Uint8Array(t.wasmMemory.buffer,f,y);try{if(m.set(r),b.set(n),g.fill(0),w.fill(0),v.fill(0),0!==t._cpace_ristretto255_scalarmult(h,l,d))throw new Error("cpace: peer share is invalid or the identity");if(0!==t._sha512_init(u))throw new Error("sha512_init failed");if(Pe(t,u,{data:Ue}),Pe(t,u,{data:i}),Ce(t,u,Me(E)),0!==t._sha512_update(u,h,E))throw new Error("sha512_update failed");if(Pe(t,u,{data:a}),Pe(t,u,{data:s}),Pe(t,u,{data:o}),Pe(t,u,{data:c}),0!==t._sha512_final(u,f))throw new Error("sha512_final failed");return Uint8Array.from(v)}finally{I(t,m),t._free(d),I(t,g),I(t,w),I(t,v)}})({y:v,peerShare:N,sid:Q,initiatorShare:X,responderShare:G},r)}const le=((e,t)=>(new TextEncoder).encode("pin"===e?`p2party-v4-hybrid-root-cpace21-3dh-ml-kem-${String(t)}-v4`:`p2party-v4-hybrid-root-3dh-ml-kem-${String(t)}-v4`))(n,u.suite.parameterSet);x=await Ge("pin"===n?[U,K,B.sharedSecret]:[K,B.sharedSecret]),S=re(it,x,r);const de=await Ge([le,o,Z,J,ee,ie,ae,ce]);M=ne(S,de,32,r);const ue=await Ge([st,o,Q,j,Y,W,Z,J,ee,ie,ae,ce]);try{R=new Uint8Array(await crypto.subtle.digest("SHA-256",ue.slice().buffer))}finally{ue.fill(0)}C=re(at,M,r);const ye=await Ge([ot,R]);try{P=ne(C,ye,32,r)}finally{ye.fill(0),C.fill(0),C=void 0}K.fill(0),U?.fill(0),x.fill(0),S.fill(0),B.destroy();const pe=(e,t,r,n=[])=>Ge([et,e,Q,j,Y,W,X,G,Z,J,ee,ie,ae,oe,se,ce,t,...r?[r]:[],...n,o]);if(s){const t=await e.recv();if(97!==t.length||2!==t[0])throw new Error("Malformed handshake CONFIRM");const n=Uint8Array.from(t.subarray(1,33)),i=t.subarray(33,97);L=he(M,!0,n,r,m);const a=L.dhSelfPub,o=await pe(rt,n,a,[i]),s=dt(M,o,r);try{await e.send(ut(a,s));const t=await pe(tt,n),o=dt(M,t,r),c=await Ze(i,o);if(o.fill(0),!c)throw new Error("Handshake key-confirmation failed");const l=await e.recv();if(65!==l.length||3!==l[0])throw new Error("Malformed handshake FINISH");const d=l.subarray(1,65),h=await pe(nt,n,a,[i,s]),u=dt(M,h,r),f=await Ze(d,u);if(u.fill(0),!f)throw new Error("Handshake final confirmation failed")}finally{s.fill(0)}}else{L=he(M,!1,null,r,m);const t=L.dhSelfPub,n=await pe(tt,t),i=dt(M,n,r);try{await e.send(ut(t,i));const n=await e.recv();if(97!==n.length||2!==n[0])throw new Error("Malformed handshake CONFIRM");const a=Uint8Array.from(n.subarray(1,33)),o=n.subarray(33,97),s=await pe(rt,t,a,[i]),c=dt(M,s,r),l=await Ze(o,c);if(c.fill(0),!l)throw new Error("Handshake key-confirmation failed");((e,t,r)=>{if(t.length!==H)throw new Error("ratchet: invalid initiator DH public key");if(e.sendingChainKey||e.receivingChainKey||e.dhRemotePub||0!==e.Ns||0!==e.Nr||0!==e.PN||0!==e.skipped.size)throw new Error("ratchet: responder bootstrap requires pristine state");fe(e,{dhPub:t},r)})(L,a,r);const d=await pe(nt,t,a,[i,o]),h=dt(M,d,r);try{await e.send((e=>{const t=new Uint8Array(65);return t[0]=3,t.set(e,1),t})(h))}finally{h.fill(0)}}finally{i.fill(0)}}if(!L)throw new Error("Handshake ratchet initialization failed");if(!P||!R)throw new Error("Handshake PQ-healing bootstrap failed");const me=L;L=null;const be={rootKey:P,binding:R,nextOfferer:s?"local":"remote"};return P=void 0,R=void 0,{state:me,secret:M,pqHealing:be}}catch(e){throw M?.fill(0),P?.fill(0),R?.fill(0),e}finally{g.secretKey.fill(0),v?.fill(0),K?.fill(0),U?.fill(0),x?.fill(0),S?.fill(0),C?.fill(0),P?.fill(0),R?.fill(0),B?.destroy(),O?.destroy(),L&&ve(L)}},yt=(1n<<64n)-1n,pt=(e,t,r)=>{if(!Number.isInteger(r)||r<0||r>Number.MAX_SAFE_INTEGER)throw new Error("chunkFrame: ratchet counter out of safe-integer range");new DataView(e.buffer,e.byteOffset,e.byteLength).setBigUint64(t,BigInt(r),!1)},mt=(e,t)=>{const r=new DataView(e.buffer,e.byteOffset,e.byteLength).getBigUint64(t,!1);if(r>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("chunkFrame: ratchet counter exceeds safe-integer range");return Number(r)},bt=(e,t,r=0n)=>{if(e.dhPub.length!==H)throw new Error("chunkFrame: dhPub must be 32 bytes");if(12!==t.length)throw new Error("chunkFrame: nonce must be 12 bytes");const n=new Uint8Array(69);return n[0]=2,n.set(e.dhPub,1),pt(n,33,e.N),pt(n,41,e.PN),((e,t,r)=>{if("bigint"!=typeof r||r<0n||r>yt)throw new Error("chunkFrame: PQ epoch out of u64 range");new DataView(e.buffer,e.byteOffset,e.byteLength).setBigUint64(t,r,!1)})(n,49,r),n.set(t,57),n},gt=e=>{if(e.length<69)throw new Error("chunkFrame: frame shorter than the header");if(2!==e[0])throw new Error("chunkFrame: leading byte is not FRAME_TYPE_CHUNK");return{header:{dhPub:e.subarray(1,33),N:mt(e,33),PN:mt(e,41)},pqEpoch:(t=e,r=49,new DataView(t.buffer,t.byteOffset,t.byteLength).getBigUint64(r,!1)),nonce:e.subarray(57,69),ciphertext:e.subarray(69)};var t,r},wt=v,vt=(1n<<64n)-1n,At=(new TextEncoder).encode("p2party/pq-message-key/v1\0"),kt=(e,t,r)=>{if(!(e instanceof Uint8Array)||e.length!==r)throw new Error(`pqMessageKey: ${t} must be ${String(r)} bytes`)},Et=(e,t)=>{if(!Number.isSafeInteger(e)||e<0)throw new Error(`pqMessageKey: ${t} is outside the safe u64 range`)},Kt=(e,t)=>{if("string"!=typeof(r=e.rootSuite)||!X.includes(r))throw new Error("pqMessageKey: unsupported root suite");var r;kt(e.rootKey,"rootKey",32),kt(e.binding,"binding",32),(e=>{if("bigint"!=typeof e||e<0n||e>vt)throw new Error("pqMessageKey: epoch is outside the u64 range")})(e.epoch),kt(t.dhPub,"header.dhPub",H),Et(t.N,"header.N"),Et(t.PN,"header.PN");const n=(new TextEncoder).encode(e.rootSuite);if(n.length>65535)throw new Error("pqMessageKey: root suite identifier is too long");const i=At.length+2+n.length+32+8+1+H+8+8,a=new Uint8Array(i);let o=0;a.set(At,o),o+=At.length;const s=new DataView(a.buffer);return s.setUint16(o,n.length,!1),o+=2,a.set(n,o),o+=n.length,a.set(e.binding,o),o+=32,s.setBigUint64(o,e.epoch,!1),o+=8,a[o++]=2,a.set(t.dhPub,o),o+=H,s.setBigUint64(o,BigInt(t.N),!1),o+=8,s.setBigUint64(o,BigInt(t.PN),!1),a},_t=(e,t,r,n)=>{if(!(e instanceof Uint8Array))throw new Error("pqMessageKey: classicalMessageKey must be a Uint8Array");if(t?.rootKey instanceof Uint8Array&&(i=e,a=t.rootKey,i.buffer===a.buffer&&i.byteOffset<a.byteOffset+a.byteLength&&a.byteOffset<i.byteOffset+i.byteLength))throw new Error("pqMessageKey: classicalMessageKey must not alias context.rootKey");var i,a;let o=null,s=null;try{kt(e,"classicalMessageKey",wt);const i=Kt(t,r);return o=Uint8Array.from(t.rootKey),s=re(o,e,n),ne(s,i,wt,n)}finally{e.fill(0),o?.fill(0),s?.fill(0)}},Ut=v,xt=A,St=k,Mt=y+57,Ct=(1n<<64n)-1n,Pt=(e,t,r)=>{const n=`${i=e,Array.from(i,e=>e.toString(16).padStart(2,"0")).join("")}:${t}`;var i;if(void 0===r)return n;if("bigint"!=typeof r||r<0n||r>Ct)throw new Error("messageChunkCrypto: PQ epoch out of u64 range");return`${n}:${r.toString(10)}`},Rt=(e,t,r,n)=>{const i=e._malloc(L),a=e._malloc(V),o=e._malloc(y),s=e._malloc(Ut),c=new Uint8Array(e.wasmMemory.buffer,i,L),l=new Uint8Array(e.wasmMemory.buffer,a,V);c.fill(0),l.fill(0),c.set(t.subarray(0,L),0),new Uint8Array(e.wasmMemory.buffer,o,y).set(r),new Uint8Array(e.wasmMemory.buffer,s,Ut).set(n);const d=e._receive_message_with_key(a,i,o,s),h=0===d?Uint8Array.from(l):null;return e._free(i),e._free(o),I(e,new Uint8Array(e.wasmMemory.buffer,s,Ut)),I(e,l),{code:d,decrypted:h}},Ot=(e,t,r,n,i,a)=>{if(n.length!==y)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const o=(()=>{const e=new Uint8Array(xt);return crypto.getRandomValues(e),e})(),s=bt(t,o,a?.epoch??0n),c=((e,t)=>{if(t.length<57)throw new Error("messageChunkCrypto: incomplete chunk frame header");const r=new Uint8Array(Mt);return r.set(e,0),r.set(t.subarray(0,57),y),r})(n,s);let l=null;try{const n=((e,t,r,n,i)=>{const a=Math.max(n.length,1),o=Math.max(i.length,1),s=n.length+St,c=e._malloc(Ut),l=e._malloc(xt),d=e._malloc(a),h=e._malloc(o),u=e._malloc(s);new Uint8Array(e.wasmMemory.buffer,c,Ut).set(t),new Uint8Array(e.wasmMemory.buffer,l,xt).set(r),n.length&&new Uint8Array(e.wasmMemory.buffer,d,n.length).set(n),i.length&&new Uint8Array(e.wasmMemory.buffer,h,i.length).set(i);const f=0===e._encrypt_chachapoly_symmetric(u,d,n.length,c,l,h,i.length)?Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,u,s)):null;if(I(e,new Uint8Array(e.wasmMemory.buffer,c,Ut)),e._free(l),I(e,new Uint8Array(e.wasmMemory.buffer,d,a)),e._free(h),I(e,new Uint8Array(e.wasmMemory.buffer,u,s)),!f)throw new Error("messageChunkCrypto: AEAD encrypt failed");return f})(i,a?l=_t(Uint8Array.from(e),a,t,i):e,o,r,c),d=new Uint8Array(s.length+n.length);return d.set(s,0),d.set(n,s.length),d}finally{l?.fill(0)}},Bt=(e,t,r,n,i,a)=>{if(n.length!==y)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const{header:o,pqEpoch:s}=gt(t);let c=null;if(a){try{c=a(s)}catch{return{decrypted:null,ok:!1,stateAdvanced:!1}}if(!(c&&(l=c,d=s,h=e.rootSuite,l.epoch===d&&l.rootSuite===h&&l.rootKey instanceof Uint8Array&&32===l.rootKey.length&&l.binding instanceof Uint8Array&&32===l.binding.length)))return{decrypted:null,ok:!1,stateAdvanced:!1}}else if(0n!==s)return{decrypted:null,ok:!1,stateAdvanced:!1};var l,d,h;const u=Pt(o.dhPub,o.N,a?s:void 0),f=r.get(u);if(f){const{code:e,decrypted:r}=Rt(i,t,n,f);return{decrypted:0===e?r:null,ok:0===e,stateAdvanced:!1}}const p=we(e);let m;try{m=It(p,o,i),c&&(m=_t(m,c,o,i))}catch{return ve(p),{decrypted:null,ok:!1,stateAdvanced:!1}}const{code:b,decrypted:g}=Rt(i,t,n,m);return-2===b?(m.fill(0),ve(p),{decrypted:null,ok:!1,stateAdvanced:!1}):(Ae(e,p),r.set(u,m),{decrypted:0===b?g:null,ok:0===b,stateAdvanced:!0})},It=(e,t,r)=>{try{return ye(e,t,r)}catch(t){throw ve(e),t}},Nt=32,Ft=32,Lt=64,Tt=new Uint8Array([80,50,81,72]),Dt=(new TextEncoder).encode("p2party/pq-healing/root/v1\0"),qt=(1n<<64n)-1n;class Vt extends Error{code;constructor(e,t){super(`pqHealing: ${t}`),this.name="PqHealingError",this.code=e}}const $t=(e,t)=>{throw new Vt(e,t)},Ht=(e,t,r)=>e instanceof Uint8Array?e.length!==r?$t("invalid-record",`${t} must be exactly ${String(r)} bytes`):e:$t("invalid-record",`${t} must be a Uint8Array`),zt=(e,t)=>{("bigint"!=typeof e||e<0n||e>qt)&&$t("overflow",`${t} is outside the unsigned 64-bit range`)},Qt=(e,t)=>{zt(e,t),e===qt&&$t("overflow",`${t} cannot advance beyond uint64`)},jt=e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return $t("invalid-record","advance acknowledgement must be a plain record");const t=e,r=Reflect.ownKeys(t);2===r.length&&r.includes("epoch")&&r.includes("advanceCounter")||$t("invalid-record","advance acknowledgement must contain only epoch and advanceCounter");const n=Object.getOwnPropertyDescriptor(t,"epoch"),i=Object.getOwnPropertyDescriptor(t,"advanceCounter");if(!(void 0!==n&&void 0!==i&&"value"in n&&"value"in i&&n.enumerable&&i.enumerable))return $t("invalid-record","advance acknowledgement fields must be enumerable data properties");const a=n.value,o=i.value;return"bigint"!=typeof a||"bigint"!=typeof o?$t("invalid-record","advance acknowledgement fields must be bigint values"):(zt(a,"advance acknowledgement epoch"),zt(o,"advance acknowledgement counter"),{epoch:a,advanceCounter:o})},Yt=(e,t,r)=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return $t("invalid-record",`${t} must be a plain record`);const n=e,i=Reflect.ownKeys(n);if(i.length!==r.length||r.some(e=>!i.includes(e)))return $t("invalid-record",`${t} does not contain exactly its canonical fields`);for(const e of r){const r=Object.getOwnPropertyDescriptor(n,e);void 0!==r&&"value"in r&&r.enumerable||$t("invalid-record",`${t}.${e} must be an enumerable data property`)}return n},Wt=(e,t)=>{if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n+=1)r|=e[n]^t[n];return 0===r},Xt=e=>768===e?1:512===e?2:1024===e?3:$t("suite-mismatch","unsupported ML-KEM parameter set"),Gt=e=>1===e?768:2===e?512:3===e?1024:$t("invalid-record","record has an unknown ML-KEM suite tag"),Zt=(e,t)=>Reflect.get(e,t),Jt=e=>{const t=De(e.parameterSet);e.standardName===t.standardName&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes&&Zt(e,"sharedSecretBytes")===t.sharedSecretBytes&&Zt(e,"keyPairRandomBytes")===t.keyPairRandomBytes&&Zt(e,"encapsRandomBytes")===t.encapsRandomBytes||$t("suite-mismatch","selected suite does not match its canonical FIPS 203 descriptor")},er=(e,t)=>{Jt(e),Jt(t),e.parameterSet===t.parameterSet&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes||$t("suite-mismatch","room-selected suite does not exactly match the ML-KEM backend")},tr=e=>Lt+e.publicKeyBytes,rr=e=>Lt+tr(e)+e.ciphertextBytes,nr=(e,t,r)=>{Jt(t),Ht(r,"binding",Nt),Ht(e,"ACK",64),Wt(e.subarray(0,4),Tt)||$t("invalid-record","ACK magic is invalid"),1!==e[4]&&$t("invalid-record","ACK version is unsupported"),3!==e[5]&&$t("invalid-record","ACK type is unexpected"),0!==e[7]&&$t("invalid-record","ACK reserved flags must be zero");Gt(e[6])!==t.parameterSet&&$t("suite-mismatch","ACK suite differs from the authenticated room suite"),Wt(e.subarray(8,40),r)||$t("binding-mismatch","ACK belongs to a different authenticated edge");const n=new DataView(e.buffer,e.byteOffset,e.byteLength);return 0n!==n.getBigUint64(56,!1)&&$t("invalid-record","ACK reserved bytes must be zero"),{advanceCounter:n.getBigUint64(40,!1),epoch:n.getBigUint64(48,!1)}},ir=(e,t,r,n,i,a,o)=>{Ht(r,"binding",Nt),zt(n,"sender counter"),zt(i,"from epoch"),zt(a,"to epoch"),i!==qt&&a===i+1n||$t("invalid-record","record must advance exactly one PQ epoch");const s=new Uint8Array(o);s.set(Tt,0),s[4]=1,s[5]=e,s[6]=Xt(t.parameterSet),s[7]=0,s.set(r,8);const c=new DataView(s.buffer,s.byteOffset,s.byteLength);return c.setBigUint64(40,n,!1),c.setBigUint64(48,i,!1),c.setBigUint64(56,a,!1),s},ar=(e,t,r,n)=>{e instanceof Uint8Array||$t("invalid-record","record must be a Uint8Array"),e.length<Lt&&$t("invalid-record","record is shorter than its canonical header"),Wt(e.subarray(0,4),Tt)||$t("invalid-record","record magic is invalid"),1!==e[4]&&$t("invalid-record","record version is unsupported"),e[5]!==t&&$t("invalid-record","record type is unexpected"),0!==e[7]&&$t("invalid-record","record reserved flags must be zero");Gt(e[6])!==r.parameterSet&&$t("suite-mismatch","record suite differs from the authenticated room suite");const i=e.subarray(8,40);void 0===n||Wt(i,n)||$t("binding-mismatch","record belongs to a different authenticated edge");const a=new DataView(e.buffer,e.byteOffset,e.byteLength),o=a.getBigUint64(40,!1),s=a.getBigUint64(48,!1),c=a.getBigUint64(56,!1);return s!==qt&&c===s+1n||$t("invalid-record","record must advance exactly one PQ epoch"),{senderCounter:o,fromEpoch:s,toEpoch:c}},or=(e,t,r)=>{const n=ar(e,1,t,r);return e.length!==tr(t)&&$t("invalid-record","OFFER length is not canonical for its suite"),{...n,bytes:Uint8Array.from(e),publicKey:e.slice(Lt)}},sr=(e,t,r)=>{const n=ar(e,2,t,r);e.length!==rr(t)&&$t("invalid-record","ADVANCE length is not canonical for its suite");const i=tr(t),a=e.slice(Lt,Lt+i),o=or(a,t,r);return o.fromEpoch===n.fromEpoch&&o.toEpoch===n.toEpoch||$t("fork","ADVANCE epoch does not exactly match its embedded OFFER"),{...n,bytes:Uint8Array.from(e),offer:o,ciphertext:e.slice(Lt+i)}},cr=(e,t)=>{if(Jt(t),!(e instanceof Uint8Array))return $t("invalid-record","record must be a Uint8Array");if(e.length<Lt)return $t("invalid-record","record is shorter than its canonical header");if(1===e[5]){const r=or(e,t);return{type:"offer",parameterSet:t.parameterSet,binding:r.bytes.slice(8,40),senderCounter:r.senderCounter,fromEpoch:r.fromEpoch,toEpoch:r.toEpoch,publicKey:Uint8Array.from(r.publicKey)}}if(2===e[5]){const r=sr(e,t),n={type:"offer",parameterSet:t.parameterSet,binding:r.offer.bytes.slice(8,40),senderCounter:r.offer.senderCounter,fromEpoch:r.offer.fromEpoch,toEpoch:r.offer.toEpoch,publicKey:Uint8Array.from(r.offer.publicKey)};return{type:"advance",parameterSet:t.parameterSet,binding:r.bytes.slice(8,40),senderCounter:r.senderCounter,fromEpoch:r.fromEpoch,toEpoch:r.toEpoch,offerBytes:Uint8Array.from(r.offer.bytes),offer:n,ciphertext:Uint8Array.from(r.ciphertext)}}return $t("invalid-record","record type is unknown")},lr=(e,t,r,n)=>{Ht(e,"PQ root",Ft);const i=re(e,t,n),a=((...e)=>{const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r})(Dt,r);try{return ne(i,a,Ft,n)}finally{i.fill(0)}},dr=(e,t)=>{const r=Uint8Array.from(e),n=Uint8Array.from(t);let i=!1;return{publicKey:r,secretKey:n,get destroyed(){return i},destroy(){i||(n.fill(0),i=!0)}}},hr=e=>{switch(e.kind){case"idle":return{kind:"idle"};case"outbound-offer":return{kind:e.dispatched?"outbound-offer-dispatched":"outbound-offer-prepared",offer:Uint8Array.from(e.offer.bytes),secretKey:Uint8Array.from(e.keyPair.secretKey)};case"inbound-offer":return{kind:"inbound-offer",offer:Uint8Array.from(e.offer.bytes)};case"outbound-advance-prepared":return{kind:"outbound-advance-prepared",advance:Uint8Array.from(e.advance.bytes),nextRoot:Uint8Array.from(e.nextRoot)};case"outbound-advance-awaiting-ack":return{kind:"outbound-advance-awaiting-ack",advance:Uint8Array.from(e.advance.bytes)};case"inbound-advance-prepared":return{kind:"inbound-advance-prepared",advance:Uint8Array.from(e.advance.bytes),secretKey:Uint8Array.from(e.keyPair.secretKey),nextRoot:Uint8Array.from(e.nextRoot)};case"inbound-advance-awaiting-ack-dispatch":return{kind:"inbound-advance-awaiting-ack-dispatch",advance:Uint8Array.from(e.advance.bytes)}}},ur=(e,t)=>"bigint"!=typeof e?$t("invalid-record",`${t} must be a bigint`):(zt(e,t),e),fr=(e,t,r)=>{const n=(e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return $t("invalid-record","snapshot.phase must be a plain record");const t=Object.getOwnPropertyDescriptor(e,"kind");return void 0!==t&&"value"in t&&t.enumerable&&"string"==typeof t.value?t.value:$t("invalid-record","snapshot.phase.kind must be an enumerable string data property")})(e);switch(n){case"idle":return Yt(e,"snapshot.phase",["kind"]),{kind:"idle"};case"outbound-offer-prepared":case"outbound-offer-dispatched":{const i=Yt(e,"snapshot.phase",["kind","offer","secretKey"]),a=or(Ht(i.offer,"snapshot.phase.offer",tr(t)),t,r),o=Ht(i.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes);return{kind:"outbound-offer",dispatched:"outbound-offer-dispatched"===n,offer:a,keyPair:dr(a.publicKey,o)}}case"inbound-offer":{const n=Yt(e,"snapshot.phase",["kind","offer"]);return{kind:"inbound-offer",offer:or(Ht(n.offer,"snapshot.phase.offer",tr(t)),t,r)}}case"outbound-advance-prepared":{const n=Yt(e,"snapshot.phase",["kind","advance","nextRoot"]),i=sr(Ht(n.advance,"snapshot.phase.advance",rr(t)),t,r);return{kind:"outbound-advance-prepared",offer:i.offer,advance:i,nextRoot:Uint8Array.from(Ht(n.nextRoot,"snapshot.phase.nextRoot",Ft))}}case"outbound-advance-awaiting-ack":{const n=Yt(e,"snapshot.phase",["kind","advance"]),i=sr(Ht(n.advance,"snapshot.phase.advance",rr(t)),t,r);return{kind:"outbound-advance-awaiting-ack",offer:i.offer,advance:i}}case"inbound-advance-prepared":{const n=Yt(e,"snapshot.phase",["kind","advance","secretKey","nextRoot"]),i=sr(Ht(n.advance,"snapshot.phase.advance",rr(t)),t,r),a=Ht(n.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes),o=Uint8Array.from(Ht(n.nextRoot,"snapshot.phase.nextRoot",Ft));return{kind:"inbound-advance-prepared",offer:i.offer,advance:i,keyPair:dr(i.offer.publicKey,a),nextRoot:o}}case"inbound-advance-awaiting-ack-dispatch":{const n=Yt(e,"snapshot.phase",["kind","advance"]);return{kind:"inbound-advance-awaiting-ack-dispatch",advance:sr(Ht(n.advance,"snapshot.phase.advance",rr(t)),t,r)}}default:return $t("invalid-record","snapshot phase is unknown")}},yr=(e,t)=>{e||$t("invalid-record",`snapshot ${t}`)},pr=(e,t)=>{er(t.suite,t.backend.suite),Ht(t.binding,"binding",Nt);const r=Yt(e,"snapshot",["formatVersion","parameterSet","binding","rootKey","epoch","localCounter","remoteCounter","nextOfferer","phase","lastInboundOffer","lastInboundAdvance"]);1!==r.formatVersion&&$t("invalid-record","snapshot format version is unsupported"),r.parameterSet!==t.suite.parameterSet&&$t("suite-mismatch","snapshot suite differs from the authenticated room suite");const n=Ht(r.binding,"snapshot.binding",Nt);Wt(n,t.binding)||$t("binding-mismatch","snapshot belongs to a different authenticated edge");const i=Ht(r.rootKey,"snapshot.rootKey",Ft),a=ur(r.epoch,"snapshot.epoch"),o=ur(r.localCounter,"snapshot.localCounter"),s=ur(r.remoteCounter,"snapshot.remoteCounter");if("local"!==r.nextOfferer&&"remote"!==r.nextOfferer)return $t("invalid-record","snapshot.nextOfferer must be local or remote");const c=Uint8Array.from(i);let l;try{l=fr(r.phase,t.suite,t.binding);const e=null===r.lastInboundOffer?null:or(Ht(r.lastInboundOffer,"snapshot.lastInboundOffer",tr(t.suite)),t.suite,t.binding),n=null===r.lastInboundAdvance?null:sr(Ht(r.lastInboundAdvance,"snapshot.lastInboundAdvance",rr(t.suite)),t.suite,t.binding),i={rootKey:c,epoch:a,localCounter:o,remoteCounter:s,nextOfferer:r.nextOfferer,phase:l,lastInboundOffer:e,lastInboundAdvance:n};return(e=>{const{epoch:t,localCounter:r,remoteCounter:n,nextOfferer:i,phase:a,lastInboundOffer:o,lastInboundAdvance:s}=e;switch(null!==o&&(yr(o.toEpoch<=t,"last inbound OFFER is from a future epoch"),yr(o.senderCounter<n,"last inbound OFFER counter was not consumed")),null!==s&&(yr(s.toEpoch<=t,"last inbound ADVANCE is from a future epoch"),yr(s.senderCounter<n,"last inbound ADVANCE counter was not consumed")),a.kind){case"idle":return;case"outbound-offer":return void yr("local"===i&&a.offer.senderCounter===r&&a.offer.fromEpoch===t,"outbound OFFER does not match the current turn/counter/epoch");case"inbound-offer":return void yr("remote"===i&&a.offer.senderCounter===n&&a.offer.fromEpoch===t,"inbound OFFER does not match the current turn/counter/epoch");case"outbound-advance-prepared":return void yr("remote"===i&&a.advance.senderCounter===r&&a.offer.senderCounter===n&&a.advance.fromEpoch===t,"prepared outbound ADVANCE does not match current state");case"outbound-advance-awaiting-ack":return yr("local"===i&&a.advance.senderCounter+1n===r&&a.offer.senderCounter+1n===n&&a.advance.toEpoch===t,"outbound ADVANCE awaiting ACK does not match committed state"),void yr(null!==o&&Wt(o.bytes,a.offer.bytes),"outbound ADVANCE is missing its exact inbound OFFER replay record");case"inbound-advance-prepared":return void yr("local"===i&&a.advance.senderCounter===n&&a.offer.senderCounter===r&&a.advance.fromEpoch===t,"prepared inbound ADVANCE does not match current state");case"inbound-advance-awaiting-ack-dispatch":yr("remote"===i&&a.advance.senderCounter+1n===n&&a.advance.offer.senderCounter+1n===r&&a.advance.toEpoch===t,"inbound ADVANCE awaiting ACK dispatch does not match committed state"),yr(null!==s&&Wt(s.bytes,a.advance.bytes),"pending ACK is missing its exact inbound ADVANCE replay record")}})(i),i}catch(e){throw c.fill(0),void 0!==l&&("outbound-offer"===l.kind&&l.keyPair.destroy(),"outbound-advance-prepared"===l.kind&&l.nextRoot.fill(0),"inbound-advance-prepared"===l.kind&&(l.keyPair.destroy(),l.nextRoot.fill(0))),e}};class mr{#e;#r;#n;#i;#a;#o;#s;#c;#l;#d={kind:"idle"};#h=null;#u=null;#f=!1;#y=!1;constructor(e){er(e.suite,e.backend.suite),Ht(e.binding,"binding",Nt),Ht(e.rootKey,"PQ root",Ft);const t=e.nextOfferer;"local"!==t&&"remote"!==t&&$t("invalid-state","nextOfferer must be local or remote");const r=e.epoch??0n,n=e.localCounter??0n,i=e.remoteCounter??0n;zt(r,"epoch"),zt(n,"local counter"),zt(i,"remote counter"),this.#e=e.module,this.#r=e.backend,this.#n=e.suite,this.#i=Uint8Array.from(e.binding),this.#a=Uint8Array.from(e.rootKey),this.#o=r,this.#s=n,this.#c=i,this.#l=e.nextOfferer}static restore(e,t){const r=pr(e,t);try{const e=new mr({...t,rootKey:r.rootKey,epoch:r.epoch,localCounter:r.localCounter,remoteCounter:r.remoteCounter,nextOfferer:r.nextOfferer});return e.#d=r.phase,e.#h=r.lastInboundOffer,e.#u=r.lastInboundAdvance,r.rootKey.fill(0),e}catch(e){throw r.rootKey.fill(0),"outbound-offer"===r.phase.kind&&r.phase.keyPair.destroy(),"outbound-advance-prepared"===r.phase.kind&&r.phase.nextRoot.fill(0),"inbound-advance-prepared"===r.phase.kind&&(r.phase.keyPair.destroy(),r.phase.nextRoot.fill(0)),e}}get suite(){return this.#n}get phase(){return this.#y?"destroyed":(e=>{switch(e.kind){case"idle":return"idle";case"outbound-offer":return e.dispatched?"outbound-offer-dispatched":"outbound-offer-prepared";case"inbound-offer":return"inbound-offer";case"outbound-advance-prepared":return"outbound-advance-prepared";case"outbound-advance-awaiting-ack":return"outbound-advance-awaiting-ack";case"inbound-advance-prepared":return"inbound-advance-prepared";case"inbound-advance-awaiting-ack-dispatch":return"inbound-advance-awaiting-ack-dispatch"}})(this.#d)}get epoch(){return this.#p(),this.#o}get localCounter(){return this.#p(),this.#s}get remoteCounter(){return this.#p(),this.#c}get nextOfferer(){return this.#p(),this.#l}get trafficBlocked(){return this.#y||"idle"!==this.#d.kind}copyRootKey(){return this.#p(),Uint8Array.from(this.#a)}snapshot(){return this.#m(),{formatVersion:1,parameterSet:this.#n.parameterSet,binding:Uint8Array.from(this.#i),rootKey:Uint8Array.from(this.#a),epoch:this.#o,localCounter:this.#s,remoteCounter:this.#c,nextOfferer:this.#l,phase:hr(this.#d),lastInboundOffer:null===this.#h?null:Uint8Array.from(this.#h.bytes),lastInboundAdvance:null===this.#u?null:Uint8Array.from(this.#u.bytes)}}clone(){const e=this.snapshot();try{return mr.restore(e,{module:this.#e,backend:this.#r,suite:this.#n,binding:this.#i})}finally{br(e)}}adopt(e){this.#m(),e.#m(),e===this&&$t("invalid-state","cannot adopt a machine into itself"),this.#n.parameterSet===e.#n.parameterSet&&Wt(this.#i,e.#i)||$t("invalid-state","cannot adopt a machine from another suite or authenticated edge"),this.#b(this.#d),this.#a.fill(0),this.#a=e.#a,this.#o=e.#o,this.#s=e.#s,this.#c=e.#c,this.#l=e.#l,this.#d=e.#d,this.#h=e.#h,this.#u=e.#u,e.#a=new Uint8Array(Ft),e.#i.fill(0),e.#d={kind:"idle"},e.#h=null,e.#u=null,e.#y=!0}copyPendingOutboundRecord(){this.#m();const e=this.#d;return"outbound-offer"===e.kind?Uint8Array.from(e.offer.bytes):"outbound-advance-prepared"===e.kind||"outbound-advance-awaiting-ack"===e.kind?Uint8Array.from(e.advance.bytes):$t("invalid-state","there is no pending outbound record")}async prepareOffer(){let e;this.#g();try{"idle"!==this.#d.kind&&$t("invalid-state","cannot prepare an OFFER while another transition is pending"),"local"!==this.#l&&$t("wrong-turn","the remote peer owns the next OFFER turn"),this.#w(),e=await this.#r.generateKeyPair(),this.#p(),Ht(e.publicKey,"ML-KEM public key",this.#n.publicKeyBytes),Ht(e.secretKey,"ML-KEM secret key",this.#n.secretKeyBytes);const t=((e,t,r,n,i)=>{Ht(i,"ML-KEM public key",e.publicKeyBytes);const a=ir(1,e,t,r,n,n+1n,tr(e));return a.set(i,Lt),a})(this.#n,this.#i,this.#s,this.#o,e.publicKey),r=or(t,this.#n,this.#i);return this.#d={kind:"outbound-offer",dispatched:!1,offer:r,keyPair:e},e=void 0,Uint8Array.from(t)}finally{e?.destroy(),this.#v()}}markOfferDispatched(){this.#m();const e=this.#d;if("outbound-offer"!==e.kind)return $t("invalid-state","there is no outbound OFFER to dispatch");e.dispatched&&$t("invalid-state","outbound OFFER was already marked dispatched"),this.#d={...e,dispatched:!0}}abortUnsentOffer(){this.#m();const e=this.#d;if("outbound-offer"!==e.kind||e.dispatched)return $t("invalid-state","only an undispatched OFFER can be aborted");e.keyPair.destroy(),this.#d={kind:"idle"}}acceptAuthenticatedOffer(e){this.#m();const t=or(e,this.#n,this.#i);this.#A(t),"idle"!==this.#d.kind&&$t("invalid-state","another PQ healing transition is pending"),"remote"!==this.#l&&$t("wrong-turn","the local peer owns the next OFFER turn"),this.#k(t.senderCounter),this.#E(t.fromEpoch),this.#w(),this.#d={kind:"inbound-offer",offer:t}}async prepareAdvance(){let e;this.#g();try{const t=this.#d;if("inbound-offer"!==t.kind)return $t("invalid-state","an authenticated inbound OFFER is required");Qt(this.#s,"local counter"),e=await this.#r.encapsulate(t.offer.publicKey),this.#p(),Ht(e.ciphertext,"ML-KEM ciphertext",this.#n.ciphertextBytes),Ht(e.sharedSecret,"ML-KEM shared secret",this.#n.sharedSecretBytes);const r=((e,t,r,n,i)=>{Ht(i,"ML-KEM ciphertext",e.ciphertextBytes);const a=ir(2,e,t,r,n.fromEpoch,n.toEpoch,rr(e));return a.set(n.bytes,Lt),a.set(i,Lt+n.bytes.length),a})(this.#n,this.#i,this.#s,t.offer,e.ciphertext),n=sr(r,this.#n,this.#i),i=lr(this.#a,e.sharedSecret,r,this.#e);return this.#d={kind:"outbound-advance-prepared",offer:t.offer,advance:n,nextRoot:i},Uint8Array.from(r)}finally{e?.destroy(),this.#v()}}commitPreparedAdvance(){this.#m();const e=this.#d;return"outbound-advance-prepared"!==e.kind?$t("invalid-state","there is no prepared outbound ADVANCE"):(this.#K(e.nextRoot),this.#o=e.advance.toEpoch,this.#s+=1n,this.#c+=1n,this.#l="local",this.#h=e.offer,this.#d={kind:"outbound-advance-awaiting-ack",offer:e.offer,advance:e.advance},Uint8Array.from(e.advance.bytes))}acceptAuthenticatedAdvanceAcknowledgement(e){this.#m();const t=jt(e),r=this.#d;if("outbound-advance-awaiting-ack"!==r.kind)return $t("invalid-state","no outbound ADVANCE is awaiting acknowledgement");t.epoch===this.#o&&t.advanceCounter===r.advance.senderCounter||$t("invalid-record","advance acknowledgement does not bind the pending transition"),this.#d={kind:"idle"}}async acceptAuthenticatedAdvance(e){let t;this.#g();try{const r=sr(e,this.#n,this.#i);this.#_(r);const n=this.#d;if("outbound-offer"!==n.kind||!n.dispatched)return $t("invalid-state","a dispatched outbound OFFER is required before ADVANCE");this.#k(r.senderCounter),this.#E(r.fromEpoch),Wt(r.offer.bytes,n.offer.bytes)||$t("fork","ADVANCE answers a different OFFER"),t=await this.#r.decapsulate(r.ciphertext,n.keyPair.secretKey),this.#p(),Ht(t.sharedSecret,"ML-KEM shared secret",this.#n.sharedSecretBytes);const i=lr(this.#a,t.sharedSecret,r.bytes,this.#e);this.#d={kind:"inbound-advance-prepared",offer:n.offer,advance:r,keyPair:n.keyPair,nextRoot:i}}finally{t?.destroy(),this.#v()}}commitAcceptedAdvance(){this.#m();const e=this.#d;return"inbound-advance-prepared"!==e.kind?$t("invalid-state","there is no accepted ADVANCE to commit"):(e.keyPair.destroy(),this.#K(e.nextRoot),this.#o=e.advance.toEpoch,this.#s+=1n,this.#c+=1n,this.#l="remote",this.#u=e.advance,this.#d={kind:"inbound-advance-awaiting-ack-dispatch",advance:e.advance},{epoch:this.#o,advanceCounter:e.advance.senderCounter})}markAdvanceAcknowledgementDispatched(e){this.#m();const t=jt(e),r=this.#d;if("inbound-advance-awaiting-ack-dispatch"!==r.kind)return $t("invalid-state","no advance acknowledgement is pending dispatch");t.epoch===this.#o&&t.advanceCounter===r.advance.senderCounter||$t("invalid-record","advance acknowledgement does not bind the committed transition"),this.#d={kind:"idle"}}destroy(){this.#y||(this.#b(this.#d),this.#a.fill(0),this.#i.fill(0),this.#h=null,this.#u=null,this.#d={kind:"idle"},this.#y=!0)}#p(){this.#y&&$t("destroyed","state machine is destroyed")}#m(){this.#p(),this.#f&&$t("invalid-state","another asynchronous transition is in flight")}#g(){this.#m(),this.#f=!0}#v(){this.#f=!1}#w(){Qt(this.#o,"epoch"),Qt(this.#s,"local counter"),Qt(this.#c,"remote counter")}#k(e){e<this.#c&&$t("replay","record sender counter was already consumed"),e>this.#c&&$t("counter-gap","record sender counter skips an expected transition")}#E(e){e<this.#o&&$t("replay","record PQ epoch was already consumed"),e>this.#o&&$t("epoch-gap","record skips the current PQ epoch")}#A(e){let t=this.#h;const r=this.#d;var n,i;("inbound-offer"!==r.kind&&"outbound-advance-prepared"!==r.kind&&"outbound-advance-awaiting-ack"!==r.kind||(t=r.offer),null!==t&&(i=t,(n=e).senderCounter===i.senderCounter&&n.fromEpoch===i.fromEpoch&&n.toEpoch===i.toEpoch))&&(Wt(e.bytes,t.bytes)&&$t("replay","OFFER is an exact replay"),$t("fork","different OFFER bytes reuse an authenticated slot"))}#_(e){let t=this.#u;const r=this.#d;var n,i;("inbound-advance-prepared"!==r.kind&&"inbound-advance-awaiting-ack-dispatch"!==r.kind||(t=r.advance),null!==t&&(i=t,(n=e).senderCounter===i.senderCounter&&n.fromEpoch===i.fromEpoch&&n.toEpoch===i.toEpoch))&&(Wt(e.bytes,t.bytes)&&$t("replay","ADVANCE is an exact replay"),$t("fork","different ADVANCE bytes reuse an authenticated slot"))}#K(e){Ht(e,"candidate PQ root",Ft),this.#a.fill(0),this.#a=e}#b(e){"outbound-offer"===e.kind&&e.keyPair.destroy(),"outbound-advance-prepared"===e.kind&&e.nextRoot.fill(0),"inbound-advance-prepared"===e.kind&&(e.keyPair.destroy(),e.nextRoot.fill(0))}}const br=e=>{e.binding.fill(0),e.rootKey.fill(0),e.lastInboundOffer?.fill(0),e.lastInboundAdvance?.fill(0);const t=e.phase;switch(t.kind){case"idle":return;case"outbound-offer-prepared":case"outbound-offer-dispatched":return t.offer.fill(0),void t.secretKey.fill(0);case"inbound-offer":return void t.offer.fill(0);case"outbound-advance-prepared":return t.advance.fill(0),void t.nextRoot.fill(0);case"outbound-advance-awaiting-ack":case"inbound-advance-awaiting-ack-dispatch":return void t.advance.fill(0);case"inbound-advance-prepared":return t.advance.fill(0),t.secretKey.fill(0),void t.nextRoot.fill(0)}},gr=z-69-k,wr=(1n<<64n)-1n,vr=(new TextEncoder).encode("p2party/pq-control-frame/key/v1\0");class Ar extends Error{code;constructor(e,t){super(`pqHealingFrame: ${t}`),this.name="PqControlFrameError",this.code=e}}const kr=(e,t)=>{throw new Ar(e,t)},Er=(e,t)=>{if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n+=1)r|=e[n]^t[n];return 0===r},Kr=(e,t,r)=>e instanceof Uint8Array?(void 0!==r&&e.length!==r&&kr("invalid-frame",`${t} must be exactly ${String(r)} bytes`),e):kr("invalid-frame",`${t} must be a Uint8Array`),_r=(e,t)=>"bigint"!=typeof e||e<0n||e>wr?kr("invalid-frame",`${t} must be an unsigned 64-bit bigint`):e,Ur=(e,t,r,n,i,a)=>{Kr(r,"PQ root",Ft),Kr(n,"binding",Nt);const o=(e=>{const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,e,!1),t})(_r(a,"keyEpoch")),s=new Uint8Array(vr.length+1+1+n.length+o.length);s.set(vr,0),s[vr.length]=(e=>{const t=De(e.parameterSet);return e.standardName!==t.standardName||e.publicKeyBytes!==t.publicKeyBytes||e.secretKeyBytes!==t.secretKeyBytes||e.ciphertextBytes!==t.ciphertextBytes||e.sharedSecretBytes!==t.sharedSecretBytes||e.keyPairRandomBytes!==t.keyPairRandomBytes||e.encapsRandomBytes!==t.encapsRandomBytes?kr("invalid-frame","ML-KEM suite descriptor is not canonical"):768===e.parameterSet?1:512===e.parameterSet?2:1024===e.parameterSet?3:kr("invalid-frame","ML-KEM suite is unsupported")})(t),s[vr.length+1]=(e=>"initiator-to-responder"===e?1:"responder-to-initiator"===e?2:kr("invalid-direction","control direction is unknown"))(i),s.set(n,vr.length+2),s.set(o,vr.length+2+n.length);const c=re(r,n,e);try{return ne(c,s,v,e)}finally{c.fill(0),o.fill(0)}},xr=(e,t,r)=>{if(Kr(e,"control record"),64===e.length){const n=nr(e,t,r);return{counter:n.advanceCounter,keyEpoch:n.epoch}}const n=cr(e,t);return Er(n.binding,r)?{counter:n.senderCounter,keyEpoch:n.fromEpoch}:kr("binding-mismatch","control record belongs to another authenticated edge")},Sr=e=>{const t=Kr(e.binding,"binding",Nt),r=_r(e.keyEpoch,"keyEpoch"),n=xr(e.record,e.suite,t);n.keyEpoch!==r&&kr("epoch-mismatch","control record is not authenticated under its required epoch"),e.record.length>gr-4&&kr("invalid-frame","control record does not fit the uniform cell");const i=(()=>{const e=new Uint8Array(A);return crypto.getRandomValues(e),e})(),a=new Uint8Array(69);a[0]=5,a.set(t,1);const o=new DataView(a.buffer,a.byteOffset,a.byteLength);o.setBigUint64(33,n.counter,!1),o.setBigUint64(49,r,!1),a.set(i,57);const s=new Uint8Array(gr);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e.record.length,!1),s.set(e.record,4);const c=Ur(e.module,e.suite,e.rootKey,t,e.direction,r);try{const t=((e,t,r,n,i)=>{const a=n.length+k,o=e._malloc(t.length),s=e._malloc(r.length),c=e._malloc(n.length),l=e._malloc(i.length),d=e._malloc(a);try{return new Uint8Array(e.wasmMemory.buffer,o,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,c,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,l,i.length).set(i),0!==e._encrypt_chachapoly_symmetric(d,c,n.length,o,s,l,i.length)?kr("invalid-frame","control-frame AEAD encryption failed"):Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,d,a))}finally{I(e,new Uint8Array(e.wasmMemory.buffer,o,t.length)),e._free(s),I(e,new Uint8Array(e.wasmMemory.buffer,c,n.length)),e._free(l),I(e,new Uint8Array(e.wasmMemory.buffer,d,a))}})(e.module,c,i,s,a),r=new Uint8Array(z);return r.set(a,0),r.set(t,69),r}finally{c.fill(0),s.fill(0)}},Mr=e=>{const t=Kr(e.frame,"control frame",z),r=Kr(e.binding,"binding",Nt),n=_r(e.keyEpoch,"keyEpoch");5!==t[0]&&kr("invalid-frame","frame type is not PQ control"),Er(t.subarray(1,33),r)||kr("binding-mismatch","control frame belongs to another edge");const i=t.subarray(0,69),a=new DataView(t.buffer,t.byteOffset,t.byteLength),o=a.getBigUint64(33,!1);0n!==a.getBigUint64(41,!1)&&kr("invalid-frame","control-frame reserved header must be zero"),a.getBigUint64(49,!1)!==n&&kr("epoch-mismatch","control-frame epoch is not the expected epoch");const s=t.subarray(57,69),c=t.subarray(69),l=Ur(e.module,e.suite,e.rootKey,r,e.direction,n);let d;try{d=((e,t,r,n,i)=>{const a=n.length-k,o=e._malloc(t.length),s=e._malloc(r.length),c=e._malloc(n.length),l=e._malloc(i.length),d=e._malloc(a);try{new Uint8Array(e.wasmMemory.buffer,o,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,c,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,l,i.length).set(i);const h=new Uint8Array(e.wasmMemory.buffer,d,a);return h.fill(0),0!==e._decrypt_chachapoly_symmetric(d,c,n.length,o,s,l,i.length)?kr("authentication-failed","control-frame authentication failed"):Uint8Array.from(h)}finally{I(e,new Uint8Array(e.wasmMemory.buffer,o,t.length)),e._free(s),e._free(c),e._free(l),I(e,new Uint8Array(e.wasmMemory.buffer,d,a))}})(e.module,l,s,c,i);const t=new DataView(d.buffer,d.byteOffset,d.byteLength).getUint32(0,!1);(0===t||t>gr-4)&&kr("invalid-padding","encrypted control-record length is invalid");const a=4+t;let h=0;for(let e=a;e<d.length;e+=1)h|=d[e];0!==h&&kr("invalid-padding","encrypted control padding must be all zero");const u=d.slice(4,a),f=xr(u,e.suite,r);return f.keyEpoch!==n&&kr("epoch-mismatch","decrypted control record does not match its frame epoch"),f.counter!==o&&kr("record-mismatch","decrypted control counter does not match its public header"),u}finally{l.fill(0),d?.fill(0)}},Cr=new Uint8Array([80,50,69,68,71,69,52,0]),Pr=(1n<<64n)-1n,Rr=262144,Or=Math.min(Z,256),Br=/^[0-9a-f]{64}:[0-9]+:[0-9]+$/,Ir=new TextEncoder,Nr=new TextDecoder("utf-8",{fatal:!0}),Fr=e=>{throw new Error(`pqHealingRuntime: ${e}`)},Lr=(e,t)=>{if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n+=1)r|=e[n]^t[n];return 0===r},Tr=(e,t,r)=>e instanceof Uint8Array?(void 0!==r&&e.length!==r&&Fr(`${t} must be exactly ${String(r)} bytes`),e):Fr(`${t} must be a Uint8Array`),Dr=(e,t)=>"number"!=typeof e||!Number.isSafeInteger(e)||e<0?Fr(`${t} must be a non-negative safe integer`):e,qr=e=>1===e?"local":2===e?"remote":Fr("checkpoint has an invalid next-offerer turn");class Vr{#U=[];#x=0;bytes(e){const t=Uint8Array.from(e);this.#U.push(t),this.#x+=t.length,this.#x>Rr&&Fr("checkpoint exceeds the encrypted edge-state budget")}u8(e){(!Number.isInteger(e)||e<0||e>255)&&Fr("u8 value is out of range"),this.bytes(Uint8Array.of(e))}u16(e){(!Number.isInteger(e)||e<0||e>65535)&&Fr("u16 value is out of range");const t=new Uint8Array(2);new DataView(t.buffer).setUint16(0,e,!1),this.bytes(t),t.fill(0)}u32(e){(!Number.isInteger(e)||e<0||e>4294967295)&&Fr("u32 value is out of range");const t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,e,!1),this.bytes(t),t.fill(0)}u64(e){((e,t)=>{("bigint"!=typeof e||e<0n||e>Pr)&&Fr(`${t} must be an unsigned 64-bit bigint`)})(e,"checkpoint counter");const t=new Uint8Array(8);new DataView(t.buffer).setBigUint64(0,e,!1),this.bytes(t),t.fill(0)}sized(e){null!==e?(0===e.length&&Fr("present checkpoint byte strings must not be empty"),this.u32(e.length),this.bytes(e)):this.u32(0)}finish(){const e=new Uint8Array(this.#x);let t=0;try{for(const r of this.#U)e.set(r,t),t+=r.length;return e}finally{for(const e of this.#U)e.fill(0);this.#U.length=0,this.#x=0}}}class $r{#S;#M=0;constructor(e){(0===e.length||e.length>Rr)&&Fr("checkpoint length is invalid"),this.#S=Uint8Array.from(e)}take(e){if(!Number.isSafeInteger(e)||e<0||this.#M+e>this.#S.length)return Fr("checkpoint is truncated");const t=this.#S.slice(this.#M,this.#M+e);return this.#M+=e,t}u8(){const e=this.take(1),t=e[0];return e.fill(0),t}u16(){const e=this.take(2),t=new DataView(e.buffer).getUint16(0,!1);return e.fill(0),t}u32(){const e=this.take(4),t=new DataView(e.buffer).getUint32(0,!1);return e.fill(0),t}u64(){const e=this.take(8),t=new DataView(e.buffer).getBigUint64(0,!1);return e.fill(0),t}sized(e){const t=this.u32();return 0===t?null:t>e?Fr("checkpoint field exceeds its budget"):this.take(t)}finish(){this.#M!==this.#S.length&&Fr("checkpoint contains trailing bytes")}destroy(){this.#S.fill(0),this.#M=this.#S.length}}const Hr=(e,t,r)=>e.sized(t)??Fr(`${r} is missing`),zr=(e,t)=>{const r=64+t.publicKeyBytes,n=64+r+t.ciphertextBytes;switch(e.u8()){case 0:return{kind:"idle"};case 1:return{kind:"outbound-offer-prepared",offer:Hr(e,r,"prepared OFFER"),secretKey:Hr(e,t.secretKeyBytes,"prepared OFFER secret key")};case 2:return{kind:"outbound-offer-dispatched",offer:Hr(e,r,"dispatched OFFER"),secretKey:Hr(e,t.secretKeyBytes,"dispatched OFFER secret key")};case 3:return{kind:"inbound-offer",offer:Hr(e,r,"inbound OFFER")};case 4:return{kind:"outbound-advance-prepared",advance:Hr(e,n,"prepared ADVANCE"),nextRoot:Hr(e,32,"candidate PQ root")};case 5:return{kind:"outbound-advance-awaiting-ack",advance:Hr(e,n,"outbound ADVANCE")};case 6:return{kind:"inbound-advance-prepared",advance:Hr(e,n,"inbound ADVANCE"),secretKey:Hr(e,t.secretKeyBytes,"inbound ADVANCE secret key"),nextRoot:Hr(e,32,"candidate PQ root")};case 7:return{kind:"inbound-advance-awaiting-ack-dispatch",advance:Hr(e,n,"acknowledged ADVANCE")};default:return Fr("checkpoint has an unknown PQ phase")}},Qr=e=>{for(const t of e.values())t.fill(0);e.clear()};class jr{#e;#C;#P;#n;#r;#i;#R;#O;#B;#I;#N=null;#F=null;#L=null;#T=null;#D=new Map;#q=0;#V;#y=!1;constructor(e){const t=Ye(e.pqMode);We(e.pqMode)!==e.rootSuite&&Fr("authenticated root suite and room PQ mode disagree"),Tr(e.binding,"edge binding",32),Tr(e.rootKey,"PQ root",32),this.#e=e.module,this.#C=e.pqMode,this.#P=e.rootSuite,this.#n=De(t),this.#r=je(e.module,this.#n),this.#i=Uint8Array.from(e.binding),this.#B=new mr({module:e.module,backend:this.#r,suite:this.#n,binding:this.#i,rootKey:e.rootKey,nextOfferer:e.nextOfferer}),this.#I=this.#B.copyRootKey(),this.#V=Dr(e.now??Date.now(),"initial healing time"),this.#R=e.amInitiator?"initiator-to-responder":"responder-to-initiator",this.#O=e.amInitiator?"responder-to-initiator":"initiator-to-responder"}get pqMode(){return this.#C}get rootSuite(){return this.#P}get epoch(){return this.#$(),this.#B.epoch}get phase(){return this.#B.phase}get trafficBlocked(){return this.#y||this.#B.trafficBlocked}get nextOfferer(){return this.#B.nextOfferer}get activeReceiveKeys(){return this.#$(),this.#D}get messagesSinceHealing(){return this.#$(),this.#q}get lastHealedAt(){return this.#$(),this.#V}currentMessageContext(){return this.#$(),{rootKey:this.#I,binding:this.#i,rootSuite:this.#P,epoch:this.#B.epoch}}resolveMessageContext(e){return this.#$(),e===this.#B.epoch?this.currentMessageContext():null}noteApplicationMessage(){this.#$(),this.#q>=Number.MAX_SAFE_INTEGER&&Fr("application-message counter overflow"),this.#q+=1}healingDue(e=Date.now()){return this.#$(),Dr(e,"healing clock"),!this.#B.trafficBlocked&&"local"===this.#B.nextOfferer&&(this.#q>=64||e-this.#V>=864e5)}copyPendingFrame(){return this.#$(),this.#N?Uint8Array.from(this.#N.frame):null}get pendingRetryAt(){return this.#$(),this.#N?.nextRetryAt??null}get pendingAttempts(){return this.#$(),this.#N?.attempts??0}markPendingDispatched(e=Date.now()){this.#$();const t=this.#N;if(!t)return Fr("there is no PQ control outbox");Dr(e,"dispatch clock"),t.attempts>=8&&Fr("PQ control retry budget is exhausted"),this.#N={kind:t.kind,frame:t.frame,attempts:t.attempts+1,nextRetryAt:e+5e3}}async prepareHealingOffer(e=Date.now()){this.#$(),this.healingDue(e)||Fr("a local sparse-PQ healing exchange is not due");const t=await this.#B.prepareOffer(),r=this.#B.copyRootKey();try{const n=Sr({module:this.#e,suite:this.#n,rootKey:r,binding:this.#i,direction:this.#R,keyEpoch:this.#B.epoch,record:t});return this.#B.markOfferDispatched(),this.#N?.frame.fill(0),this.#N={kind:"offer",frame:Uint8Array.from(n),attempts:0,nextRetryAt:e},this.#H(),n}finally{r.fill(0),t.fill(0)}}async acceptControlFrame(e,t=Date.now()){if(this.#$(),Tr(e,"PQ control frame",z),Dr(t,"control clock"),this.#F&&"advance"===this.#N?.kind&&Lr(e,this.#F))return{dispatch:Uint8Array.from(this.#N.frame),changed:!1};if(this.#L&&this.#T&&Lr(e,this.#L))return{dispatch:Uint8Array.from(this.#T),changed:!1};const r=this.#B.copyRootKey();let n=null;try{if(n=Mr({module:this.#e,suite:this.#n,rootKey:r,binding:this.#i,direction:this.#O,keyEpoch:this.#B.epoch,frame:e}),64===n.length){const e=this.#N;if("advance"!==e?.kind)return Fr("unexpected PQ ADVANCE acknowledgement");const r=nr(n,this.#n,this.#i);return this.#B.acceptAuthenticatedAdvanceAcknowledgement(r),e.frame.fill(0),this.#N=null,this.#H(),this.#q=0,this.#V=t,this.#z(),{dispatch:null,changed:!0}}if("offer"===cr(n,this.#n).type){this.#B.acceptAuthenticatedOffer(n);const i=await this.#B.prepareAdvance();let a;try{a=Sr({module:this.#e,suite:this.#n,rootKey:r,binding:this.#i,direction:this.#R,keyEpoch:this.#B.epoch,record:i}),this.#B.commitPreparedAdvance()}finally{i.fill(0)}return this.#N?.frame.fill(0),this.#N={kind:"advance",frame:Uint8Array.from(a),attempts:0,nextRetryAt:t},this.#F?.fill(0),this.#F=Uint8Array.from(e),this.#L?.fill(0),this.#L=null,this.#T?.fill(0),this.#T=null,this.#z(),{dispatch:a,changed:!0}}const i=this.#N;if("offer"!==i?.kind)return Fr("unexpected PQ ADVANCE without a persisted OFFER");await this.#B.acceptAuthenticatedAdvance(n);const a=this.#B.commitAcceptedAdvance(),o=((e,t,r)=>{Jt(t),Ht(r,"binding",Nt);const n=jt(e),i=new Uint8Array(64);i.set(Tt,0),i[4]=1,i[5]=3,i[6]=Xt(t.parameterSet),i[7]=0,i.set(r,8);const a=new DataView(i.buffer,i.byteOffset,i.byteLength);return a.setBigUint64(40,n.advanceCounter,!1),a.setBigUint64(48,n.epoch,!1),i})(a,this.#n,this.#i),s=this.#B.copyRootKey();try{const r=Sr({module:this.#e,suite:this.#n,rootKey:s,binding:this.#i,direction:this.#R,keyEpoch:a.epoch,record:o});return this.#B.markAdvanceAcknowledgementDispatched(a),i.frame.fill(0),this.#N=null,this.#L?.fill(0),this.#L=Uint8Array.from(e),this.#T?.fill(0),this.#T=Uint8Array.from(r),this.#F?.fill(0),this.#F=null,this.#q=0,this.#V=t,this.#z(),{dispatch:r,changed:!0}}finally{s.fill(0),o.fill(0)}}finally{r.fill(0),n?.fill(0)}}clone(){this.#$();const e=this.#B.copyRootKey();let t=null;try{return t=new jr({module:this.#e,pqMode:this.#C,rootSuite:this.#P,binding:this.#i,rootKey:e,nextOfferer:this.#B.nextOfferer,amInitiator:"initiator-to-responder"===this.#R,now:this.#V}),t.#B.destroy(),t.#B=this.#B.clone(),t.#I.fill(0),t.#I=Uint8Array.from(this.#I),t.#N=null===(r=this.#N)?null:{kind:r.kind,frame:Uint8Array.from(r.frame),attempts:r.attempts,nextRetryAt:r.nextRetryAt},t.#F=null===this.#F?null:Uint8Array.from(this.#F),t.#L=null===this.#L?null:Uint8Array.from(this.#L),t.#T=null===this.#T?null:Uint8Array.from(this.#T),t.#D=(e=>{const t=new Map;for(const[r,n]of e)t.set(r,Uint8Array.from(n));return t})(this.#D),t.#q=this.#q,t.#V=this.#V,t}catch(e){throw t?.destroy(),e}finally{e.fill(0)}var r}adopt(e){this.#$(),e.#$(),e===this&&Fr("cannot adopt a PQ runtime into itself"),e.#e===this.#e&&e.#C===this.#C&&e.#P===this.#P&&e.#R===this.#R&&Lr(e.#i,this.#i)||Fr("cannot adopt a PQ runtime from another authenticated edge"),this.#B.destroy(),this.#I.fill(0),this.#N?.frame.fill(0),this.#F?.fill(0),this.#L?.fill(0),this.#T?.fill(0),Qr(this.#D),this.#B=e.#B,this.#I=e.#I,this.#N=e.#N,this.#F=e.#F,this.#L=e.#L,this.#T=e.#T,this.#D=e.#D,this.#q=e.#q,this.#V=e.#V,e.#I=new Uint8Array(32),e.#N=null,e.#F=null,e.#L=null,e.#T=null,e.#D=new Map,e.#i.fill(0),e.#y=!0}serialize(e=this.#D){this.#$();const t=this.#B.snapshot(),r=new Vr;try{return r.bytes(Cr),r.u8(1),r.u8(512===(i=this.#n.parameterSet)?1:768===i?2:1024===i?3:Fr("unsupported ML-KEM suite")),r.u8("initiator-to-responder"===this.#R?1:2),r.u8(0),r.u64(BigInt(this.#V)),r.u64(BigInt(this.#q)),r.bytes(t.binding),r.bytes(t.rootKey),r.u64(t.epoch),r.u64(t.localCounter),r.u64(t.remoteCounter),r.u8("local"===(n=t.nextOfferer)?1:"remote"===n?2:Fr("invalid next-offerer turn")),((e,t)=>{switch(e.u8((e=>{switch(e.kind){case"idle":return 0;case"outbound-offer-prepared":return 1;case"outbound-offer-dispatched":return 2;case"inbound-offer":return 3;case"outbound-advance-prepared":return 4;case"outbound-advance-awaiting-ack":return 5;case"inbound-advance-prepared":return 6;case"inbound-advance-awaiting-ack-dispatch":return 7}})(t)),t.kind){case"idle":return;case"outbound-offer-prepared":case"outbound-offer-dispatched":return e.sized(t.offer),void e.sized(t.secretKey);case"inbound-offer":return void e.sized(t.offer);case"outbound-advance-prepared":return e.sized(t.advance),void e.sized(t.nextRoot);case"outbound-advance-awaiting-ack":case"inbound-advance-awaiting-ack-dispatch":return void e.sized(t.advance);case"inbound-advance-prepared":e.sized(t.advance),e.sized(t.secretKey),e.sized(t.nextRoot)}})(r,t.phase),r.sized(t.lastInboundOffer),r.sized(t.lastInboundAdvance),((e,t)=>{null!==t?(e.u8("offer"===t.kind?1:2),e.u8(t.attempts),e.u64(BigInt(t.nextRetryAt)),e.sized(t.frame)):e.u8(0)})(r,this.#N),r.sized(this.#F),r.sized(this.#L),r.sized(this.#T),((e,t)=>{t.size>Or&&Fr("too many active receive message keys");const r=[...t.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0);e.u16(r.length);for(const[t,n]of r){Br.test(t)||Fr("active receive cache key is non-canonical");const r=Ir.encode(t);(0===r.length||r.length>160)&&Fr("active receive cache key length is invalid"),Tr(n,"active receive message key",32),e.u16(r.length),e.bytes(r),e.bytes(n)}})(r,e),r.finish()}finally{br(t)}var n,i}static readCheckpointBinding(e){Tr(e,"checkpoint");const t=Cr.length+1+1+1+1+8+8;return e.length<t+32?Fr("checkpoint is too short to contain a binding"):e.slice(t,t+32)}static restore(e,t){Tr(e,"encrypted edge checkpoint plaintext"),Tr(t.binding,"expected edge binding",32);const r=new $r(e);let n=null,i=null,a=null,o=null,s=null,c=null,l=null,d=null;try{const e=r.take(Cr.length),u=Lr(e,Cr);e.fill(0),u||Fr("checkpoint magic is invalid"),1!==r.u8()&&Fr("checkpoint version is unsupported");const f=1===(h=r.u8())?512:2===h?768:3===h?1024:Fr("checkpoint has an unknown ML-KEM suite");f!==Ye(t.pqMode)&&Fr("checkpoint suite disagrees with the authenticated room policy"),We(t.pqMode)!==t.rootSuite&&Fr("authenticated root suite and room PQ mode disagree");const y=r.u8();y!==(t.amInitiator?1:2)&&Fr("checkpoint belongs to the opposite edge direction"),0!==r.u8()&&Fr("checkpoint reserved byte is non-zero");const p=r.u64(),m=r.u64();(p>BigInt(Number.MAX_SAFE_INTEGER)||m>BigInt(Number.MAX_SAFE_INTEGER))&&Fr("checkpoint counters exceed the safe-integer range");const b=r.take(32);Lr(b,t.binding)||Fr("checkpoint belongs to another authenticated edge");const g=r.take(32),w=De(f);n={formatVersion:1,parameterSet:f,binding:b,rootKey:g,epoch:r.u64(),localCounter:r.u64(),remoteCounter:r.u64(),nextOfferer:qr(r.u8()),phase:zr(r,w),lastInboundOffer:r.sized(8192),lastInboundAdvance:r.sized(8192)},s=(e=>{const t=e.u8();if(0===t)return null;if(1!==t&&2!==t)return Fr("checkpoint outbox kind is invalid");const r=e.u8();r>8&&Fr("checkpoint outbox attempts exceed the retry budget");const n=e.u64();n>BigInt(Number.MAX_SAFE_INTEGER)&&Fr("checkpoint retry deadline exceeds the safe-integer range");const i=Hr(e,z,"outbox frame");return Tr(i,"outbox frame",z),{kind:1===t?"offer":"advance",attempts:r,nextRetryAt:Number(n),frame:i}})(r),c=r.sized(z),l=r.sized(z),d=r.sized(z);for(const e of[c,l,d])e&&Tr(e,"cached control frame",z);o=(e=>{const t=e.u16();t>Or&&Fr("checkpoint has too many active receive message keys");const r=new Map;try{for(let n=0;n<t;n+=1){const t=e.u16();(0===t||t>160)&&Fr("checkpoint active receive cache key length is invalid");const n=e.take(t);let i;try{i=Nr.decode(n)}finally{n.fill(0)}0!==i.length&&Br.test(i)&&!r.has(i)||Fr("checkpoint active receive cache key is non-canonical"),r.set(i,e.take(32))}return r}catch(e){for(const e of r.values())e.fill(0);throw r.clear(),e}})(r),r.finish();const v=je(t.module,w);i=mr.restore(n,{module:t.module,backend:v,suite:w,binding:t.binding});const A=i.copyRootKey();try{a=new jr({module:t.module,pqMode:t.pqMode,rootSuite:t.rootSuite,binding:t.binding,rootKey:A,nextOfferer:i.nextOfferer,amInitiator:t.amInitiator,now:Number(p)})}finally{A.fill(0)}return a.#B.destroy(),a.#B=i,i=null,a.#I.fill(0),a.#I=a.#B.copyRootKey(),a.#N=s,s=null,a.#F=c,c=null,a.#L=l,l=null,a.#T=d,d=null,a.#D=o,o=null,a.#q=Number(m),a.#Q(),a}catch(e){throw a?.destroy(),e}finally{r.destroy(),n&&br(n),i?.destroy(),s?.frame.fill(0),c?.fill(0),l?.fill(0),d?.fill(0),o&&Qr(o)}var h}destroy(){this.#y||(this.#B.destroy(),this.#i.fill(0),this.#I.fill(0),this.#N?.frame.fill(0),this.#F?.fill(0),this.#L?.fill(0),this.#T?.fill(0),Qr(this.#D),this.#N=null,this.#F=null,this.#L=null,this.#T=null,this.#y=!0)}#z(){const e=this.#B.copyRootKey();this.#I.fill(0),this.#I=e}#H(){this.#F?.fill(0),this.#L?.fill(0),this.#T?.fill(0),this.#F=null,this.#L=null,this.#T=null}#Q(){const e=this.#B.phase;("outbound-offer-dispatched"===e&&"offer"!==this.#N?.kind||"outbound-advance-awaiting-ack"===e&&"advance"!==this.#N?.kind||"offer"===this.#N?.kind&&"outbound-offer-dispatched"!==e||"advance"===this.#N?.kind&&"outbound-advance-awaiting-ack"!==e)&&Fr("checkpoint PQ phase and sealed outbox disagree"),null!==this.#F&&"advance"!==this.#N?.kind&&Fr("checkpoint cached OFFER has no matching ADVANCE outbox"),null===this.#L!=(null===this.#T)&&Fr("checkpoint ADVANCE replay and ACK cache must be paired"),null!==this.#F&&null!==this.#L&&Fr("checkpoint contains mutually exclusive replay caches")}#$(){this.#y&&Fr("state is destroyed")}}const Yr=e=>{const t=new Uint8Array(T);let r=0;new DataView(t.buffer,r,8).setBigUint64(0,BigInt(e.schemaVersion),!1),r+=8,t[r]=e.messageType,r+=1,t.set(e.hash,r),r+=y;new DataView(t.buffer,r,8).setBigUint64(0,BigInt(e.totalSize),!1),r+=8;new DataView(t.buffer,r,8).setBigInt64(0,BigInt(e.date.getTime()),!1),r+=8;const n=(new TextEncoder).encode(e.name),i=new Uint8Array(256);i.set(n.subarray(0,Math.min(256,n.length))),t.set(i,r),r+=256;new DataView(t.buffer,r,8).setBigUint64(0,BigInt(e.chunkStartIndex),!1),r+=8;new DataView(t.buffer,r,8).setBigUint64(0,BigInt(e.chunkEndIndex),!1),r+=8;return new DataView(t.buffer,r,8).setBigUint64(0,BigInt(e.chunkIndex),!1),t},Wr=e=>{if(e.length!==T)throw new Error("Invalid metadata buffer totalSize");let t=0;const r=new DataView(e.buffer,e.byteOffset+t,8),n=Number(r.getBigUint64(0,!1));t+=8;const i=e[t];t+=1;const a=e.slice(t,t+y);t+=y;const o=new DataView(e.buffer,e.byteOffset+t,8),s=Number(o.getBigUint64(0,!1));t+=8;const c=new DataView(e.buffer,e.byteOffset+t,8),l=Number(c.getBigUint64(0,!1)),d=new Date(l);t+=8;const h=e.slice(t,t+256);let u=(new TextDecoder).decode(h).replace(/\0+$/,"");u=u.replace(/[/\\]/g,"_").replace(/[<>:"'|?*]/g,"_").replace(/[\u0000-\u001f\u007f]/g,""),t+=256;const f=new DataView(e.buffer,e.byteOffset+t,8),p=Number(f.getBigUint64(0,!1));t+=8;const m=new DataView(e.buffer,e.byteOffset+t,8),b=Number(m.getBigUint64(0,!1));t+=8;const g=new DataView(e.buffer,e.byteOffset+t,8);return{schemaVersion:n,messageType:i,hash:a,totalSize:s,date:d,name:u,chunkStartIndex:p,chunkEndIndex:b,chunkIndex:Number(g.getBigUint64(0,!1))}},Xr=64;class Gr{queue=[];locked=!1;idleWaiters=[];async acquire(){if(this.locked)return new Promise(e=>{this.queue.push(e)});this.locked=!0}release(){const e=this.queue.shift();if(e)e();else{this.locked=!1;for(const e of this.idleWaiters.splice(0))e()}}isIdle(){return!this.locked&&0===this.queue.length}whenIdle(){return this.isIdle()?Promise.resolve():new Promise(e=>{this.idleWaiters.push(e)})}async runExclusive(e){await this.acquire();try{return await e()}finally{this.release()}}}const Zr=new Uint8Array([80,50,80,83,69,83,83,0]),Jr=262144,en=Zr.length+4+24+32+32+32+2,tn="p2party-session",rn=e=>Uint8Array.from(e);function nn(e,t,r){if(!(e instanceof Uint8Array))throw new TypeError(`${t} must be a Uint8Array`);if(void 0!==r&&e.length!==r)throw new RangeError(`${t} must be ${String(r)} bytes`)}const an=(e,t)=>{if(!Number.isSafeInteger(e)||e<0||e>Number.MAX_SAFE_INTEGER)throw new RangeError(`${t} must be a non-negative safe integer`)},on=(e,t)=>{if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r},sn=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),cn=async e=>new Uint8Array(await globalThis.crypto.subtle.digest("SHA-512",e.slice().buffer)),ln=async e=>{const t=new WebAssembly.Memory({initial:32,maximum:32});return e?.wasmBinary?await a({wasmBinary:(r=e.wasmBinary,r instanceof Uint8Array?r.slice().buffer:r.slice(0)),wasmMemory:t,getRandomValue:s}):await u(t);var r},dn=async(e,t)=>{const r=e.length,n=Math.max(1,Math.ceil(r/q)),i=[],a=[];try{for(let t=0;t<n;t++){const n=t*q,a=Math.min(q,Math.max(0,r-n)),o=globalThis.crypto.getRandomValues(new Uint8Array(q));o.set(e.subarray(n,n+a),0),i.push(o)}const o=await cn(e),s=new Uint8Array(n*y);for(let e=0;e<i.length;e++)s.set(ke(i[e],t),e*y);const c=Uint8Array.from(await(async(e,t)=>{if(e.length%y!==0)throw new Error("Hashes were not passed");const r=e.length/y;if(0===r)throw new Error("Cannot calculate Merkle root of tree with no leaves.");if(1===r)return e;const n=t?.wasmMemory??O(r),i=t??await u(n),a=i._malloc(r*y),o=new Uint8Array(n.buffer,a,r*y);o.set(e);const s=i._malloc(y),c=new Uint8Array(n.buffer,s,y),l=i._get_merkle_root(r,o.byteOffset,c.byteOffset);switch(i._free(a),l){case 0:{const e=Uint8Array.from([...c]);return i._free(s),e}case-1:throw i._free(s),new Error("Could not allocate memory for hash concatenation helper array.");case-2:throw i._free(s),new Error("Could not calculate hash.");default:throw i._free(s),new Error("Unexpected error occured.")}})(s,t));for(let e=0;e<i.length;e++){const n=await Ee(s,ke(i[e],t),t,D),c=Math.min(q,Math.max(0,r-e*q)),l=Yr({schemaVersion:1,messageType:Xr,hash:o,totalSize:r,date:new Date(0),name:tn,chunkStartIndex:0,chunkEndIndex:c,chunkIndex:e}),d=new Uint8Array(V);d.set(l,0),d.set(n,T),d.set(i[e],T+D),a.push(d)}return o.fill(0),s.fill(0),{root:c,chunks:i,plaintexts:a}}catch(e){for(const e of i)e.fill(0);for(const e of a)e.fill(0);throw e}},hn=(e,t)=>e.N===t.N&&e.PN===t.PN&&on(e.dhPub,t.dhPub);class un{protocolVersion=4;#e;#j=new Gr;#Y;#W;#X;#y=!1;constructor(e,t,r,n){this.#W=e,this.#e=t,this.#X=r,this.#Y=n}get pqMode(){return Xe(this.#W.rootSuite)}get canEncrypt(){return!this.#y&&null!==this.#W.sendingChainKey&&!this.#X.trafficBlocked}get pqEpoch(){return this.#$(),this.#X.epoch}get healingInProgress(){return!this.#y&&this.#X.trafficBlocked}#$(){if(this.#y)throw new Error("session: session is destroyed")}async encrypt(e){nn(e,"plaintext");const t=rn(e);return this.#j.runExclusive(async()=>{let e=null,r=null,n=null,i=null,a=!1;try{if(this.#$(),this.#X.trafficBlocked)throw new Error("session: sparse-PQ healing is in progress");if(!this.#W.sendingChainKey)throw new Error("ratchet: no sending chain");e=await dn(t,this.#e),r=we(this.#W);const o=((e,t)=>{if(!e.sendingChainKey)throw new Error("ratchet: no sending chain");const{chainKey:r,messageKey:n}=de(e.sendingChainKey,t),i={dhPub:Uint8Array.from(e.dhSelfPub),N:e.Ns,PN:e.PN};return e.sendingChainKey.fill(0),e.sendingChainKey=r,e.Ns+=1,{messageKey:n,header:i}})(r,this.#e);n=o.messageKey,i=this.#X.currentMessageContext();const s=e.plaintexts.map(t=>Ot(n,o.header,t,e.root,this.#e,i));return Ae(this.#W,r),this.#X.noteApplicationMessage(),a=!0,{protocolVersion:4,root:rn(e.root),frames:s}}finally{t.fill(0),n?.fill(0),r&&!a&&ve(r),e&&(e=>{for(const t of e.chunks)t.fill(0);for(const t of e.plaintexts)t.fill(0)})(e)}})}async decrypt(e){if(!e||"object"!=typeof e)throw new TypeError("message is required");if(4!==e.protocolVersion)throw new Error("session: unsupported protocol version");if(nn(e.root,"message.root",y),!Array.isArray(e.frames)||0===e.frames.length)throw new Error("session: encrypted message has no frames");for(const t of e.frames)if(nn(t,"message frame"),t.length!==z)throw new Error("session: invalid encrypted frame length");const t=rn(e.root),r=e.frames.map(rn);return this.#j.runExclusive(async()=>{this.#$();const e=r.map(e=>gt(e));for(let t=1;t<e.length;t++)if(!hn(e[0].header,e[t].header))throw new Error("session: mixed ratchet headers");const n=new Set;for(const t of e){const e=sn(t.nonce);if(n.has(e))throw new Error("session: duplicate chunk nonce");n.add(e)}const i=we(this.#W),a=new Map(this.#X.activeReceiveKeys),o=[];let s=!1;try{const e=[];for(const n of r){const r=Bt(i,n,a,t,this.#e,e=>this.#X.resolveMessageContext(e));if(!r.ok||!r.decrypted)throw new Error("session: encrypted frame authentication failed");o.push(r.decrypted);const s=Wr(r.decrypted.subarray(0,T));e.push({metadata:s,chunk:r.decrypted.subarray(T+D)})}const n=await(async e=>{if(0===e.length)throw new Error("session: encrypted message has no frames");const t=e[0].metadata;an(t.totalSize,"metadata.totalSize");const r=Math.max(1,Math.ceil(t.totalSize/q));if(e.length!==r)throw new Error("session: incomplete or excessive frame set");const n=new Map;for(const i of e){const e=i.metadata;if(an(e.chunkIndex,"metadata.chunkIndex"),an(e.chunkStartIndex,"metadata.chunkStartIndex"),an(e.chunkEndIndex,"metadata.chunkEndIndex"),an(e.totalSize,"metadata.totalSize"),1!==e.schemaVersion||e.messageType!==Xr||e.name!==tn||0!==e.date.getTime())throw new Error("session: unsupported encrypted metadata");if(e.totalSize!==t.totalSize||!on(e.hash,t.hash))throw new Error("session: inconsistent encrypted metadata");if(e.chunkIndex>=r||0!==e.chunkStartIndex)throw new Error("session: invalid encrypted chunk range");const a=Math.min(q,Math.max(0,t.totalSize-e.chunkIndex*q));if(e.chunkEndIndex!==a)throw new Error("session: invalid encrypted chunk length");if(n.has(e.chunkIndex))throw new Error("session: duplicate encrypted chunk");n.set(e.chunkIndex,i)}const i=new Uint8Array(t.totalSize);for(let e=0;e<r;e++){const t=n.get(e);if(!t)throw new Error("session: missing encrypted chunk");const r=t.metadata.chunkEndIndex;i.set(t.chunk.subarray(0,r),e*q)}const a=await cn(i),o=on(a,t.hash);if(a.fill(0),!o)throw i.fill(0),new Error("session: plaintext hash mismatch");return i})(e);return Ae(this.#W,i),this.#G(a),this.#X.noteApplicationMessage(),s=!0,n}finally{t.fill(0);for(const e of o)e.fill(0);if(!s){for(const[e,t]of a)this.#X.activeReceiveKeys.has(e)||t.fill(0);ve(i)}}})}#G(e){const t=this.#X.activeReceiveKeys;for(const[r,n]of e)t.has(r)||t.set(r,n)}async prepareHealing(){return this.#j.runExclusive(async()=>{if(this.#$(),!this.#X.healingDue())return fn;const e=await this.#X.prepareHealingOffer();return this.#X.markPendingDispatched(),{frame:e,requiresPersistBeforeSend:!0}})}async acceptControlFrame(e){nn(e,"control frame",z);const t=rn(e);return this.#j.runExclusive(async()=>{this.#$();const e=await this.#X.acceptControlFrame(t);return e.changed&&e.dispatch&&null!==this.#X.pendingRetryAt&&this.#X.markPendingDispatched(),{frame:e.dispatch,requiresPersistBeforeSend:e.changed}})}async pendingControl(){return this.#j.runExclusive(async()=>(this.#$(),this.#X.copyPendingFrame()))}async serialize(){return this.#j.runExclusive(async()=>(this.#$(),pn(this.#W,this.#X,this.#Y)))}async destroy(){await this.#j.runExclusive(async()=>{this.#y||(ve(this.#W),this.#X.destroy(),this.#y=!0)})}}const fn={frame:null,requiresPersistBeforeSend:!1},yn=(e,t,r)=>(an(r,"snapshot counter"),e.setBigUint64(t,BigInt(r),!1),t+8),pn=(e,t,r)=>{(e=>{if(nn(e.rootKey,"snapshot.rootKey",32),nn(e.dhSelfPub,"snapshot.dhSelfPub",32),nn(e.dhSelfSec,"snapshot.dhSelfSec",32),e.sendingChainKey&&nn(e.sendingChainKey,"snapshot.sendingChainKey",32),e.receivingChainKey&&nn(e.receivingChainKey,"snapshot.receivingChainKey",32),e.dhRemotePub&&nn(e.dhRemotePub,"snapshot.dhRemotePub",32),an(e.Ns,"snapshot.Ns"),an(e.Nr,"snapshot.Nr"),an(e.PN,"snapshot.PN"),(e.sendingChainKey||e.receivingChainKey||e.skipped.size>0)&&!e.dhRemotePub)throw new Error("snapshot: chain state requires a remote DH key");if(e.skipped.size>Z)throw new Error("snapshot: too many skipped message keys")})(e);const n=be(e),i=t.serialize();if(0===i.length||i.length>Jr)throw i.fill(0),new Error("snapshot: PQ checkpoint length is invalid");try{const e=(n.sendingChainKey?1:0)|(n.receivingChainKey?2:0)|(n.dhRemotePub?4:0)|(r?8:0),t=Number(Boolean(n.sendingChainKey))+Number(Boolean(n.receivingChainKey))+Number(Boolean(n.dhRemotePub)),a=new Uint8Array(en+32*t+72*n.skippedMessageKeys.length+4+i.length),o=new DataView(a.buffer);let s=0;a.set(Zr,s),s+=Zr.length,a[s++]=4,a[s++]=4,a[s++]=e,a[s++]=(e=>{if(e===Y)return 3;if(e===j)return 4;if(e===W)return 5;throw new Error("snapshot: unsupported root suite")})(n.rootSuite),s=yn(o,s,n.Ns),s=yn(o,s,n.Nr),s=yn(o,s,n.PN),a.set(new Uint8Array(n.rootKey),s),s+=32,n.sendingChainKey&&(a.set(new Uint8Array(n.sendingChainKey),s),s+=32),n.receivingChainKey&&(a.set(new Uint8Array(n.receivingChainKey),s),s+=32),a.set(new Uint8Array(n.dhSelfPub),s),s+=32,a.set(new Uint8Array(n.dhSelfSec),s),s+=32,n.dhRemotePub&&(a.set(new Uint8Array(n.dhRemotePub),s),s+=32),o.setUint16(s,n.skippedMessageKeys.length,!1),s+=2;for(const e of n.skippedMessageKeys)nn(new Uint8Array(e.dhPub),"snapshot.skipped.dhPub",32),nn(new Uint8Array(e.messageKey),"snapshot.skipped.messageKey",32),a.set(new Uint8Array(e.dhPub),s),s+=32,s=yn(o,s,e.n),a.set(new Uint8Array(e.messageKey),s),s+=32;return o.setUint32(s,i.length,!1),s+=4,a.set(i,s),s+=i.length,a}finally{i.fill(0),new Uint8Array(n.rootKey).fill(0),n.sendingChainKey&&new Uint8Array(n.sendingChainKey).fill(0),n.receivingChainKey&&new Uint8Array(n.receivingChainKey).fill(0),new Uint8Array(n.dhSelfSec).fill(0);for(const e of n.skippedMessageKeys)new Uint8Array(e.messageKey).fill(0)}},mn=e=>{nn(e,"snapshot");const t=rn(e);let r=0,n=!1;const i=[],a=e=>{if(!Number.isSafeInteger(e)||e<0||r+e>t.length)throw new Error("snapshot: truncated input");const n=t.subarray(r,r+e);return r+=e,n},o=(e,t=!1)=>{const r=a(e).slice().buffer;return t&&i.push(new Uint8Array(r)),r},s=()=>{if(r+8>t.length)throw new Error("snapshot: truncated counter");const e=new DataView(t.buffer,t.byteOffset+r,8).getBigUint64(0,!1);if(r+=8,e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("snapshot: counter exceeds safe-integer range");return Number(e)};try{if(!on(a(Zr.length),Zr))throw new Error("snapshot: invalid magic");if(4!==a(1)[0])throw new Error("snapshot: unsupported snapshot version");if(4!==a(1)[0])throw new Error("snapshot: unsupported protocol version");const e=a(1)[0];if(-16&e)throw new Error("snapshot: unknown flags");const c=(e=>{if(3===e)return Y;if(4===e)return j;if(5===e)return W;throw new Error("snapshot: unsupported root suite")})(a(1)[0]),l=s(),d=s(),h=s(),u=o(32,!0),f=1&e?o(32,!0):null,y=2&e?o(32,!0):null,p=o(32),m=o(32,!0),b=4&e?o(32):null;if((f||y)&&null===b)throw new Error("snapshot: chain state requires a remote DH key");if(r+2>t.length)throw new Error("snapshot: missing skipped-key count");const g=new DataView(t.buffer,t.byteOffset+r,2).getUint16(0,!1);if(r+=2,g>Z)throw new Error("snapshot: too many skipped message keys");if(null===b&&g>0)throw new Error("snapshot: skipped keys require a remote DH key");const w=72*g;if(t.length-r<w+4)throw new Error("snapshot: truncated input");const v=[],A=new Set;for(let e=0;e<g;e++){const e=a(32),t=s(),r=a(32),n=`${sn(e)}:${String(t)}`;if(A.has(n))throw new Error("snapshot: duplicate skipped message key");A.add(n),v.push({dhPub:e.slice().buffer,n:t,messageKey:(()=>{const e=r.slice().buffer;return i.push(new Uint8Array(e)),e})()})}const k=new DataView(t.buffer,t.byteOffset+r,4).getUint32(0,!1);if(r+=4,0===k||k>Jr)throw new Error("snapshot: PQ checkpoint length is invalid");if(t.length-r!==k)throw new Error("snapshot: truncated input or trailing bytes");const E=a(k).slice();i.push(E);const K=ge({rootSuite:c,rootKey:u,sendingChainKey:f,receivingChainKey:y,dhSelfPub:p,dhSelfSec:m,dhRemotePub:b,Ns:l,Nr:d,PN:h,skippedMessageKeys:v});return n=!0,{state:K,pqCheckpoint:E,amInitiator:!!(8&e)}}finally{if(t.fill(0),!n)for(const e of i)e.fill(0)}};exports.PROTOCOL_VERSION=4,exports.WIRE_CHUNK_FRAME_LEN=z,exports.createSession=async e=>{if(!e||"object"!=typeof e)throw new TypeError("session options are required");if("initiator"!==e.role&&"responder"!==e.role)throw new Error("role must be initiator or responder");if(!e.transport||"function"!=typeof e.transport.send||"function"!=typeof e.transport.recv)throw new TypeError("transport must provide send() and recv()");if((e=>{if(!e||"object"!=typeof e)throw new TypeError("identity is required");nn(e.ed25519PublicKey,"identity.ed25519PublicKey",g),nn(e.x25519PublicKey,"identity.x25519PublicKey",U),nn(e.x25519SecretKey,"identity.x25519SecretKey",x),nn(e.x25519CrossSignature,"identity.x25519CrossSignature",m)})(e.identity),nn(e.peerIdentityEd25519PublicKey,"peerIdentityEd25519PublicKey",g),!e.channel||"object"!=typeof e.channel)throw new TypeError("channel binding is required");if(nn(e.channel.channelId,"channel.channelId"),0===e.channel.channelId.length)throw new RangeError("channel.channelId must not be empty");nn(e.channel.localFingerprint,"channel.localFingerprint",32),nn(e.channel.remoteFingerprint,"channel.remoteFingerprint",32);const t=e;if("pin"!==t.mode&&"nopin"!==t.mode)throw new Error("mode must be pin or nopin");const r=t.mode,n=t.pqMode??"hybrid-mlkem768";if("hybrid-mlkem512"!==n&&"hybrid-mlkem768"!==n&&"hybrid-mlkem1024"!==n)throw new Error("pqMode must select ML-KEM-512, ML-KEM-768, or ML-KEM-1024");let i=null;if("pin"===r){if(nn(t.pin,"pin"),0===t.pin.length)throw new RangeError("pin must not be empty");i=rn(t.pin)}else if(void 0!==t.pin)throw new Error("pin must not be provided in nopin mode");const a=rn(e.identity.x25519SecretKey),o=rn(e.identity.ed25519PublicKey),s=rn(e.identity.x25519PublicKey),c=rn(e.identity.x25519CrossSignature),l=rn(e.peerIdentityEd25519PublicKey),d=rn(e.channel.channelId),h=rn(e.channel.localFingerprint),u=rn(e.channel.remoteFingerprint);let f=null,y=null,p=null,b=null,w=null;try{const t=await ln(e.crypto);await(async(e,t)=>{const r=new Uint8Array(U);r[0]=9;const n=F(e.x25519SecretKey,r,t);try{if(!on(n,e.x25519PublicKey))throw new Error("identity X25519 public and secret keys do not match")}finally{n.fill(0)}if(!await te(e.x25519PublicKey,e.x25519CrossSignature,e.ed25519PublicKey,t))throw new Error("identity X25519 cross-signature is invalid")})({ed25519PublicKey:o,x25519PublicKey:s,x25519SecretKey:a,x25519CrossSignature:c},t);const m="initiator"===e.role,g=Je({channelId:d,ikInitiator:m?o:l,ikResponder:m?l:o,fpInitiator:m?h:u,fpResponder:m?u:h,pqMode:n}),v=await ft(e.transport,{mode:r,pqMode:n,pin:i,channelInput:g,amInitiator:m,idSelfSec:a,selfIdentityX25519Pub:s,selfIdentityCrossSignature:c,peerIdentityEd25519Pub:l},t);b=v.state,f=v.secret,y=v.pqHealing.rootKey,p=v.pqHealing.binding,w=new jr({module:t,pqMode:n,rootSuite:b.rootSuite,binding:p,rootKey:y,nextOfferer:v.pqHealing.nextOfferer,amInitiator:m});const A=new un(b,t,w,m);return b=null,w=null,A}finally{a.fill(0),i?.fill(0),f?.fill(0),y?.fill(0),p?.fill(0),b&&ve(b),w?.destroy()}},exports.generateSessionIdentity=async(e={})=>{const t=await ln(e);let r=null,n=null,i=null;try{if(e.ed25519KeyPair)nn(e.ed25519KeyPair.publicKey,"ed25519KeyPair.publicKey",g),nn(e.ed25519KeyPair.secretKey,"ed25519KeyPair.secretKey",w),r=rn(e.ed25519KeyPair.publicKey),n=rn(e.ed25519KeyPair.secretKey);else{const e=await(async e=>{const t=e?.wasmMemory??M(),r=e??await u(t),n=r._malloc(g),i=new Uint8Array(t.buffer,n,g),a=r._malloc(w),o=new Uint8Array(t.buffer,a,w),s=r._malloc(b),l=new Uint8Array(t.buffer,s,b);try{if(c(l),0!==r._keypair_from_seed(i.byteOffset,o.byteOffset,l.byteOffset))throw new Error("An unexpected error occured.");return{publicKey:Uint8Array.from(i),secretKey:Uint8Array.from(o)}}finally{r._free(n),I(r,o),I(r,l)}})(t);r=e.publicKey,n=e.secretKey}const a=await(async e=>{const t=e?.wasmMemory??C(),r=e??await u(t);return N(r)})(t);i=a.secretKey;const o=await ee(a.publicKey,n,t);if(!await te(a.publicKey,o,r,t))throw new Error("ed25519KeyPair public and secret keys do not match");const s={ed25519PublicKey:r,ed25519SecretKey:n,x25519PublicKey:a.publicKey,x25519SecretKey:i,x25519CrossSignature:o};return r=null,n=null,i=null,s}finally{r?.fill(0),n?.fill(0),i?.fill(0)}},exports.restoreSession=async(e,t)=>{const r=mn(e);let n=null;try{const e=await ln(t),i=jr.readCheckpointBinding(r.pqCheckpoint);try{n=jr.restore(r.pqCheckpoint,{module:e,pqMode:Xe(r.state.rootSuite),rootSuite:r.state.rootSuite,binding:i,amInitiator:r.amInitiator})}finally{i.fill(0)}const a=new un(r.state,e,n,r.amInitiator);return n=null,a}catch(e){throw ve(r.state),n?.destroy(),e}finally{r.pqCheckpoint.fill(0)}};
1
+ "use strict";var e="undefined"!=typeof document?document.currentScript:null;function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var r,n={exports:{}};var i=(r||(r=1,function(e){var t,r=(t=globalThis.document?.currentScript?.src,async function(e={}){var r=e,n=!!globalThis.window,i=!!globalThis.WorkerGlobalScope;globalThis.process?.versions?.node&&globalThis.process,i&&(t=self.location.href);var a,o,s="";if(n||i){try{s=new URL(".",t).href}catch{}i&&(o=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),a=async e=>{var t=await fetch(e,{credentials:"same-origin"});if(t.ok)return t.arrayBuffer();throw new Error(t.status+" : "+t.url)}}console.log.bind(console);var c,l=console.error.bind(console),d=!1;function h(e,t,r){const n=e.BYTES_PER_ELEMENT,i=t*n;if(t<=0&&k(`segmentation fault ${r} ${n} bytes at address ${i}`),v){var a=O(0);i+n>a&&k(`segmentation fault, exceeded the top of the available dynamic heap when ${r} ${n} bytes at address ${i}. DYNAMICTOP=${a}`),a<B()&&k(`brk >= _emscripten_stack_get_base() (brk=${a}, _emscripten_stack_get_base()=${B()})`),a>w.buffer.byteLength&&k(`brk <= wasmMemory.buffer.byteLength (brk=${a}, wasmMemory.buffer.byteLength=${w.buffer.byteLength})`)}return t}var u,f,y,p,m,b,g,w,v=!1;function A(){if(!p?.buffer?.resizable){var e=w.buffer;p=new Int8Array(e),g=new Uint8Array(e),f=new Int32Array(e),b=new Uint32Array(e),m=new Float64Array(e),y=new BigInt64Array(e),new BigUint64Array(e)}}function k(e){throw l(e=`Aborted(${e})`),d=!0,e+=". Build with -sASSERTIONS for more info.",new WebAssembly.RuntimeError(e)}function E(){return s+"libcrypto.wasm"}async function K(e){if(!c)try{var t=await a(e);return new Uint8Array(t)}catch{}return function(e){if(e==u&&c)return new Uint8Array(c);if(o)return o(e);throw"both async and sync fetching of the wasm failed"}(e)}async function _(e,t,r){if(!e)try{var n=fetch(t,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(n,r)}catch(e){l(`wasm streaming compile failed: ${e}`),l("falling back to ArrayBuffer instantiation")}return async function(e,t){try{var r=await K(e);return await WebAssembly.instantiate(r,t)}catch(e){l(`failed to asynchronously prepare wasm: ${e}`),k(e)}}(t,r)}var U=globalThis.TextDecoder&&new TextDecoder,x=(e,t,r)=>e?((e,t=0,r)=>{var n=((e,t,r)=>{for(var n=t+r;e[t]&&!(t>=n);)++t;return t})(e,t,r);if(n-t>16&&e.buffer&&U)return U.decode(e.subarray(t,n));for(var i="";t<n;){var a=e[t++];if(128&a){var o=63&e[t++];if(192!=(224&a)){var s=63&e[t++];if((a=224==(240&a)?(15&a)<<12|o<<6|s:(7&a)<<18|o<<12|s<<6|63&e[t++])<65536)i+=String.fromCharCode(a);else{var c=a-65536;i+=String.fromCharCode(55296|c>>10,56320|1023&c)}}else i+=String.fromCharCode((31&a)<<6|o)}else i+=String.fromCharCode(a)}return i})(g,e,t):"",S=[],M=(e,t,r)=>{var n=((e,t)=>{var r;for(S.length=0;r=g[h(g,e++,"loading")];){var n=105!=r;t+=(n&=112!=r)&&t%8?4:0,S.push(112==r?b[h(b,t>>2,"loading")]:106==r?y[h(y,t>>3,"loading")]:105==r?f[h(f,t>>2,"loading")]:m[h(m,t>>3,"loading")]),t+=n?8:4}return S})(t,r);return N[e](...n)},C=e=>{k("OOM")},P=(e,t)=>Math.ceil(e/t)*t,R=e=>{var t=(e-w.buffer.byteLength+65535)/65536|0;try{return w.grow(t),A(),1}catch(e){}};!function(){if(r.wasmMemory)w=r.wasmMemory;else{var e=r.INITIAL_MEMORY||2097152;w=new WebAssembly.Memory({initial:e/65536,maximum:16384})}A()}(),r.wasmBinary&&(c=r.wasmBinary);var O,B,I,N={38164:()=>r.getRandomValue(),38200:()=>{if(void 0===r.getRandomValue)try{var e="object"==typeof window?window:self,t=void 0!==e.crypto?e.crypto:e.msCrypto;t=void 0===t?i:t;var n=function(){var e=new Uint32Array(1);return t.getRandomValues(e),e[0]>>>0};n(),r.getRandomValue=n}catch(e){try{var i=require("crypto"),a=function(){var e=i.randomBytes(4);return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0};a(),r.getRandomValue=a}catch(e){throw"No secure random number generator found"}}}},F={e:(e,t,r,n)=>k(`Assertion failed: ${x(e)}, at: `+[t?x(t):"unknown filename",r,n?x(n):"unknown function"]),g:()=>k(""),c:function(){k("alignment fault")},d:(e,t,r)=>M(e,t,r),f:e=>{var t=g.length,r=1073741824;(e>>>=0)>r&&C();for(var n=1;n<=4;n*=2){var i=t*(1+.2/n);i=Math.min(i,e+100663296);var a=Math.min(r,P(Math.max(e,i),65536));if(R(a))return!0}C()},a:w,b:function(){k("segmentation fault")}};return I=await async function(){function e(e){return function(e){r._crypto_init=e.i,r._argon2=e.j,r._keypair_from_seed=e.k,r._keypair_from_secret_key=e.l,r._sign=e.m,r._verify=e.n,r._get_merkle_root=e.o,r._get_merkle_proof=e.p,r._get_merkle_root_from_proof=e.q,r._verify_merkle_proof=e.r,r._cpace_ristretto255_from_hash=e.s,r._cpace_ristretto255_scalarmult=e.t,r._cpace_ristretto255_scalar_random=e.u,r._x25519_keypair=e.v,r._x25519_dh=e.w,r._hkdf_sha512_extract=e.x,r._hkdf_sha512_expand=e.y,r._encrypt_chachapoly_symmetric=e.z,r._decrypt_chachapoly_symmetric=e.A,r._receive_message_with_key=e.B,r._sha512_init=e.C,r._sha512_update=e.D,r._sha512_final=e.E,r._mlkem512_keypair=e.F,r._mlkem512_encaps=e.G,r._mlkem512_decaps=e.H,r._mlkem768_keypair=e.I,r._mlkem768_encaps=e.J,r._mlkem768_decaps=e.K,r._mlkem1024_keypair=e.L,r._mlkem1024_encaps=e.M,r._mlkem1024_decaps=e.N,r._free=e.O,r._malloc=e.P,O=e.Q,B=e.R,e.__indirect_function_table}(I=e.exports),I}var t={a:F};u??=E();var n=function(t){return e(t.instance)}(await _(c,u,t));return n}(),await async function(){d||(v=!0,I.h())}(),r});e.exports=r,e.exports.default=r}(n)),n.exports),a=t(i);const o=new Uint32Array(1),s=()=>{const e=globalThis.crypto;if("function"!=typeof e?.getRandomValues)throw new Error("Web Crypto secure randomness is unavailable");try{return e.getRandomValues(o),o[0]>>>0}finally{o[0]=0}},c=(e,t=e=>{const t=globalThis.crypto;if("function"!=typeof t?.getRandomValues)throw new Error("Web Crypto secure randomness is unavailable");t.getRandomValues(e)})=>{if(!(e instanceof Uint8Array))throw new TypeError("random: destination must be a Uint8Array");const r=new Uint8Array(e.byteLength);try{t(r),e.set(r)}finally{r.fill(0)}};if("object"!=typeof WebAssembly)throw new Error("no native wasm support detected");const l="0.14.3";let d=new URL(`https://cdn.p2party.com/@${l}/libcrypto.wasm`);const h={integrity:"sha384-pBMyUqQ3KBztxgeJMgDFZeohfj9QlAFNwt4/gRlqT0vlZ2kbkKxv+q5DwbZOBuUP"},u=async t=>{const r=("undefined"!=typeof process&&Boolean(process.versions?.node)?await(async()=>{try{const[{readFile:t},{createHash:r}]=await Promise.all([import("node:fs/promises"),import("node:crypto")]),n=await t(new URL("./libcrypto.wasm","undefined"==typeof document?require("url").pathToFileURL(__filename).href:e&&"SCRIPT"===e.tagName.toUpperCase()&&e.src||new URL("session.js",document.baseURI).href));return`sha384-${r("sha384").update(n).digest("base64")}`!==h.integrity?null:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}catch{return null}})():null)??await(async()=>{const e=await fetch(d,h);if(!e.ok)throw new Error(`Unable to load p2party ${l} WASM: HTTP ${String(e.status)}`);return await e.arrayBuffer()})();return await a({wasmBinary:r,wasmMemory:t,getRandomValue:s})},f=64*Uint8Array.BYTES_PER_ELEMENT,y=64*Uint8Array.BYTES_PER_ELEMENT,p=208,m=64*Uint8Array.BYTES_PER_ELEMENT,b=32*Uint8Array.BYTES_PER_ELEMENT,g=32*Uint8Array.BYTES_PER_ELEMENT,w=64*Uint8Array.BYTES_PER_ELEMENT,v=32*Uint8Array.BYTES_PER_ELEMENT,A=12*Uint8Array.BYTES_PER_ELEMENT,k=16*Uint8Array.BYTES_PER_ELEMENT,E=(Uint8Array.BYTES_PER_ELEMENT,32*Uint8Array.BYTES_PER_ELEMENT),K=64*Uint8Array.BYTES_PER_ELEMENT,_=32*Uint8Array.BYTES_PER_ELEMENT,U=32*Uint8Array.BYTES_PER_ELEMENT,x=32*Uint8Array.BYTES_PER_ELEMENT,S=(e,t,r)=>{t=t??32,r=r??16384;const n=65536,i=Math.ceil((e+1048576)/n);if(i>r)throw new Error(`Memory required is ${String(i*n)} bytes while declared maximum is ${String(r*n)} bytes`);return i<t?t:i};var M=()=>{const e=(g+w)*Uint8Array.BYTES_PER_ELEMENT,t=S(e);return new WebAssembly.Memory({initial:t,maximum:t})},C=()=>{const e=(U+x)*Uint8Array.BYTES_PER_ELEMENT,t=S(e);return new WebAssembly.Memory({initial:t,maximum:t})},P=e=>{const t=(e+m+w+y)*Uint8Array.BYTES_PER_ELEMENT,r=S(t);return new WebAssembly.Memory({initial:r,maximum:r})},R=e=>{const t=(e+m+g)*Uint8Array.BYTES_PER_ELEMENT,r=S(t);return new WebAssembly.Memory({initial:r,maximum:r})},O=e=>{const t=S((2*e+3)*y);return new WebAssembly.Memory({initial:t,maximum:t})},B=e=>{const t=S(e*y+e*(y+1)+3*y);return new WebAssembly.Memory({initial:t,maximum:t})};const I=(e,t)=>{t.fill(0),e._free(t.byteOffset)},N=e=>{const t=e._malloc(U),r=e._malloc(x);if(0!==e._x25519_keypair(t,r))throw e._free(t),I(e,new Uint8Array(e.wasmMemory.buffer,r,x)),new Error("x25519_keypair failed");const n=Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,t,U)),i=Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,r,x));return e._free(t),I(e,new Uint8Array(e.wasmMemory.buffer,r,x)),{publicKey:n,secretKey:i}},F=(e,t,r)=>{const n=r._malloc(U),i=r._malloc(x),a=r._malloc(U);new Uint8Array(r.wasmMemory.buffer,i,x).set(e),new Uint8Array(r.wasmMemory.buffer,a,U).set(t);const o=0===r._x25519_dh(n,i,a)?Uint8Array.from(new Uint8Array(r.wasmMemory.buffer,n,U)):null;if(I(r,new Uint8Array(r.wasmMemory.buffer,n,U)),I(r,new Uint8Array(r.wasmMemory.buffer,i,x)),r._free(a),!o)throw new Error("x25519_dh failed (identity point)");return o},L=65536,T=9+y+8+8+256+8+8+8,D=4+48*(y+1),q=65405-(T+D),V=65405,$=new Uint8Array([1]),H=32,z=65474+k,Q=(new TextEncoder).encode("p2party-x25519-idsig-v1"),j="hybrid-3dh-mlkem512-cpace21-v4",Y="hybrid-3dh-mlkem768-cpace21-v4",W="hybrid-3dh-mlkem1024-cpace21-v4",X=[j,Y,W],G=Y,Z=2e3,J=e=>{const t=new Uint8Array(Q.length+e.length);return t.set(Q,0),t.set(e,Q.length),t},ee=async(e,t,r)=>(async(e,t,r)=>{if(t.length!==w)throw new Error(`Ed25519 secret key must be ${String(w)} bytes`);const n=e.length,i=r?r.wasmMemory:P(n),a=r??await u(i),o=a._malloc(Math.max(n*Uint8Array.BYTES_PER_ELEMENT,1)),s=new Uint8Array(i.buffer,o,n*Uint8Array.BYTES_PER_ELEMENT);s.set(e);const c=a._malloc(m),l=new Uint8Array(i.buffer,c,m),d=a._malloc(w),h=new Uint8Array(i.buffer,d,w);h.set(t);try{if(0!==a._sign(n,s.byteOffset,h.byteOffset,l.byteOffset))throw new Error("Could not sign with Ed25519");return Uint8Array.from(l)}finally{a._free(o),a._free(c),I(a,h)}})(J(e),t,r),te=async(e,t,r,n)=>(async(e,t,r,n)=>{const i=e.length,a=n?n.wasmMemory:R(i),o=n??await u(a),s=o._malloc(i*Uint8Array.BYTES_PER_ELEMENT),c=new Uint8Array(a.buffer,s,i*Uint8Array.BYTES_PER_ELEMENT);c.set(e);const l=o._malloc(m),d=new Uint8Array(a.buffer,l,m);d.set(t);const h=o._malloc(g),f=new Uint8Array(a.buffer,h,g);f.set(r);const y=o._verify(i,c.byteOffset,f.byteOffset,d.byteOffset);return o._free(s),o._free(l),o._free(h),0===y})(J(e),t,r,n),re=(e,t,r)=>{const n=Math.max(e.length,1),i=Math.max(t.length,1),a=r._malloc(f),o=r._malloc(n),s=r._malloc(i);try{new Uint8Array(r.wasmMemory.buffer,o,e.length).set(e),new Uint8Array(r.wasmMemory.buffer,s,t.length).set(t);if(0!==r._hkdf_sha512_extract(a,o,e.length,s,t.length))throw new Error("hkdf_sha512_extract failed");return Uint8Array.from(new Uint8Array(r.wasmMemory.buffer,a,f))}finally{I(r,new Uint8Array(r.wasmMemory.buffer,a,f)),I(r,new Uint8Array(r.wasmMemory.buffer,o,n)),I(r,new Uint8Array(r.wasmMemory.buffer,s,i))}},ne=(e,t,r,n)=>{const i=n._malloc(r),a=n._malloc(f),o=n._malloc(Math.max(t.length,1));try{new Uint8Array(n.wasmMemory.buffer,a,f).set(e),new Uint8Array(n.wasmMemory.buffer,o,t.length).set(t);if(0!==n._hkdf_sha512_expand(i,r,a,o,t.length))throw new Error("hkdf_sha512_expand failed");return Uint8Array.from(new Uint8Array(n.wasmMemory.buffer,i,r))}finally{I(n,new Uint8Array(n.wasmMemory.buffer,i,r)),I(n,new Uint8Array(n.wasmMemory.buffer,a,f)),n._free(o)}},ie=(new TextEncoder).encode("p2party-rk-v1"),ae=(new TextEncoder).encode("p2party-ck-v1"),oe=(new TextEncoder).encode("p2party-mk-v1"),se=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),ce=e=>{const t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r++)t[r]=parseInt(e.slice(2*r,2*r+2),16);return t},le=(e,t,r)=>{const n=re(e,t,r),i=ne(n,ie,64,r);n.fill(0);const a=i.slice(0,32),o=i.slice(32,64);return i.fill(0),{rootKey:a,chainKey:o}},de=(e,t)=>{const r=re(e,oe,t),n=re(e,ae,t),i=r.slice(0,32),a=n.slice(0,32);return r.fill(0),n.fill(0),{chainKey:a,messageKey:i}},he=(e,t,r,n,i=G)=>{const a=N(n),o={rootSuite:i,rootKey:Uint8Array.from(e),sendingChainKey:null,receivingChainKey:null,dhSelfPub:a.publicKey,dhSelfSec:a.secretKey,dhRemotePub:null,Ns:0,Nr:0,PN:0,skipped:new Map};if(t){if(!r)throw new Error("ratchet: initiator requires remoteDhPub");o.dhRemotePub=Uint8Array.from(r);const e=F(o.dhSelfSec,o.dhRemotePub,n),t=le(o.rootKey,e,n);e.fill(0),o.rootKey.fill(0),o.rootKey=t.rootKey,o.sendingChainKey=t.chainKey}return o},ue=(e,t,r)=>{if(e.Nr+512<t)throw new Error("ratchet: MAX_SKIP exceeded");if(e.receivingChainKey){for(;e.Nr<t;){const{chainKey:t,messageKey:n}=de(e.receivingChainKey,r);e.receivingChainKey.fill(0),e.receivingChainKey=t,e.skipped.set(`${se(e.dhRemotePub)}:${e.Nr}`,n),e.Nr+=1}if(e.skipped.size>Z)for(const t of e.skipped.keys()){if(e.skipped.size<=Z)break;e.skipped.get(t)?.fill(0),e.skipped.delete(t)}}},fe=(e,t,r)=>{e.PN=e.Ns,e.Ns=0,e.Nr=0,e.dhRemotePub=Uint8Array.from(t.dhPub);let n=F(e.dhSelfSec,e.dhRemotePub,r),i=le(e.rootKey,n,r);n.fill(0),e.rootKey.fill(0),e.rootKey=i.rootKey,e.receivingChainKey?.fill(0),e.receivingChainKey=i.chainKey;const a=e.dhSelfSec,o=N(r);e.dhSelfPub=o.publicKey,e.dhSelfSec=o.secretKey,a.fill(0),n=F(e.dhSelfSec,e.dhRemotePub,r),i=le(e.rootKey,n,r),n.fill(0),e.rootKey.fill(0),e.rootKey=i.rootKey,e.sendingChainKey?.fill(0),e.sendingChainKey=i.chainKey},ye=(e,t,r)=>{if(!Number.isInteger(t.N)||t.N<0||!Number.isInteger(t.PN)||t.PN<0)throw new Error("invalid ratchet header");const n=((e,t)=>{const r=`${se(t.dhPub)}:${t.N}`,n=e.skipped.get(r);return n?(e.skipped.delete(r),n):null})(e,t);if(n)return n;if((!e.dhRemotePub||!((e,t)=>{if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r})(t.dhPub,e.dhRemotePub))&&(ue(e,t.PN,r),fe(e,t,r)),t.N<e.Nr)throw new Error("ratchet: message key already consumed");ue(e,t.N,r);const{chainKey:i,messageKey:a}=de(e.receivingChainKey,r);return e.receivingChainKey.fill(0),e.receivingChainKey=i,e.Nr+=1,a},pe=e=>e.slice().buffer,me=e=>e?e.slice().buffer:null,be=e=>({rootSuite:e.rootSuite,rootKey:pe(e.rootKey),sendingChainKey:me(e.sendingChainKey),receivingChainKey:me(e.receivingChainKey),dhSelfPub:pe(e.dhSelfPub),dhSelfSec:pe(e.dhSelfSec),dhRemotePub:me(e.dhRemotePub),Ns:e.Ns,Nr:e.Nr,PN:e.PN,skippedMessageKeys:Array.from(e.skipped.entries()).map(([e,t])=>{const r=e.lastIndexOf(":");return{dhPub:ce(e.slice(0,r)).slice().buffer,n:Number(e.slice(r+1)),messageKey:t.slice().buffer}})}),ge=e=>{const t=new Map;for(const r of e.skippedMessageKeys){const e=new Uint8Array(r.dhPub);t.set(`${se(e)}:${r.n}`,new Uint8Array(r.messageKey))}return{rootSuite:e.rootSuite,rootKey:new Uint8Array(e.rootKey),sendingChainKey:e.sendingChainKey?new Uint8Array(e.sendingChainKey):null,receivingChainKey:e.receivingChainKey?new Uint8Array(e.receivingChainKey):null,dhSelfPub:new Uint8Array(e.dhSelfPub),dhSelfSec:new Uint8Array(e.dhSelfSec),dhRemotePub:e.dhRemotePub?new Uint8Array(e.dhRemotePub):null,Ns:e.Ns,Nr:e.Nr,PN:e.PN,skipped:t}},we=e=>ge(be(e)),ve=e=>{e.rootKey.fill(0),e.sendingChainKey?.fill(0),e.receivingChainKey?.fill(0),e.dhSelfSec.fill(0);for(const t of e.skipped.values())t.fill(0)},Ae=(e,t)=>{if(e.rootSuite!==t.rootSuite)throw new Error("ratchet: cannot adopt a different root suite");ve(e),e.rootSuite=t.rootSuite,e.rootKey=t.rootKey,e.sendingChainKey=t.sendingChainKey,e.receivingChainKey=t.receivingChainKey,e.dhSelfPub=t.dhSelfPub,e.dhSelfSec=t.dhSelfSec,e.dhRemotePub=t.dhRemotePub,e.Ns=t.Ns,e.Nr=t.Nr,e.PN=t.PN,e.skipped=t.skipped},ke=(e,t)=>{const r=t._malloc(p),n=t._malloc(1+e.length),i=t._malloc(y);try{const a=new Uint8Array(t.wasmMemory.buffer,n,1+e.length);if(a[0]=0,a.set(e,1),0!==t._sha512_init(r))throw new Error("hashMerkleLeafWasm: sha512_init failed");if(0!==t._sha512_update(r,n,1+e.length))throw new Error("hashMerkleLeafWasm: sha512_update failed");if(0!==t._sha512_final(r,i))throw new Error("hashMerkleLeafWasm: sha512_final failed");return Uint8Array.from(new Uint8Array(t.wasmMemory.buffer,i,y))}finally{t._free(r),t._free(n),t._free(i)}},Ee=async(e,t,r,n)=>{if(e.length%y!==0)throw new Error("Hashes were not passed");const i=e.length/y;if(0===i)throw new Error("Cannot calculate Merkle proof of element of empty tree.");if(1===i){const e=new Uint8Array(y+1);if(e.set(t),n){const t=y+1,r=globalThis.crypto.getRandomValues(new Uint8Array(n));let i=0;const a=4;return new DataView(r.buffer,i,a).setUint32(0,t,!1),i+=a,r.set(e,i),r}return e}const a=r?.wasmMemory??B(i),o=r??await u(a),s=o._malloc(i*y),c=new Uint8Array(a.buffer,s,i*y);c.set(e);const l=o._malloc(y),d=new Uint8Array(a.buffer,l,y);d.set(t);const h=i*(y+1),f=o._malloc(h),p=new Uint8Array(a.buffer,f,h),m=o._get_merkle_proof(i,c.byteOffset,d.byteOffset,p.byteOffset);switch(o._free(s),o._free(l),m){case-1:throw o._free(f),new Error("Element not in tree.");case-2:throw o._free(f),new Error("Could not allocate memory for hash concatenation helper array.");case-3:throw o._free(f),new Error("Could not calculate hash.");default:if(m>0){if(n&&n>=m){const e=globalThis.crypto.getRandomValues(new Uint8Array(n));let t=0;const r=4;return new DataView(e.buffer,t,r).setUint32(0,m,!1),t+=r,e.set(p.slice(0,m),t),o._free(f),e}{const e=Uint8Array.from([...p.slice(0,m)]);return o._free(f),e}}throw o._free(f),new Error("An unexpected error occured")}},Ke=new TextEncoder,_e=Ke.encode("CPaceRistretto255"),Ue=Ke.encode("CPaceRistretto255_ISK"),xe=new Uint8Array(0),Se=(e,t,r)=>{if(t.length!==r)throw new Error(`cpace: ${e} must be ${r} bytes`)},Me=e=>{if(!Number.isSafeInteger(e)||e<0)throw new Error("cpace: invalid transcript field length");const t=[];let r=e;do{let e=r%128;r=Math.floor(r/128),0!==r&&(e|=128),t.push(e)}while(0!==r);return Uint8Array.from(t)},Ce=(e,t,r,n=!1)=>{if(0===r.length)return;const i=e._malloc(r.length),a=new Uint8Array(e.wasmMemory.buffer,i,r.length);try{if(a.set(r),0!==e._sha512_update(t,i,r.length))throw new Error("sha512_update failed")}finally{n?I(e,a):e._free(i)}},Pe=(e,t,r)=>{Ce(e,t,Me(r.data.length)),Ce(e,t,r.data,r.secret)},Re=(e,t,r,n)=>{const i=Math.max(0,127-(Me(_e.length).length+_e.length)-(Me(e.length).length+e.length)),a=((e,t)=>{const r=e._malloc(p),n=e._malloc(y),i=new Uint8Array(e.wasmMemory.buffer,r,p),a=new Uint8Array(e.wasmMemory.buffer,n,y);try{if(i.fill(0),a.fill(0),0!==e._sha512_init(r))throw new Error("sha512_init failed");for(const n of t)Pe(e,r,n);if(0!==e._sha512_final(r,n))throw new Error("sha512_final failed");return Uint8Array.from(a)}finally{I(e,i),I(e,a)}})(n,[{data:_e},{data:e,secret:!0},{data:new Uint8Array(i)},{data:r},{data:t}]),o=n._malloc(K),s=n._malloc(E),c=new Uint8Array(n.wasmMemory.buffer,o,K),l=new Uint8Array(n.wasmMemory.buffer,s,E);try{return c.set(a),l.fill(0),n._cpace_ristretto255_from_hash(s,o),Uint8Array.from(l)}finally{a.fill(0),I(n,c),n._free(s)}},Oe=(new TextEncoder).encode("p2party-interactive-3dh-v2"),Be=new Uint8Array(64),Ie=e=>Object.freeze({...e,wasmExports:Object.freeze({...e.wasmExports})}),Ne=Ie({parameterSet:512,standardName:"ML-KEM-512",publicKeyBytes:800,secretKeyBytes:1632,ciphertextBytes:768,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem512_keypair",encaps:"_mlkem512_encaps",decaps:"_mlkem512_decaps"}}),Fe=Ie({parameterSet:768,standardName:"ML-KEM-768",publicKeyBytes:1184,secretKeyBytes:2400,ciphertextBytes:1088,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem768_keypair",encaps:"_mlkem768_encaps",decaps:"_mlkem768_decaps"}}),Le=Ie({parameterSet:1024,standardName:"ML-KEM-1024",publicKeyBytes:1568,secretKeyBytes:3168,ciphertextBytes:1568,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem1024_keypair",encaps:"_mlkem1024_encaps",decaps:"_mlkem1024_decaps"}}),Te=Object.freeze({512:Ne,768:Fe,1024:Le}),De=e=>{const t=Te[e];if(void 0===t)throw new RangeError(`unsupported ML-KEM parameter set: ${String(e)}`);return t},qe=(e,t,r)=>{if(!(e instanceof Uint8Array))throw new TypeError(`${t} must be a Uint8Array`);if(e.length!==r)throw new RangeError(`${t} must be exactly ${String(r)} bytes`)},Ve=(e,t,r,n)=>{const i=e._malloc(r);if(0===i)throw new Error(`${t.standardName}: failed to allocate ${n}`);return i},$e=(e,t,r)=>new Uint8Array(e.wasmMemory.buffer,t,r),He=(e,t)=>{void 0!==t&&e._free(t)},ze=(e,t,r)=>{void 0!==t&&I(e,$e(e,t,r))};class Qe{#e;#t;suite;constructor(e,t){this.#e=e,this.suite=t,this.#t=((e,t)=>{const r=e,n=t.wasmExports,i=[n.keypair,n.encaps,n.decaps].filter(e=>"function"!=typeof r[e]);if(0!==i.length)throw new Error(`${t.standardName} WASM exports are unavailable; rebuild libcrypto.wasm (missing ${i.join(", ")})`);return{keypair:r[n.keypair].bind(e),encaps:r[n.encaps].bind(e),decaps:r[n.decaps].bind(e)}})(e,t)}async generateKeyPair(){await Promise.resolve();const e=this.#e,t=this.suite;let r,n,i;try{r=Ve(e,t,t.publicKeyBytes,"public key"),n=Ve(e,t,t.secretKeyBytes,"secret key"),i=Ve(e,t,t.keyPairRandomBytes,"key-generation randomness");const a=$e(e,i,t.keyPairRandomBytes);c(a);const o=this.#t.keypair(r,n,i);if(0!==o)throw new Error(`${t.standardName} key generation failed (${String(o)})`);return((e,t)=>{let r=!1;return{publicKey:e,secretKey:t,get destroyed(){return r},destroy(){r||(t.fill(0),r=!0)}}})(Uint8Array.from($e(e,r,t.publicKeyBytes)),Uint8Array.from($e(e,n,t.secretKeyBytes)))}finally{He(e,r),ze(e,n,t.secretKeyBytes),ze(e,i,t.keyPairRandomBytes)}}async encapsulate(e){await Promise.resolve();const t=this.#e,r=this.suite;let n,i,a,o;qe(e,`${r.standardName} public key`,r.publicKeyBytes);try{n=Ve(t,r,r.ciphertextBytes,"ciphertext"),i=Ve(t,r,r.sharedSecretBytes,"shared secret"),a=Ve(t,r,r.publicKeyBytes,"public key"),o=Ve(t,r,r.encapsRandomBytes,"encapsulation randomness"),$e(t,a,r.publicKeyBytes).set(e);const s=$e(t,o,r.encapsRandomBytes);c(s);const l=this.#t.encaps(n,i,a,o);if(0!==l)throw new Error(`${r.standardName} encapsulation failed (${String(l)})`);return((e,t)=>{let r=!1;return{ciphertext:e,sharedSecret:t,get destroyed(){return r},destroy(){r||(t.fill(0),r=!0)}}})(Uint8Array.from($e(t,n,r.ciphertextBytes)),Uint8Array.from($e(t,i,r.sharedSecretBytes)))}finally{He(t,n),ze(t,i,r.sharedSecretBytes),He(t,a),ze(t,o,r.encapsRandomBytes)}}async decapsulate(e,t){await Promise.resolve();const r=this.#e,n=this.suite;let i,a,o;qe(e,`${n.standardName} ciphertext`,n.ciphertextBytes),qe(t,`${n.standardName} secret key`,n.secretKeyBytes);try{i=Ve(r,n,n.sharedSecretBytes,"shared secret"),a=Ve(r,n,n.ciphertextBytes,"ciphertext"),o=Ve(r,n,n.secretKeyBytes,"secret key"),$e(r,a,n.ciphertextBytes).set(e),$e(r,o,n.secretKeyBytes).set(t);const s=this.#t.decaps(i,a,o);if(0!==s)throw new Error(`${n.standardName} decapsulation failed (${String(s)})`);return(e=>{let t=!1;return{sharedSecret:e,get destroyed(){return t},destroy(){t||(e.fill(0),t=!0)}}})(Uint8Array.from($e(r,i,n.sharedSecretBytes)))}finally{ze(r,i,n.sharedSecretBytes),He(r,a),ze(r,o,n.secretKeyBytes)}}}const je=(e,t)=>{const r=De(t.parameterSet);if(t!==r)throw new TypeError("ML-KEM suite descriptor must be one of the exported canonical suites");return new Qe(e,r)},Ye=e=>{if("hybrid-mlkem512"===e)return 512;if("hybrid-mlkem768"===e)return 768;if("hybrid-mlkem1024"===e)return 1024;throw new Error("roomPolicy: unsupported PQ mode")},We=e=>{if("hybrid-mlkem512"===e)return j;if("hybrid-mlkem768"===e)return Y;if("hybrid-mlkem1024"===e)return W;throw new Error("roomPolicy: unsupported PQ mode")},Xe=e=>{if(e===j)return"hybrid-mlkem512";if(e===Y)return"hybrid-mlkem768";if(e===W)return"hybrid-mlkem1024";throw new Error("roomPolicy: unsupported ratchet root suite")};(new TextEncoder).encode("p2party/room-policy/v1\0"),new Array(64),new Array(128);const Ge=e=>new Promise(t=>{let r=0;const n=e.length;for(let t=0;t<n;t++)r+=e[t].length;const i=new Uint8Array(r);let a=0;for(const t of e)i.set(t,a),a+=t.length;t(i)}),Ze=(e,t)=>new Promise(r=>{const n=e.length;if(n!==t.length)return void r(!1);let i=0;for(let r=0;r<n;r++)i|=e[r]^t[r];r(0===i)}),Je=e=>{const t=(e=>{if("hybrid-mlkem768"===e)return $;if("hybrid-mlkem512"===e)return new Uint8Array([2]);if("hybrid-mlkem1024"===e)return new Uint8Array([3]);throw new Error("handshake: unsupported room PQ mode")})(e.pqMode??"hybrid-mlkem768"),r=[e.channelId,e.ikInitiator,e.ikResponder,e.fpInitiator,e.fpResponder,t];let n=0;for(const e of r)n+=e.length;const i=new Uint8Array(n);let a=0;for(const e of r)i.set(e,a),a+=e.length;return i},et=(new TextEncoder).encode("p2party-v4-hs-kc-transcript-v4"),tt=(new TextEncoder).encode("p2party-v4-hs-kc-responder-v4"),rt=(new TextEncoder).encode("p2party-v4-hs-kc-initiator-ratchet-dh-v4"),nt=(new TextEncoder).encode("p2party-v4-hs-kc-responder-finish-v4"),it=new Uint8Array(64),at=(new TextEncoder).encode("p2party-v4-pq-healing-extract-v1"),ot=(new TextEncoder).encode("p2party-v4-pq-healing-root-v1"),st=(new TextEncoder).encode("p2party-v4-pq-healing-binding-v1\0"),ct=64,lt=129,dt=(e,t,r)=>{const n=r._malloc(e.length),i=r._malloc(t.length),a=r._malloc(ct);try{new Uint8Array(r.wasmMemory.buffer,n,e.length).set(e),new Uint8Array(r.wasmMemory.buffer,i,t.length).set(t);if(0!==r._hkdf_sha512_extract(a,n,e.length,i,t.length))throw new Error("handshake hmac_sha512 failed");return Uint8Array.from(new Uint8Array(r.wasmMemory.buffer,a,ct))}finally{I(r,new Uint8Array(r.wasmMemory.buffer,n,e.length)),r._free(i),r._free(a)}},ht=e=>{let t=0;for(const r of e)t|=r;return 0===t},ut=(e,t)=>{const r=new Uint8Array(97);return r[0]=2,r.set(e,1),r.set(t,33),r},ft=async(e,t,r)=>{const{mode:n,pqMode:i="hybrid-mlkem768",pin:a,channelInput:o,amInitiator:s,idSelfSec:c,selfIdentityX25519Pub:l,selfIdentityCrossSignature:d,peerIdentityEd25519Pub:h}=t,u=(e=>{const t=De(Ye(e)),r=193+t.publicKeyBytes;return{suite:t,publicKeyOffset:193,ciphertextOffset:r,length:r+t.ciphertextBytes}})(i),f=je(r,u.suite),m=We(i),b=crypto.getRandomValues(new Uint8Array(32)),g=N(r);let w=new Uint8Array(32),v=null;const A=new Uint8Array(u.suite.publicKeyBytes),k=new Uint8Array(u.suite.ciphertextBytes);let K,U,x,S,M,C,P,R,O=null,B=null,L=null;const T=e=>{if("pin"!==n)return null;if(!a)throw new Error("PIN mode requires a PIN");const t=Re(a,e,o,r),i=((e,t)=>{Se("generator",e,E);const r=t._malloc(_),n=t._malloc(E),i=t._malloc(E),a=new Uint8Array(t.wasmMemory.buffer,r,_),o=new Uint8Array(t.wasmMemory.buffer,n,E),s=new Uint8Array(t.wasmMemory.buffer,i,E);try{if(a.fill(0),s.fill(0),o.set(e),t._cpace_ristretto255_scalar_random(r),0!==t._cpace_ristretto255_scalarmult(i,r,n))throw new Error("cpace: public share is the identity");return{y:Uint8Array.from(a),Y:Uint8Array.from(s)}}finally{I(t,a),t._free(n),t._free(i)}})(t,r);return t.fill(0),i},D=()=>((e,t,r,n,i,a,o,s)=>{const c=new Uint8Array(e.length);return c[0]=1,c.set(t,1),c.set(r,33),c.set(n,65),c.set(i,97),c.set(a,lt),c.set(o,e.publicKeyOffset),c.set(s,e.ciphertextOffset),c})(u,b,g.publicKey,w,l,d,A,k);try{let t;if(s){O=await f.generateKeyPair(),A.set(O.publicKey);const r=T(b);r&&(v=r.y,w=r.Y),await e.send(D()),t=await e.recv()}else t=await e.recv();if(t.length!==u.length||1!==t[0])throw new Error("Malformed handshake HELLO");const i=t.subarray(1,33),a=t.subarray(33,65),N=t.subarray(65,97),q=t.subarray(97,129),V=t.subarray(lt,193),$=t.subarray(u.publicKeyOffset,u.publicKeyOffset+u.suite.publicKeyBytes),z=t.subarray(u.ciphertextOffset,u.ciphertextOffset+u.suite.ciphertextBytes);if(s){if(!ht($))throw new Error("Malformed handshake HELLO: responder ML-KEM public-key field must be zero");if(ht(z))throw new Error("Malformed handshake HELLO: responder ML-KEM ciphertext is required")}else{if(ht($))throw new Error("Malformed handshake HELLO: initiator ML-KEM public key is required");if(!ht(z))throw new Error("Malformed handshake HELLO: initiator ML-KEM ciphertext field must be zero")}if(!await te(q,V,h,r))throw new Error("Handshake peer X25519 identity cross-signature invalid");if(s){if(!O)throw new Error("Handshake ML-KEM initiator keypair is unavailable");B=await f.decapsulate(z,O.secretKey),O.destroy()}else{const t=await f.encapsulate($);B=t,k.set(t.ciphertext);const r=T(i);r&&(v=r.y,w=r.Y),await e.send(D())}K=((e,t,r,n,i,a)=>{let o,s;const c=F(r,n,a);i?(o=F(e,n,a),s=F(r,t,a)):(o=F(r,t,a),s=F(e,n,a));const l=new Uint8Array(96);l.set(o,0),l.set(s,32),l.set(c,64);const d=re(Be,l,a),h=ne(d,Oe,32,a);return l.fill(0),o.fill(0),s.fill(0),c.fill(0),d.fill(0),h})(c,q,g.secretKey,a,s,r);const Q=s?b:i,j=s?i:b,Y=s?g.publicKey:a,W=s?a:g.publicKey,X=s?w:N,G=s?N:w,Z=s?l:q,J=s?d:V,ee=s?q:l,ie=s?V:d,ae=s?A:$,oe=s?k:z,se=s?$:A,ce=s?z:k;if("pin"===n){if(!v)throw new Error("Handshake CPace scalar is unavailable");U=((e,t)=>{const{y:r,peerShare:n,sid:i,initiatorShare:a,responderShare:o,initiatorAssociatedData:s=xe,responderAssociatedData:c=xe}=e;Se("private scalar",r,_),Se("peer share",n,E),Se("initiator share",a,E),Se("responder share",o,E);const l=t._malloc(_),d=t._malloc(E),h=t._malloc(E),u=t._malloc(p),f=t._malloc(y),m=new Uint8Array(t.wasmMemory.buffer,l,_),b=new Uint8Array(t.wasmMemory.buffer,d,E),g=new Uint8Array(t.wasmMemory.buffer,h,E),w=new Uint8Array(t.wasmMemory.buffer,u,p),v=new Uint8Array(t.wasmMemory.buffer,f,y);try{if(m.set(r),b.set(n),g.fill(0),w.fill(0),v.fill(0),0!==t._cpace_ristretto255_scalarmult(h,l,d))throw new Error("cpace: peer share is invalid or the identity");if(0!==t._sha512_init(u))throw new Error("sha512_init failed");if(Pe(t,u,{data:Ue}),Pe(t,u,{data:i}),Ce(t,u,Me(E)),0!==t._sha512_update(u,h,E))throw new Error("sha512_update failed");if(Pe(t,u,{data:a}),Pe(t,u,{data:s}),Pe(t,u,{data:o}),Pe(t,u,{data:c}),0!==t._sha512_final(u,f))throw new Error("sha512_final failed");return Uint8Array.from(v)}finally{I(t,m),t._free(d),I(t,g),I(t,w),I(t,v)}})({y:v,peerShare:N,sid:Q,initiatorShare:X,responderShare:G},r)}const le=((e,t)=>(new TextEncoder).encode("pin"===e?`p2party-v4-hybrid-root-cpace21-3dh-ml-kem-${String(t)}-v4`:`p2party-v4-hybrid-root-3dh-ml-kem-${String(t)}-v4`))(n,u.suite.parameterSet);x=await Ge("pin"===n?[U,K,B.sharedSecret]:[K,B.sharedSecret]),S=re(it,x,r);const de=await Ge([le,o,Z,J,ee,ie,ae,ce]);M=ne(S,de,32,r);const ue=await Ge([st,o,Q,j,Y,W,Z,J,ee,ie,ae,ce]);try{R=new Uint8Array(await crypto.subtle.digest("SHA-256",ue.slice().buffer))}finally{ue.fill(0)}C=re(at,M,r);const ye=await Ge([ot,R]);try{P=ne(C,ye,32,r)}finally{ye.fill(0),C.fill(0),C=void 0}K.fill(0),U?.fill(0),x.fill(0),S.fill(0),B.destroy();const pe=(e,t,r,n=[])=>Ge([et,e,Q,j,Y,W,X,G,Z,J,ee,ie,ae,oe,se,ce,t,...r?[r]:[],...n,o]);if(s){const t=await e.recv();if(97!==t.length||2!==t[0])throw new Error("Malformed handshake CONFIRM");const n=Uint8Array.from(t.subarray(1,33)),i=t.subarray(33,97);L=he(M,!0,n,r,m);const a=L.dhSelfPub,o=await pe(rt,n,a,[i]),s=dt(M,o,r);try{await e.send(ut(a,s));const t=await pe(tt,n),o=dt(M,t,r),c=await Ze(i,o);if(o.fill(0),!c)throw new Error("Handshake key-confirmation failed");const l=await e.recv();if(65!==l.length||3!==l[0])throw new Error("Malformed handshake FINISH");const d=l.subarray(1,65),h=await pe(nt,n,a,[i,s]),u=dt(M,h,r),f=await Ze(d,u);if(u.fill(0),!f)throw new Error("Handshake final confirmation failed")}finally{s.fill(0)}}else{L=he(M,!1,null,r,m);const t=L.dhSelfPub,n=await pe(tt,t),i=dt(M,n,r);try{await e.send(ut(t,i));const n=await e.recv();if(97!==n.length||2!==n[0])throw new Error("Malformed handshake CONFIRM");const a=Uint8Array.from(n.subarray(1,33)),o=n.subarray(33,97),s=await pe(rt,t,a,[i]),c=dt(M,s,r),l=await Ze(o,c);if(c.fill(0),!l)throw new Error("Handshake key-confirmation failed");((e,t,r)=>{if(t.length!==H)throw new Error("ratchet: invalid initiator DH public key");if(e.sendingChainKey||e.receivingChainKey||e.dhRemotePub||0!==e.Ns||0!==e.Nr||0!==e.PN||0!==e.skipped.size)throw new Error("ratchet: responder bootstrap requires pristine state");fe(e,{dhPub:t},r)})(L,a,r);const d=await pe(nt,t,a,[i,o]),h=dt(M,d,r);try{await e.send((e=>{const t=new Uint8Array(65);return t[0]=3,t.set(e,1),t})(h))}finally{h.fill(0)}}finally{i.fill(0)}}if(!L)throw new Error("Handshake ratchet initialization failed");if(!P||!R)throw new Error("Handshake PQ-healing bootstrap failed");const me=L;L=null;const be={rootKey:P,binding:R,nextOfferer:s?"local":"remote"};return P=void 0,R=void 0,{state:me,secret:M,pqHealing:be}}catch(e){throw M?.fill(0),P?.fill(0),R?.fill(0),e}finally{g.secretKey.fill(0),v?.fill(0),K?.fill(0),U?.fill(0),x?.fill(0),S?.fill(0),C?.fill(0),P?.fill(0),R?.fill(0),B?.destroy(),O?.destroy(),L&&ve(L)}},yt=(1n<<64n)-1n,pt=(e,t,r)=>{if(!Number.isInteger(r)||r<0||r>Number.MAX_SAFE_INTEGER)throw new Error("chunkFrame: ratchet counter out of safe-integer range");new DataView(e.buffer,e.byteOffset,e.byteLength).setBigUint64(t,BigInt(r),!1)},mt=(e,t)=>{const r=new DataView(e.buffer,e.byteOffset,e.byteLength).getBigUint64(t,!1);if(r>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("chunkFrame: ratchet counter exceeds safe-integer range");return Number(r)},bt=(e,t,r=0n)=>{if(e.dhPub.length!==H)throw new Error("chunkFrame: dhPub must be 32 bytes");if(12!==t.length)throw new Error("chunkFrame: nonce must be 12 bytes");const n=new Uint8Array(69);return n[0]=2,n.set(e.dhPub,1),pt(n,33,e.N),pt(n,41,e.PN),((e,t,r)=>{if("bigint"!=typeof r||r<0n||r>yt)throw new Error("chunkFrame: PQ epoch out of u64 range");new DataView(e.buffer,e.byteOffset,e.byteLength).setBigUint64(t,r,!1)})(n,49,r),n.set(t,57),n},gt=e=>{if(e.length<69)throw new Error("chunkFrame: frame shorter than the header");if(2!==e[0])throw new Error("chunkFrame: leading byte is not FRAME_TYPE_CHUNK");return{header:{dhPub:e.subarray(1,33),N:mt(e,33),PN:mt(e,41)},pqEpoch:(t=e,r=49,new DataView(t.buffer,t.byteOffset,t.byteLength).getBigUint64(r,!1)),nonce:e.subarray(57,69),ciphertext:e.subarray(69)};var t,r},wt=v,vt=(1n<<64n)-1n,At=(new TextEncoder).encode("p2party/pq-message-key/v1\0"),kt=(e,t,r)=>{if(!(e instanceof Uint8Array)||e.length!==r)throw new Error(`pqMessageKey: ${t} must be ${String(r)} bytes`)},Et=(e,t)=>{if(!Number.isSafeInteger(e)||e<0)throw new Error(`pqMessageKey: ${t} is outside the safe u64 range`)},Kt=(e,t)=>{if("string"!=typeof(r=e.rootSuite)||!X.includes(r))throw new Error("pqMessageKey: unsupported root suite");var r;kt(e.rootKey,"rootKey",32),kt(e.binding,"binding",32),(e=>{if("bigint"!=typeof e||e<0n||e>vt)throw new Error("pqMessageKey: epoch is outside the u64 range")})(e.epoch),kt(t.dhPub,"header.dhPub",H),Et(t.N,"header.N"),Et(t.PN,"header.PN");const n=(new TextEncoder).encode(e.rootSuite);if(n.length>65535)throw new Error("pqMessageKey: root suite identifier is too long");const i=At.length+2+n.length+32+8+1+H+8+8,a=new Uint8Array(i);let o=0;a.set(At,o),o+=At.length;const s=new DataView(a.buffer);return s.setUint16(o,n.length,!1),o+=2,a.set(n,o),o+=n.length,a.set(e.binding,o),o+=32,s.setBigUint64(o,e.epoch,!1),o+=8,a[o++]=2,a.set(t.dhPub,o),o+=H,s.setBigUint64(o,BigInt(t.N),!1),o+=8,s.setBigUint64(o,BigInt(t.PN),!1),a},_t=(e,t,r,n)=>{if(!(e instanceof Uint8Array))throw new Error("pqMessageKey: classicalMessageKey must be a Uint8Array");if(t?.rootKey instanceof Uint8Array&&(i=e,a=t.rootKey,i.buffer===a.buffer&&i.byteOffset<a.byteOffset+a.byteLength&&a.byteOffset<i.byteOffset+i.byteLength))throw new Error("pqMessageKey: classicalMessageKey must not alias context.rootKey");var i,a;let o=null,s=null;try{kt(e,"classicalMessageKey",wt);const i=Kt(t,r);return o=Uint8Array.from(t.rootKey),s=re(o,e,n),ne(s,i,wt,n)}finally{e.fill(0),o?.fill(0),s?.fill(0)}},Ut=v,xt=A,St=k,Mt=y+57,Ct=(1n<<64n)-1n,Pt=(e,t,r)=>{const n=`${i=e,Array.from(i,e=>e.toString(16).padStart(2,"0")).join("")}:${t}`;var i;if(void 0===r)return n;if("bigint"!=typeof r||r<0n||r>Ct)throw new Error("messageChunkCrypto: PQ epoch out of u64 range");return`${n}:${r.toString(10)}`},Rt=(e,t,r,n)=>{const i=e._malloc(L),a=e._malloc(V),o=e._malloc(y),s=e._malloc(Ut),c=new Uint8Array(e.wasmMemory.buffer,i,L),l=new Uint8Array(e.wasmMemory.buffer,a,V);c.fill(0),l.fill(0),c.set(t.subarray(0,L),0),new Uint8Array(e.wasmMemory.buffer,o,y).set(r),new Uint8Array(e.wasmMemory.buffer,s,Ut).set(n);const d=e._receive_message_with_key(a,i,o,s),h=0===d?Uint8Array.from(l):null;return e._free(i),e._free(o),I(e,new Uint8Array(e.wasmMemory.buffer,s,Ut)),I(e,l),{code:d,decrypted:h}},Ot=(e,t,r,n,i,a)=>{if(n.length!==y)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const o=(()=>{const e=new Uint8Array(xt);return crypto.getRandomValues(e),e})(),s=bt(t,o,a?.epoch??0n),c=((e,t)=>{if(t.length<57)throw new Error("messageChunkCrypto: incomplete chunk frame header");const r=new Uint8Array(Mt);return r.set(e,0),r.set(t.subarray(0,57),y),r})(n,s);let l=null;try{const n=((e,t,r,n,i)=>{const a=Math.max(n.length,1),o=Math.max(i.length,1),s=n.length+St,c=e._malloc(Ut),l=e._malloc(xt),d=e._malloc(a),h=e._malloc(o),u=e._malloc(s);new Uint8Array(e.wasmMemory.buffer,c,Ut).set(t),new Uint8Array(e.wasmMemory.buffer,l,xt).set(r),n.length&&new Uint8Array(e.wasmMemory.buffer,d,n.length).set(n),i.length&&new Uint8Array(e.wasmMemory.buffer,h,i.length).set(i);const f=0===e._encrypt_chachapoly_symmetric(u,d,n.length,c,l,h,i.length)?Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,u,s)):null;if(I(e,new Uint8Array(e.wasmMemory.buffer,c,Ut)),e._free(l),I(e,new Uint8Array(e.wasmMemory.buffer,d,a)),e._free(h),I(e,new Uint8Array(e.wasmMemory.buffer,u,s)),!f)throw new Error("messageChunkCrypto: AEAD encrypt failed");return f})(i,a?l=_t(Uint8Array.from(e),a,t,i):e,o,r,c),d=new Uint8Array(s.length+n.length);return d.set(s,0),d.set(n,s.length),d}finally{l?.fill(0)}},Bt=(e,t,r,n,i,a)=>{if(n.length!==y)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const{header:o,pqEpoch:s}=gt(t);let c=null;if(a){try{c=a(s)}catch{return{decrypted:null,ok:!1,stateAdvanced:!1}}if(!(c&&(l=c,d=s,h=e.rootSuite,l.epoch===d&&l.rootSuite===h&&l.rootKey instanceof Uint8Array&&32===l.rootKey.length&&l.binding instanceof Uint8Array&&32===l.binding.length)))return{decrypted:null,ok:!1,stateAdvanced:!1}}else if(0n!==s)return{decrypted:null,ok:!1,stateAdvanced:!1};var l,d,h;const u=Pt(o.dhPub,o.N,a?s:void 0),f=r.get(u);if(f){const{code:e,decrypted:r}=Rt(i,t,n,f);return{decrypted:0===e?r:null,ok:0===e,stateAdvanced:!1}}const p=we(e);let m;try{m=It(p,o,i),c&&(m=_t(m,c,o,i))}catch{return ve(p),{decrypted:null,ok:!1,stateAdvanced:!1}}const{code:b,decrypted:g}=Rt(i,t,n,m);return-2===b?(m.fill(0),ve(p),{decrypted:null,ok:!1,stateAdvanced:!1}):(Ae(e,p),r.set(u,m),{decrypted:0===b?g:null,ok:0===b,stateAdvanced:!0})},It=(e,t,r)=>{try{return ye(e,t,r)}catch(t){throw ve(e),t}},Nt=32,Ft=32,Lt=64,Tt=new Uint8Array([80,50,81,72]),Dt=(new TextEncoder).encode("p2party/pq-healing/root/v1\0"),qt=(1n<<64n)-1n;class Vt extends Error{code;constructor(e,t){super(`pqHealing: ${t}`),this.name="PqHealingError",this.code=e}}const $t=(e,t)=>{throw new Vt(e,t)},Ht=(e,t,r)=>e instanceof Uint8Array?e.length!==r?$t("invalid-record",`${t} must be exactly ${String(r)} bytes`):e:$t("invalid-record",`${t} must be a Uint8Array`),zt=(e,t)=>{("bigint"!=typeof e||e<0n||e>qt)&&$t("overflow",`${t} is outside the unsigned 64-bit range`)},Qt=(e,t)=>{zt(e,t),e===qt&&$t("overflow",`${t} cannot advance beyond uint64`)},jt=e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return $t("invalid-record","advance acknowledgement must be a plain record");const t=e,r=Reflect.ownKeys(t);2===r.length&&r.includes("epoch")&&r.includes("advanceCounter")||$t("invalid-record","advance acknowledgement must contain only epoch and advanceCounter");const n=Object.getOwnPropertyDescriptor(t,"epoch"),i=Object.getOwnPropertyDescriptor(t,"advanceCounter");if(!(void 0!==n&&void 0!==i&&"value"in n&&"value"in i&&n.enumerable&&i.enumerable))return $t("invalid-record","advance acknowledgement fields must be enumerable data properties");const a=n.value,o=i.value;return"bigint"!=typeof a||"bigint"!=typeof o?$t("invalid-record","advance acknowledgement fields must be bigint values"):(zt(a,"advance acknowledgement epoch"),zt(o,"advance acknowledgement counter"),{epoch:a,advanceCounter:o})},Yt=(e,t,r)=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return $t("invalid-record",`${t} must be a plain record`);const n=e,i=Reflect.ownKeys(n);if(i.length!==r.length||r.some(e=>!i.includes(e)))return $t("invalid-record",`${t} does not contain exactly its canonical fields`);for(const e of r){const r=Object.getOwnPropertyDescriptor(n,e);void 0!==r&&"value"in r&&r.enumerable||$t("invalid-record",`${t}.${e} must be an enumerable data property`)}return n},Wt=(e,t)=>{if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n+=1)r|=e[n]^t[n];return 0===r},Xt=e=>768===e?1:512===e?2:1024===e?3:$t("suite-mismatch","unsupported ML-KEM parameter set"),Gt=e=>1===e?768:2===e?512:3===e?1024:$t("invalid-record","record has an unknown ML-KEM suite tag"),Zt=(e,t)=>Reflect.get(e,t),Jt=e=>{const t=De(e.parameterSet);e.standardName===t.standardName&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes&&Zt(e,"sharedSecretBytes")===t.sharedSecretBytes&&Zt(e,"keyPairRandomBytes")===t.keyPairRandomBytes&&Zt(e,"encapsRandomBytes")===t.encapsRandomBytes||$t("suite-mismatch","selected suite does not match its canonical FIPS 203 descriptor")},er=(e,t)=>{Jt(e),Jt(t),e.parameterSet===t.parameterSet&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes||$t("suite-mismatch","room-selected suite does not exactly match the ML-KEM backend")},tr=e=>Lt+e.publicKeyBytes,rr=e=>Lt+tr(e)+e.ciphertextBytes,nr=(e,t,r)=>{Jt(t),Ht(r,"binding",Nt),Ht(e,"ACK",64),Wt(e.subarray(0,4),Tt)||$t("invalid-record","ACK magic is invalid"),1!==e[4]&&$t("invalid-record","ACK version is unsupported"),3!==e[5]&&$t("invalid-record","ACK type is unexpected"),0!==e[7]&&$t("invalid-record","ACK reserved flags must be zero");Gt(e[6])!==t.parameterSet&&$t("suite-mismatch","ACK suite differs from the authenticated room suite"),Wt(e.subarray(8,40),r)||$t("binding-mismatch","ACK belongs to a different authenticated edge");const n=new DataView(e.buffer,e.byteOffset,e.byteLength);return 0n!==n.getBigUint64(56,!1)&&$t("invalid-record","ACK reserved bytes must be zero"),{advanceCounter:n.getBigUint64(40,!1),epoch:n.getBigUint64(48,!1)}},ir=(e,t,r,n,i,a,o)=>{Ht(r,"binding",Nt),zt(n,"sender counter"),zt(i,"from epoch"),zt(a,"to epoch"),i!==qt&&a===i+1n||$t("invalid-record","record must advance exactly one PQ epoch");const s=new Uint8Array(o);s.set(Tt,0),s[4]=1,s[5]=e,s[6]=Xt(t.parameterSet),s[7]=0,s.set(r,8);const c=new DataView(s.buffer,s.byteOffset,s.byteLength);return c.setBigUint64(40,n,!1),c.setBigUint64(48,i,!1),c.setBigUint64(56,a,!1),s},ar=(e,t,r,n)=>{e instanceof Uint8Array||$t("invalid-record","record must be a Uint8Array"),e.length<Lt&&$t("invalid-record","record is shorter than its canonical header"),Wt(e.subarray(0,4),Tt)||$t("invalid-record","record magic is invalid"),1!==e[4]&&$t("invalid-record","record version is unsupported"),e[5]!==t&&$t("invalid-record","record type is unexpected"),0!==e[7]&&$t("invalid-record","record reserved flags must be zero");Gt(e[6])!==r.parameterSet&&$t("suite-mismatch","record suite differs from the authenticated room suite");const i=e.subarray(8,40);void 0===n||Wt(i,n)||$t("binding-mismatch","record belongs to a different authenticated edge");const a=new DataView(e.buffer,e.byteOffset,e.byteLength),o=a.getBigUint64(40,!1),s=a.getBigUint64(48,!1),c=a.getBigUint64(56,!1);return s!==qt&&c===s+1n||$t("invalid-record","record must advance exactly one PQ epoch"),{senderCounter:o,fromEpoch:s,toEpoch:c}},or=(e,t,r)=>{const n=ar(e,1,t,r);return e.length!==tr(t)&&$t("invalid-record","OFFER length is not canonical for its suite"),{...n,bytes:Uint8Array.from(e),publicKey:e.slice(Lt)}},sr=(e,t,r)=>{const n=ar(e,2,t,r);e.length!==rr(t)&&$t("invalid-record","ADVANCE length is not canonical for its suite");const i=tr(t),a=e.slice(Lt,Lt+i),o=or(a,t,r);return o.fromEpoch===n.fromEpoch&&o.toEpoch===n.toEpoch||$t("fork","ADVANCE epoch does not exactly match its embedded OFFER"),{...n,bytes:Uint8Array.from(e),offer:o,ciphertext:e.slice(Lt+i)}},cr=(e,t)=>{if(Jt(t),!(e instanceof Uint8Array))return $t("invalid-record","record must be a Uint8Array");if(e.length<Lt)return $t("invalid-record","record is shorter than its canonical header");if(1===e[5]){const r=or(e,t);return{type:"offer",parameterSet:t.parameterSet,binding:r.bytes.slice(8,40),senderCounter:r.senderCounter,fromEpoch:r.fromEpoch,toEpoch:r.toEpoch,publicKey:Uint8Array.from(r.publicKey)}}if(2===e[5]){const r=sr(e,t),n={type:"offer",parameterSet:t.parameterSet,binding:r.offer.bytes.slice(8,40),senderCounter:r.offer.senderCounter,fromEpoch:r.offer.fromEpoch,toEpoch:r.offer.toEpoch,publicKey:Uint8Array.from(r.offer.publicKey)};return{type:"advance",parameterSet:t.parameterSet,binding:r.bytes.slice(8,40),senderCounter:r.senderCounter,fromEpoch:r.fromEpoch,toEpoch:r.toEpoch,offerBytes:Uint8Array.from(r.offer.bytes),offer:n,ciphertext:Uint8Array.from(r.ciphertext)}}return $t("invalid-record","record type is unknown")},lr=(e,t,r,n)=>{Ht(e,"PQ root",Ft);const i=re(e,t,n),a=((...e)=>{const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r})(Dt,r);try{return ne(i,a,Ft,n)}finally{i.fill(0)}},dr=(e,t)=>{const r=Uint8Array.from(e),n=Uint8Array.from(t);let i=!1;return{publicKey:r,secretKey:n,get destroyed(){return i},destroy(){i||(n.fill(0),i=!0)}}},hr=e=>{switch(e.kind){case"idle":return{kind:"idle"};case"outbound-offer":return{kind:e.dispatched?"outbound-offer-dispatched":"outbound-offer-prepared",offer:Uint8Array.from(e.offer.bytes),secretKey:Uint8Array.from(e.keyPair.secretKey)};case"inbound-offer":return{kind:"inbound-offer",offer:Uint8Array.from(e.offer.bytes)};case"outbound-advance-prepared":return{kind:"outbound-advance-prepared",advance:Uint8Array.from(e.advance.bytes),nextRoot:Uint8Array.from(e.nextRoot)};case"outbound-advance-awaiting-ack":return{kind:"outbound-advance-awaiting-ack",advance:Uint8Array.from(e.advance.bytes)};case"inbound-advance-prepared":return{kind:"inbound-advance-prepared",advance:Uint8Array.from(e.advance.bytes),secretKey:Uint8Array.from(e.keyPair.secretKey),nextRoot:Uint8Array.from(e.nextRoot)};case"inbound-advance-awaiting-ack-dispatch":return{kind:"inbound-advance-awaiting-ack-dispatch",advance:Uint8Array.from(e.advance.bytes)}}},ur=(e,t)=>"bigint"!=typeof e?$t("invalid-record",`${t} must be a bigint`):(zt(e,t),e),fr=(e,t,r)=>{const n=(e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return $t("invalid-record","snapshot.phase must be a plain record");const t=Object.getOwnPropertyDescriptor(e,"kind");return void 0!==t&&"value"in t&&t.enumerable&&"string"==typeof t.value?t.value:$t("invalid-record","snapshot.phase.kind must be an enumerable string data property")})(e);switch(n){case"idle":return Yt(e,"snapshot.phase",["kind"]),{kind:"idle"};case"outbound-offer-prepared":case"outbound-offer-dispatched":{const i=Yt(e,"snapshot.phase",["kind","offer","secretKey"]),a=or(Ht(i.offer,"snapshot.phase.offer",tr(t)),t,r),o=Ht(i.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes);return{kind:"outbound-offer",dispatched:"outbound-offer-dispatched"===n,offer:a,keyPair:dr(a.publicKey,o)}}case"inbound-offer":{const n=Yt(e,"snapshot.phase",["kind","offer"]);return{kind:"inbound-offer",offer:or(Ht(n.offer,"snapshot.phase.offer",tr(t)),t,r)}}case"outbound-advance-prepared":{const n=Yt(e,"snapshot.phase",["kind","advance","nextRoot"]),i=sr(Ht(n.advance,"snapshot.phase.advance",rr(t)),t,r);return{kind:"outbound-advance-prepared",offer:i.offer,advance:i,nextRoot:Uint8Array.from(Ht(n.nextRoot,"snapshot.phase.nextRoot",Ft))}}case"outbound-advance-awaiting-ack":{const n=Yt(e,"snapshot.phase",["kind","advance"]),i=sr(Ht(n.advance,"snapshot.phase.advance",rr(t)),t,r);return{kind:"outbound-advance-awaiting-ack",offer:i.offer,advance:i}}case"inbound-advance-prepared":{const n=Yt(e,"snapshot.phase",["kind","advance","secretKey","nextRoot"]),i=sr(Ht(n.advance,"snapshot.phase.advance",rr(t)),t,r),a=Ht(n.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes),o=Uint8Array.from(Ht(n.nextRoot,"snapshot.phase.nextRoot",Ft));return{kind:"inbound-advance-prepared",offer:i.offer,advance:i,keyPair:dr(i.offer.publicKey,a),nextRoot:o}}case"inbound-advance-awaiting-ack-dispatch":{const n=Yt(e,"snapshot.phase",["kind","advance"]);return{kind:"inbound-advance-awaiting-ack-dispatch",advance:sr(Ht(n.advance,"snapshot.phase.advance",rr(t)),t,r)}}default:return $t("invalid-record","snapshot phase is unknown")}},yr=(e,t)=>{e||$t("invalid-record",`snapshot ${t}`)},pr=(e,t)=>{er(t.suite,t.backend.suite),Ht(t.binding,"binding",Nt);const r=Yt(e,"snapshot",["formatVersion","parameterSet","binding","rootKey","epoch","localCounter","remoteCounter","nextOfferer","phase","lastInboundOffer","lastInboundAdvance"]);1!==r.formatVersion&&$t("invalid-record","snapshot format version is unsupported"),r.parameterSet!==t.suite.parameterSet&&$t("suite-mismatch","snapshot suite differs from the authenticated room suite");const n=Ht(r.binding,"snapshot.binding",Nt);Wt(n,t.binding)||$t("binding-mismatch","snapshot belongs to a different authenticated edge");const i=Ht(r.rootKey,"snapshot.rootKey",Ft),a=ur(r.epoch,"snapshot.epoch"),o=ur(r.localCounter,"snapshot.localCounter"),s=ur(r.remoteCounter,"snapshot.remoteCounter");if("local"!==r.nextOfferer&&"remote"!==r.nextOfferer)return $t("invalid-record","snapshot.nextOfferer must be local or remote");const c=Uint8Array.from(i);let l;try{l=fr(r.phase,t.suite,t.binding);const e=null===r.lastInboundOffer?null:or(Ht(r.lastInboundOffer,"snapshot.lastInboundOffer",tr(t.suite)),t.suite,t.binding),n=null===r.lastInboundAdvance?null:sr(Ht(r.lastInboundAdvance,"snapshot.lastInboundAdvance",rr(t.suite)),t.suite,t.binding),i={rootKey:c,epoch:a,localCounter:o,remoteCounter:s,nextOfferer:r.nextOfferer,phase:l,lastInboundOffer:e,lastInboundAdvance:n};return(e=>{const{epoch:t,localCounter:r,remoteCounter:n,nextOfferer:i,phase:a,lastInboundOffer:o,lastInboundAdvance:s}=e;switch(null!==o&&(yr(o.toEpoch<=t,"last inbound OFFER is from a future epoch"),yr(o.senderCounter<n,"last inbound OFFER counter was not consumed")),null!==s&&(yr(s.toEpoch<=t,"last inbound ADVANCE is from a future epoch"),yr(s.senderCounter<n,"last inbound ADVANCE counter was not consumed")),a.kind){case"idle":return;case"outbound-offer":return void yr("local"===i&&a.offer.senderCounter===r&&a.offer.fromEpoch===t,"outbound OFFER does not match the current turn/counter/epoch");case"inbound-offer":return void yr("remote"===i&&a.offer.senderCounter===n&&a.offer.fromEpoch===t,"inbound OFFER does not match the current turn/counter/epoch");case"outbound-advance-prepared":return void yr("remote"===i&&a.advance.senderCounter===r&&a.offer.senderCounter===n&&a.advance.fromEpoch===t,"prepared outbound ADVANCE does not match current state");case"outbound-advance-awaiting-ack":return yr("local"===i&&a.advance.senderCounter+1n===r&&a.offer.senderCounter+1n===n&&a.advance.toEpoch===t,"outbound ADVANCE awaiting ACK does not match committed state"),void yr(null!==o&&Wt(o.bytes,a.offer.bytes),"outbound ADVANCE is missing its exact inbound OFFER replay record");case"inbound-advance-prepared":return void yr("local"===i&&a.advance.senderCounter===n&&a.offer.senderCounter===r&&a.advance.fromEpoch===t,"prepared inbound ADVANCE does not match current state");case"inbound-advance-awaiting-ack-dispatch":yr("remote"===i&&a.advance.senderCounter+1n===n&&a.advance.offer.senderCounter+1n===r&&a.advance.toEpoch===t,"inbound ADVANCE awaiting ACK dispatch does not match committed state"),yr(null!==s&&Wt(s.bytes,a.advance.bytes),"pending ACK is missing its exact inbound ADVANCE replay record")}})(i),i}catch(e){throw c.fill(0),void 0!==l&&("outbound-offer"===l.kind&&l.keyPair.destroy(),"outbound-advance-prepared"===l.kind&&l.nextRoot.fill(0),"inbound-advance-prepared"===l.kind&&(l.keyPair.destroy(),l.nextRoot.fill(0))),e}};class mr{#e;#r;#n;#i;#a;#o;#s;#c;#l;#d={kind:"idle"};#h=null;#u=null;#f=!1;#y=!1;constructor(e){er(e.suite,e.backend.suite),Ht(e.binding,"binding",Nt),Ht(e.rootKey,"PQ root",Ft);const t=e.nextOfferer;"local"!==t&&"remote"!==t&&$t("invalid-state","nextOfferer must be local or remote");const r=e.epoch??0n,n=e.localCounter??0n,i=e.remoteCounter??0n;zt(r,"epoch"),zt(n,"local counter"),zt(i,"remote counter"),this.#e=e.module,this.#r=e.backend,this.#n=e.suite,this.#i=Uint8Array.from(e.binding),this.#a=Uint8Array.from(e.rootKey),this.#o=r,this.#s=n,this.#c=i,this.#l=e.nextOfferer}static restore(e,t){const r=pr(e,t);try{const e=new mr({...t,rootKey:r.rootKey,epoch:r.epoch,localCounter:r.localCounter,remoteCounter:r.remoteCounter,nextOfferer:r.nextOfferer});return e.#d=r.phase,e.#h=r.lastInboundOffer,e.#u=r.lastInboundAdvance,r.rootKey.fill(0),e}catch(e){throw r.rootKey.fill(0),"outbound-offer"===r.phase.kind&&r.phase.keyPair.destroy(),"outbound-advance-prepared"===r.phase.kind&&r.phase.nextRoot.fill(0),"inbound-advance-prepared"===r.phase.kind&&(r.phase.keyPair.destroy(),r.phase.nextRoot.fill(0)),e}}get suite(){return this.#n}get phase(){return this.#y?"destroyed":(e=>{switch(e.kind){case"idle":return"idle";case"outbound-offer":return e.dispatched?"outbound-offer-dispatched":"outbound-offer-prepared";case"inbound-offer":return"inbound-offer";case"outbound-advance-prepared":return"outbound-advance-prepared";case"outbound-advance-awaiting-ack":return"outbound-advance-awaiting-ack";case"inbound-advance-prepared":return"inbound-advance-prepared";case"inbound-advance-awaiting-ack-dispatch":return"inbound-advance-awaiting-ack-dispatch"}})(this.#d)}get epoch(){return this.#p(),this.#o}get localCounter(){return this.#p(),this.#s}get remoteCounter(){return this.#p(),this.#c}get nextOfferer(){return this.#p(),this.#l}get trafficBlocked(){return this.#y||"idle"!==this.#d.kind}copyRootKey(){return this.#p(),Uint8Array.from(this.#a)}snapshot(){return this.#m(),{formatVersion:1,parameterSet:this.#n.parameterSet,binding:Uint8Array.from(this.#i),rootKey:Uint8Array.from(this.#a),epoch:this.#o,localCounter:this.#s,remoteCounter:this.#c,nextOfferer:this.#l,phase:hr(this.#d),lastInboundOffer:null===this.#h?null:Uint8Array.from(this.#h.bytes),lastInboundAdvance:null===this.#u?null:Uint8Array.from(this.#u.bytes)}}clone(){const e=this.snapshot();try{return mr.restore(e,{module:this.#e,backend:this.#r,suite:this.#n,binding:this.#i})}finally{br(e)}}adopt(e){this.#m(),e.#m(),e===this&&$t("invalid-state","cannot adopt a machine into itself"),this.#n.parameterSet===e.#n.parameterSet&&Wt(this.#i,e.#i)||$t("invalid-state","cannot adopt a machine from another suite or authenticated edge"),this.#b(this.#d),this.#a.fill(0),this.#a=e.#a,this.#o=e.#o,this.#s=e.#s,this.#c=e.#c,this.#l=e.#l,this.#d=e.#d,this.#h=e.#h,this.#u=e.#u,e.#a=new Uint8Array(Ft),e.#i.fill(0),e.#d={kind:"idle"},e.#h=null,e.#u=null,e.#y=!0}copyPendingOutboundRecord(){this.#m();const e=this.#d;return"outbound-offer"===e.kind?Uint8Array.from(e.offer.bytes):"outbound-advance-prepared"===e.kind||"outbound-advance-awaiting-ack"===e.kind?Uint8Array.from(e.advance.bytes):$t("invalid-state","there is no pending outbound record")}async prepareOffer(){let e;this.#g();try{"idle"!==this.#d.kind&&$t("invalid-state","cannot prepare an OFFER while another transition is pending"),"local"!==this.#l&&$t("wrong-turn","the remote peer owns the next OFFER turn"),this.#w(),e=await this.#r.generateKeyPair(),this.#p(),Ht(e.publicKey,"ML-KEM public key",this.#n.publicKeyBytes),Ht(e.secretKey,"ML-KEM secret key",this.#n.secretKeyBytes);const t=((e,t,r,n,i)=>{Ht(i,"ML-KEM public key",e.publicKeyBytes);const a=ir(1,e,t,r,n,n+1n,tr(e));return a.set(i,Lt),a})(this.#n,this.#i,this.#s,this.#o,e.publicKey),r=or(t,this.#n,this.#i);return this.#d={kind:"outbound-offer",dispatched:!1,offer:r,keyPair:e},e=void 0,Uint8Array.from(t)}finally{e?.destroy(),this.#v()}}markOfferDispatched(){this.#m();const e=this.#d;if("outbound-offer"!==e.kind)return $t("invalid-state","there is no outbound OFFER to dispatch");e.dispatched&&$t("invalid-state","outbound OFFER was already marked dispatched"),this.#d={...e,dispatched:!0}}abortUnsentOffer(){this.#m();const e=this.#d;if("outbound-offer"!==e.kind||e.dispatched)return $t("invalid-state","only an undispatched OFFER can be aborted");e.keyPair.destroy(),this.#d={kind:"idle"}}acceptAuthenticatedOffer(e){this.#m();const t=or(e,this.#n,this.#i);this.#A(t),"idle"!==this.#d.kind&&$t("invalid-state","another PQ healing transition is pending"),"remote"!==this.#l&&$t("wrong-turn","the local peer owns the next OFFER turn"),this.#k(t.senderCounter),this.#E(t.fromEpoch),this.#w(),this.#d={kind:"inbound-offer",offer:t}}async prepareAdvance(){let e;this.#g();try{const t=this.#d;if("inbound-offer"!==t.kind)return $t("invalid-state","an authenticated inbound OFFER is required");Qt(this.#s,"local counter"),e=await this.#r.encapsulate(t.offer.publicKey),this.#p(),Ht(e.ciphertext,"ML-KEM ciphertext",this.#n.ciphertextBytes),Ht(e.sharedSecret,"ML-KEM shared secret",this.#n.sharedSecretBytes);const r=((e,t,r,n,i)=>{Ht(i,"ML-KEM ciphertext",e.ciphertextBytes);const a=ir(2,e,t,r,n.fromEpoch,n.toEpoch,rr(e));return a.set(n.bytes,Lt),a.set(i,Lt+n.bytes.length),a})(this.#n,this.#i,this.#s,t.offer,e.ciphertext),n=sr(r,this.#n,this.#i),i=lr(this.#a,e.sharedSecret,r,this.#e);return this.#d={kind:"outbound-advance-prepared",offer:t.offer,advance:n,nextRoot:i},Uint8Array.from(r)}finally{e?.destroy(),this.#v()}}commitPreparedAdvance(){this.#m();const e=this.#d;return"outbound-advance-prepared"!==e.kind?$t("invalid-state","there is no prepared outbound ADVANCE"):(this.#K(e.nextRoot),this.#o=e.advance.toEpoch,this.#s+=1n,this.#c+=1n,this.#l="local",this.#h=e.offer,this.#d={kind:"outbound-advance-awaiting-ack",offer:e.offer,advance:e.advance},Uint8Array.from(e.advance.bytes))}acceptAuthenticatedAdvanceAcknowledgement(e){this.#m();const t=jt(e),r=this.#d;if("outbound-advance-awaiting-ack"!==r.kind)return $t("invalid-state","no outbound ADVANCE is awaiting acknowledgement");t.epoch===this.#o&&t.advanceCounter===r.advance.senderCounter||$t("invalid-record","advance acknowledgement does not bind the pending transition"),this.#d={kind:"idle"}}async acceptAuthenticatedAdvance(e){let t;this.#g();try{const r=sr(e,this.#n,this.#i);this.#_(r);const n=this.#d;if("outbound-offer"!==n.kind||!n.dispatched)return $t("invalid-state","a dispatched outbound OFFER is required before ADVANCE");this.#k(r.senderCounter),this.#E(r.fromEpoch),Wt(r.offer.bytes,n.offer.bytes)||$t("fork","ADVANCE answers a different OFFER"),t=await this.#r.decapsulate(r.ciphertext,n.keyPair.secretKey),this.#p(),Ht(t.sharedSecret,"ML-KEM shared secret",this.#n.sharedSecretBytes);const i=lr(this.#a,t.sharedSecret,r.bytes,this.#e);this.#d={kind:"inbound-advance-prepared",offer:n.offer,advance:r,keyPair:n.keyPair,nextRoot:i}}finally{t?.destroy(),this.#v()}}commitAcceptedAdvance(){this.#m();const e=this.#d;return"inbound-advance-prepared"!==e.kind?$t("invalid-state","there is no accepted ADVANCE to commit"):(e.keyPair.destroy(),this.#K(e.nextRoot),this.#o=e.advance.toEpoch,this.#s+=1n,this.#c+=1n,this.#l="remote",this.#u=e.advance,this.#d={kind:"inbound-advance-awaiting-ack-dispatch",advance:e.advance},{epoch:this.#o,advanceCounter:e.advance.senderCounter})}markAdvanceAcknowledgementDispatched(e){this.#m();const t=jt(e),r=this.#d;if("inbound-advance-awaiting-ack-dispatch"!==r.kind)return $t("invalid-state","no advance acknowledgement is pending dispatch");t.epoch===this.#o&&t.advanceCounter===r.advance.senderCounter||$t("invalid-record","advance acknowledgement does not bind the committed transition"),this.#d={kind:"idle"}}destroy(){this.#y||(this.#b(this.#d),this.#a.fill(0),this.#i.fill(0),this.#h=null,this.#u=null,this.#d={kind:"idle"},this.#y=!0)}#p(){this.#y&&$t("destroyed","state machine is destroyed")}#m(){this.#p(),this.#f&&$t("invalid-state","another asynchronous transition is in flight")}#g(){this.#m(),this.#f=!0}#v(){this.#f=!1}#w(){Qt(this.#o,"epoch"),Qt(this.#s,"local counter"),Qt(this.#c,"remote counter")}#k(e){e<this.#c&&$t("replay","record sender counter was already consumed"),e>this.#c&&$t("counter-gap","record sender counter skips an expected transition")}#E(e){e<this.#o&&$t("replay","record PQ epoch was already consumed"),e>this.#o&&$t("epoch-gap","record skips the current PQ epoch")}#A(e){let t=this.#h;const r=this.#d;var n,i;("inbound-offer"!==r.kind&&"outbound-advance-prepared"!==r.kind&&"outbound-advance-awaiting-ack"!==r.kind||(t=r.offer),null!==t&&(i=t,(n=e).senderCounter===i.senderCounter&&n.fromEpoch===i.fromEpoch&&n.toEpoch===i.toEpoch))&&(Wt(e.bytes,t.bytes)&&$t("replay","OFFER is an exact replay"),$t("fork","different OFFER bytes reuse an authenticated slot"))}#_(e){let t=this.#u;const r=this.#d;var n,i;("inbound-advance-prepared"!==r.kind&&"inbound-advance-awaiting-ack-dispatch"!==r.kind||(t=r.advance),null!==t&&(i=t,(n=e).senderCounter===i.senderCounter&&n.fromEpoch===i.fromEpoch&&n.toEpoch===i.toEpoch))&&(Wt(e.bytes,t.bytes)&&$t("replay","ADVANCE is an exact replay"),$t("fork","different ADVANCE bytes reuse an authenticated slot"))}#K(e){Ht(e,"candidate PQ root",Ft),this.#a.fill(0),this.#a=e}#b(e){"outbound-offer"===e.kind&&e.keyPair.destroy(),"outbound-advance-prepared"===e.kind&&e.nextRoot.fill(0),"inbound-advance-prepared"===e.kind&&(e.keyPair.destroy(),e.nextRoot.fill(0))}}const br=e=>{e.binding.fill(0),e.rootKey.fill(0),e.lastInboundOffer?.fill(0),e.lastInboundAdvance?.fill(0);const t=e.phase;switch(t.kind){case"idle":return;case"outbound-offer-prepared":case"outbound-offer-dispatched":return t.offer.fill(0),void t.secretKey.fill(0);case"inbound-offer":return void t.offer.fill(0);case"outbound-advance-prepared":return t.advance.fill(0),void t.nextRoot.fill(0);case"outbound-advance-awaiting-ack":case"inbound-advance-awaiting-ack-dispatch":return void t.advance.fill(0);case"inbound-advance-prepared":return t.advance.fill(0),t.secretKey.fill(0),void t.nextRoot.fill(0)}},gr=z-69-k,wr=(1n<<64n)-1n,vr=(new TextEncoder).encode("p2party/pq-control-frame/key/v1\0");class Ar extends Error{code;constructor(e,t){super(`pqHealingFrame: ${t}`),this.name="PqControlFrameError",this.code=e}}const kr=(e,t)=>{throw new Ar(e,t)},Er=(e,t)=>{if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n+=1)r|=e[n]^t[n];return 0===r},Kr=(e,t,r)=>e instanceof Uint8Array?(void 0!==r&&e.length!==r&&kr("invalid-frame",`${t} must be exactly ${String(r)} bytes`),e):kr("invalid-frame",`${t} must be a Uint8Array`),_r=(e,t)=>"bigint"!=typeof e||e<0n||e>wr?kr("invalid-frame",`${t} must be an unsigned 64-bit bigint`):e,Ur=(e,t,r,n,i,a)=>{Kr(r,"PQ root",Ft),Kr(n,"binding",Nt);const o=(e=>{const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,e,!1),t})(_r(a,"keyEpoch")),s=new Uint8Array(vr.length+1+1+n.length+o.length);s.set(vr,0),s[vr.length]=(e=>{const t=De(e.parameterSet);return e.standardName!==t.standardName||e.publicKeyBytes!==t.publicKeyBytes||e.secretKeyBytes!==t.secretKeyBytes||e.ciphertextBytes!==t.ciphertextBytes||e.sharedSecretBytes!==t.sharedSecretBytes||e.keyPairRandomBytes!==t.keyPairRandomBytes||e.encapsRandomBytes!==t.encapsRandomBytes?kr("invalid-frame","ML-KEM suite descriptor is not canonical"):768===e.parameterSet?1:512===e.parameterSet?2:1024===e.parameterSet?3:kr("invalid-frame","ML-KEM suite is unsupported")})(t),s[vr.length+1]=(e=>"initiator-to-responder"===e?1:"responder-to-initiator"===e?2:kr("invalid-direction","control direction is unknown"))(i),s.set(n,vr.length+2),s.set(o,vr.length+2+n.length);const c=re(r,n,e);try{return ne(c,s,v,e)}finally{c.fill(0),o.fill(0)}},xr=(e,t,r)=>{if(Kr(e,"control record"),64===e.length){const n=nr(e,t,r);return{counter:n.advanceCounter,keyEpoch:n.epoch}}const n=cr(e,t);return Er(n.binding,r)?{counter:n.senderCounter,keyEpoch:n.fromEpoch}:kr("binding-mismatch","control record belongs to another authenticated edge")},Sr=e=>{const t=Kr(e.binding,"binding",Nt),r=_r(e.keyEpoch,"keyEpoch"),n=xr(e.record,e.suite,t);n.keyEpoch!==r&&kr("epoch-mismatch","control record is not authenticated under its required epoch"),e.record.length>gr-4&&kr("invalid-frame","control record does not fit the uniform cell");const i=(()=>{const e=new Uint8Array(A);return crypto.getRandomValues(e),e})(),a=new Uint8Array(69);a[0]=5,a.set(t,1);const o=new DataView(a.buffer,a.byteOffset,a.byteLength);o.setBigUint64(33,n.counter,!1),o.setBigUint64(49,r,!1),a.set(i,57);const s=new Uint8Array(gr);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e.record.length,!1),s.set(e.record,4);const c=Ur(e.module,e.suite,e.rootKey,t,e.direction,r);try{const t=((e,t,r,n,i)=>{const a=n.length+k,o=e._malloc(t.length),s=e._malloc(r.length),c=e._malloc(n.length),l=e._malloc(i.length),d=e._malloc(a);try{return new Uint8Array(e.wasmMemory.buffer,o,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,c,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,l,i.length).set(i),0!==e._encrypt_chachapoly_symmetric(d,c,n.length,o,s,l,i.length)?kr("invalid-frame","control-frame AEAD encryption failed"):Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,d,a))}finally{I(e,new Uint8Array(e.wasmMemory.buffer,o,t.length)),e._free(s),I(e,new Uint8Array(e.wasmMemory.buffer,c,n.length)),e._free(l),I(e,new Uint8Array(e.wasmMemory.buffer,d,a))}})(e.module,c,i,s,a),r=new Uint8Array(z);return r.set(a,0),r.set(t,69),r}finally{c.fill(0),s.fill(0)}},Mr=e=>{const t=Kr(e.frame,"control frame",z),r=Kr(e.binding,"binding",Nt),n=_r(e.keyEpoch,"keyEpoch");5!==t[0]&&kr("invalid-frame","frame type is not PQ control"),Er(t.subarray(1,33),r)||kr("binding-mismatch","control frame belongs to another edge");const i=t.subarray(0,69),a=new DataView(t.buffer,t.byteOffset,t.byteLength),o=a.getBigUint64(33,!1);0n!==a.getBigUint64(41,!1)&&kr("invalid-frame","control-frame reserved header must be zero"),a.getBigUint64(49,!1)!==n&&kr("epoch-mismatch","control-frame epoch is not the expected epoch");const s=t.subarray(57,69),c=t.subarray(69),l=Ur(e.module,e.suite,e.rootKey,r,e.direction,n);let d;try{d=((e,t,r,n,i)=>{const a=n.length-k,o=e._malloc(t.length),s=e._malloc(r.length),c=e._malloc(n.length),l=e._malloc(i.length),d=e._malloc(a);try{new Uint8Array(e.wasmMemory.buffer,o,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,c,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,l,i.length).set(i);const h=new Uint8Array(e.wasmMemory.buffer,d,a);return h.fill(0),0!==e._decrypt_chachapoly_symmetric(d,c,n.length,o,s,l,i.length)?kr("authentication-failed","control-frame authentication failed"):Uint8Array.from(h)}finally{I(e,new Uint8Array(e.wasmMemory.buffer,o,t.length)),e._free(s),e._free(c),e._free(l),I(e,new Uint8Array(e.wasmMemory.buffer,d,a))}})(e.module,l,s,c,i);const t=new DataView(d.buffer,d.byteOffset,d.byteLength).getUint32(0,!1);(0===t||t>gr-4)&&kr("invalid-padding","encrypted control-record length is invalid");const a=4+t;let h=0;for(let e=a;e<d.length;e+=1)h|=d[e];0!==h&&kr("invalid-padding","encrypted control padding must be all zero");const u=d.slice(4,a),f=xr(u,e.suite,r);return f.keyEpoch!==n&&kr("epoch-mismatch","decrypted control record does not match its frame epoch"),f.counter!==o&&kr("record-mismatch","decrypted control counter does not match its public header"),u}finally{l.fill(0),d?.fill(0)}},Cr=new Uint8Array([80,50,69,68,71,69,52,0]),Pr=(1n<<64n)-1n,Rr=262144,Or=Math.min(Z,256),Br=/^[0-9a-f]{64}:[0-9]+:[0-9]+$/,Ir=new TextEncoder,Nr=new TextDecoder("utf-8",{fatal:!0}),Fr=e=>{throw new Error(`pqHealingRuntime: ${e}`)},Lr=(e,t)=>{if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n+=1)r|=e[n]^t[n];return 0===r},Tr=(e,t,r)=>e instanceof Uint8Array?(void 0!==r&&e.length!==r&&Fr(`${t} must be exactly ${String(r)} bytes`),e):Fr(`${t} must be a Uint8Array`),Dr=(e,t)=>"number"!=typeof e||!Number.isSafeInteger(e)||e<0?Fr(`${t} must be a non-negative safe integer`):e,qr=e=>1===e?"local":2===e?"remote":Fr("checkpoint has an invalid next-offerer turn");class Vr{#U=[];#x=0;bytes(e){const t=Uint8Array.from(e);this.#U.push(t),this.#x+=t.length,this.#x>Rr&&Fr("checkpoint exceeds the encrypted edge-state budget")}u8(e){(!Number.isInteger(e)||e<0||e>255)&&Fr("u8 value is out of range"),this.bytes(Uint8Array.of(e))}u16(e){(!Number.isInteger(e)||e<0||e>65535)&&Fr("u16 value is out of range");const t=new Uint8Array(2);new DataView(t.buffer).setUint16(0,e,!1),this.bytes(t),t.fill(0)}u32(e){(!Number.isInteger(e)||e<0||e>4294967295)&&Fr("u32 value is out of range");const t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,e,!1),this.bytes(t),t.fill(0)}u64(e){((e,t)=>{("bigint"!=typeof e||e<0n||e>Pr)&&Fr(`${t} must be an unsigned 64-bit bigint`)})(e,"checkpoint counter");const t=new Uint8Array(8);new DataView(t.buffer).setBigUint64(0,e,!1),this.bytes(t),t.fill(0)}sized(e){null!==e?(0===e.length&&Fr("present checkpoint byte strings must not be empty"),this.u32(e.length),this.bytes(e)):this.u32(0)}finish(){const e=new Uint8Array(this.#x);let t=0;try{for(const r of this.#U)e.set(r,t),t+=r.length;return e}finally{for(const e of this.#U)e.fill(0);this.#U.length=0,this.#x=0}}}class $r{#S;#M=0;constructor(e){(0===e.length||e.length>Rr)&&Fr("checkpoint length is invalid"),this.#S=Uint8Array.from(e)}take(e){if(!Number.isSafeInteger(e)||e<0||this.#M+e>this.#S.length)return Fr("checkpoint is truncated");const t=this.#S.slice(this.#M,this.#M+e);return this.#M+=e,t}u8(){const e=this.take(1),t=e[0];return e.fill(0),t}u16(){const e=this.take(2),t=new DataView(e.buffer).getUint16(0,!1);return e.fill(0),t}u32(){const e=this.take(4),t=new DataView(e.buffer).getUint32(0,!1);return e.fill(0),t}u64(){const e=this.take(8),t=new DataView(e.buffer).getBigUint64(0,!1);return e.fill(0),t}sized(e){const t=this.u32();return 0===t?null:t>e?Fr("checkpoint field exceeds its budget"):this.take(t)}finish(){this.#M!==this.#S.length&&Fr("checkpoint contains trailing bytes")}destroy(){this.#S.fill(0),this.#M=this.#S.length}}const Hr=(e,t,r)=>e.sized(t)??Fr(`${r} is missing`),zr=(e,t)=>{const r=64+t.publicKeyBytes,n=64+r+t.ciphertextBytes;switch(e.u8()){case 0:return{kind:"idle"};case 1:return{kind:"outbound-offer-prepared",offer:Hr(e,r,"prepared OFFER"),secretKey:Hr(e,t.secretKeyBytes,"prepared OFFER secret key")};case 2:return{kind:"outbound-offer-dispatched",offer:Hr(e,r,"dispatched OFFER"),secretKey:Hr(e,t.secretKeyBytes,"dispatched OFFER secret key")};case 3:return{kind:"inbound-offer",offer:Hr(e,r,"inbound OFFER")};case 4:return{kind:"outbound-advance-prepared",advance:Hr(e,n,"prepared ADVANCE"),nextRoot:Hr(e,32,"candidate PQ root")};case 5:return{kind:"outbound-advance-awaiting-ack",advance:Hr(e,n,"outbound ADVANCE")};case 6:return{kind:"inbound-advance-prepared",advance:Hr(e,n,"inbound ADVANCE"),secretKey:Hr(e,t.secretKeyBytes,"inbound ADVANCE secret key"),nextRoot:Hr(e,32,"candidate PQ root")};case 7:return{kind:"inbound-advance-awaiting-ack-dispatch",advance:Hr(e,n,"acknowledged ADVANCE")};default:return Fr("checkpoint has an unknown PQ phase")}},Qr=e=>{for(const t of e.values())t.fill(0);e.clear()};class jr{#e;#C;#P;#n;#r;#i;#R;#O;#B;#I;#N=null;#F=null;#L=null;#T=null;#D=new Map;#q=0;#V;#y=!1;constructor(e){const t=Ye(e.pqMode);We(e.pqMode)!==e.rootSuite&&Fr("authenticated root suite and room PQ mode disagree"),Tr(e.binding,"edge binding",32),Tr(e.rootKey,"PQ root",32),this.#e=e.module,this.#C=e.pqMode,this.#P=e.rootSuite,this.#n=De(t),this.#r=je(e.module,this.#n),this.#i=Uint8Array.from(e.binding),this.#B=new mr({module:e.module,backend:this.#r,suite:this.#n,binding:this.#i,rootKey:e.rootKey,nextOfferer:e.nextOfferer}),this.#I=this.#B.copyRootKey(),this.#V=Dr(e.now??Date.now(),"initial healing time"),this.#R=e.amInitiator?"initiator-to-responder":"responder-to-initiator",this.#O=e.amInitiator?"responder-to-initiator":"initiator-to-responder"}get pqMode(){return this.#C}get rootSuite(){return this.#P}get epoch(){return this.#$(),this.#B.epoch}get phase(){return this.#B.phase}get trafficBlocked(){return this.#y||this.#B.trafficBlocked}get nextOfferer(){return this.#B.nextOfferer}get activeReceiveKeys(){return this.#$(),this.#D}get messagesSinceHealing(){return this.#$(),this.#q}get lastHealedAt(){return this.#$(),this.#V}currentMessageContext(){return this.#$(),{rootKey:this.#I,binding:this.#i,rootSuite:this.#P,epoch:this.#B.epoch}}resolveMessageContext(e){return this.#$(),e===this.#B.epoch?this.currentMessageContext():null}noteApplicationMessage(){this.#$(),this.#q>=Number.MAX_SAFE_INTEGER&&Fr("application-message counter overflow"),this.#q+=1}healingDue(e=Date.now()){return this.#$(),Dr(e,"healing clock"),!this.#B.trafficBlocked&&"local"===this.#B.nextOfferer&&(this.#q>=64||e-this.#V>=864e5)}copyPendingFrame(){return this.#$(),this.#N?Uint8Array.from(this.#N.frame):null}get pendingRetryAt(){return this.#$(),this.#N?.nextRetryAt??null}get pendingAttempts(){return this.#$(),this.#N?.attempts??0}markPendingDispatched(e=Date.now()){this.#$();const t=this.#N;if(!t)return Fr("there is no PQ control outbox");Dr(e,"dispatch clock"),t.attempts>=8&&Fr("PQ control retry budget is exhausted"),this.#N={kind:t.kind,frame:t.frame,attempts:t.attempts+1,nextRetryAt:e+5e3}}async prepareHealingOffer(e=Date.now()){this.#$(),this.healingDue(e)||Fr("a local sparse-PQ healing exchange is not due");const t=await this.#B.prepareOffer(),r=this.#B.copyRootKey();try{const n=Sr({module:this.#e,suite:this.#n,rootKey:r,binding:this.#i,direction:this.#R,keyEpoch:this.#B.epoch,record:t});return this.#B.markOfferDispatched(),this.#N?.frame.fill(0),this.#N={kind:"offer",frame:Uint8Array.from(n),attempts:0,nextRetryAt:e},this.#H(),n}finally{r.fill(0),t.fill(0)}}async acceptControlFrame(e,t=Date.now()){if(this.#$(),Tr(e,"PQ control frame",z),Dr(t,"control clock"),this.#F&&"advance"===this.#N?.kind&&Lr(e,this.#F))return{dispatch:Uint8Array.from(this.#N.frame),changed:!1};if(this.#L&&this.#T&&Lr(e,this.#L))return{dispatch:Uint8Array.from(this.#T),changed:!1};const r=this.#B.copyRootKey();let n=null;try{if(n=Mr({module:this.#e,suite:this.#n,rootKey:r,binding:this.#i,direction:this.#O,keyEpoch:this.#B.epoch,frame:e}),64===n.length){const e=this.#N;if("advance"!==e?.kind)return Fr("unexpected PQ ADVANCE acknowledgement");const r=nr(n,this.#n,this.#i);return this.#B.acceptAuthenticatedAdvanceAcknowledgement(r),e.frame.fill(0),this.#N=null,this.#H(),this.#q=0,this.#V=t,this.#z(),{dispatch:null,changed:!0}}if("offer"===cr(n,this.#n).type){this.#B.acceptAuthenticatedOffer(n);const i=await this.#B.prepareAdvance();let a;try{a=Sr({module:this.#e,suite:this.#n,rootKey:r,binding:this.#i,direction:this.#R,keyEpoch:this.#B.epoch,record:i}),this.#B.commitPreparedAdvance()}finally{i.fill(0)}return this.#N?.frame.fill(0),this.#N={kind:"advance",frame:Uint8Array.from(a),attempts:0,nextRetryAt:t},this.#F?.fill(0),this.#F=Uint8Array.from(e),this.#L?.fill(0),this.#L=null,this.#T?.fill(0),this.#T=null,this.#z(),{dispatch:a,changed:!0}}const i=this.#N;if("offer"!==i?.kind)return Fr("unexpected PQ ADVANCE without a persisted OFFER");await this.#B.acceptAuthenticatedAdvance(n);const a=this.#B.commitAcceptedAdvance(),o=((e,t,r)=>{Jt(t),Ht(r,"binding",Nt);const n=jt(e),i=new Uint8Array(64);i.set(Tt,0),i[4]=1,i[5]=3,i[6]=Xt(t.parameterSet),i[7]=0,i.set(r,8);const a=new DataView(i.buffer,i.byteOffset,i.byteLength);return a.setBigUint64(40,n.advanceCounter,!1),a.setBigUint64(48,n.epoch,!1),i})(a,this.#n,this.#i),s=this.#B.copyRootKey();try{const r=Sr({module:this.#e,suite:this.#n,rootKey:s,binding:this.#i,direction:this.#R,keyEpoch:a.epoch,record:o});return this.#B.markAdvanceAcknowledgementDispatched(a),i.frame.fill(0),this.#N=null,this.#L?.fill(0),this.#L=Uint8Array.from(e),this.#T?.fill(0),this.#T=Uint8Array.from(r),this.#F?.fill(0),this.#F=null,this.#q=0,this.#V=t,this.#z(),{dispatch:r,changed:!0}}finally{s.fill(0),o.fill(0)}}finally{r.fill(0),n?.fill(0)}}clone(){this.#$();const e=this.#B.copyRootKey();let t=null;try{return t=new jr({module:this.#e,pqMode:this.#C,rootSuite:this.#P,binding:this.#i,rootKey:e,nextOfferer:this.#B.nextOfferer,amInitiator:"initiator-to-responder"===this.#R,now:this.#V}),t.#B.destroy(),t.#B=this.#B.clone(),t.#I.fill(0),t.#I=Uint8Array.from(this.#I),t.#N=null===(r=this.#N)?null:{kind:r.kind,frame:Uint8Array.from(r.frame),attempts:r.attempts,nextRetryAt:r.nextRetryAt},t.#F=null===this.#F?null:Uint8Array.from(this.#F),t.#L=null===this.#L?null:Uint8Array.from(this.#L),t.#T=null===this.#T?null:Uint8Array.from(this.#T),t.#D=(e=>{const t=new Map;for(const[r,n]of e)t.set(r,Uint8Array.from(n));return t})(this.#D),t.#q=this.#q,t.#V=this.#V,t}catch(e){throw t?.destroy(),e}finally{e.fill(0)}var r}adopt(e){this.#$(),e.#$(),e===this&&Fr("cannot adopt a PQ runtime into itself"),e.#e===this.#e&&e.#C===this.#C&&e.#P===this.#P&&e.#R===this.#R&&Lr(e.#i,this.#i)||Fr("cannot adopt a PQ runtime from another authenticated edge"),this.#B.destroy(),this.#I.fill(0),this.#N?.frame.fill(0),this.#F?.fill(0),this.#L?.fill(0),this.#T?.fill(0),Qr(this.#D),this.#B=e.#B,this.#I=e.#I,this.#N=e.#N,this.#F=e.#F,this.#L=e.#L,this.#T=e.#T,this.#D=e.#D,this.#q=e.#q,this.#V=e.#V,e.#I=new Uint8Array(32),e.#N=null,e.#F=null,e.#L=null,e.#T=null,e.#D=new Map,e.#i.fill(0),e.#y=!0}serialize(e=this.#D){this.#$();const t=this.#B.snapshot(),r=new Vr;try{return r.bytes(Cr),r.u8(1),r.u8(512===(i=this.#n.parameterSet)?1:768===i?2:1024===i?3:Fr("unsupported ML-KEM suite")),r.u8("initiator-to-responder"===this.#R?1:2),r.u8(0),r.u64(BigInt(this.#V)),r.u64(BigInt(this.#q)),r.bytes(t.binding),r.bytes(t.rootKey),r.u64(t.epoch),r.u64(t.localCounter),r.u64(t.remoteCounter),r.u8("local"===(n=t.nextOfferer)?1:"remote"===n?2:Fr("invalid next-offerer turn")),((e,t)=>{switch(e.u8((e=>{switch(e.kind){case"idle":return 0;case"outbound-offer-prepared":return 1;case"outbound-offer-dispatched":return 2;case"inbound-offer":return 3;case"outbound-advance-prepared":return 4;case"outbound-advance-awaiting-ack":return 5;case"inbound-advance-prepared":return 6;case"inbound-advance-awaiting-ack-dispatch":return 7}})(t)),t.kind){case"idle":return;case"outbound-offer-prepared":case"outbound-offer-dispatched":return e.sized(t.offer),void e.sized(t.secretKey);case"inbound-offer":return void e.sized(t.offer);case"outbound-advance-prepared":return e.sized(t.advance),void e.sized(t.nextRoot);case"outbound-advance-awaiting-ack":case"inbound-advance-awaiting-ack-dispatch":return void e.sized(t.advance);case"inbound-advance-prepared":e.sized(t.advance),e.sized(t.secretKey),e.sized(t.nextRoot)}})(r,t.phase),r.sized(t.lastInboundOffer),r.sized(t.lastInboundAdvance),((e,t)=>{null!==t?(e.u8("offer"===t.kind?1:2),e.u8(t.attempts),e.u64(BigInt(t.nextRetryAt)),e.sized(t.frame)):e.u8(0)})(r,this.#N),r.sized(this.#F),r.sized(this.#L),r.sized(this.#T),((e,t)=>{t.size>Or&&Fr("too many active receive message keys");const r=[...t.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0);e.u16(r.length);for(const[t,n]of r){Br.test(t)||Fr("active receive cache key is non-canonical");const r=Ir.encode(t);(0===r.length||r.length>160)&&Fr("active receive cache key length is invalid"),Tr(n,"active receive message key",32),e.u16(r.length),e.bytes(r),e.bytes(n)}})(r,e),r.finish()}finally{br(t)}var n,i}static readCheckpointBinding(e){Tr(e,"checkpoint");const t=Cr.length+1+1+1+1+8+8;return e.length<t+32?Fr("checkpoint is too short to contain a binding"):e.slice(t,t+32)}static restore(e,t){Tr(e,"encrypted edge checkpoint plaintext"),Tr(t.binding,"expected edge binding",32);const r=new $r(e);let n=null,i=null,a=null,o=null,s=null,c=null,l=null,d=null;try{const e=r.take(Cr.length),u=Lr(e,Cr);e.fill(0),u||Fr("checkpoint magic is invalid"),1!==r.u8()&&Fr("checkpoint version is unsupported");const f=1===(h=r.u8())?512:2===h?768:3===h?1024:Fr("checkpoint has an unknown ML-KEM suite");f!==Ye(t.pqMode)&&Fr("checkpoint suite disagrees with the authenticated room policy"),We(t.pqMode)!==t.rootSuite&&Fr("authenticated root suite and room PQ mode disagree");const y=r.u8();y!==(t.amInitiator?1:2)&&Fr("checkpoint belongs to the opposite edge direction"),0!==r.u8()&&Fr("checkpoint reserved byte is non-zero");const p=r.u64(),m=r.u64();(p>BigInt(Number.MAX_SAFE_INTEGER)||m>BigInt(Number.MAX_SAFE_INTEGER))&&Fr("checkpoint counters exceed the safe-integer range");const b=r.take(32);Lr(b,t.binding)||Fr("checkpoint belongs to another authenticated edge");const g=r.take(32),w=De(f);n={formatVersion:1,parameterSet:f,binding:b,rootKey:g,epoch:r.u64(),localCounter:r.u64(),remoteCounter:r.u64(),nextOfferer:qr(r.u8()),phase:zr(r,w),lastInboundOffer:r.sized(8192),lastInboundAdvance:r.sized(8192)},s=(e=>{const t=e.u8();if(0===t)return null;if(1!==t&&2!==t)return Fr("checkpoint outbox kind is invalid");const r=e.u8();r>8&&Fr("checkpoint outbox attempts exceed the retry budget");const n=e.u64();n>BigInt(Number.MAX_SAFE_INTEGER)&&Fr("checkpoint retry deadline exceeds the safe-integer range");const i=Hr(e,z,"outbox frame");return Tr(i,"outbox frame",z),{kind:1===t?"offer":"advance",attempts:r,nextRetryAt:Number(n),frame:i}})(r),c=r.sized(z),l=r.sized(z),d=r.sized(z);for(const e of[c,l,d])e&&Tr(e,"cached control frame",z);o=(e=>{const t=e.u16();t>Or&&Fr("checkpoint has too many active receive message keys");const r=new Map;try{for(let n=0;n<t;n+=1){const t=e.u16();(0===t||t>160)&&Fr("checkpoint active receive cache key length is invalid");const n=e.take(t);let i;try{i=Nr.decode(n)}finally{n.fill(0)}0!==i.length&&Br.test(i)&&!r.has(i)||Fr("checkpoint active receive cache key is non-canonical"),r.set(i,e.take(32))}return r}catch(e){for(const e of r.values())e.fill(0);throw r.clear(),e}})(r),r.finish();const v=je(t.module,w);i=mr.restore(n,{module:t.module,backend:v,suite:w,binding:t.binding});const A=i.copyRootKey();try{a=new jr({module:t.module,pqMode:t.pqMode,rootSuite:t.rootSuite,binding:t.binding,rootKey:A,nextOfferer:i.nextOfferer,amInitiator:t.amInitiator,now:Number(p)})}finally{A.fill(0)}return a.#B.destroy(),a.#B=i,i=null,a.#I.fill(0),a.#I=a.#B.copyRootKey(),a.#N=s,s=null,a.#F=c,c=null,a.#L=l,l=null,a.#T=d,d=null,a.#D=o,o=null,a.#q=Number(m),a.#Q(),a}catch(e){throw a?.destroy(),e}finally{r.destroy(),n&&br(n),i?.destroy(),s?.frame.fill(0),c?.fill(0),l?.fill(0),d?.fill(0),o&&Qr(o)}var h}destroy(){this.#y||(this.#B.destroy(),this.#i.fill(0),this.#I.fill(0),this.#N?.frame.fill(0),this.#F?.fill(0),this.#L?.fill(0),this.#T?.fill(0),Qr(this.#D),this.#N=null,this.#F=null,this.#L=null,this.#T=null,this.#y=!0)}#z(){const e=this.#B.copyRootKey();this.#I.fill(0),this.#I=e}#H(){this.#F?.fill(0),this.#L?.fill(0),this.#T?.fill(0),this.#F=null,this.#L=null,this.#T=null}#Q(){const e=this.#B.phase;("outbound-offer-dispatched"===e&&"offer"!==this.#N?.kind||"outbound-advance-awaiting-ack"===e&&"advance"!==this.#N?.kind||"offer"===this.#N?.kind&&"outbound-offer-dispatched"!==e||"advance"===this.#N?.kind&&"outbound-advance-awaiting-ack"!==e)&&Fr("checkpoint PQ phase and sealed outbox disagree"),null!==this.#F&&"advance"!==this.#N?.kind&&Fr("checkpoint cached OFFER has no matching ADVANCE outbox"),null===this.#L!=(null===this.#T)&&Fr("checkpoint ADVANCE replay and ACK cache must be paired"),null!==this.#F&&null!==this.#L&&Fr("checkpoint contains mutually exclusive replay caches")}#$(){this.#y&&Fr("state is destroyed")}}const Yr=e=>{const t=new Uint8Array(T);let r=0;new DataView(t.buffer,r,8).setBigUint64(0,BigInt(e.schemaVersion),!1),r+=8,t[r]=e.messageType,r+=1,t.set(e.hash,r),r+=y;new DataView(t.buffer,r,8).setBigUint64(0,BigInt(e.totalSize),!1),r+=8;new DataView(t.buffer,r,8).setBigInt64(0,BigInt(e.date.getTime()),!1),r+=8;const n=(new TextEncoder).encode(e.name),i=new Uint8Array(256);i.set(n.subarray(0,Math.min(256,n.length))),t.set(i,r),r+=256;new DataView(t.buffer,r,8).setBigUint64(0,BigInt(e.chunkStartIndex),!1),r+=8;new DataView(t.buffer,r,8).setBigUint64(0,BigInt(e.chunkEndIndex),!1),r+=8;return new DataView(t.buffer,r,8).setBigUint64(0,BigInt(e.chunkIndex),!1),t},Wr=e=>{if(e.length!==T)throw new Error("Invalid metadata buffer totalSize");let t=0;const r=new DataView(e.buffer,e.byteOffset+t,8),n=Number(r.getBigUint64(0,!1));t+=8;const i=e[t];t+=1;const a=e.slice(t,t+y);t+=y;const o=new DataView(e.buffer,e.byteOffset+t,8),s=Number(o.getBigUint64(0,!1));t+=8;const c=new DataView(e.buffer,e.byteOffset+t,8),l=Number(c.getBigUint64(0,!1)),d=new Date(l);t+=8;const h=e.slice(t,t+256);let u=(new TextDecoder).decode(h).replace(/\0+$/,"");u=u.replace(/[/\\]/g,"_").replace(/[<>:"'|?*]/g,"_").replace(/[\u0000-\u001f\u007f]/g,""),t+=256;const f=new DataView(e.buffer,e.byteOffset+t,8),p=Number(f.getBigUint64(0,!1));t+=8;const m=new DataView(e.buffer,e.byteOffset+t,8),b=Number(m.getBigUint64(0,!1));t+=8;const g=new DataView(e.buffer,e.byteOffset+t,8);return{schemaVersion:n,messageType:i,hash:a,totalSize:s,date:d,name:u,chunkStartIndex:p,chunkEndIndex:b,chunkIndex:Number(g.getBigUint64(0,!1))}},Xr=64;class Gr{queue=[];locked=!1;idleWaiters=[];async acquire(){if(this.locked)return new Promise(e=>{this.queue.push(e)});this.locked=!0}release(){const e=this.queue.shift();if(e)e();else{this.locked=!1;for(const e of this.idleWaiters.splice(0))e()}}isIdle(){return!this.locked&&0===this.queue.length}whenIdle(){return this.isIdle()?Promise.resolve():new Promise(e=>{this.idleWaiters.push(e)})}async runExclusive(e){await this.acquire();try{return await e()}finally{this.release()}}}const Zr=new Uint8Array([80,50,80,83,69,83,83,0]),Jr=262144,en=Zr.length+4+24+32+32+32+2,tn="p2party-session",rn=e=>Uint8Array.from(e);function nn(e,t,r){if(!(e instanceof Uint8Array))throw new TypeError(`${t} must be a Uint8Array`);if(void 0!==r&&e.length!==r)throw new RangeError(`${t} must be ${String(r)} bytes`)}const an=(e,t)=>{if(!Number.isSafeInteger(e)||e<0||e>Number.MAX_SAFE_INTEGER)throw new RangeError(`${t} must be a non-negative safe integer`)},on=(e,t)=>{if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r},sn=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),cn=async e=>new Uint8Array(await globalThis.crypto.subtle.digest("SHA-512",e.slice().buffer)),ln=async e=>{const t=new WebAssembly.Memory({initial:32,maximum:32});return e?.wasmBinary?await a({wasmBinary:(r=e.wasmBinary,r instanceof Uint8Array?r.slice().buffer:r.slice(0)),wasmMemory:t,getRandomValue:s}):await u(t);var r},dn=async(e,t)=>{const r=e.length,n=Math.max(1,Math.ceil(r/q)),i=[],a=[];try{for(let t=0;t<n;t++){const n=t*q,a=Math.min(q,Math.max(0,r-n)),o=globalThis.crypto.getRandomValues(new Uint8Array(q));o.set(e.subarray(n,n+a),0),i.push(o)}const o=await cn(e),s=new Uint8Array(n*y);for(let e=0;e<i.length;e++)s.set(ke(i[e],t),e*y);const c=Uint8Array.from(await(async(e,t)=>{if(e.length%y!==0)throw new Error("Hashes were not passed");const r=e.length/y;if(0===r)throw new Error("Cannot calculate Merkle root of tree with no leaves.");if(1===r)return e;const n=t?.wasmMemory??O(r),i=t??await u(n),a=i._malloc(r*y),o=new Uint8Array(n.buffer,a,r*y);o.set(e);const s=i._malloc(y),c=new Uint8Array(n.buffer,s,y),l=i._get_merkle_root(r,o.byteOffset,c.byteOffset);switch(i._free(a),l){case 0:{const e=Uint8Array.from([...c]);return i._free(s),e}case-1:throw i._free(s),new Error("Could not allocate memory for hash concatenation helper array.");case-2:throw i._free(s),new Error("Could not calculate hash.");default:throw i._free(s),new Error("Unexpected error occured.")}})(s,t));for(let e=0;e<i.length;e++){const n=await Ee(s,ke(i[e],t),t,D),c=Math.min(q,Math.max(0,r-e*q)),l=Yr({schemaVersion:1,messageType:Xr,hash:o,totalSize:r,date:new Date(0),name:tn,chunkStartIndex:0,chunkEndIndex:c,chunkIndex:e}),d=new Uint8Array(V);d.set(l,0),d.set(n,T),d.set(i[e],T+D),a.push(d)}return o.fill(0),s.fill(0),{root:c,chunks:i,plaintexts:a}}catch(e){for(const e of i)e.fill(0);for(const e of a)e.fill(0);throw e}},hn=(e,t)=>e.N===t.N&&e.PN===t.PN&&on(e.dhPub,t.dhPub);class un{protocolVersion=4;#e;#j=new Gr;#Y;#W;#X;#y=!1;constructor(e,t,r,n){this.#W=e,this.#e=t,this.#X=r,this.#Y=n}get pqMode(){return Xe(this.#W.rootSuite)}get canEncrypt(){return!this.#y&&null!==this.#W.sendingChainKey&&!this.#X.trafficBlocked}get pqEpoch(){return this.#$(),this.#X.epoch}get healingInProgress(){return!this.#y&&this.#X.trafficBlocked}#$(){if(this.#y)throw new Error("session: session is destroyed")}async encrypt(e){nn(e,"plaintext");const t=rn(e);return this.#j.runExclusive(async()=>{let e=null,r=null,n=null,i=null,a=!1;try{if(this.#$(),this.#X.trafficBlocked)throw new Error("session: sparse-PQ healing is in progress");if(!this.#W.sendingChainKey)throw new Error("ratchet: no sending chain");e=await dn(t,this.#e),r=we(this.#W);const o=((e,t)=>{if(!e.sendingChainKey)throw new Error("ratchet: no sending chain");const{chainKey:r,messageKey:n}=de(e.sendingChainKey,t),i={dhPub:Uint8Array.from(e.dhSelfPub),N:e.Ns,PN:e.PN};return e.sendingChainKey.fill(0),e.sendingChainKey=r,e.Ns+=1,{messageKey:n,header:i}})(r,this.#e);n=o.messageKey,i=this.#X.currentMessageContext();const s=e.plaintexts.map(t=>Ot(n,o.header,t,e.root,this.#e,i));return Ae(this.#W,r),this.#X.noteApplicationMessage(),a=!0,{protocolVersion:4,root:rn(e.root),frames:s}}finally{t.fill(0),n?.fill(0),r&&!a&&ve(r),e&&(e=>{for(const t of e.chunks)t.fill(0);for(const t of e.plaintexts)t.fill(0)})(e)}})}async decrypt(e){if(!e||"object"!=typeof e)throw new TypeError("message is required");if(4!==e.protocolVersion)throw new Error("session: unsupported protocol version");if(nn(e.root,"message.root",y),!Array.isArray(e.frames)||0===e.frames.length)throw new Error("session: encrypted message has no frames");for(const t of e.frames)if(nn(t,"message frame"),t.length!==z)throw new Error("session: invalid encrypted frame length");const t=rn(e.root),r=e.frames.map(rn);return this.#j.runExclusive(async()=>{this.#$();const e=r.map(e=>gt(e));for(let t=1;t<e.length;t++)if(!hn(e[0].header,e[t].header))throw new Error("session: mixed ratchet headers");const n=new Set;for(const t of e){const e=sn(t.nonce);if(n.has(e))throw new Error("session: duplicate chunk nonce");n.add(e)}const i=we(this.#W),a=new Map(this.#X.activeReceiveKeys),o=[];let s=!1;try{const e=[];for(const n of r){const r=Bt(i,n,a,t,this.#e,e=>this.#X.resolveMessageContext(e));if(!r.ok||!r.decrypted)throw new Error("session: encrypted frame authentication failed");o.push(r.decrypted);const s=Wr(r.decrypted.subarray(0,T));e.push({metadata:s,chunk:r.decrypted.subarray(T+D)})}const n=await(async e=>{if(0===e.length)throw new Error("session: encrypted message has no frames");const t=e[0].metadata;an(t.totalSize,"metadata.totalSize");const r=Math.max(1,Math.ceil(t.totalSize/q));if(e.length!==r)throw new Error("session: incomplete or excessive frame set");const n=new Map;for(const i of e){const e=i.metadata;if(an(e.chunkIndex,"metadata.chunkIndex"),an(e.chunkStartIndex,"metadata.chunkStartIndex"),an(e.chunkEndIndex,"metadata.chunkEndIndex"),an(e.totalSize,"metadata.totalSize"),1!==e.schemaVersion||e.messageType!==Xr||e.name!==tn||0!==e.date.getTime())throw new Error("session: unsupported encrypted metadata");if(e.totalSize!==t.totalSize||!on(e.hash,t.hash))throw new Error("session: inconsistent encrypted metadata");if(e.chunkIndex>=r||0!==e.chunkStartIndex)throw new Error("session: invalid encrypted chunk range");const a=Math.min(q,Math.max(0,t.totalSize-e.chunkIndex*q));if(e.chunkEndIndex!==a)throw new Error("session: invalid encrypted chunk length");if(n.has(e.chunkIndex))throw new Error("session: duplicate encrypted chunk");n.set(e.chunkIndex,i)}const i=new Uint8Array(t.totalSize);for(let e=0;e<r;e++){const t=n.get(e);if(!t)throw new Error("session: missing encrypted chunk");const r=t.metadata.chunkEndIndex;i.set(t.chunk.subarray(0,r),e*q)}const a=await cn(i),o=on(a,t.hash);if(a.fill(0),!o)throw i.fill(0),new Error("session: plaintext hash mismatch");return i})(e);return Ae(this.#W,i),this.#G(a),this.#X.noteApplicationMessage(),s=!0,n}finally{t.fill(0);for(const e of o)e.fill(0);if(!s){for(const[e,t]of a)this.#X.activeReceiveKeys.has(e)||t.fill(0);ve(i)}}})}#G(e){const t=this.#X.activeReceiveKeys;for(const[r,n]of e)t.has(r)||t.set(r,n)}async prepareHealing(){return this.#j.runExclusive(async()=>{if(this.#$(),!this.#X.healingDue())return fn;const e=await this.#X.prepareHealingOffer();return this.#X.markPendingDispatched(),{frame:e,requiresPersistBeforeSend:!0}})}async acceptControlFrame(e){nn(e,"control frame",z);const t=rn(e);return this.#j.runExclusive(async()=>{this.#$();const e=await this.#X.acceptControlFrame(t);return e.changed&&e.dispatch&&null!==this.#X.pendingRetryAt&&this.#X.markPendingDispatched(),{frame:e.dispatch,requiresPersistBeforeSend:e.changed}})}async pendingControl(){return this.#j.runExclusive(async()=>(this.#$(),this.#X.copyPendingFrame()))}async serialize(){return this.#j.runExclusive(async()=>(this.#$(),pn(this.#W,this.#X,this.#Y)))}async destroy(){await this.#j.runExclusive(async()=>{this.#y||(ve(this.#W),this.#X.destroy(),this.#y=!0)})}}const fn={frame:null,requiresPersistBeforeSend:!1},yn=(e,t,r)=>(an(r,"snapshot counter"),e.setBigUint64(t,BigInt(r),!1),t+8),pn=(e,t,r)=>{(e=>{if(nn(e.rootKey,"snapshot.rootKey",32),nn(e.dhSelfPub,"snapshot.dhSelfPub",32),nn(e.dhSelfSec,"snapshot.dhSelfSec",32),e.sendingChainKey&&nn(e.sendingChainKey,"snapshot.sendingChainKey",32),e.receivingChainKey&&nn(e.receivingChainKey,"snapshot.receivingChainKey",32),e.dhRemotePub&&nn(e.dhRemotePub,"snapshot.dhRemotePub",32),an(e.Ns,"snapshot.Ns"),an(e.Nr,"snapshot.Nr"),an(e.PN,"snapshot.PN"),(e.sendingChainKey||e.receivingChainKey||e.skipped.size>0)&&!e.dhRemotePub)throw new Error("snapshot: chain state requires a remote DH key");if(e.skipped.size>Z)throw new Error("snapshot: too many skipped message keys")})(e);const n=be(e),i=t.serialize();if(0===i.length||i.length>Jr)throw i.fill(0),new Error("snapshot: PQ checkpoint length is invalid");try{const e=(n.sendingChainKey?1:0)|(n.receivingChainKey?2:0)|(n.dhRemotePub?4:0)|(r?8:0),t=Number(Boolean(n.sendingChainKey))+Number(Boolean(n.receivingChainKey))+Number(Boolean(n.dhRemotePub)),a=new Uint8Array(en+32*t+72*n.skippedMessageKeys.length+4+i.length),o=new DataView(a.buffer);let s=0;a.set(Zr,s),s+=Zr.length,a[s++]=4,a[s++]=4,a[s++]=e,a[s++]=(e=>{if(e===Y)return 3;if(e===j)return 4;if(e===W)return 5;throw new Error("snapshot: unsupported root suite")})(n.rootSuite),s=yn(o,s,n.Ns),s=yn(o,s,n.Nr),s=yn(o,s,n.PN),a.set(new Uint8Array(n.rootKey),s),s+=32,n.sendingChainKey&&(a.set(new Uint8Array(n.sendingChainKey),s),s+=32),n.receivingChainKey&&(a.set(new Uint8Array(n.receivingChainKey),s),s+=32),a.set(new Uint8Array(n.dhSelfPub),s),s+=32,a.set(new Uint8Array(n.dhSelfSec),s),s+=32,n.dhRemotePub&&(a.set(new Uint8Array(n.dhRemotePub),s),s+=32),o.setUint16(s,n.skippedMessageKeys.length,!1),s+=2;for(const e of n.skippedMessageKeys)nn(new Uint8Array(e.dhPub),"snapshot.skipped.dhPub",32),nn(new Uint8Array(e.messageKey),"snapshot.skipped.messageKey",32),a.set(new Uint8Array(e.dhPub),s),s+=32,s=yn(o,s,e.n),a.set(new Uint8Array(e.messageKey),s),s+=32;return o.setUint32(s,i.length,!1),s+=4,a.set(i,s),s+=i.length,a}finally{i.fill(0),new Uint8Array(n.rootKey).fill(0),n.sendingChainKey&&new Uint8Array(n.sendingChainKey).fill(0),n.receivingChainKey&&new Uint8Array(n.receivingChainKey).fill(0),new Uint8Array(n.dhSelfSec).fill(0);for(const e of n.skippedMessageKeys)new Uint8Array(e.messageKey).fill(0)}},mn=e=>{nn(e,"snapshot");const t=rn(e);let r=0,n=!1;const i=[],a=e=>{if(!Number.isSafeInteger(e)||e<0||r+e>t.length)throw new Error("snapshot: truncated input");const n=t.subarray(r,r+e);return r+=e,n},o=(e,t=!1)=>{const r=a(e).slice().buffer;return t&&i.push(new Uint8Array(r)),r},s=()=>{if(r+8>t.length)throw new Error("snapshot: truncated counter");const e=new DataView(t.buffer,t.byteOffset+r,8).getBigUint64(0,!1);if(r+=8,e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("snapshot: counter exceeds safe-integer range");return Number(e)};try{if(!on(a(Zr.length),Zr))throw new Error("snapshot: invalid magic");if(4!==a(1)[0])throw new Error("snapshot: unsupported snapshot version");if(4!==a(1)[0])throw new Error("snapshot: unsupported protocol version");const e=a(1)[0];if(-16&e)throw new Error("snapshot: unknown flags");const c=(e=>{if(3===e)return Y;if(4===e)return j;if(5===e)return W;throw new Error("snapshot: unsupported root suite")})(a(1)[0]),l=s(),d=s(),h=s(),u=o(32,!0),f=1&e?o(32,!0):null,y=2&e?o(32,!0):null,p=o(32),m=o(32,!0),b=4&e?o(32):null;if((f||y)&&null===b)throw new Error("snapshot: chain state requires a remote DH key");if(r+2>t.length)throw new Error("snapshot: missing skipped-key count");const g=new DataView(t.buffer,t.byteOffset+r,2).getUint16(0,!1);if(r+=2,g>Z)throw new Error("snapshot: too many skipped message keys");if(null===b&&g>0)throw new Error("snapshot: skipped keys require a remote DH key");const w=72*g;if(t.length-r<w+4)throw new Error("snapshot: truncated input");const v=[],A=new Set;for(let e=0;e<g;e++){const e=a(32),t=s(),r=a(32),n=`${sn(e)}:${String(t)}`;if(A.has(n))throw new Error("snapshot: duplicate skipped message key");A.add(n),v.push({dhPub:e.slice().buffer,n:t,messageKey:(()=>{const e=r.slice().buffer;return i.push(new Uint8Array(e)),e})()})}const k=new DataView(t.buffer,t.byteOffset+r,4).getUint32(0,!1);if(r+=4,0===k||k>Jr)throw new Error("snapshot: PQ checkpoint length is invalid");if(t.length-r!==k)throw new Error("snapshot: truncated input or trailing bytes");const E=a(k).slice();i.push(E);const K=ge({rootSuite:c,rootKey:u,sendingChainKey:f,receivingChainKey:y,dhSelfPub:p,dhSelfSec:m,dhRemotePub:b,Ns:l,Nr:d,PN:h,skippedMessageKeys:v});return n=!0,{state:K,pqCheckpoint:E,amInitiator:!!(8&e)}}finally{if(t.fill(0),!n)for(const e of i)e.fill(0)}};exports.PROTOCOL_VERSION=4,exports.WIRE_CHUNK_FRAME_LEN=z,exports.createSession=async e=>{if(!e||"object"!=typeof e)throw new TypeError("session options are required");if("initiator"!==e.role&&"responder"!==e.role)throw new Error("role must be initiator or responder");if(!e.transport||"function"!=typeof e.transport.send||"function"!=typeof e.transport.recv)throw new TypeError("transport must provide send() and recv()");if((e=>{if(!e||"object"!=typeof e)throw new TypeError("identity is required");nn(e.ed25519PublicKey,"identity.ed25519PublicKey",g),nn(e.x25519PublicKey,"identity.x25519PublicKey",U),nn(e.x25519SecretKey,"identity.x25519SecretKey",x),nn(e.x25519CrossSignature,"identity.x25519CrossSignature",m)})(e.identity),nn(e.peerIdentityEd25519PublicKey,"peerIdentityEd25519PublicKey",g),!e.channel||"object"!=typeof e.channel)throw new TypeError("channel binding is required");if(nn(e.channel.channelId,"channel.channelId"),0===e.channel.channelId.length)throw new RangeError("channel.channelId must not be empty");nn(e.channel.localFingerprint,"channel.localFingerprint",32),nn(e.channel.remoteFingerprint,"channel.remoteFingerprint",32);const t=e;if("pin"!==t.mode&&"nopin"!==t.mode)throw new Error("mode must be pin or nopin");const r=t.mode,n=t.pqMode??"hybrid-mlkem768";if("hybrid-mlkem512"!==n&&"hybrid-mlkem768"!==n&&"hybrid-mlkem1024"!==n)throw new Error("pqMode must select ML-KEM-512, ML-KEM-768, or ML-KEM-1024");let i=null;if("pin"===r){if(nn(t.pin,"pin"),0===t.pin.length)throw new RangeError("pin must not be empty");i=rn(t.pin)}else if(void 0!==t.pin)throw new Error("pin must not be provided in nopin mode");const a=rn(e.identity.x25519SecretKey),o=rn(e.identity.ed25519PublicKey),s=rn(e.identity.x25519PublicKey),c=rn(e.identity.x25519CrossSignature),l=rn(e.peerIdentityEd25519PublicKey),d=rn(e.channel.channelId),h=rn(e.channel.localFingerprint),u=rn(e.channel.remoteFingerprint);let f=null,y=null,p=null,b=null,w=null;try{const t=await ln(e.crypto);await(async(e,t)=>{const r=new Uint8Array(U);r[0]=9;const n=F(e.x25519SecretKey,r,t);try{if(!on(n,e.x25519PublicKey))throw new Error("identity X25519 public and secret keys do not match")}finally{n.fill(0)}if(!await te(e.x25519PublicKey,e.x25519CrossSignature,e.ed25519PublicKey,t))throw new Error("identity X25519 cross-signature is invalid")})({ed25519PublicKey:o,x25519PublicKey:s,x25519SecretKey:a,x25519CrossSignature:c},t);const m="initiator"===e.role,g=Je({channelId:d,ikInitiator:m?o:l,ikResponder:m?l:o,fpInitiator:m?h:u,fpResponder:m?u:h,pqMode:n}),v=await ft(e.transport,{mode:r,pqMode:n,pin:i,channelInput:g,amInitiator:m,idSelfSec:a,selfIdentityX25519Pub:s,selfIdentityCrossSignature:c,peerIdentityEd25519Pub:l},t);b=v.state,f=v.secret,y=v.pqHealing.rootKey,p=v.pqHealing.binding,w=new jr({module:t,pqMode:n,rootSuite:b.rootSuite,binding:p,rootKey:y,nextOfferer:v.pqHealing.nextOfferer,amInitiator:m});const A=new un(b,t,w,m);return b=null,w=null,A}finally{a.fill(0),i?.fill(0),f?.fill(0),y?.fill(0),p?.fill(0),b&&ve(b),w?.destroy()}},exports.generateSessionIdentity=async(e={})=>{const t=await ln(e);let r=null,n=null,i=null;try{if(e.ed25519KeyPair)nn(e.ed25519KeyPair.publicKey,"ed25519KeyPair.publicKey",g),nn(e.ed25519KeyPair.secretKey,"ed25519KeyPair.secretKey",w),r=rn(e.ed25519KeyPair.publicKey),n=rn(e.ed25519KeyPair.secretKey);else{const e=await(async e=>{const t=e?.wasmMemory??M(),r=e??await u(t),n=r._malloc(g),i=new Uint8Array(t.buffer,n,g),a=r._malloc(w),o=new Uint8Array(t.buffer,a,w),s=r._malloc(b),l=new Uint8Array(t.buffer,s,b);try{if(c(l),0!==r._keypair_from_seed(i.byteOffset,o.byteOffset,l.byteOffset))throw new Error("An unexpected error occured.");return{publicKey:Uint8Array.from(i),secretKey:Uint8Array.from(o)}}finally{r._free(n),I(r,o),I(r,l)}})(t);r=e.publicKey,n=e.secretKey}const a=await(async e=>{const t=e?.wasmMemory??C(),r=e??await u(t);return N(r)})(t);i=a.secretKey;const o=await ee(a.publicKey,n,t);if(!await te(a.publicKey,o,r,t))throw new Error("ed25519KeyPair public and secret keys do not match");const s={ed25519PublicKey:r,ed25519SecretKey:n,x25519PublicKey:a.publicKey,x25519SecretKey:i,x25519CrossSignature:o};return r=null,n=null,i=null,s}finally{r?.fill(0),n?.fill(0),i?.fill(0)}},exports.restoreSession=async(e,t)=>{const r=mn(e);let n=null;try{const e=await ln(t),i=jr.readCheckpointBinding(r.pqCheckpoint);try{n=jr.restore(r.pqCheckpoint,{module:e,pqMode:Xe(r.state.rootSuite),rootSuite:r.state.rootSuite,binding:i,amInitiator:r.amInitiator})}finally{i.fill(0)}const a=new un(r.state,e,n,r.amInitiator);return n=null,a}catch(e){throw ve(r.state),n?.destroy(),e}finally{r.pqCheckpoint.fill(0)}};