@calimero-network/mero-js 27.0.2 → 27.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,9 @@
1
- function T(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function ce(t,e,r){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length!==r*2)throw new Error(`${e} must be ${r*2} hex characters, got ${n.length}`);let i=new Uint8Array(r);for(let s=0;s<r;s+=1)i[s]=Number.parseInt(n.slice(s*2,s*2+2),16);return i}function p(...t){let e=new Uint8Array(t.reduce((n,i)=>n+i.length,0)),r=0;for(let n of t)e.set(n,r),r+=n.length;return e}var Xt="Noise_NK_25519_AESGCM_SHA256",ve=32,Wt=16,er=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Ne=class t{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(Xt),r=new Uint8Array(32);return r.set(e),new t(r)}async mixHash(e){this.h=await tr(p(this.h,e))}async mixKey(e){let[r,n]=await tt(this.ck,e);this.ck=r,this.k=await crypto.subtle.importKey("raw",n,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:et(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(r),r}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let r=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:et(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),r}split(){return tt(this.ck,new Uint8Array)}};async function rt(t,e,r){let n=await Ne.initialize();await n.mixHash(e),await n.mixHash(t);let i=await L(r);return await n.mixHash(i.publicKey),await n.mixKey(await Y(i.privateKey,t)),{message1:p(i.publicKey,await n.encryptAndHash(new Uint8Array)),async finish(o){if(o.length<ve+Wt)throw new Error("Noise: message 2 is too short");let a=o.slice(0,ve);return await n.mixHash(a),await n.mixKey(await Y(i.privateKey,a)),{payload:await n.decryptAndHash(o.slice(ve)),split:await n.split()}}}}async function L(t){if(!t){let n;try{n=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"])}catch(s){throw new Error(`Sealed transport needs WebCrypto with X25519, which this runtime lacks (${s?.name??"no crypto.subtle"}). Current browsers and Node have it; in React Native, install react-native-quick-crypto as the global crypto.`)}let i=new Uint8Array(await crypto.subtle.exportKey("raw",n.publicKey));return{privateKey:n.privateKey,publicKey:i}}let e=await crypto.subtle.importKey("pkcs8",p(er,t),{name:"X25519"},!0,["deriveBits"]),r=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:rr(r.x)}}async function Y(t,e){let r=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:r},t,256))}function et(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}async function tr(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}async function Ie(t,e){let r=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",r,e))}async function tt(t,e){let r=await Ie(t,e),n=await Ie(r,new Uint8Array([1])),i=await Ie(r,p(n,new Uint8Array([2])));return[n,i]}function rr(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(r,n=>n.charCodeAt(0))}var ot="/sealed/v2/handshake",at="/sealed/v2",X="application/vnd.calimero.sealed",Oe=2,nr=new TextEncoder().encode("calimero/sealed-http/v2"),Z=16,ir=1+Z+8,sr=0,or=1,ar=2,cr=1+64*1024+16,lr=1024,ur=6e4,dr="calimero.tee-attest.transport-key.v1",gr=[101,204,205,304],ct=new TextEncoder,W=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},S=class extends Error{constructor(r,n,i,s){super(i);this.status=r;this.code=n;this.retryAfterMs=s;this.name="SealedTransportError"}};async function De(t,e){let r=await crypto.subtle.digest("SHA-256",p(ct.encode(dr),t,e));return new Uint8Array(r)}function Me(t){let e=new URL(t.baseUrl),r=e.pathname.replace(/\/+$/,""),n=`${e.origin}${r}`,i=t.fetch??((g,f)=>fetch(g,f)),s=typeof t.transportPublicKey=="function"?t.transportPublicKey:void 0,o=s?Promise.resolve().then(s):Promise.resolve(t.transportPublicKey);o.catch(()=>{});let a,c=async()=>{try{return await it(i,n,await nt(o))}catch(g){if(!(g instanceof W)||!s)throw g;return o=Promise.resolve().then(s),it(i,n,await nt(o))}},d=async()=>{let g=a??u(void 0),f=await g;if(Date.now()<f.renewAt)return[f,g];let h=u(g);return[await h,h]},u=g=>{if(a===g){let f=c();a=f,f.catch(()=>{a===f&&(a=void 0)})}return a};return async(g,f)=>{let h=new Request(g,f),y=new URL(h.url);if(y.origin!==e.origin||!y.pathname.startsWith(`${r}/`))throw new Error(`Refusing to send ${y.href} outside the sealed node at ${t.baseUrl}`);let b=[];h.headers.forEach((P,K)=>b.push([K,P]));let O={method:h.method,path:y.pathname.slice(r.length)+y.search,headers:b},E=new Uint8Array(await h.arrayBuffer()),R=f?.signal??(g instanceof Request?g.signal:void 0),D=async P=>{let{requestId:K,header:z,envelope:ae}=await yr(P,O,E),V=await i(`${n}${at}`,{method:"POST",headers:{"content-type":X},body:ae,signal:R});if(V.headers.get("content-type")!==X)throw await ut(V);return hr(V,P.responseKey,z,K)},[xe,Se]=await d();try{return await D(xe)}catch(P){if(!(P instanceof S)||P.code!=="unknown_session")throw P;return D(await u(Se))}}}async function nt(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function it(t,e,r){try{return await st(t,e,r)}catch(n){if(!(n instanceof S)||n.code!=="busy")throw n;return await new Promise(i=>setTimeout(i,n.retryAfterMs??1e3)),st(t,e,r)}}async function st(t,e,r){let n=await rt(r,nr),i=await t(`${e}${ot}`,{method:"POST",headers:{"content-type":X},body:p(new Uint8Array([Oe]),r,n.message1)});if(i.headers.get("content-type")!==X)throw await ut(i);let s=await mr(i,lr);return fr(n,s)}async function fr(t,e){if(e[0]!==Oe)throw new Error("The handshake reply is malformed");let r;try{r=await t.finish(e.slice(1))}catch{throw new Error("The handshake reply did not open: it did not come from the attested node")}let{payload:n,split:i}=r;if(n.length!==Z+4)throw new Error("The handshake reply is malformed");let s=n.slice(0,Z),o=new DataView(n.buffer,n.byteOffset).getUint32(Z,!1),[a,c]=await Promise.all([crypto.subtle.importKey("raw",i[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",i[1],"AES-GCM",!1,["decrypt"])]);return i[0].fill(0),i[1].fill(0),{requestKey:a,responseKey:c,nextRequestId:1,renewAt:Date.now()+o*1e3-ur,header(d){let u=new Uint8Array(ir);return u[0]=Oe,u.set(s,1),new DataView(u.buffer).setBigUint64(1+Z,BigInt(d),!1),u}}}async function yr(t,e,r){let n=t.nextRequestId;t.nextRequestId+=1;let i=t.header(n),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:lt(n,0),additionalData:i},t.requestKey,pr(e,r));return{requestId:n,header:i,envelope:p(i,new Uint8Array(s))}}function lt(t,e){let r=new Uint8Array(12),n=new DataView(r.buffer);return n.setBigUint64(0,BigInt(t),!1),n.setUint32(8,e,!1),r}function pr(t,e){let r=ct.encode(JSON.stringify(t)),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,r.length,!1),p(n,r,e)}async function hr(t,e,r,n){if(!t.body)throw new Error("The sealed response has no body");let i=wr(t.body.getReader()),s=0,o=async()=>{let u=await i.next();if(!u)return null;let g;try{g=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:lt(n,s),additionalData:r},e,u))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return s+=1,{kind:g[0],data:g.slice(1)}},a=await o();if(!a||a.kind!==sr)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(gr.includes(c.status))return await i.cancel(),new Response(null,{status:c.status,headers:c.headers});let d=new ReadableStream({async pull(u){try{let g=await o();g?g.kind===or?u.enqueue(g.data):g.kind===ar?(u.close(),await i.cancel()):u.error(new Error("The sealed response is malformed")):u.error(new Error("The sealed response was cut short"))}catch(g){u.error(g)}},cancel(){return i.cancel()}});return new Response(d,{status:c.status,headers:c.headers})}function wr(t){let e=new Uint8Array,r=async n=>{for(;e.length<n;){let{done:i,value:s}=await t.read();if(i)return!1;e=p(e,s)}return!0};return{async next(){if(!await r(4))return null;let n=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(n>cr)throw await t.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await r(4+n))return null;let i=e.slice(4,4+n);return e=e.slice(4+n),i},cancel:()=>t.cancel()}}async function mr(t,e){if(!t.body)return new Uint8Array;let r=t.body.getReader(),n=new Uint8Array;for(;;){let{done:i,value:s}=await r.read();if(i)return n;if(n=p(n,s),n.length>e)throw await r.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function ut(t){let e,r=`Sealed request refused: HTTP ${t.status}`;try{let s=await t.json();e=s?.error?.code,s?.error?.message&&(r=`Sealed request refused: ${s.error.message}`)}catch{}if(e==="stale_transport_key")return new W;let n=Number(t.headers.get("retry-after")),i=Number.isFinite(n)&&n>0?Math.min(n,5)*1e3:void 0;return new S(t.status,e,r,i)}var dt=[{uri:"https://fulcio.sigstore.dev",validFor:{start:"2021-03-07T03:20:29Z",end:"2022-12-31T23:59:59.999Z"},certChain:["MIIB+DCCAX6gAwIBAgITNVkDZoCiofPDsy7dfm6geLbuhzAKBggqhkjOPQQDAzAqMRUwEwYDVQQKEwxzaWdzdG9yZS5kZXYxETAPBgNVBAMTCHNpZ3N0b3JlMB4XDTIxMDMwNzAzMjAyOVoXDTMxMDIyMzAzMjAyOVowKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTB2MBAGByqGSM49AgEGBSuBBAAiA2IABLSyA7Ii5k+pNO8ZEWY0ylemWDowOkNa3kL+GZE5Z5GWehL9/A9bRNA3RbrsZ5i0JcastaRL7Sp5fp/jD5dxqc/UdTVnlvS16an+2Yfswe/QuLolRUCrcOE2+2iA5+tzd6NmMGQwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwHQYDVR0OBBYEFMjFHQBBmiQpMlEk6w2uSu1KBtPsMB8GA1UdIwQYMBaAFMjFHQBBmiQpMlEk6w2uSu1KBtPsMAoGCCqGSM49BAMDA2gAMGUCMH8liWJfMui6vXXBhjDgY4MwslmN/TJxVe/83WrFomwmNf056y1X48F9c4m3a3ozXAIxAKjRay5/aj/jsKKGIkmQatjI8uupHr/+CxFvaJWmpYqNkLDGRU+9orzh5hI2RrcuaQ=="]},{uri:"https://fulcio.sigstore.dev",validFor:{start:"2022-04-13T20:06:15Z"},certChain:["MIICGjCCAaGgAwIBAgIUALnViVfnU0brJasmRkHrn/UnfaQwCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMjA0MTMyMDA2MTVaFw0zMTEwMDUxMzU2NThaMDcxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjEeMBwGA1UEAxMVc2lnc3RvcmUtaW50ZXJtZWRpYXRlMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8RVS/ysH+NOvuDZyPIZtilgUF9NlarYpAd9HP1vBBH1U5CV77LSS7s0ZiH4nE7Hv7ptS6LvvR/STk798LVgMzLlJ4HeIfF3tHSaexLcYpSASr1kS0N/RgBJz/9jWCiXno3sweTAOBgNVHQ8BAf8EBAMCAQYwEwYDVR0lBAwwCgYIKwYBBQUHAwMwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQU39Ppz1YkEZb5qNjpKFWixi4YZD8wHwYDVR0jBBgwFoAUWMAeX5FFpWapesyQoZMi0CrFxfowCgYIKoZIzj0EAwMDZwAwZAIwPCsQK4DYiZYDPIaDi5HFKnfxXx6ASSVmERfsynYBiX2X6SJRnZU84/9DZdnFvvxmAjBOt6QpBlc4J/0DxvkTCqpclvziL6BCCPnjdlIB3Pu3BxsPmygUY7Ii2zbdCdliiow=","MIIB9zCCAXygAwIBAgIUALZNAPFdxHPwjeDloDwyYChAO/4wCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMTEwMDcxMzU2NTlaFw0zMTEwMDUxMzU2NThaMCoxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjERMA8GA1UEAxMIc2lnc3RvcmUwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT7XeFT4rb3PQGwS4IajtLk3/OlnpgangaBclYpsYBr5i+4ynB07ceb3LP0OIOZdxexX69c5iVuyJRQ+Hz05yi+UF3uBWAlHpiS5sh0+H2GHE7SXrk1EC5m1Tr19L9gg92jYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRYwB5fkUWlZql6zJChkyLQKsXF+jAfBgNVHSMEGDAWgBRYwB5fkUWlZql6zJChkyLQKsXF+jAKBggqhkjOPQQDAwNpADBmAjEAj1nHeXZp+13NWBNa+EDsDP8G1WWg1tCMWP/WHPqpaVo0jhsweNFZgSs0eE7wYI4qAjEA2WB9ot98sIkoF3vZYdd3/VtWB5b9TNMea7Ix/stJ5TfcLLeABLE4BNJOsQ4vnBHJ"]}],gt=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var Ar="1.2.840.10045.2.1",br={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},Er={"P-256":32,"P-384":48},Tr={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function ft(t,e,r){if(e+2>r)throw new Error("it is truncated");let n=t[e];if((n&31)===31)throw new Error("it uses a tag this parser does not read");let i=t[e+1],s=e+2;if(i&128){let a=i&127;if(a===0||a>4||s+a>r)throw new Error("it has a length this parser does not read");i=0;for(let c=0;c<a;c+=1)i=i*256+t[s+c];s+=a}let o=s+i;if(o>r)throw new Error("it is truncated");return{tag:n,bytes:t,offset:e,start:s,end:o}}function j(t){let e=ft(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function m(t){let e=[];for(let r=t.start;r<t.end;){let n=ft(t.bytes,r,t.end);e.push(n),r=n.end}return e}function w(t,e,r){if(!t||t.tag!==e)throw new Error(`${r} is not where it should be`);return t}function k(t){return t.bytes.slice(t.start,t.end)}function le(t){return t.bytes.slice(t.offset,t.end)}function F(t){let e=k(w(t,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let r=[],n=0;for(let o of e)n=n*128+(o&127),o&128||(r.push(n),n=0);let i=r.shift();return[...i<80?[Math.floor(i/40),i%40]:[2,i-80],...r].join(".")}function Pr(t){let e=new TextDecoder().decode(k(t)),r=t.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,n=t.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,i=r??n;if(!i)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let s=Number(i[1]);r&&(s+=s<50?2e3:1900);let[o,a,c,d,u]=i.slice(2).map(Number);return Date.UTC(s,o-1,a,c,d,u)}function _e(t){try{let[e,r,n,...i]=m(w(j(t),48,"The certificate"));if(i.length>0)throw new Error("it has fields after its signature");let s=m(w(e,48,"The signed part")),o=s[0]?.tag===160?1:0,[a,c,d,u,g,f,...h]=s.slice(o);w(a,2,"The serial number");let y=F(m(w(r,48,"The signature algorithm"))[0]);if(F(m(w(c,48,"The signature algorithm"))[0])!==y)throw new Error("it names two different signature algorithms");let O=Tr[y];if(!O)throw new Error(`it is signed with ${y}, not ECDSA with SHA-256 or SHA-384`);let[E,R]=m(w(u,48,"The validity")).map(Pr);if(R===void 0)throw new Error("its validity is incomplete");let[D,xe]=m(w(f,48,"The public key"));w(xe,3,"The public key");let[Se,P]=m(w(D,48,"The key algorithm"));if(F(Se)!==Ar)throw new Error("its key is not an elliptic-curve key");let K=br[F(P)];if(!K)throw new Error("its key is on a curve other than P-256 or P-384");let z=new Map,ae=h.find(ke=>ke.tag===163);if(ae){let[ke]=m(ae);for(let Zt of m(w(ke,48,"The extensions"))){let H=m(w(Zt,48,"An extension"));if(H.length===3)w(H[1],1,"An extension's critical flag");else if(H.length!==2)throw new Error("it has a malformed extension");let Ce=F(H[0]);if(z.has(Ce))throw new Error(`it has extension ${Ce} twice`);z.set(Ce,k(w(H[H.length-1],4,"An extension value")))}}let V=k(w(n,3,"The signature"));if(V[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:le(e),signatureHash:O,signature:V.slice(1),issuer:le(w(d,48,"The issuer")),subject:le(w(g,48,"The subject")),notBefore:E,notAfter:R,spki:le(f),curve:K,extensions:z}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function yt(t){return m(w(j(t),48,"The list")).map(F)}function Ur(t,e){let r=Er[e],n=m(w(j(t),48,"The signature"));if(n.length!==2)throw new Error("The signature is not an ECDSA signature");let i=new Uint8Array(r*2);return n.forEach((s,o)=>{let a=k(w(s,2,"The signature"));if(a.length===0||a[0]&128)throw new Error("The signature is not an ECDSA signature");for(;a.length>1&&a[0]===0;)a=a.subarray(1);if(a.length>r)throw new Error("The signature is not an ECDSA signature");i.set(a,o*r+r-a.length)}),i}async function ue(t,e,r,n,i){let s;try{s=Ur(n,e)}catch{return!1}let o=await crypto.subtle.importKey("spki",t,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:r},o,s,i)}function U(t,e){let r=t.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(r)||r.length%4!==0)throw new Error(`${e} is not base64`);let n=atob(r),i=new Uint8Array(n.length);for(let s=0;s<n.length;s+=1)i[s]=n.charCodeAt(s);return i}function $e(t,e){let r=[...t.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(r.length!==1||t.replace(r[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return U(r[0][1],e)}var Rr="2.5.29.17",xr="2.5.29.37",Sr="1.3.6.1.5.5.7.3.3",kr="1.3.6.1.4.1.57264.1.8",Cr="1.3.6.1.4.1.57264.1.1",vr=134,Ir=12,Nr=48,Or=new TextEncoder,G=t=>new TextDecoder().decode(t);async function de(t,e,r,n){let{base64Signature:i,cert:s,rekorBundle:o}=$r(e),a=o.Payload;if(n!==void 0&&n.trim()!==i.trim())throw new Error("The detached signature is not the one in the bundle");let c=U(i,"The bundle signature"),d=$e(G(U(s,"The bundle certificate")),"The bundle certificate"),u=_e(d),g=gt.find(R=>R.logId===a.logID.toLowerCase());if(!g)throw new Error(`The bundle names Rekor log ${a.logID}, which the Sigstore trust root does not know`);let f=Or.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await ue(U(g.publicKey,"The Rekor key"),"P-256","SHA-256",U(o.SignedEntryTimestamp,"The signed entry timestamp"),f))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let y=a.integratedTime*1e3;if(!wt(y,g.validFor))throw new Error(`Rekor log ${g.baseUrl} was not in use at ${ee(y)}, when the entry says it was logged`);let b=Br(a.body),O=T(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(b.hash!==O)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!Be(U(b.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let E=$e(G(U(b.publicKey,"The logged certificate")),"The logged certificate");if(!Be(E,d))throw new Error("The bundle's certificate is not the one Rekor logged");if(u.curve!=="P-256"||!await ue(u.spki,"P-256","SHA-256",c,t))throw new Error("The signature over the file does not verify with the bundle's certificate");return await Dr(u,y),_r(u,r),{integratedTime:a.integratedTime}}async function Dr(t,e){if(!ht(t,e))throw new Error(`The signing certificate was valid ${ee(t.notBefore)} to ${ee(t.notAfter)}, not at ${ee(e)} when Rekor logged it`);let r=[];for(let n of dt){let i=n.certChain.map(o=>_e(U(o,"A Fulcio certificate")));if(!await pt(t,i[0]))continue;let s=await Mr(i,n.validFor,e);if(!s)return;r.push(`${n.uri} (valid from ${n.validFor.start}): ${s}`)}throw new Error(r.length>0?`The signing certificate's CA is not trusted at ${ee(e)}: ${r.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function Mr(t,e,r){if(!wt(r,e))return"the trust root says it was not issuing certificates then";for(let[n,i]of t.entries()){if(!ht(i,r))return`its certificate ${n} was not valid then`;let s=t[n+1]??i;if(!await pt(i,s))return`its certificate ${n} is not signed by the next`}}async function pt(t,e){return Be(t.issuer,e.subject)?ue(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function _r(t,e){let r=t.extensions.get(Rr);if(!r)throw new Error("The signing certificate names no identity");let n=m(w(j(r),Nr,"The subject alternative name")),i=n.filter(d=>d.tag===vr).map(d=>G(k(d)));if(i.length!==1||n.length!==1||i[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(i.length===1?i[0]:i)}, not by ${e.identity}`);let s=t.extensions.get(kr),o=t.extensions.get(Cr),a=s?G(k(w(j(s),Ir,"The OIDC issuer"))):o?G(o):void 0;if(a!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${a===void 0?"missing":JSON.stringify(a)}, not ${e.issuer}`);let c=t.extensions.get(xr);if(!c||!yt(c).includes(Sr))throw new Error("The signing certificate is not for code signing")}function $r(t){let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let r=e,n=r?.rekorBundle?.Payload;if(!(typeof r?.base64Signature=="string"&&typeof r.cert=="string"&&typeof r.rekorBundle?.SignedEntryTimestamp=="string"&&typeof n?.body=="string"&&typeof n.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(n.logID)&&Number.isSafeInteger(n.integratedTime)&&n.integratedTime>=0&&Number.isSafeInteger(n.logIndex)&&n.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return r}function Br(t){let e;try{e=JSON.parse(G(U(t,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let r=e?.spec?.data?.hash,n=e?.spec?.signature;if(e?.kind!=="hashedrekord"||r?.algorithm!=="sha256"||typeof r.value!="string"||typeof n?.content!="string"||typeof n.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:r.value.toLowerCase(),signature:n.content,publicKey:n.publicKey.content}}function ht(t,e){return t.notBefore<=e&&e<=t.notAfter}function wt(t,e){return Date.parse(e.start)<=t&&(e.end===void 0||t<=Date.parse(e.end))}function ee(t){return new Date(t).toISOString()}function Be(t,e){return t.length===e.length&&t.every((r,n)=>r===e[n])}var Kr=/^[0-9a-f]{96}$/,Vr=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function _(t){let e=Q(t.allowedMrtd??[],"allowedMrtd"),r=(t.allowedMeasurements??[]).map((a,c)=>{let d=`allowedMeasurements[${c}]`;return Vr.map(u=>Q([a?.[u]??""],`${d}.${u}`)[0]).join()}),n=[Q(t.allowedRtmr0??[],"allowedRtmr0"),Q(t.allowedRtmr1??[],"allowedRtmr1"),Q(t.allowedRtmr2??[],"allowedRtmr2"),Q(t.allowedRtmr3??[],"allowedRtmr3")];if(t.allowedMeasurements!==void 0&&r.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(r.length===0){if(e.length===0)throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");if(n.slice(1).some(a=>a.length===0))throw new Error("allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too")}let i=t.allowedTcbStatuses??["UpToDate"],s=t.now??Date.now;return Object.assign(async({quoteB64:a,nonce:c,reportDataSuffix:d,collateral:u})=>{let g=Lr(a),f=u??await t.fetchCollateral?.(g);if(!f)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let h;try{h=t.dcapVerify(g,f,Math.floor(s()/1e3))}catch(E){throw new Error(`The quote did not verify: ${E?.message??String(E)}`)}if(h.status==="Revoked"||!i.includes(h.status))throw new Error(`The platform's TCB status is ${h.status}, which is not accepted`);let y=Hr(h.report);if(y.tdAttributes?.length!==8||(y.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let b=[y.mrTd,y.rtMr0,y.rtMr1,y.rtMr2,y.rtMr3].map(E=>T(E));if(r.length>0&&!r.includes(b.join()))throw new Error(`The measurements (MRTD ${b[0]}, RTMR0-3 ${b.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(b[0]))throw new Error(`MRTD ${b[0]} is not an image this verifier trusts`);if([y.rtMr0,y.rtMr1,y.rtMr2,y.rtMr3].forEach((E,R)=>{let D=n[R];if(D.length>0&&!D.includes(T(E)))throw new Error(`RTMR${R} ${T(E)} is not one this verifier trusts`)}),T(y.reportData)!==`${c}${d}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function Q(t,e){return t.map(r=>{let n=r.trim().toLowerCase();if(!Kr.test(n))throw new Error(`${e} holds ${JSON.stringify(r)}, which is not a 48-byte hex measurement`);return n})}function Hr(t){let e=t.data;if(t.type==="td10"&&e)return e;if(t.type==="td15"&&e?.base)return e.base;throw new Error(`The quote is a ${t.type} quote, not a TDX one`)}function Lr(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)r[n]=e.charCodeAt(n);return r}var Fr=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],M="locked-read-only";function Ke(t,{profile:e,allowDebugProfile:r=!1}){if(t.length===0)throw new Error("No release given, so no image would be trusted");let n,i=t.map((s,o)=>{let a=s?.tag??`releases[${o}]`;if(s?.role!==void 0&&s.role!=="node")throw new Error(`${a} lists the measurements of a ${s.role}, not of a node image`);let c=s?.profiles?.[e];if(!c){let u=Object.keys(s?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${u})`)}if(e!==M&&!r)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(M)}, or pass allowDebugProfile to test`);let d=(c.allowed_tcb_statuses??["uptodate"]).map(u=>jr(u,a));return n=n===void 0?d:n.filter(u=>d.includes(u)),{mrtd:c.mrtd,rtmr0:c.rtmr0,rtmr1:c.rtmr1,rtmr2:c.rtmr2,rtmr3:c.rtmr3}});if(!n||n.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:i,allowedTcbStatuses:n}}function jr(t,e){let r=Fr.find(n=>n.toLowerCase()===String(t).toLowerCase());if(!r)throw new Error(`${e} accepts TCB status ${JSON.stringify(t)}, which this verifier does not know`);return r}var Ve=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-node-image-gcp.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),Gr=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],He="https://cloud.calimero.network";async function At(t,e,r={}){let n=typeof t=="string"?new TextEncoder().encode(t):t;await de(n,e,{identity:r.identity??Ve.identity,issuer:r.issuer??Ve.issuer},r.signature);let i;try{i=JSON.parse(new TextDecoder().decode(n))}catch{throw new Error("The signed release is not JSON")}if(i?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(i?.role)} release, not a node one`);let s=Object.values(i.profiles??{}),o=a=>Gr.every(c=>/^[0-9a-f]{96}$/i.test(String(a?.[c])));if(typeof i.tag!="string"||s.length===0||!s.every(o))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(r.expectedVersion!==void 0&&i.tag!==r.expectedVersion)throw new Error(`The signed release is ${i.tag}, not ${r.expectedVersion}`);return i}async function Le(t,e={}){let r=await(e.fetch??fetch)(t,{headers:{accept:"application/json"}});if(!r.ok)throw new Error(`Fetching the node release from ${t} failed: HTTP ${r.status}`);let n;try{n=(await r.json())?.data}catch{throw new Error(`${t} did not answer with JSON`)}if(typeof n?.version!="string"||typeof n.publishedMrtds!="string"||typeof n.bundle!="string")throw new Error(`${t} did not answer with a signed node release`);return{version:n.version,publishedMrtds:n.publishedMrtds,bundle:n.bundle}}var bt="https://github.com/calimero-network/mero-tee/releases/download";async function Fe(t,e={}){let r=`mero-tee-v${C(t,"version")}`,n=`${(e.base??bt).replace(/\/+$/,"")}/${r}/published-mrtds.json`,i=async a=>{let c=await(e.fetch??fetch)(a);if(!c.ok)throw new Error(`Fetching ${a} failed: HTTP ${c.status}`);return c.text()},[s,o]=await Promise.all([i(n),i(`${n}.bundle.json`)]);return{version:t,publishedMrtds:s,bundle:o}}function je(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${C(e,"version")}`}async function ge(t){let e=C(t.minReleaseVersion,"minReleaseVersion"),r=C(t.release?.version,"The release version"),n=await At(t.release.publishedMrtds,t.release.bundle,{expectedVersion:r,identity:t.identity,issuer:t.issuer});if(Ge(r,e)<0)throw new Error(`Release ${r} is older than the minimum trusted, ${e}`);return Ke([n],{profile:t.profile,allowDebugProfile:t.allowDebugProfile})}function Qr(t){return C(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async r=>{let n=await ge({release:await t.release(),profile:t.profile,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer});return _({dcapVerify:t.dcapVerify,fetchCollateral:t.fetchCollateral,now:t.now,...n})(r)},{includeCollateral:!0})}var Et=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function C(t,e){let r=typeof t=="string"?Et.exec(t):null,n=r?.[4];if(!r||n!==void 0&&n.split(".").some(i=>i===""))throw new Error(`${e} is ${JSON.stringify(t)}, not a release version like 2.3.87`);return t}function Ge(t,e){let[r,n]=mt(t),[i,s]=mt(e);for(let c=0;c<3;c+=1)if(r[c]!==i[c])return r[c]<i[c]?-1:1;if(n===void 0||s===void 0)return n===s?0:n===void 0?1:-1;let o=n.split("."),a=s.split(".");for(let c=0;c<Math.max(o.length,a.length);c+=1){let[d,u]=[o[c],a[c]];if(d===void 0||u===void 0)return d===void 0?-1:1;let[g,f]=[/^\d+$/.test(d),/^\d+$/.test(u)],h=g&&f?Math.sign(Number(d)-Number(u)):g!==f?g?-1:1:d<u?-1:d>u?1:0;if(h!==0)return h}return 0}function mt(t){let e=Et.exec(t);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var Ut="MOCK_TDX_QUOTE_V1";function qr(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function Qe(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}var Tt;async function Pt(t){Tt??(Tt=import("@phala/dcap-qvl"));let e=await Tt,r=typeof e[t]=="function"?e[t]:e.default?.[t];if(typeof r!="function")throw new TypeError(`@phala/dcap-qvl loaded without ${t}`);return r}function Rt(t,e){let r=C(e,"minReleaseVersion"),n=String(t.release?.version??"").trim().replace(/^mero-tee-v/,"").replace(/^v/,""),i=C(n,"The release the node names");if(Ge(i,r)<0)throw new Error(`mero-tee release ${i} is older than the minimum ${r}`);return i}async function Jr(t,e,r){let n=e.releaseSource;return typeof n=="function"?n(t):n==="github"?Fe(t,{fetch:r}):Le(je(n??He,t),{fetch:r})}async function zr(t,e,r,n){let i=Rt(t,r.minReleaseVersion),s=await ge({release:await Jr(i,r,n),profile:r.profile??M,allowDebugProfile:r.allowDebugProfile,minReleaseVersion:r.minReleaseVersion,identity:r.identity,issuer:r.issuer}),o=r.fetchCollateral??(async c=>(await Pt("getCollateralFromPcs"))(c));return _({dcapVerify:r.dcapVerify??await Pt("verify"),fetchCollateral:o,now:r.now,...s})(e)}async function qe(t,e,r=(n,i)=>fetch(n,i)){let n=T(crypto.getRandomValues(new Uint8Array(32))),i=new URL(`${t.replace(/\/+$/,"")}/attestation`);i.searchParams.set("nonce",n),e.appHash&&i.searchParams.set("appHash",e.appHash);let s=await r(i.toString());if(!s.ok)throw new Error(`The node refused to attest: HTTP ${s.status}`);let o=await s.json(),a=ce(o.transportKey,"transportKey",32),c=e.appHash?ce(e.appHash,"appHash",32):new Uint8Array(32),d=await De(c,a),u=qr(o.quote),g=new TextEncoder().encode(Ut);if(Qe(u.slice(0,g.length),g)){if(!e.allowMock)throw new Error("mock quote refused: this client only trusts real TEEs");let y=u.slice(g.length,g.length+64);if(!Qe(y.slice(0,32),ce(n,"nonce",32))||!Qe(y.slice(32),d))throw new Error("the quote does not bind this transport key, app and nonce");return a}let f={quoteB64:o.quote,nonce:n,reportDataSuffix:T(d)},h;if(e.verifyQuote)h=await e.verifyQuote(f);else if(e.release)h=await zr(o,f,e.release,r);else throw new Error("real quote refused: this client trusts no TD image (set policy.release)");if(!h)throw new Error("The attestation did not verify, so its transport key is not trusted");return a}var A=class extends Error{constructor(r,n,i,s={}){super(`${r} ${n}: ${i}`);this.status=r;this.code=n;this.details=s;this.name="CalimeroError"}},fe=class extends A{constructor(e,r={}){super(401,"UNAUTHENTICATED",e,r),this.name="LoginRequired"}},ye=class extends A{constructor(e,r={}){super(404,"NOT_FOUND",e,r),this.name="NotFound"}},q=class extends A{constructor(e,r={}){super(412,"CONFIRM_REQUIRED",e,r),this.name="ConfirmRequired"}},te=class extends Error{constructor(r){super("the passkey confirmation was cancelled");this.cause=r;this.name="ConfirmCancelled"}},pe=class extends A{constructor(e,r={}){super(413,"ARGS_TOO_LARGE",e,r),this.name="ArgsTooLarge"}},he=class extends A{constructor(e,r={}){super(409,"IDEMPOTENCY_MISMATCH",e,r),this.name="IdempotencyMismatch"}},we=class extends A{constructor(e,r={}){super(422,"APP_ERROR",e,r),this.name="AppError";let{appCode:n,fields:i}=Yr(r);this.appCode=n,this.fields=i}},me=class extends A{constructor(e,r={}){super(422,"TRAP",e,r),this.name="TrapError",this.kind=typeof r.kind=="string"?r.kind:""}},$=class extends A{constructor(e,r,n={},i,s){super(503,e,r,n),this.name="UnavailableError",this.reason=e.toLowerCase(),this.committed=e==="TIMEOUT"||e==="MIGRATING"?!1:"unknown",this.retryAfter=i,this.cause=s}};function Ae(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Yr(t){let e=typeof t.code=="string"?t:Ae(t.error);return{appCode:typeof e.code=="string"?e.code:"",fields:{...Ae(e.fields)}}}function Zr(t,e){for(let r of[t.retryAfter,e==null?void 0:Number(e)])if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}function be(t,e,r){let n=Ae(e),i=typeof n.error=="string"?n.error:"ERROR",s=typeof n.message=="string"?n.message:"",o=Ae(n.details);if(t===503)return new $(i,s,o,Zr(o,r));switch(`${t} ${i}`){case"401 UNAUTHENTICATED":return new fe(s,o);case"404 NOT_FOUND":return new ye(s,o);case"409 IDEMPOTENCY_MISMATCH":return new he(s,o);case"412 CONFIRM_REQUIRED":return new q(s,o);case"413 ARGS_TOO_LARGE":return new pe(s,o);case"422 APP_ERROR":return new we(s,o);case"422 TRAP":return new me(s,o);default:return new A(t,i,s,o)}}function x(t){let e="";for(let r of t)e+=String.fromCharCode(r);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function v(t){let e=t.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((t.length+3)%4),r=atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return n}var re=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);function xt(t){let e=new Error(t);return e.name="NotAllowedError",e}function Xr(){return{async create(t){let e=t,r=await navigator.credentials.create({publicKey:{challenge:re(v(e.challenge)),rp:e.rp,user:{...e.user,id:re(v(e.user.id))},pubKeyCredParams:e.pubKeyCredParams,excludeCredentials:(e.excludeCredentials??[]).map(i=>({type:i.type,id:re(v(i.id))})),authenticatorSelection:e.authenticatorSelection,attestation:"none",timeout:e.timeout}});if(!r)throw xt("passkey creation was cancelled");let n=r.response;return{attestationObject:x(new Uint8Array(n.attestationObject)),clientDataJson:x(new Uint8Array(n.clientDataJSON))}},async get(t,e,r){let n=await navigator.credentials.get({publicKey:{challenge:re(t),rpId:e,userVerification:"preferred",allowCredentials:(r??[]).map(s=>({type:"public-key",id:re(v(s))}))}});if(!n)throw xt("passkey sign-in was cancelled");let i=n.response;return{credentialId:x(new Uint8Array(n.rawId)),authenticatorData:x(new Uint8Array(i.authenticatorData)),clientDataJson:x(new Uint8Array(i.clientDataJSON)),signature:x(new Uint8Array(i.signature))}}}}function l(t){return encodeURIComponent(t)}function Wr(t){return t instanceof S&&t.status===413?be(413,{error:"TOO_LARGE",message:t.message.replace(/^Sealed request refused: /,"")}):t}async function Ee(t){let e=await t.text().catch(()=>""),r={};try{r=e?JSON.parse(e):{}}catch{r={message:e}}return be(t.status,r,t.headers.get("retry-after"))}async function*en(t){let e=t.getReader(),r=new TextDecoder,n="";for(;;){let{value:i,done:s}=await e.read();if(s)return;n+=r.decode(i,{stream:!0});let o;for(;(o=n.indexOf(`
1
+ function R(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function de(t,e,r){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length!==r*2)throw new Error(`${e} must be ${r*2} hex characters, got ${n.length}`);let i=new Uint8Array(r);for(let s=0;s<r;s+=1)i[s]=Number.parseInt(n.slice(s*2,s*2+2),16);return i}function y(...t){let e=new Uint8Array(t.reduce((n,i)=>n+i.length,0)),r=0;for(let n of t)e.set(n,r),r+=n.length;return e}var ur="Noise_NK_25519_AESGCM_SHA256",Me=32,dr=16,gr=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),_e=class t{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(ur),r=new Uint8Array(32);return r.set(e),new t(r)}async mixHash(e){this.h=await pr(y(this.h,e))}async mixKey(e){let[r,n]=await at(this.ck,e);this.ck=r,this.k=await crypto.subtle.importKey("raw",n,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:ot(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(r),r}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let r=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:ot(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),r}split(){return at(this.ck,new Uint8Array)}};async function ct(t,e,r){let n=await _e.initialize();await n.mixHash(e),await n.mixHash(t);let i=await L(r);return await n.mixHash(i.publicKey),await n.mixKey(await Y(i.privateKey,t)),{message1:y(i.publicKey,await n.encryptAndHash(new Uint8Array)),async finish(o){if(o.length<Me+dr)throw new Error("Noise: message 2 is too short");let a=o.slice(0,Me);return await n.mixHash(a),await n.mixKey(await Y(i.privateKey,a)),{payload:await n.decryptAndHash(o.slice(Me)),split:await n.split()}}}}async function L(t){if(!t){let n;try{n=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"])}catch(s){throw new Error(`Sealed transport needs WebCrypto with X25519, which this runtime lacks (${s?.name??"no crypto.subtle"}). Current browsers and Node have it; in React Native, install react-native-quick-crypto as the global crypto.`)}let i=new Uint8Array(await crypto.subtle.exportKey("raw",n.publicKey));return{privateKey:n.privateKey,publicKey:i}}let e=await crypto.subtle.importKey("pkcs8",y(gr,t),{name:"X25519"},!0,["deriveBits"]),r=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:fr(r.x)}}async function Y(t,e){let r=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:r},t,256))}function ot(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}async function pr(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}async function $e(t,e){let r=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",r,e))}async function at(t,e){let r=await $e(t,e),n=await $e(r,new Uint8Array([1])),i=await $e(r,y(n,new Uint8Array([2])));return[n,i]}function fr(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(r,n=>n.charCodeAt(0))}var gt="/sealed/v2/handshake",pt="/sealed/v2",X="application/vnd.calimero.sealed",Be=2,yr=new TextEncoder().encode("calimero/sealed-http/v2"),Z=16,hr=1+Z+8,wr=0,mr=1,Ar=2,br=1+64*1024+16,Er=1024,Rr=6e4,Pr="calimero.tee-attest.transport-key.v1",Ur=[101,204,205,304],ft=new TextEncoder,W=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},S=class extends Error{constructor(r,n,i,s){super(i);this.status=r;this.code=n;this.retryAfterMs=s;this.name="SealedTransportError"}};async function Ke(t,e){let r=await crypto.subtle.digest("SHA-256",y(ft.encode(Pr),t,e));return new Uint8Array(r)}function Ve(t){let e=new URL(t.baseUrl),r=e.pathname.replace(/\/+$/,""),n=`${e.origin}${r}`,i=t.fetch??((g,p)=>fetch(g,p)),s=typeof t.transportPublicKey=="function"?t.transportPublicKey:void 0,o=s?Promise.resolve().then(s):Promise.resolve(t.transportPublicKey);o.catch(()=>{});let a,c=async()=>{try{return await ut(i,n,await lt(o))}catch(g){if(!(g instanceof W)||!s)throw g;return o=Promise.resolve().then(s),ut(i,n,await lt(o))}},u=async()=>{let g=a??d(void 0),p=await g;if(Date.now()<p.renewAt)return[p,g];let h=d(g);return[await h,h]},d=g=>{if(a===g){let p=c();a=p,p.catch(()=>{a===p&&(a=void 0)})}return a};return async(g,p)=>{let h=new Request(g,p),f=new URL(h.url);if(f.origin!==e.origin||!f.pathname.startsWith(`${r}/`))throw new Error(`Refusing to send ${f.href} outside the sealed node at ${t.baseUrl}`);let b=[];h.headers.forEach((P,K)=>b.push([K,P]));let N={method:h.method,path:f.pathname.slice(r.length)+f.search,headers:b},E=new Uint8Array(await h.arrayBuffer()),x=p?.signal??(g instanceof Request?g.signal:void 0),D=async P=>{let{requestId:K,header:z,envelope:ue}=await Tr(P,N,E),V=await i(`${n}${pt}`,{method:"POST",headers:{"content-type":X},body:ue,signal:x});if(V.headers.get("content-type")!==X)throw await ht(V);return kr(V,P.responseKey,z,K)},[Ie,Oe]=await u();try{return await D(Ie)}catch(P){if(!(P instanceof S)||P.code!=="unknown_session")throw P;return D(await d(Oe))}}}async function lt(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function ut(t,e,r){try{return await dt(t,e,r)}catch(n){if(!(n instanceof S)||n.code!=="busy")throw n;return await new Promise(i=>setTimeout(i,n.retryAfterMs??1e3)),dt(t,e,r)}}async function dt(t,e,r){let n=await ct(r,yr),i=await t(`${e}${gt}`,{method:"POST",headers:{"content-type":X},body:y(new Uint8Array([Be]),r,n.message1)});if(i.headers.get("content-type")!==X)throw await ht(i);let s=await Cr(i,Er);return xr(n,s)}async function xr(t,e){if(e[0]!==Be)throw new Error("The handshake reply is malformed");let r;try{r=await t.finish(e.slice(1))}catch{throw new Error("The handshake reply did not open: it did not come from the attested node")}let{payload:n,split:i}=r;if(n.length!==Z+4)throw new Error("The handshake reply is malformed");let s=n.slice(0,Z),o=new DataView(n.buffer,n.byteOffset).getUint32(Z,!1),[a,c]=await Promise.all([crypto.subtle.importKey("raw",i[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",i[1],"AES-GCM",!1,["decrypt"])]);return i[0].fill(0),i[1].fill(0),{requestKey:a,responseKey:c,nextRequestId:1,renewAt:Date.now()+o*1e3-Rr,header(u){let d=new Uint8Array(hr);return d[0]=Be,d.set(s,1),new DataView(d.buffer).setBigUint64(1+Z,BigInt(u),!1),d}}}async function Tr(t,e,r){let n=t.nextRequestId;t.nextRequestId+=1;let i=t.header(n),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:yt(n,0),additionalData:i},t.requestKey,Sr(e,r));return{requestId:n,header:i,envelope:y(i,new Uint8Array(s))}}function yt(t,e){let r=new Uint8Array(12),n=new DataView(r.buffer);return n.setBigUint64(0,BigInt(t),!1),n.setUint32(8,e,!1),r}function Sr(t,e){let r=ft.encode(JSON.stringify(t)),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,r.length,!1),y(n,r,e)}async function kr(t,e,r,n){if(!t.body)throw new Error("The sealed response has no body");let i=vr(t.body.getReader()),s=0,o=async()=>{let d=await i.next();if(!d)return null;let g;try{g=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:yt(n,s),additionalData:r},e,d))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return s+=1,{kind:g[0],data:g.slice(1)}},a=await o();if(!a||a.kind!==wr)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(Ur.includes(c.status))return await i.cancel(),new Response(null,{status:c.status,headers:c.headers});let u=new ReadableStream({async pull(d){try{let g=await o();g?g.kind===mr?d.enqueue(g.data):g.kind===Ar?(d.close(),await i.cancel()):d.error(new Error("The sealed response is malformed")):d.error(new Error("The sealed response was cut short"))}catch(g){d.error(g)}},cancel(){return i.cancel()}});return new Response(u,{status:c.status,headers:c.headers})}function vr(t){let e=new Uint8Array,r=async n=>{for(;e.length<n;){let{done:i,value:s}=await t.read();if(i)return!1;e=y(e,s)}return!0};return{async next(){if(!await r(4))return null;let n=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(n>br)throw await t.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await r(4+n))return null;let i=e.slice(4,4+n);return e=e.slice(4+n),i},cancel:()=>t.cancel()}}async function Cr(t,e){if(!t.body)return new Uint8Array;let r=t.body.getReader(),n=new Uint8Array;for(;;){let{done:i,value:s}=await r.read();if(i)return n;if(n=y(n,s),n.length>e)throw await r.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function ht(t){let e,r=`Sealed request refused: HTTP ${t.status}`;try{let s=await t.json();e=s?.error?.code,s?.error?.message&&(r=`Sealed request refused: ${s.error.message}`)}catch{}if(e==="stale_transport_key")return new W;let n=Number(t.headers.get("retry-after")),i=Number.isFinite(n)&&n>0?Math.min(n,5)*1e3:void 0;return new S(t.status,e,r,i)}var wt=[{uri:"https://fulcio.sigstore.dev",validFor:{start:"2021-03-07T03:20:29Z",end:"2022-12-31T23:59:59.999Z"},certChain:["MIIB+DCCAX6gAwIBAgITNVkDZoCiofPDsy7dfm6geLbuhzAKBggqhkjOPQQDAzAqMRUwEwYDVQQKEwxzaWdzdG9yZS5kZXYxETAPBgNVBAMTCHNpZ3N0b3JlMB4XDTIxMDMwNzAzMjAyOVoXDTMxMDIyMzAzMjAyOVowKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTB2MBAGByqGSM49AgEGBSuBBAAiA2IABLSyA7Ii5k+pNO8ZEWY0ylemWDowOkNa3kL+GZE5Z5GWehL9/A9bRNA3RbrsZ5i0JcastaRL7Sp5fp/jD5dxqc/UdTVnlvS16an+2Yfswe/QuLolRUCrcOE2+2iA5+tzd6NmMGQwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwHQYDVR0OBBYEFMjFHQBBmiQpMlEk6w2uSu1KBtPsMB8GA1UdIwQYMBaAFMjFHQBBmiQpMlEk6w2uSu1KBtPsMAoGCCqGSM49BAMDA2gAMGUCMH8liWJfMui6vXXBhjDgY4MwslmN/TJxVe/83WrFomwmNf056y1X48F9c4m3a3ozXAIxAKjRay5/aj/jsKKGIkmQatjI8uupHr/+CxFvaJWmpYqNkLDGRU+9orzh5hI2RrcuaQ=="]},{uri:"https://fulcio.sigstore.dev",validFor:{start:"2022-04-13T20:06:15Z"},certChain:["MIICGjCCAaGgAwIBAgIUALnViVfnU0brJasmRkHrn/UnfaQwCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMjA0MTMyMDA2MTVaFw0zMTEwMDUxMzU2NThaMDcxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjEeMBwGA1UEAxMVc2lnc3RvcmUtaW50ZXJtZWRpYXRlMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8RVS/ysH+NOvuDZyPIZtilgUF9NlarYpAd9HP1vBBH1U5CV77LSS7s0ZiH4nE7Hv7ptS6LvvR/STk798LVgMzLlJ4HeIfF3tHSaexLcYpSASr1kS0N/RgBJz/9jWCiXno3sweTAOBgNVHQ8BAf8EBAMCAQYwEwYDVR0lBAwwCgYIKwYBBQUHAwMwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQU39Ppz1YkEZb5qNjpKFWixi4YZD8wHwYDVR0jBBgwFoAUWMAeX5FFpWapesyQoZMi0CrFxfowCgYIKoZIzj0EAwMDZwAwZAIwPCsQK4DYiZYDPIaDi5HFKnfxXx6ASSVmERfsynYBiX2X6SJRnZU84/9DZdnFvvxmAjBOt6QpBlc4J/0DxvkTCqpclvziL6BCCPnjdlIB3Pu3BxsPmygUY7Ii2zbdCdliiow=","MIIB9zCCAXygAwIBAgIUALZNAPFdxHPwjeDloDwyYChAO/4wCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMTEwMDcxMzU2NTlaFw0zMTEwMDUxMzU2NThaMCoxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjERMA8GA1UEAxMIc2lnc3RvcmUwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT7XeFT4rb3PQGwS4IajtLk3/OlnpgangaBclYpsYBr5i+4ynB07ceb3LP0OIOZdxexX69c5iVuyJRQ+Hz05yi+UF3uBWAlHpiS5sh0+H2GHE7SXrk1EC5m1Tr19L9gg92jYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRYwB5fkUWlZql6zJChkyLQKsXF+jAfBgNVHSMEGDAWgBRYwB5fkUWlZql6zJChkyLQKsXF+jAKBggqhkjOPQQDAwNpADBmAjEAj1nHeXZp+13NWBNa+EDsDP8G1WWg1tCMWP/WHPqpaVo0jhsweNFZgSs0eE7wYI4qAjEA2WB9ot98sIkoF3vZYdd3/VtWB5b9TNMea7Ix/stJ5TfcLLeABLE4BNJOsQ4vnBHJ"]}],mt=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var Ir="1.2.840.10045.2.1",Or={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},Nr={"P-256":32,"P-384":48},Dr={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function At(t,e,r){if(e+2>r)throw new Error("it is truncated");let n=t[e];if((n&31)===31)throw new Error("it uses a tag this parser does not read");let i=t[e+1],s=e+2;if(i&128){let a=i&127;if(a===0||a>4||s+a>r)throw new Error("it has a length this parser does not read");i=0;for(let c=0;c<a;c+=1)i=i*256+t[s+c];s+=a}let o=s+i;if(o>r)throw new Error("it is truncated");return{tag:n,bytes:t,offset:e,start:s,end:o}}function F(t){let e=At(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function A(t){let e=[];for(let r=t.start;r<t.end;){let n=At(t.bytes,r,t.end);e.push(n),r=n.end}return e}function w(t,e,r){if(!t||t.tag!==e)throw new Error(`${r} is not where it should be`);return t}function k(t){return t.bytes.slice(t.start,t.end)}function ge(t){return t.bytes.slice(t.offset,t.end)}function G(t){let e=k(w(t,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let r=[],n=0;for(let o of e)n=n*128+(o&127),o&128||(r.push(n),n=0);let i=r.shift();return[...i<80?[Math.floor(i/40),i%40]:[2,i-80],...r].join(".")}function Mr(t){let e=new TextDecoder().decode(k(t)),r=t.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,n=t.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,i=r??n;if(!i)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let s=Number(i[1]);r&&(s+=s<50?2e3:1900);let[o,a,c,u,d]=i.slice(2).map(Number);return Date.UTC(s,o-1,a,c,u,d)}function He(t){try{let[e,r,n,...i]=A(w(F(t),48,"The certificate"));if(i.length>0)throw new Error("it has fields after its signature");let s=A(w(e,48,"The signed part")),o=s[0]?.tag===160?1:0,[a,c,u,d,g,p,...h]=s.slice(o);w(a,2,"The serial number");let f=G(A(w(r,48,"The signature algorithm"))[0]);if(G(A(w(c,48,"The signature algorithm"))[0])!==f)throw new Error("it names two different signature algorithms");let N=Dr[f];if(!N)throw new Error(`it is signed with ${f}, not ECDSA with SHA-256 or SHA-384`);let[E,x]=A(w(d,48,"The validity")).map(Mr);if(x===void 0)throw new Error("its validity is incomplete");let[D,Ie]=A(w(p,48,"The public key"));w(Ie,3,"The public key");let[Oe,P]=A(w(D,48,"The key algorithm"));if(G(Oe)!==Ir)throw new Error("its key is not an elliptic-curve key");let K=Or[G(P)];if(!K)throw new Error("its key is on a curve other than P-256 or P-384");let z=new Map,ue=h.find(Ne=>Ne.tag===163);if(ue){let[Ne]=A(ue);for(let lr of A(w(Ne,48,"The extensions"))){let H=A(w(lr,48,"An extension"));if(H.length===3)w(H[1],1,"An extension's critical flag");else if(H.length!==2)throw new Error("it has a malformed extension");let De=G(H[0]);if(z.has(De))throw new Error(`it has extension ${De} twice`);z.set(De,k(w(H[H.length-1],4,"An extension value")))}}let V=k(w(n,3,"The signature"));if(V[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:ge(e),signatureHash:N,signature:V.slice(1),issuer:ge(w(u,48,"The issuer")),subject:ge(w(g,48,"The subject")),notBefore:E,notAfter:x,spki:ge(p),curve:K,extensions:z}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function bt(t){return A(w(F(t),48,"The list")).map(G)}function $r(t,e){let r=Nr[e],n=A(w(F(t),48,"The signature"));if(n.length!==2)throw new Error("The signature is not an ECDSA signature");let i=new Uint8Array(r*2);return n.forEach((s,o)=>{let a=k(w(s,2,"The signature"));if(a.length===0||a[0]&128)throw new Error("The signature is not an ECDSA signature");for(;a.length>1&&a[0]===0;)a=a.subarray(1);if(a.length>r)throw new Error("The signature is not an ECDSA signature");i.set(a,o*r+r-a.length)}),i}async function pe(t,e,r,n,i){let s;try{s=$r(n,e)}catch{return!1}let o=await crypto.subtle.importKey("spki",t,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:r},o,s,i)}function U(t,e){let r=t.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(r)||r.length%4!==0)throw new Error(`${e} is not base64`);let n=atob(r),i=new Uint8Array(n.length);for(let s=0;s<n.length;s+=1)i[s]=n.charCodeAt(s);return i}function Le(t,e){let r=[...t.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(r.length!==1||t.replace(r[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return U(r[0][1],e)}var _r="2.5.29.17",Br="2.5.29.37",Kr="1.3.6.1.5.5.7.3.3",Vr="1.3.6.1.4.1.57264.1.8",Hr="1.3.6.1.4.1.57264.1.1",Lr=134,Gr=12,Fr=48,jr=new TextEncoder,j=t=>new TextDecoder().decode(t);async function fe(t,e,r,n){let{base64Signature:i,cert:s,rekorBundle:o}=zr(e),a=o.Payload;if(n!==void 0&&n.trim()!==i.trim())throw new Error("The detached signature is not the one in the bundle");let c=U(i,"The bundle signature"),u=Le(j(U(s,"The bundle certificate")),"The bundle certificate"),d=He(u),g=mt.find(x=>x.logId===a.logID.toLowerCase());if(!g)throw new Error(`The bundle names Rekor log ${a.logID}, which the Sigstore trust root does not know`);let p=jr.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await pe(U(g.publicKey,"The Rekor key"),"P-256","SHA-256",U(o.SignedEntryTimestamp,"The signed entry timestamp"),p))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let f=a.integratedTime*1e3;if(!Pt(f,g.validFor))throw new Error(`Rekor log ${g.baseUrl} was not in use at ${ee(f)}, when the entry says it was logged`);let b=Yr(a.body),N=R(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(b.hash!==N)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!Ge(U(b.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let E=Le(j(U(b.publicKey,"The logged certificate")),"The logged certificate");if(!Ge(E,u))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await pe(d.spki,"P-256","SHA-256",c,t))throw new Error("The signature over the file does not verify with the bundle's certificate");return await Qr(d,f),Jr(d,r),{integratedTime:a.integratedTime}}async function Qr(t,e){if(!Rt(t,e))throw new Error(`The signing certificate was valid ${ee(t.notBefore)} to ${ee(t.notAfter)}, not at ${ee(e)} when Rekor logged it`);let r=[];for(let n of wt){let i=n.certChain.map(o=>He(U(o,"A Fulcio certificate")));if(!await Et(t,i[0]))continue;let s=await qr(i,n.validFor,e);if(!s)return;r.push(`${n.uri} (valid from ${n.validFor.start}): ${s}`)}throw new Error(r.length>0?`The signing certificate's CA is not trusted at ${ee(e)}: ${r.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function qr(t,e,r){if(!Pt(r,e))return"the trust root says it was not issuing certificates then";for(let[n,i]of t.entries()){if(!Rt(i,r))return`its certificate ${n} was not valid then`;let s=t[n+1]??i;if(!await Et(i,s))return`its certificate ${n} is not signed by the next`}}async function Et(t,e){return Ge(t.issuer,e.subject)?pe(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function Jr(t,e){let r=t.extensions.get(_r);if(!r)throw new Error("The signing certificate names no identity");let n=A(w(F(r),Fr,"The subject alternative name")),i=n.filter(u=>u.tag===Lr).map(u=>j(k(u)));if(i.length!==1||n.length!==1||i[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(i.length===1?i[0]:i)}, not by ${e.identity}`);let s=t.extensions.get(Vr),o=t.extensions.get(Hr),a=s?j(k(w(F(s),Gr,"The OIDC issuer"))):o?j(o):void 0;if(a!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${a===void 0?"missing":JSON.stringify(a)}, not ${e.issuer}`);let c=t.extensions.get(Br);if(!c||!bt(c).includes(Kr))throw new Error("The signing certificate is not for code signing")}function zr(t){let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let r=e,n=r?.rekorBundle?.Payload;if(!(typeof r?.base64Signature=="string"&&typeof r.cert=="string"&&typeof r.rekorBundle?.SignedEntryTimestamp=="string"&&typeof n?.body=="string"&&typeof n.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(n.logID)&&Number.isSafeInteger(n.integratedTime)&&n.integratedTime>=0&&Number.isSafeInteger(n.logIndex)&&n.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return r}function Yr(t){let e;try{e=JSON.parse(j(U(t,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let r=e?.spec?.data?.hash,n=e?.spec?.signature;if(e?.kind!=="hashedrekord"||r?.algorithm!=="sha256"||typeof r.value!="string"||typeof n?.content!="string"||typeof n.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:r.value.toLowerCase(),signature:n.content,publicKey:n.publicKey.content}}function Rt(t,e){return t.notBefore<=e&&e<=t.notAfter}function Pt(t,e){return Date.parse(e.start)<=t&&(e.end===void 0||t<=Date.parse(e.end))}function ee(t){return new Date(t).toISOString()}function Ge(t,e){return t.length===e.length&&t.every((r,n)=>r===e[n])}var Zr=/^[0-9a-f]{96}$/,Xr=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function $(t){let e=Q(t.allowedMrtd??[],"allowedMrtd"),r=(t.allowedMeasurements??[]).map((a,c)=>{let u=`allowedMeasurements[${c}]`;return Xr.map(d=>Q([a?.[d]??""],`${u}.${d}`)[0]).join()}),n=[Q(t.allowedRtmr0??[],"allowedRtmr0"),Q(t.allowedRtmr1??[],"allowedRtmr1"),Q(t.allowedRtmr2??[],"allowedRtmr2"),Q(t.allowedRtmr3??[],"allowedRtmr3")];if(t.allowedMeasurements!==void 0&&r.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(r.length===0){if(e.length===0)throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");if(n.slice(1).some(a=>a.length===0))throw new Error("allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too")}let i=t.allowedTcbStatuses??["UpToDate"],s=t.now??Date.now;return Object.assign(async({quoteB64:a,nonce:c,reportDataSuffix:u,collateral:d})=>{let g=en(a),p=d??await t.fetchCollateral?.(g);if(!p)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let h;try{h=t.dcapVerify(g,p,Math.floor(s()/1e3))}catch(E){throw new Error(`The quote did not verify: ${E?.message??String(E)}`)}if(h.status==="Revoked"||!i.includes(h.status))throw new Error(`The platform's TCB status is ${h.status}, which is not accepted`);let f=Wr(h.report);if(f.tdAttributes?.length!==8||(f.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let b=[f.mrTd,f.rtMr0,f.rtMr1,f.rtMr2,f.rtMr3].map(E=>R(E));if(r.length>0&&!r.includes(b.join()))throw new Error(`The measurements (MRTD ${b[0]}, RTMR0-3 ${b.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(b[0]))throw new Error(`MRTD ${b[0]} is not an image this verifier trusts`);if([f.rtMr0,f.rtMr1,f.rtMr2,f.rtMr3].forEach((E,x)=>{let D=n[x];if(D.length>0&&!D.includes(R(E)))throw new Error(`RTMR${x} ${R(E)} is not one this verifier trusts`)}),R(f.reportData)!==`${c}${u}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function Q(t,e){return t.map(r=>{let n=r.trim().toLowerCase();if(!Zr.test(n))throw new Error(`${e} holds ${JSON.stringify(r)}, which is not a 48-byte hex measurement`);return n})}function Wr(t){let e=t.data;if(t.type==="td10"&&e)return e;if(t.type==="td15"&&e?.base)return e.base;throw new Error(`The quote is a ${t.type} quote, not a TDX one`)}function en(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)r[n]=e.charCodeAt(n);return r}var tn=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],M="locked-read-only";function Fe(t,{profile:e,allowDebugProfile:r=!1}){if(t.length===0)throw new Error("No release given, so no image would be trusted");let n,i=t.map((s,o)=>{let a=s?.tag??`releases[${o}]`;if(s?.role!==void 0&&s.role!=="node")throw new Error(`${a} lists the measurements of a ${s.role}, not of a node image`);let c=s?.profiles?.[e];if(!c){let d=Object.keys(s?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${d})`)}if(e!==M&&!r)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(M)}, or pass allowDebugProfile to test`);let u=(c.allowed_tcb_statuses??["uptodate"]).map(d=>rn(d,a));return n=n===void 0?u:n.filter(d=>u.includes(d)),{mrtd:c.mrtd,rtmr0:c.rtmr0,rtmr1:c.rtmr1,rtmr2:c.rtmr2,rtmr3:c.rtmr3}});if(!n||n.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:i,allowedTcbStatuses:n}}function rn(t,e){let r=tn.find(n=>n.toLowerCase()===String(t).toLowerCase());if(!r)throw new Error(`${e} accepts TCB status ${JSON.stringify(t)}, which this verifier does not know`);return r}var je=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-node-image-gcp.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),nn=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],Qe="https://cloud.calimero.network";async function xt(t,e,r={}){let n=typeof t=="string"?new TextEncoder().encode(t):t;await fe(n,e,{identity:r.identity??je.identity,issuer:r.issuer??je.issuer},r.signature);let i;try{i=JSON.parse(new TextDecoder().decode(n))}catch{throw new Error("The signed release is not JSON")}if(i?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(i?.role)} release, not a node one`);let s=Object.values(i.profiles??{}),o=a=>nn.every(c=>/^[0-9a-f]{96}$/i.test(String(a?.[c])));if(typeof i.tag!="string"||s.length===0||!s.every(o))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(r.expectedVersion!==void 0&&i.tag!==r.expectedVersion)throw new Error(`The signed release is ${i.tag}, not ${r.expectedVersion}`);return i}async function qe(t,e={}){let r=await(e.fetch??fetch)(t,{headers:{accept:"application/json"}});if(!r.ok)throw new Error(`Fetching the node release from ${t} failed: HTTP ${r.status}`);let n;try{n=(await r.json())?.data}catch{throw new Error(`${t} did not answer with JSON`)}if(typeof n?.version!="string"||typeof n.publishedMrtds!="string"||typeof n.bundle!="string")throw new Error(`${t} did not answer with a signed node release`);return{version:n.version,publishedMrtds:n.publishedMrtds,bundle:n.bundle}}var Tt="https://github.com/calimero-network/mero-tee/releases/download";async function Je(t,e={}){let r=`mero-tee-v${v(t,"version")}`,n=`${(e.base??Tt).replace(/\/+$/,"")}/${r}/published-mrtds.json`,i=async a=>{let c=await(e.fetch??fetch)(a);if(!c.ok)throw new Error(`Fetching ${a} failed: HTTP ${c.status}`);return c.text()},[s,o]=await Promise.all([i(n),i(`${n}.bundle.json`)]);return{version:t,publishedMrtds:s,bundle:o}}function ze(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${v(e,"version")}`}async function ye(t){let e=v(t.minReleaseVersion,"minReleaseVersion"),r=v(t.release?.version,"The release version"),n=await xt(t.release.publishedMrtds,t.release.bundle,{expectedVersion:r,identity:t.identity,issuer:t.issuer});if(te(r,e)<0)throw new Error(`Release ${r} is older than the minimum trusted, ${e}`);return Fe([n],{profile:t.profile,allowDebugProfile:t.allowDebugProfile})}function sn(t){return v(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async r=>{let n=await ye({release:await t.release(),profile:t.profile,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer});return $({dcapVerify:t.dcapVerify,fetchCollateral:t.fetchCollateral,now:t.now,...n})(r)},{includeCollateral:!0})}var St=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function v(t,e){let r=typeof t=="string"?St.exec(t):null,n=r?.[4];if(!r||n!==void 0&&n.split(".").some(i=>i===""))throw new Error(`${e} is ${JSON.stringify(t)}, not a release version like 2.3.87`);return t}function te(t,e){let[r,n]=Ut(t),[i,s]=Ut(e);for(let c=0;c<3;c+=1)if(r[c]!==i[c])return r[c]<i[c]?-1:1;if(n===void 0||s===void 0)return n===s?0:n===void 0?1:-1;let o=n.split("."),a=s.split(".");for(let c=0;c<Math.max(o.length,a.length);c+=1){let[u,d]=[o[c],a[c]];if(u===void 0||d===void 0)return u===void 0?-1:1;let[g,p]=[/^\d+$/.test(u),/^\d+$/.test(d)],h=g&&p?Math.sign(Number(u)-Number(d)):g!==p?g?-1:1:u<d?-1:u>d?1:0;if(h!==0)return h}return 0}function Ut(t){let e=St.exec(t);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var Ct="MOCK_TDX_QUOTE_V1";function on(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function Ye(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}var kt;async function vt(t){kt??(kt=import("@phala/dcap-qvl"));let e=await kt,r=typeof e[t]=="function"?e[t]:e.default?.[t];if(typeof r!="function")throw new TypeError(`@phala/dcap-qvl loaded without ${t}`);return r}function It(t,e){let r=v(e,"minReleaseVersion"),n=String(t.release?.version??"").trim().replace(/^mero-tee-v/,"").replace(/^v/,""),i=v(n,"The release the node names");if(te(i,r)<0)throw new Error(`mero-tee release ${i} is older than the minimum ${r}`);return i}async function an(t,e,r){let n=e.releaseSource;return typeof n=="function"?n(t):n==="github"?Je(t,{fetch:r}):qe(ze(n??Qe,t),{fetch:r})}async function cn(t,e,r,n){let i=It(t,r.minReleaseVersion),s=await ye({release:await an(i,r,n),profile:r.profile??M,allowDebugProfile:r.allowDebugProfile,minReleaseVersion:r.minReleaseVersion,identity:r.identity,issuer:r.issuer}),o=r.fetchCollateral??(async c=>(await vt("getCollateralFromPcs"))(c));return $({dcapVerify:r.dcapVerify??await vt("verify"),fetchCollateral:o,now:r.now,...s})(e)}async function Ze(t,e,r=(n,i)=>fetch(n,i)){let n=R(crypto.getRandomValues(new Uint8Array(32))),i=new URL(`${t.replace(/\/+$/,"")}/attestation`);i.searchParams.set("nonce",n),e.appHash&&i.searchParams.set("appHash",e.appHash);let s=await r(i.toString());if(!s.ok)throw new Error(`The node refused to attest: HTTP ${s.status}`);let o=await s.json(),a=de(o.transportKey,"transportKey",32),c=e.appHash?de(e.appHash,"appHash",32):new Uint8Array(32),u=await Ke(c,a),d=on(o.quote),g=new TextEncoder().encode(Ct);if(Ye(d.slice(0,g.length),g)){if(!e.allowMock)throw new Error("mock quote refused: this client only trusts real TEEs");let f=d.slice(g.length,g.length+64);if(!Ye(f.slice(0,32),de(n,"nonce",32))||!Ye(f.slice(32),u))throw new Error("the quote does not bind this transport key, app and nonce");return a}let p={quoteB64:o.quote,nonce:n,reportDataSuffix:R(u)},h;if(e.verifyQuote)h=await e.verifyQuote(p);else if(e.release)h=await cn(o,p,e.release,r);else throw new Error("real quote refused: this client trusts no TD image (set policy.release)");if(!h)throw new Error("The attestation did not verify, so its transport key is not trusted");return a}var m=class extends Error{constructor(r,n,i,s={}){super(`${r} ${n}: ${i}`);this.status=r;this.code=n;this.details=s;this.name="CalimeroError"}},he=class extends m{constructor(e,r={}){super(401,"UNAUTHENTICATED",e,r),this.name="LoginRequired"}},we=class extends m{constructor(e,r={}){super(404,"NOT_FOUND",e,r),this.name="NotFound"}},q=class extends m{constructor(e,r={}){super(412,"CONFIRM_REQUIRED",e,r),this.name="ConfirmRequired"}},re=class extends Error{constructor(r){super("the passkey confirmation was cancelled");this.cause=r;this.name="ConfirmCancelled"}},me=class extends m{constructor(e,r={}){super(413,"ARGS_TOO_LARGE",e,r),this.name="ArgsTooLarge"}},Ae=class extends m{constructor(e,r={}){super(409,"IDEMPOTENCY_MISMATCH",e,r),this.name="IdempotencyMismatch"}},be=class extends m{constructor(e,r={}){super(409,"RELEASE_DEADLINE",e,r),this.name="ReleaseDeadlineError",this.release=typeof r.release=="string"?r.release:"",this.after=typeof r.after=="string"?r.after:""}},Ee=class extends m{constructor(e,r={}){super(409,"CONSENT_STALE",e,r),this.name="ConsentStale"}},Re=class extends m{constructor(e,r={}){super(422,"APP_ERROR",e,r),this.name="AppError";let{appCode:n,fields:i}=ln(r);this.appCode=n,this.fields=i}},Pe=class extends m{constructor(e,r={}){super(422,"TRAP",e,r),this.name="TrapError",this.kind=typeof r.kind=="string"?r.kind:""}},_=class extends m{constructor(e,r,n={},i,s){super(503,e,r,n),this.name="UnavailableError",this.reason=e.toLowerCase(),this.committed=e==="TIMEOUT"||e==="MIGRATING"?!1:"unknown",this.retryAfter=i,this.cause=s}};function Ue(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function ln(t){let e=typeof t.code=="string"?t:Ue(t.error);return{appCode:typeof e.code=="string"?e.code:"",fields:{...Ue(e.fields)}}}function un(t,e){for(let r of[t.retryAfter,e==null?void 0:Number(e)])if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}function xe(t,e,r){let n=Ue(e),i=typeof n.error=="string"?n.error:"ERROR",s=typeof n.message=="string"?n.message:"",o=Ue(n.details);if(t===503)return new _(i,s,o,un(o,r));switch(`${t} ${i}`){case"401 UNAUTHENTICATED":return new he(s,o);case"404 NOT_FOUND":return new we(s,o);case"409 IDEMPOTENCY_MISMATCH":return new Ae(s,o);case"409 RELEASE_DEADLINE":return new be(s,o);case"409 CONSENT_STALE":return new Ee(s,o);case"412 CONFIRM_REQUIRED":return new q(s,o);case"413 ARGS_TOO_LARGE":return new me(s,o);case"422 APP_ERROR":return new Re(s,o);case"422 TRAP":return new Pe(s,o);default:return new m(t,i,s,o)}}function T(t){let e="";for(let r of t)e+=String.fromCharCode(r);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function C(t){let e=t.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((t.length+3)%4),r=atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return n}var ne=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);function Ot(t){let e=new Error(t);return e.name="NotAllowedError",e}function dn(){return{async create(t){let e=t,r=await navigator.credentials.create({publicKey:{challenge:ne(C(e.challenge)),rp:e.rp,user:{...e.user,id:ne(C(e.user.id))},pubKeyCredParams:e.pubKeyCredParams,excludeCredentials:(e.excludeCredentials??[]).map(i=>({type:i.type,id:ne(C(i.id))})),authenticatorSelection:e.authenticatorSelection,attestation:"none",timeout:e.timeout}});if(!r)throw Ot("passkey creation was cancelled");let n=r.response;return{attestationObject:T(new Uint8Array(n.attestationObject)),clientDataJson:T(new Uint8Array(n.clientDataJSON))}},async get(t,e,r){let n=await navigator.credentials.get({publicKey:{challenge:ne(t),rpId:e,userVerification:"preferred",allowCredentials:(r??[]).map(s=>({type:"public-key",id:ne(C(s))}))}});if(!n)throw Ot("passkey sign-in was cancelled");let i=n.response;return{credentialId:T(new Uint8Array(n.rawId)),authenticatorData:T(new Uint8Array(i.authenticatorData)),clientDataJson:T(new Uint8Array(i.clientDataJSON)),signature:T(new Uint8Array(i.signature))}}}}var Xe=100;function se(t={}){let e=new URLSearchParams;if(t.after!==void 0&&e.set("after",t.after),t.limit!==void 0){if(!Number.isInteger(t.limit)||t.limit<1||t.limit>Xe)throw new RangeError(`limit is 1 to ${Xe}`);e.set("limit",String(t.limit))}let r=e.toString();return r?`?${r}`:""}function ie(t,e){try{return te(t,e)}catch{return t<e?-1:t>e?1:0}}function Nt(t,e,r=Date.now()/1e3){if(t===null||t.length===0)return null;let n=t.reduce((s,o)=>ie(s,o)>=0?s:o),i=null;for(let s of e)s.afterSecs<=r&&ie(n,s.version)<0&&(i===null||ie(s.version,i.version)>0)&&(i=s);return i}function Dt(t,e,r,n){return`calimero-publisher-binding/v1
2
+ ${t}
3
+ ${e}
4
+ ${r}
5
+ ${n}`}function gn(t,e,r,n){return new TextEncoder().encode(Dt(t,e,r,n))}function pn(t){let e=typeof t=="string"?new URL(t):t,r=e.searchParams.get("request_id"),n=e.searchParams.get("result");return!r||n!=="approved"&&n!=="declined"?null:{requestId:r,result:n}}var Mt="https://mero-tee.vercel.app";function $t(t){return`https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(t)}`}function _t(t){return`${Mt}/mero-tee?release_tag=${encodeURIComponent(`mero-tee-v${t}`)}`}function We(t,e,r=Date.now()/1e3){let n=c=>e.deadlines.find(u=>u.version===c)??null,i=t.governance.releases==="owner",s=t.governance.appUpgrades==="owner",o=t.clusterReleases.filter(c=>!c.approved).sort((c,u)=>ie(u.release,c.release)).map(c=>({version:c.release,nodes:c.nodes,actionable:i,releaseNotesUrl:$t(c.release),verifyUrl:_t(c.release),deadline:n(c.release)})),a=[];for(let c of t.apps){let u=c.availableVersions??[];c.package===null||u.length===0||a.push({app:c.app,name:c.name??null,package:c.package.package,from:c.package.version,to:u[u.length-1],available:u,actionable:s})}return{scope:t.scope,governance:t.governance,approvedReleases:t.approvedReleases,releases:o,upgrades:a,stalledBy:Nt(t.approvedReleases,e.deadlines,r),actionable:o.some(c=>c.actionable)||a.some(c=>c.actionable)}}function Bt(t,e,r,n={}){return{kind:"release",scope:t.kind==="org"?{org:t.org}:"account",subject:n.withdraw?{version:e,withdraw:!0}:{version:e},returnTo:r}}function fn(t,e,r){return Bt(t,e,r,{withdraw:!0})}function yn(t,e,r){return{kind:"upgrade",subject:{app:t,toVersion:e},returnTo:r}}function l(t){return encodeURIComponent(t)}function hn(t){return t instanceof S&&t.status===413?xe(413,{error:"TOO_LARGE",message:t.message.replace(/^Sealed request refused: /,"")}):t}async function Te(t){let e=await t.text().catch(()=>""),r={};try{r=e?JSON.parse(e):{}}catch{r={message:e}}return xe(t.status,r,t.headers.get("retry-after"))}async function*wn(t){let e=t.getReader(),r=new TextDecoder,n="";for(;;){let{value:i,done:s}=await e.read();if(s)return;n+=r.decode(i,{stream:!0});let o;for(;(o=n.indexOf(`
2
6
 
3
- `))>=0;){let a=n.slice(0,o);n=n.slice(o+2);let c="",d="",u="";for(let f of a.split(`
4
- `))f.startsWith("id:")?c=f.slice(3).trim():f.startsWith("event:")?d=f.slice(6).trim():f.startsWith("data:")&&(u+=f.slice(5).trim());if(!d&&!u)continue;let g=u;try{g=JSON.parse(u)}catch{}yield{id:c,kind:d,data:g}}}}function St(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function kt(){return`node:c-${x(crypto.getRandomValues(new Uint8Array(16)))}`}var tn={retries:6,baseDelayMs:200,maxDelayMs:2e3};function rn(t,e){return Math.min(e.baseDelayMs*2**t,e.maxDelayMs)}var Je=class{constructor(e){this.networkFailures=new WeakSet;this.base=e.baseUrl.replace(/\/+$/,""),this.retry={...tn,...e.retry};let r=e.fetch??((i,s)=>fetch(i,s)),n=async(i,s)=>{try{return await r(i,s)}catch(o){throw o instanceof TypeError&&this.networkFailures.add(o),o}};this.raw=n,this.sealed=Me({baseUrl:this.base,transportPublicKey:()=>qe(this.base,e.policy,n),fetch:n})}useApiKey(e){this.auth=e,this.current=void 0}useSession(e){this.auth=e.sessionToken,this.current=e}get session(){return this.current}async request(e,r,n,i,s="application/wasm"){let o={};this.auth&&(o.authorization=`Bearer ${this.auth}`);let a;i?(o["content-type"]=s,a=i):n!==void 0&&(o["content-type"]="application/json",a=JSON.stringify(n));try{return await this.sealed(`${this.base}/${r}`,{method:e,headers:o,body:a})}catch(c){throw Wr(c)}}async json(e,r,n,i,s){let o=await this.request(e,r,n,i,s);if(!o.ok)throw await Ee(o);let a=await o.text();return a?JSON.parse(a):{}}async retried(e,r,n,i=this.retry.retries){for(let s=0;;s++){let o;try{return await this.json(e,r,n)}catch(c){if(c instanceof $)o=c;else if(c instanceof TypeError&&this.networkFailures.has(c))o=new $("NETWORK",`the node could not be reached: ${c.message}`,{},void 0,c);else throw c}if(s>=i)throw o;let a=rn(s,this.retry);await new Promise(c=>setTimeout(c,Math.max(a,(o.retryAfter??0)*1e3)))}}post(e,r={}){return this.json("POST",e,r)}get(e){return this.json("GET",e)}put(e,r={}){return this.json("PUT",e,r)}delete(e,r){return this.json("DELETE",e,r)}async signUp(e,r){let n=await this.post("auth/passkey/register/begin",{name:r}),i=await e.create(n.options),s=await this.post("auth/passkey/register/finish",{challengeId:n.challengeId,registration:i});return this.useSession(s),s}async signIn(e){let r=await this.post("auth/passkey/login/begin"),n=await e.get(v(r.options.challenge),r.options.rpId),i=await this.post("auth/passkey/login/finish",{challengeId:r.challengeId,assertion:n});return this.useSession(i),i}async refresh(){if(!this.current)throw new Error("no session to refresh");let e=await this.post("auth/refresh",{refreshToken:this.current.refreshToken});return this.useSession(e),e}async signOut(){await this.post("auth/logout"),this.auth=void 0,this.current=void 0}async signOutEverywhere(){await this.post("auth/logout-all"),this.auth=void 0,this.current=void 0}me(){return this.get("auth/me")}async addPasskey(e){let r=await this.post("auth/passkeys/add/begin"),n=await e.create(r.options),{credentialId:i}=await this.post("auth/passkeys/add/finish",{challengeId:r.challengeId,registration:n});return i}async removePasskey(e){await this.delete(`auth/passkeys/${l(e)}`)}async labelPasskey(e,r){await this.post(`auth/passkeys/${l(e)}`,{label:r})}usage(){return this.get("auth/usage")}async attestation(){let e=St(crypto.getRandomValues(new Uint8Array(32))),r=await this.raw(`${this.base}/attestation?nonce=${e}`);if(!r.ok)throw await Ee(r);return await r.json()}async listApiKeys(){let{keys:e}=await this.get("auth/apikeys");return e}async revokeApiKey(e){await this.delete(`auth/apikeys/${l(e)}`)}createApiKey(e){return this.post("auth/apikeys",e)}async uploadBundle(e){let{hash:r}=await this.json("POST","bundles",void 0,e);return r}uploadBlob(e,r){return this.json("POST",`apps/${l(e)}/blobs`,void 0,r)}async downloadBlob(e,r){let n=await this.request("GET",`apps/${l(e)}/blobs/${l(r)}`);if(!n.ok)throw await Ee(n);return new Uint8Array(await n.arrayBuffer())}async listBlobs(e){let{blobs:r}=await this.get(`apps/${l(e)}/blobs`);return r}blobInfo(e,r){return this.get(`apps/${l(e)}/blobs/${l(r)}/info`)}async deleteBlob(e,r){await this.delete(`apps/${l(e)}/blobs/${l(r)}`)}uploadPackage(e){return this.json("POST","packages",void 0,e,"application/octet-stream")}installPackage(e,r){return this.post("packages/install",{package:e,version:r})}async packages(){let{packages:e}=await this.get("packages");return e}package(e){return this.get(`packages/${l(e)}`)}uninstallPackage(e,r){return this.delete(r===void 0?`packages/${l(e)}`:`packages/${l(e)}/${l(r)}`)}async listApps(e={}){let r=new URLSearchParams;e.package&&r.set("package",e.package),e.bundle&&r.set("bundle",e.bundle);let n=r.toString(),{apps:i}=await this.get(n?`apps?${n}`:"apps");return i}getApp(e){return this.get(`apps/${l(e)}`)}async deleteApp(e){await this.delete(`apps/${l(e)}`)}async setAccess(e,r){await this.post(`apps/${l(e)}/access`,{access:r})}async setAppMetadata(e,r){await this.post(`apps/${l(e)}/metadata`,{metadata:r})}appStorage(e){return this.get(`apps/${l(e)}/storage`)}appAbi(e){return this.get(`apps/${l(e)}/abi`)}async transferApp(e,r,n){await this.postConfirmed(`apps/${l(e)}/transfer`,{to:r},n)}upgradeApp(e,r,n){let i=`apps/${l(e)}/upgrade`;return n?this.postConfirmed(i,r,n):this.post(i,r)}postConfirmed(e,r,n){return this.confirmed("POST",e,r,n)}deleteConfirmed(e,r,n={}){return this.confirmed("DELETE",e,n,r)}async confirmed(e,r,n,i,s=o=>this.json(e,r,o)){try{return await s(n)}catch(o){if(!(o instanceof q))throw o;let a=o.details,c;try{c=await i.get(v(a.challenge),a.rpId,a.allowCredentials)}catch(d){let u=d?.name;throw u==="NotAllowedError"||u==="AbortError"?new te(d):d}return s({...n,confirm:{challengeId:a.challengeId,assertion:c}})}}async createApp(e,r,n={}){let i=typeof r=="string"?{bundle:r}:r,{appId:s}=await this.post("apps",{name:e,...i,...n});return s}call(e,r,n={},i){let s=i??kt();return this.retried("POST",`apps/${l(e)}/intents`,{method:r,args:n,idempotencyKey:s})}async callConfirmed(e,r,n,i,s){let o=`apps/${l(e)}/intents`,a=s??kt();return this.confirmed("POST",o,{method:r,args:n,idempotencyKey:a},i,c=>this.retried("POST",o,c,c.confirm===void 0?this.retry.retries:0))}view(e,r,n={},i={}){return this.retried("POST",`apps/${l(e)}/views`,{method:r,args:n,consistency:i.stale?"stale":"strong",minIndex:i.minIndex??0})}events(e,r=0,n){return this.stream(`apps/${l(e)}/events?from=${r}`,n)}async*stream(e,r){let n={};this.auth&&(n.authorization=`Bearer ${this.auth}`);let i=await this.sealed(`${this.base}/${e}`,{headers:n,signal:r});if(!i.ok)throw await Ee(i);if(!i.body)throw new A(i.status,"EVENTS","the event stream has no body");yield*en(i.body)}async publishPresence(e,r,n){await this.post(`apps/${l(e)}/presence`,{seq:r,state:n===null?null:St(n)})}async presence(e){let{present:r}=await this.get(`apps/${l(e)}/presence`);return r}presenceStream(e,r){return this.stream(`apps/${l(e)}/presence/stream`,r)}async setAlias(e,r){await this.put(`auth/aliases/${l(e)}`,{app:r})}async aliases(){let{aliases:e}=await this.get("auth/aliases");return e}async alias(e){let{appId:r}=await this.get(`auth/aliases/${l(e)}`);return r}async deleteAlias(e){await this.delete(`auth/aliases/${l(e)}`)}async createOrg(e){let{orgId:r}=await this.post("orgs",{name:e});return r}getOrg(e){return this.get(`orgs/${l(e)}`)}async deleteOrg(e,r){await this.deleteConfirmed(`orgs/${l(e)}`,r)}async setOrgMetadata(e,r){await this.post(`orgs/${l(e)}/metadata`,{metadata:r})}async setMemberMetadata(e,r,n){await this.post(`orgs/${l(e)}/members/${l(r)}/metadata`,{metadata:n})}upgradeOrg(e,r,n){return this.postConfirmed(`orgs/${l(e)}/upgrade`,{...r},n)}upgradeRun(e,r){return this.get(`orgs/${l(e)}/upgrades/${l(r)}`)}retryUpgradeRun(e,r,n){return this.postConfirmed(`orgs/${l(e)}/upgrades/${l(r)}/retry`,{},n)}async approveRelease(e,r,n,i=!0){let s=e===null?"auth/releases":`orgs/${l(e)}/releases`;return this.postConfirmed(s,{version:r,approved:i},n)}async approveOutbound(e,r,n,i={}){let s=e===null?"auth/outbound":`orgs/${l(e)}/outbound`;return this.postConfirmed(s,{package:r,prefixes:i.prefixes??"manifest",replace:i.replace??!1},n)}async setMember(e,r,n){await this.post(`orgs/${l(e)}/members`,{account:r,role:n})}removeMember(e,r){return this.delete(`orgs/${l(e)}/members/${l(r)}`)}async setCapabilities(e,r,n={}){await this.post(`orgs/${l(e)}/capabilities`,{capabilities:r,...n})}async createTeam(e,r,n,i){let{teamId:s}=await this.post(`orgs/${l(e)}/teams`,{name:r,join:n,parent:i});return s}getTeam(e,r){return this.get(`orgs/${l(e)}/teams/${l(r)}`)}async updateTeam(e,r,n){await this.post(`orgs/${l(e)}/teams/${l(r)}`,n)}async deleteTeam(e,r){await this.delete(`orgs/${l(e)}/teams/${l(r)}`)}async setTeamMember(e,r,n,i={}){await this.post(`orgs/${l(e)}/teams/${l(r)}/members`,{account:n,...i})}async removeTeamMember(e,r,n){await this.delete(`orgs/${l(e)}/teams/${l(r)}/members/${l(n)}`)}async invite(e,r,n=[],i={}){let{token:s}=await this.post(`orgs/${l(e)}/invites`,{role:r,teams:n,...i});return s}redeemInvite(e){return this.post(`invites/${l(e)}/redeem`)}};var ze={CREATE_APP:1,INVITE_MEMBERS:2,JOIN_OPEN_TEAMS:4,MANAGE_MEMBERS:8,MANAGE_APPLICATION:16,CREATE_TEAM:32,DELETE_TEAM:64,MANAGE_VISIBILITY:128,MANAGE_METADATA:256},nn=ze.JOIN_OPEN_TEAMS;function sn(...t){return t.reduce((e,r)=>e|ze[r],0)}function Te(t,e){return(t<<e|t>>>32-e)>>>0}function I(t,e,r,n,i){t[e]=t[e]+t[r]>>>0,t[i]=Te(t[i]^t[e],16),t[n]=t[n]+t[i]>>>0,t[r]=Te(t[r]^t[n],12),t[e]=t[e]+t[r]>>>0,t[i]=Te(t[i]^t[e],8),t[n]=t[n]+t[i]>>>0,t[r]=Te(t[r]^t[n],7)}function Ct(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function Nt(t,e,r){let n=new Uint32Array(16);n[0]=1634760805,n[1]=857760878,n[2]=2036477234,n[3]=1797285236;for(let o=0;o<8;o+=1)n[4+o]=Ct(t,o*4);n[12]=e>>>0;for(let o=0;o<3;o+=1)n[13+o]=Ct(r,o*4);let i=n.slice();for(let o=0;o<10;o+=1)I(i,0,4,8,12),I(i,1,5,9,13),I(i,2,6,10,14),I(i,3,7,11,15),I(i,0,5,10,15),I(i,1,6,11,12),I(i,2,7,8,13),I(i,3,4,9,14);let s=new Uint8Array(64);for(let o=0;o<16;o+=1){let a=i[o]+n[o]>>>0;s[o*4]=a&255,s[o*4+1]=a>>>8&255,s[o*4+2]=a>>>16&255,s[o*4+3]=a>>>24&255}return s}function on(t,e,r,n){let i=new Uint8Array(n.length);for(let s=0,o=e;s<n.length;s+=64,o+=1){let a=Nt(t,o,r),c=Math.min(s+64,n.length);for(let d=s;d<c;d+=1)i[d]=n[d]^a[d-s]}return i}function Ye(t){let e=0n;for(let r=t.length-1;r>=0;r-=1)e=e<<8n|BigInt(t[r]);return e}var an=(1n<<130n)-5n;function cn(t,e){let r=Ye(t.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,n=Ye(t.subarray(16,32)),i=0n;for(let a=0;a<e.length;a+=16){let c=e.subarray(a,Math.min(a+16,e.length)),d=Ye(c)+(1n<<BigInt(8*c.length));i=(i+d)*r%an}let s=i+n&(1n<<128n)-1n,o=new Uint8Array(16);for(let a=0;a<16;a+=1)o[a]=Number(s&0xffn),s>>=8n;return o}function vt(t){return new Uint8Array((16-t%16)%16)}function It(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function ln(t,e){let r=[t,vt(t.length),e,vt(e.length),It(t.length),It(e.length)],n=new Uint8Array(r.reduce((s,o)=>s+o.length,0)),i=0;for(let s of r)n.set(s,i),i+=s.length;return n}function un(t,e){if(t.length!==32)throw new Error("ChaCha20-Poly1305 needs a 32-byte key");if(e.length!==12)throw new Error("ChaCha20-Poly1305 needs a 12-byte nonce")}function Ot(t,e,r,n=new Uint8Array(0)){un(t,e);let i=Nt(t,0,e).subarray(0,32),s=on(t,1,e,r),o=cn(i,ln(n,s)),a=new Uint8Array(s.length+16);return a.set(s),a.set(o,s.length),a}var Mt=32,dn=1,gn=3,fn=2,yn=32,pn=32,hn=12,J=t=>new TextEncoder().encode(t),ie=t=>new Uint8Array([t>>8&255,t&255]),Dt=p(J("KEM"),ie(Mt)),ne=p(J("HPKE"),ie(Mt),ie(dn),ie(gn));async function _t(t,e){let r=t.length===0?new Uint8Array(32):t,n=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",n,e))}async function wn(t,e,r){let n=new Uint8Array(r),i=new Uint8Array(0);for(let s=1,o=0;o<r;s+=1)i=await _t(t,p(i,e,new Uint8Array([s]))),n.set(i.subarray(0,Math.min(i.length,r-o)),o),o+=i.length;return n}function Pe(t,e,r,n){return _t(e,p(J("HPKE-v1"),t,J(r),n))}function Ze(t,e,r,n,i){return wn(e,p(ie(i),J("HPKE-v1"),t,J(r),n),i)}async function mn(t,e){let r=await Pe(Dt,new Uint8Array(0),"eae_prk",t);return Ze(Dt,r,"shared_secret",e,yn)}async function An(t,e){let r=new Uint8Array(0),n=await Pe(ne,r,"psk_id_hash",r),i=await Pe(ne,r,"info_hash",e),s=p(new Uint8Array([fn]),n,i),o=await Pe(ne,t,"secret",r);return{key:await Ze(ne,o,"key",s,pn),nonce:await Ze(ne,o,"base_nonce",s,hn)}}async function $t(t,e,r,n,i=new Uint8Array(0),s){if(t.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let o=await L(s),a=await L(e),c=p(await Y(o.privateKey,t),await Y(a.privateKey,t)),d=await mn(c,p(o.publicKey,t,a.publicKey)),{key:u,nonce:g}=await An(d,r);return{enc:o.publicKey,ciphertext:Ot(u,g,n,i)}}var Vt="mero-agent-gate/attest/v3",Ht="mero-agent-gate/provision/v2",bn=/^[a-z0-9][a-z0-9-]{0,62}$/,En=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,Bt=64,Kt=64*1024,N=class extends Error{constructor(r,n,i){super(r);this.status=n;this.code=i;this.name="AgentGateError"}};function Lt(t){if(!bn.test(t))throw new Error(`Agent id ${JSON.stringify(t)} must match [a-z0-9][a-z0-9-]{0,62}`)}function se(t){return new TextEncoder().encode(t)}function Ft(t){let e=se(t);return p(new Uint8Array([e.length]),e)}function B(t){let e="";for(let r of t)e+=String.fromCharCode(r);return btoa(e)}function Ue(t,e,r){let n;try{n=Uint8Array.from(atob(t.trim()),i=>i.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(r!==void 0&&n.length!==r)throw new Error(`${e} is not ${r} bytes`);return n}async function jt(t,e,r,n){let i=new Uint8Array(32),s=p(se(Vt),t,Ft(e),r??i,n??i);return new Uint8Array(await crypto.subtle.digest("SHA-256",s))}function Gt(t,e){return p(se(Ht),t,Ft(e))}async function Tn(){let t=crypto.getRandomValues(new Uint8Array(32));return{secret:t,publicKey:await Re(t)}}async function Re(t){if(t.length!==32)throw new Error("An owner key is 32 bytes");return B((await L(t)).publicKey)}function Qt(t,e){return`${t.replace(/\/+$/,"")}${e}`}async function qt(t,e,r){let n=await t(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)}),i=await n.text(),s;try{s=i?JSON.parse(i):void 0}catch{}if(!n.ok){let o=s;throw new N(`The gate answered ${n.status}${o?.error?` ${o.error}`:""}: ${o?.details??i.slice(0,200)}`,n.status,o?.error)}return s}async function Xe(t){let e=t.agentId??"";e&&Lt(e);let r=crypto.getRandomValues(new Uint8Array(32)),n=await qt(t.fetch??fetch,Qt(t.gateUrl,"/attest"),{nonceB64:B(r),...e?{agentId:e}:{}});if((n?.agentId??"")!==e)throw new Error(`Asked about agent ${JSON.stringify(e)}, the gate answered for ${JSON.stringify(n?.agentId)}`);let i=Ue(n.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),s=n.signingPublicKeyB64?Ue(n.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,o=n.ownerPublicKeyB64?Ue(n.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!s!=!o)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let a=await jt(i,e,s,o);return await t.verifier({quoteB64:n.quoteB64,nonce:T(r),reportDataSuffix:T(a)}),{agentId:e,provisioningPublicKey:B(i),...s?{signingPublicKey:B(s)}:{},...o?{ownerPublicKey:B(o)}:{}}}async function Jt(t,e){let r=await Re(e);if(t.ownerPublicKey&&t.ownerPublicKey!==r)throw new N(`This agent is claimed by another key (${t.ownerPublicKey}); it is not yours. Send it nothing and do not authorize its signing key`,void 0,"not_yours");return r}function Pn(t){let e=Object.keys(t);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>Bt)throw new Error(`At most ${Bt} secrets at once`);for(let r of e){if(!En.test(r))throw new Error(`Secret name ${JSON.stringify(r)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);if(typeof t[r]!="string")throw new Error(`Secret ${r} is not a string`);if(se(t[r]).length>Kt)throw new Error(`Secret ${r} is over ${Kt} bytes`)}}async function zt(t,e,r,n,i,s){if(!n.agentId)throw new Error("This quote names no agent; attest with the agent id");let o=await Jt(n,i),a=Ue(n.provisioningPublicKey,"provisioningPublicKey",32),c=await $t(a,i,Gt(a,n.agentId),se(JSON.stringify(s)));return qt(t,Qt(e,r),{agentId:n.agentId,provisioningPublicKeyB64:n.provisioningPublicKey,senderPublicKeyB64:o,encappedKeyB64:B(c.enc),ciphertextB64:B(c.ciphertext)})}async function Un(t){Pn(t.secrets);let e=t.fetch??fetch,r=await zt(e,t.gateUrl,"/provision",t.agent,t.ownerSecret,{secrets:t.secrets}),n=await Xe({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e}),i=await Re(t.ownerSecret);if(n.ownerPublicKey!==i||!n.signingPublicKey)throw new N("The gate accepted the secrets, but its quote does not name your key as owner");if(t.agent.signingPublicKey&&t.agent.signingPublicKey!==n.signingPublicKey)throw new N("The agent's signing key changed while provisioning");return{agentId:n.agentId,provisioningPublicKey:n.provisioningPublicKey,signingPublicKey:n.signingPublicKey,ownerPublicKey:i,written:r?.written??[],claimed:r?.claimed===!0}}async function Rn(t){if(!t.agent.ownerPublicKey)throw new Error("This agent is not claimed; there is nothing to release");let e=t.fetch??fetch;if(await zt(e,t.gateUrl,"/release",t.agent,t.ownerSecret,{release:!0}),(await Xe({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e})).ownerPublicKey)throw new N("The gate says it released the agent, but its quote still names an owner")}var We=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),xn=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function Sn(t,e,r={}){let n=typeof t=="string"?new TextEncoder().encode(t):t;await de(n,e,{identity:r.identity??We.identity,issuer:r.issuer??We.issuer});let i;try{i=JSON.parse(new TextDecoder().decode(n))}catch{throw new Error("The signed agent policy is not JSON")}let s=r.role??"agent";if(i?.role!==s)throw new Error(`The signed file is a ${JSON.stringify(i?.role)} policy, not an ${s} one`);let o=r.profile??M;if(i.profile!==o)throw new Error(`The signed agent policy is for the ${JSON.stringify(i.profile)} profile, not ${o}`);if(r.expectedVersion!==void 0&&i.version!==r.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(i.version)}, not ${r.expectedVersion}`);return Yt(i),i}function Yt(t){for(let e of xn)if(!Array.isArray(t?.[e])||t[e].length===0)throw new Error(`The agent policy's ${e} is empty, so no agent would be accepted`)}var kn=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function Cn(t){let e=kn.find(r=>r.toLowerCase()===t.trim().toLowerCase());if(!e)throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(t)}`);return e}var oe=t=>t.trim().replace(/^0x/i,"");function vn(t,e){return Yt(t),_({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:t.allowed_tcb_statuses.map(Cn),allowedMrtd:t.allowed_mrtd.map(oe),allowedRtmr0:t.allowed_rtmr0.map(oe),allowedRtmr1:t.allowed_rtmr1.map(oe),allowedRtmr2:t.allowed_rtmr2.map(oe),allowedRtmr3:t.allowed_rtmr3.map(oe)})}export{Vt as AGENT_ATTEST_DOMAIN,Ht as AGENT_PROVISION_INFO_DOMAIN,N as AgentGateError,we as AppError,pe as ArgsTooLarge,Je as CalimeroClient,A as CalimeroError,te as ConfirmCancelled,q as ConfirmRequired,nn as DEFAULT_ORG_CAPABILITIES,He as DEFAULT_RELEASE_MIRROR,bt as GITHUB_RELEASES,ot as HANDSHAKE_PATH,he as IdempotencyMismatch,We as KMS_RELEASE_SIGNER,fe as LoginRequired,Ut as MOCK_QUOTE_HEADER,Ve as NODE_RELEASE_SIGNER,ye as NotFound,ze as ORG_CAPABILITIES,M as PRODUCTION_PROFILE,X as SEALED_CONTENT_TYPE,at as SEALED_PATH,S as SealedTransportError,W as StaleTransportKeyError,me as TrapError,$ as UnavailableError,jt as agentKeyBinding,vn as agentQuoteVerifier,Xe as attestAgent,x as b64url,Xr as browserPasskey,Jt as checkOwner,Rt as claimedRelease,je as cloudNodeReleaseUrl,_ as createQuoteVerifier,Me as createSealedFetch,Qr as createSignedReleaseVerifier,be as errorFrom,qe as fetchAttestedKey,Fe as fetchGithubNodeRelease,Le as fetchNodeRelease,v as fromB64url,Tn as generateOwnerKey,sn as orgCapabilities,Re as ownerPublicKey,Un as provisionAgent,Gt as provisionInfo,Rn as releaseAgent,De as transportKeyBinding,ge as trustSignedRelease,Ke as trustedMeasurementsFromReleases,Lt as validateAgentId,Sn as verifySignedAgentPolicy,At as verifySignedNodeRelease};
7
+ `))>=0;){let a=n.slice(0,o);n=n.slice(o+2);let c="",u="",d="";for(let p of a.split(`
8
+ `))p.startsWith("id:")?c=p.slice(3).trim():p.startsWith("event:")?u=p.slice(6).trim():p.startsWith("data:")&&(d+=p.slice(5).trim());if(!u&&!d)continue;let g=d;try{g=JSON.parse(d)}catch{}yield{id:c,kind:u,data:g}}}}function Kt(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function Vt(){return`node:c-${T(crypto.getRandomValues(new Uint8Array(16)))}`}var mn={retries:6,baseDelayMs:200,maxDelayMs:2e3};function An(t,e){return Math.min(e.baseDelayMs*2**t,e.maxDelayMs)}var et=class{constructor(e){this.networkFailures=new WeakSet;this.base=e.baseUrl.replace(/\/+$/,""),this.retry={...mn,...e.retry};let r=e.fetch??((i,s)=>fetch(i,s)),n=async(i,s)=>{try{return await r(i,s)}catch(o){throw o instanceof TypeError&&this.networkFailures.add(o),o}};this.raw=n,this.sealed=Ve({baseUrl:this.base,transportPublicKey:()=>Ze(this.base,e.policy,n),fetch:n})}useApiKey(e){this.auth=e,this.current=void 0}useSession(e){this.auth=e.sessionToken,this.current=e}get session(){return this.current}async request(e,r,n,i,s="application/wasm"){let o={};this.auth&&(o.authorization=`Bearer ${this.auth}`);let a;i?(o["content-type"]=s,a=i):n!==void 0&&(o["content-type"]="application/json",a=JSON.stringify(n));try{return await this.sealed(`${this.base}/${r}`,{method:e,headers:o,body:a})}catch(c){throw hn(c)}}async json(e,r,n,i,s){let o=await this.request(e,r,n,i,s);if(!o.ok)throw await Te(o);let a=await o.text();return a?JSON.parse(a):{}}async retried(e,r,n,i=this.retry.retries){for(let s=0;;s++){let o;try{return await this.json(e,r,n)}catch(c){if(c instanceof _)o=c;else if(c instanceof TypeError&&this.networkFailures.has(c))o=new _("NETWORK",`the node could not be reached: ${c.message}`,{},void 0,c);else throw c}if(s>=i)throw o;let a=An(s,this.retry);await new Promise(c=>setTimeout(c,Math.max(a,(o.retryAfter??0)*1e3)))}}post(e,r={}){return this.json("POST",e,r)}get(e){return this.json("GET",e)}put(e,r={}){return this.json("PUT",e,r)}delete(e,r){return this.json("DELETE",e,r)}async signUp(e,r){let n=await this.post("auth/passkey/register/begin",{name:r}),i=await e.create(n.options),s=await this.post("auth/passkey/register/finish",{challengeId:n.challengeId,registration:i});return this.useSession(s),s}async signIn(e){let r=await this.post("auth/passkey/login/begin"),n=await e.get(C(r.options.challenge),r.options.rpId),i=await this.post("auth/passkey/login/finish",{challengeId:r.challengeId,assertion:n});return this.useSession(i),i}async refresh(){if(!this.current)throw new Error("no session to refresh");let e=await this.post("auth/refresh",{refreshToken:this.current.refreshToken});return this.useSession(e),e}async signOut(){await this.post("auth/logout"),this.auth=void 0,this.current=void 0}async signOutEverywhere(){await this.post("auth/logout-all"),this.auth=void 0,this.current=void 0}me(){return this.get("auth/me")}async addPasskey(e){let r=await this.post("auth/passkeys/add/begin"),n=await e.create(r.options),{credentialId:i}=await this.post("auth/passkeys/add/finish",{challengeId:r.challengeId,registration:n});return i}async removePasskey(e){await this.delete(`auth/passkeys/${l(e)}`)}async labelPasskey(e,r){await this.post(`auth/passkeys/${l(e)}`,{label:r})}usage(){return this.get("auth/usage")}async attestation(){let e=Kt(crypto.getRandomValues(new Uint8Array(32))),r=await this.raw(`${this.base}/attestation?nonce=${e}`);if(!r.ok)throw await Te(r);return await r.json()}async listApiKeys(){let{keys:e}=await this.get("auth/apikeys");return e}async revokeApiKey(e){await this.delete(`auth/apikeys/${l(e)}`)}createApiKey(e){return this.post("auth/apikeys",e)}async uploadBundle(e){let{hash:r}=await this.json("POST","bundles",void 0,e);return r}uploadBlob(e,r){return this.json("POST",`apps/${l(e)}/blobs`,void 0,r)}async downloadBlob(e,r){let n=await this.request("GET",`apps/${l(e)}/blobs/${l(r)}`);if(!n.ok)throw await Te(n);return new Uint8Array(await n.arrayBuffer())}async listBlobs(e){let{blobs:r}=await this.get(`apps/${l(e)}/blobs`);return r}blobInfo(e,r){return this.get(`apps/${l(e)}/blobs/${l(r)}/info`)}async deleteBlob(e,r){await this.delete(`apps/${l(e)}/blobs/${l(r)}`)}uploadPackage(e){return this.json("POST","packages",void 0,e,"application/octet-stream")}installPackage(e,r){return this.post("packages/install",{package:e,version:r})}async packages(){let{packages:e}=await this.get("packages");return e}package(e){return this.get(`packages/${l(e)}`)}uninstallPackage(e,r){return this.delete(r===void 0?`packages/${l(e)}`:`packages/${l(e)}/${l(r)}`)}async listApps(e={}){let r=new URLSearchParams;e.package&&r.set("package",e.package),e.bundle&&r.set("bundle",e.bundle);let n=r.toString(),{apps:i}=await this.get(n?`apps?${n}`:"apps");return i}getApp(e){return this.get(`apps/${l(e)}`)}async deleteApp(e){await this.delete(`apps/${l(e)}`)}async setAccess(e,r){await this.post(`apps/${l(e)}/access`,{access:r})}async setAppMetadata(e,r){await this.post(`apps/${l(e)}/metadata`,{metadata:r})}appStorage(e){return this.get(`apps/${l(e)}/storage`)}appAbi(e){return this.get(`apps/${l(e)}/abi`)}async transferApp(e,r,n){await this.postConfirmed(`apps/${l(e)}/transfer`,{to:r},n)}upgradeApp(e,r,n){let i=`apps/${l(e)}/upgrade`;return n?this.postConfirmed(i,r,n):this.post(i,r)}postConfirmed(e,r,n){return this.confirmed("POST",e,r,n)}deleteConfirmed(e,r,n={}){return this.confirmed("DELETE",e,n,r)}async confirmed(e,r,n,i,s=o=>this.json(e,r,o)){try{return await s(n)}catch(o){if(!(o instanceof q))throw o;let a=o.details,c;try{c=await i.get(C(a.challenge),a.rpId,a.allowCredentials)}catch(u){let d=u?.name;throw d==="NotAllowedError"||d==="AbortError"?new re(u):u}return s({...n,confirm:{challengeId:a.challengeId,assertion:c}})}}async createApp(e,r,n={}){let i=typeof r=="string"?{bundle:r}:r,{appId:s}=await this.post("apps",{name:e,...i,...n});return s}call(e,r,n={},i){let s=i??Vt();return this.retried("POST",`apps/${l(e)}/intents`,{method:r,args:n,idempotencyKey:s})}async callConfirmed(e,r,n,i,s){let o=`apps/${l(e)}/intents`,a=s??Vt();return this.confirmed("POST",o,{method:r,args:n,idempotencyKey:a},i,c=>this.retried("POST",o,c,c.confirm===void 0?this.retry.retries:0))}view(e,r,n={},i={}){return this.retried("POST",`apps/${l(e)}/views`,{method:r,args:n,consistency:i.stale?"stale":"strong",minIndex:i.minIndex??0})}events(e,r=0,n){return this.stream(`apps/${l(e)}/events?from=${r}`,n)}async*stream(e,r){let n={};this.auth&&(n.authorization=`Bearer ${this.auth}`);let i=await this.sealed(`${this.base}/${e}`,{headers:n,signal:r});if(!i.ok)throw await Te(i);if(!i.body)throw new m(i.status,"EVENTS","the event stream has no body");yield*wn(i.body)}async publishPresence(e,r,n){await this.post(`apps/${l(e)}/presence`,{seq:r,state:n===null?null:Kt(n)})}async presence(e){let{present:r}=await this.get(`apps/${l(e)}/presence`);return r}presenceStream(e,r){return this.stream(`apps/${l(e)}/presence/stream`,r)}async setAlias(e,r){await this.put(`auth/aliases/${l(e)}`,{app:r})}async aliases(){let{aliases:e}=await this.get("auth/aliases");return e}async alias(e){let{appId:r}=await this.get(`auth/aliases/${l(e)}`);return r}async deleteAlias(e){await this.delete(`auth/aliases/${l(e)}`)}async createOrg(e){let{orgId:r}=await this.post("orgs",{name:e});return r}getOrg(e){return this.get(`orgs/${l(e)}`)}async deleteOrg(e,r){await this.deleteConfirmed(`orgs/${l(e)}`,r)}async setOrgMetadata(e,r){await this.post(`orgs/${l(e)}/metadata`,{metadata:r})}async setMemberMetadata(e,r,n){await this.post(`orgs/${l(e)}/members/${l(r)}/metadata`,{metadata:n})}upgradeOrg(e,r,n){return this.postConfirmed(`orgs/${l(e)}/upgrade`,{...r},n)}upgradeRun(e,r){return this.get(`orgs/${l(e)}/upgrades/${l(r)}`)}retryUpgradeRun(e,r,n){return this.postConfirmed(`orgs/${l(e)}/upgrades/${l(r)}/retry`,{},n)}async approveRelease(e,r,n,i=!0){let s=e===null?"auth/releases":`orgs/${l(e)}/releases`;return this.postConfirmed(s,{version:r,approved:i},n)}async approveOutbound(e,r,n,i={}){let s=e===null?"auth/outbound":`orgs/${l(e)}/outbound`;return this.postConfirmed(s,{package:r,prefixes:i.prefixes??"manifest",replace:i.replace??!1},n)}appsReport(e,r={}){let n=e===null?"auth/apps":`orgs/${l(e)}/apps`;return this.get(`${n}${se(r)}`)}async appsReportAll(e){let r=await this.appsReport(e),n=[...r.apps],i=r.next;for(;i!==null;){let s=await this.appsReport(e,{after:i});n.push(...s.apps),i=s.next}return{...r,apps:n,next:null}}releaseRules(){return this.get("releases")}async pendingApprovals(e=null){let[r,n]=await Promise.all([this.appsReportAll(e),this.releaseRules()]);return We(r,n)}requestConsent(e){return this.post("consent/requests",e)}async openConsentPage(e,r=n=>{let i=globalThis.window;if(!i)throw new Error("no window to open the consent page in; pass `navigate`");i.location.assign(n)}){let n=await this.requestConsent(e);return r(n.url),n}consentResult(e){return this.get(`consent/${l(e)}/result`)}async waitForConsent(e,r={}){let n=r.intervalMs??2e3;for(;;){let i=await this.consentResult(e);if(i.status!=="pending"||r.signal?.aborted||r.expiresAt!==void 0&&Date.now()/1e3>=r.expiresAt)return i;await new Promise(s=>setTimeout(s,n))}}publisherBinding(e){return this.get(`publishers/${l(e)}`)}bindPublisher(e,r,n){return this.postConfirmed(`orgs/${l(e)}/publishers`,{...r},n)}upgradePublished(e,r,n,i){return this.postConfirmed(`orgs/${l(e)}/packages/${l(r)}/upgrade`,{...n},i)}opsApps(e={}){return this.get(`ops/apps${se(e)}`)}opsOrgs(e={}){return this.get(`ops/orgs${se(e)}`)}async setReleaseDeadline(e,r){let n=typeof r=="string"?r:r.toISOString();await this.post(`ops/releases/${l(e)}/deadline`,{after:n})}async liftReleaseDeadline(e){await this.delete(`ops/releases/${l(e)}/deadline`)}async setMember(e,r,n){await this.post(`orgs/${l(e)}/members`,{account:r,role:n})}removeMember(e,r){return this.delete(`orgs/${l(e)}/members/${l(r)}`)}async setCapabilities(e,r,n={}){await this.post(`orgs/${l(e)}/capabilities`,{capabilities:r,...n})}async createTeam(e,r,n,i){let{teamId:s}=await this.post(`orgs/${l(e)}/teams`,{name:r,join:n,parent:i});return s}getTeam(e,r){return this.get(`orgs/${l(e)}/teams/${l(r)}`)}async updateTeam(e,r,n){await this.post(`orgs/${l(e)}/teams/${l(r)}`,n)}async deleteTeam(e,r){await this.delete(`orgs/${l(e)}/teams/${l(r)}`)}async setTeamMember(e,r,n,i={}){await this.post(`orgs/${l(e)}/teams/${l(r)}/members`,{account:n,...i})}async removeTeamMember(e,r,n){await this.delete(`orgs/${l(e)}/teams/${l(r)}/members/${l(n)}`)}async invite(e,r,n=[],i={}){let{token:s}=await this.post(`orgs/${l(e)}/invites`,{role:r,teams:n,...i});return s}redeemInvite(e){return this.post(`invites/${l(e)}/redeem`)}};var tt={CREATE_APP:1,INVITE_MEMBERS:2,JOIN_OPEN_TEAMS:4,MANAGE_MEMBERS:8,MANAGE_APPLICATION:16,CREATE_TEAM:32,DELETE_TEAM:64,MANAGE_VISIBILITY:128,MANAGE_METADATA:256,APPROVE_RELEASES:1024},bn=tt.JOIN_OPEN_TEAMS;function En(...t){return t.reduce((e,r)=>e|tt[r],0)}function Se(t,e){return(t<<e|t>>>32-e)>>>0}function I(t,e,r,n,i){t[e]=t[e]+t[r]>>>0,t[i]=Se(t[i]^t[e],16),t[n]=t[n]+t[i]>>>0,t[r]=Se(t[r]^t[n],12),t[e]=t[e]+t[r]>>>0,t[i]=Se(t[i]^t[e],8),t[n]=t[n]+t[i]>>>0,t[r]=Se(t[r]^t[n],7)}function Ht(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function Ft(t,e,r){let n=new Uint32Array(16);n[0]=1634760805,n[1]=857760878,n[2]=2036477234,n[3]=1797285236;for(let o=0;o<8;o+=1)n[4+o]=Ht(t,o*4);n[12]=e>>>0;for(let o=0;o<3;o+=1)n[13+o]=Ht(r,o*4);let i=n.slice();for(let o=0;o<10;o+=1)I(i,0,4,8,12),I(i,1,5,9,13),I(i,2,6,10,14),I(i,3,7,11,15),I(i,0,5,10,15),I(i,1,6,11,12),I(i,2,7,8,13),I(i,3,4,9,14);let s=new Uint8Array(64);for(let o=0;o<16;o+=1){let a=i[o]+n[o]>>>0;s[o*4]=a&255,s[o*4+1]=a>>>8&255,s[o*4+2]=a>>>16&255,s[o*4+3]=a>>>24&255}return s}function Rn(t,e,r,n){let i=new Uint8Array(n.length);for(let s=0,o=e;s<n.length;s+=64,o+=1){let a=Ft(t,o,r),c=Math.min(s+64,n.length);for(let u=s;u<c;u+=1)i[u]=n[u]^a[u-s]}return i}function rt(t){let e=0n;for(let r=t.length-1;r>=0;r-=1)e=e<<8n|BigInt(t[r]);return e}var Pn=(1n<<130n)-5n;function Un(t,e){let r=rt(t.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,n=rt(t.subarray(16,32)),i=0n;for(let a=0;a<e.length;a+=16){let c=e.subarray(a,Math.min(a+16,e.length)),u=rt(c)+(1n<<BigInt(8*c.length));i=(i+u)*r%Pn}let s=i+n&(1n<<128n)-1n,o=new Uint8Array(16);for(let a=0;a<16;a+=1)o[a]=Number(s&0xffn),s>>=8n;return o}function Lt(t){return new Uint8Array((16-t%16)%16)}function Gt(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function xn(t,e){let r=[t,Lt(t.length),e,Lt(e.length),Gt(t.length),Gt(e.length)],n=new Uint8Array(r.reduce((s,o)=>s+o.length,0)),i=0;for(let s of r)n.set(s,i),i+=s.length;return n}function Tn(t,e){if(t.length!==32)throw new Error("ChaCha20-Poly1305 needs a 32-byte key");if(e.length!==12)throw new Error("ChaCha20-Poly1305 needs a 12-byte nonce")}function jt(t,e,r,n=new Uint8Array(0)){Tn(t,e);let i=Ft(t,0,e).subarray(0,32),s=Rn(t,1,e,r),o=Un(i,xn(n,s)),a=new Uint8Array(s.length+16);return a.set(s),a.set(o,s.length),a}var qt=32,Sn=1,kn=3,vn=2,Cn=32,In=32,On=12,J=t=>new TextEncoder().encode(t),ae=t=>new Uint8Array([t>>8&255,t&255]),Qt=y(J("KEM"),ae(qt)),oe=y(J("HPKE"),ae(qt),ae(Sn),ae(kn));async function Jt(t,e){let r=t.length===0?new Uint8Array(32):t,n=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",n,e))}async function Nn(t,e,r){let n=new Uint8Array(r),i=new Uint8Array(0);for(let s=1,o=0;o<r;s+=1)i=await Jt(t,y(i,e,new Uint8Array([s]))),n.set(i.subarray(0,Math.min(i.length,r-o)),o),o+=i.length;return n}function ke(t,e,r,n){return Jt(e,y(J("HPKE-v1"),t,J(r),n))}function nt(t,e,r,n,i){return Nn(e,y(ae(i),J("HPKE-v1"),t,J(r),n),i)}async function Dn(t,e){let r=await ke(Qt,new Uint8Array(0),"eae_prk",t);return nt(Qt,r,"shared_secret",e,Cn)}async function Mn(t,e){let r=new Uint8Array(0),n=await ke(oe,r,"psk_id_hash",r),i=await ke(oe,r,"info_hash",e),s=y(new Uint8Array([vn]),n,i),o=await ke(oe,t,"secret",r);return{key:await nt(oe,o,"key",s,In),nonce:await nt(oe,o,"base_nonce",s,On)}}async function zt(t,e,r,n,i=new Uint8Array(0),s){if(t.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let o=await L(s),a=await L(e),c=y(await Y(o.privateKey,t),await Y(a.privateKey,t)),u=await Dn(c,y(o.publicKey,t,a.publicKey)),{key:d,nonce:g}=await Mn(u,r);return{enc:o.publicKey,ciphertext:jt(d,g,n,i)}}var Xt="mero-agent-gate/attest/v3",Wt="mero-agent-gate/provision/v2",$n=/^[a-z0-9][a-z0-9-]{0,62}$/,_n=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,Yt=64,Zt=64*1024,O=class extends Error{constructor(r,n,i){super(r);this.status=n;this.code=i;this.name="AgentGateError"}};function er(t){if(!$n.test(t))throw new Error(`Agent id ${JSON.stringify(t)} must match [a-z0-9][a-z0-9-]{0,62}`)}function ce(t){return new TextEncoder().encode(t)}function tr(t){let e=ce(t);return y(new Uint8Array([e.length]),e)}function B(t){let e="";for(let r of t)e+=String.fromCharCode(r);return btoa(e)}function ve(t,e,r){let n;try{n=Uint8Array.from(atob(t.trim()),i=>i.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(r!==void 0&&n.length!==r)throw new Error(`${e} is not ${r} bytes`);return n}async function rr(t,e,r,n){let i=new Uint8Array(32),s=y(ce(Xt),t,tr(e),r??i,n??i);return new Uint8Array(await crypto.subtle.digest("SHA-256",s))}function nr(t,e){return y(ce(Wt),t,tr(e))}async function Bn(){let t=crypto.getRandomValues(new Uint8Array(32));return{secret:t,publicKey:await Ce(t)}}async function Ce(t){if(t.length!==32)throw new Error("An owner key is 32 bytes");return B((await L(t)).publicKey)}function ir(t,e){return`${t.replace(/\/+$/,"")}${e}`}async function sr(t,e,r){let n=await t(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)}),i=await n.text(),s;try{s=i?JSON.parse(i):void 0}catch{}if(!n.ok){let o=s;throw new O(`The gate answered ${n.status}${o?.error?` ${o.error}`:""}: ${o?.details??i.slice(0,200)}`,n.status,o?.error)}return s}async function it(t){let e=t.agentId??"";e&&er(e);let r=crypto.getRandomValues(new Uint8Array(32)),n=await sr(t.fetch??fetch,ir(t.gateUrl,"/attest"),{nonceB64:B(r),...e?{agentId:e}:{}});if((n?.agentId??"")!==e)throw new Error(`Asked about agent ${JSON.stringify(e)}, the gate answered for ${JSON.stringify(n?.agentId)}`);let i=ve(n.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),s=n.signingPublicKeyB64?ve(n.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,o=n.ownerPublicKeyB64?ve(n.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!s!=!o)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let a=await rr(i,e,s,o);return await t.verifier({quoteB64:n.quoteB64,nonce:R(r),reportDataSuffix:R(a)}),{agentId:e,provisioningPublicKey:B(i),...s?{signingPublicKey:B(s)}:{},...o?{ownerPublicKey:B(o)}:{}}}async function or(t,e){let r=await Ce(e);if(t.ownerPublicKey&&t.ownerPublicKey!==r)throw new O(`This agent is claimed by another key (${t.ownerPublicKey}); it is not yours. Send it nothing and do not authorize its signing key`,void 0,"not_yours");return r}function Kn(t){let e=Object.keys(t);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>Yt)throw new Error(`At most ${Yt} secrets at once`);for(let r of e){if(!_n.test(r))throw new Error(`Secret name ${JSON.stringify(r)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);if(typeof t[r]!="string")throw new Error(`Secret ${r} is not a string`);if(ce(t[r]).length>Zt)throw new Error(`Secret ${r} is over ${Zt} bytes`)}}async function ar(t,e,r,n,i,s){if(!n.agentId)throw new Error("This quote names no agent; attest with the agent id");let o=await or(n,i),a=ve(n.provisioningPublicKey,"provisioningPublicKey",32),c=await zt(a,i,nr(a,n.agentId),ce(JSON.stringify(s)));return sr(t,ir(e,r),{agentId:n.agentId,provisioningPublicKeyB64:n.provisioningPublicKey,senderPublicKeyB64:o,encappedKeyB64:B(c.enc),ciphertextB64:B(c.ciphertext)})}async function Vn(t){Kn(t.secrets);let e=t.fetch??fetch,r=await ar(e,t.gateUrl,"/provision",t.agent,t.ownerSecret,{secrets:t.secrets}),n=await it({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e}),i=await Ce(t.ownerSecret);if(n.ownerPublicKey!==i||!n.signingPublicKey)throw new O("The gate accepted the secrets, but its quote does not name your key as owner");if(t.agent.signingPublicKey&&t.agent.signingPublicKey!==n.signingPublicKey)throw new O("The agent's signing key changed while provisioning");return{agentId:n.agentId,provisioningPublicKey:n.provisioningPublicKey,signingPublicKey:n.signingPublicKey,ownerPublicKey:i,written:r?.written??[],claimed:r?.claimed===!0}}async function Hn(t){if(!t.agent.ownerPublicKey)throw new Error("This agent is not claimed; there is nothing to release");let e=t.fetch??fetch;if(await ar(e,t.gateUrl,"/release",t.agent,t.ownerSecret,{release:!0}),(await it({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e})).ownerPublicKey)throw new O("The gate says it released the agent, but its quote still names an owner")}var st=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),Ln=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function Gn(t,e,r={}){let n=typeof t=="string"?new TextEncoder().encode(t):t;await fe(n,e,{identity:r.identity??st.identity,issuer:r.issuer??st.issuer});let i;try{i=JSON.parse(new TextDecoder().decode(n))}catch{throw new Error("The signed agent policy is not JSON")}let s=r.role??"agent";if(i?.role!==s)throw new Error(`The signed file is a ${JSON.stringify(i?.role)} policy, not an ${s} one`);let o=r.profile??M;if(i.profile!==o)throw new Error(`The signed agent policy is for the ${JSON.stringify(i.profile)} profile, not ${o}`);if(r.expectedVersion!==void 0&&i.version!==r.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(i.version)}, not ${r.expectedVersion}`);return cr(i),i}function cr(t){for(let e of Ln)if(!Array.isArray(t?.[e])||t[e].length===0)throw new Error(`The agent policy's ${e} is empty, so no agent would be accepted`)}var Fn=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function jn(t){let e=Fn.find(r=>r.toLowerCase()===t.trim().toLowerCase());if(!e)throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(t)}`);return e}var le=t=>t.trim().replace(/^0x/i,"");function Qn(t,e){return cr(t),$({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:t.allowed_tcb_statuses.map(jn),allowedMrtd:t.allowed_mrtd.map(le),allowedRtmr0:t.allowed_rtmr0.map(le),allowedRtmr1:t.allowed_rtmr1.map(le),allowedRtmr2:t.allowed_rtmr2.map(le),allowedRtmr3:t.allowed_rtmr3.map(le)})}export{Xt as AGENT_ATTEST_DOMAIN,Wt as AGENT_PROVISION_INFO_DOMAIN,O as AgentGateError,Re as AppError,me as ArgsTooLarge,et as CalimeroClient,m as CalimeroError,re as ConfirmCancelled,q as ConfirmRequired,Ee as ConsentStale,bn as DEFAULT_ORG_CAPABILITIES,Qe as DEFAULT_RELEASE_MIRROR,Tt as GITHUB_RELEASES,gt as HANDSHAKE_PATH,Ae as IdempotencyMismatch,st as KMS_RELEASE_SIGNER,he as LoginRequired,Xe as MAX_REPORT_PAGE,Ct as MOCK_QUOTE_HEADER,je as NODE_RELEASE_SIGNER,we as NotFound,tt as ORG_CAPABILITIES,M as PRODUCTION_PROFILE,Mt as RELEASE_VERIFIER,be as ReleaseDeadlineError,X as SEALED_CONTENT_TYPE,pt as SEALED_PATH,S as SealedTransportError,W as StaleTransportKeyError,Pe as TrapError,_ as UnavailableError,rr as agentKeyBinding,Qn as agentQuoteVerifier,it as attestAgent,T as b64url,dn as browserPasskey,or as checkOwner,It as claimedRelease,ze as cloudNodeReleaseUrl,ie as compareVersions,pn as consentReturn,$ as createQuoteVerifier,Ve as createSealedFetch,sn as createSignedReleaseVerifier,xe as errorFrom,Ze as fetchAttestedKey,Je as fetchGithubNodeRelease,qe as fetchNodeRelease,C as fromB64url,Bn as generateOwnerKey,En as orgCapabilities,Ce as ownerPublicKey,se as pageQuery,We as pendingApprovalsFrom,Vn as provisionAgent,nr as provisionInfo,gn as publisherBindingBytes,Dt as publisherBindingMessage,Hn as releaseAgent,Bt as releaseConsent,$t as releaseNotesUrl,Nt as stalledBy,Ke as transportKeyBinding,ye as trustSignedRelease,Fe as trustedMeasurementsFromReleases,yn as upgradeConsent,er as validateAgentId,_t as verifyReleaseUrl,Gn as verifySignedAgentPolicy,xt as verifySignedNodeRelease,fn as withdrawConsent};
5
9
  //# sourceMappingURL=index.browser.mjs.map