@calimero-network/mero-js 33.0.0 → 33.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
- function T(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function Ne(n,e,t){let o=n.trim();if(!/^[0-9a-fA-F]*$/.test(o)||o.length!==t*2)throw new Error(`${e} must be ${t*2} hex characters, got ${o.length}`);let r=new Uint8Array(t);for(let s=0;s<t;s+=1)r[s]=Number.parseInt(o.slice(s*2,s*2+2),16);return r}function f(...n){let e=new Uint8Array(n.reduce((o,r)=>o+r.length,0)),t=0;for(let o of n)e.set(o,t),t+=o.length;return e}var jo="Noise_NK_25519_AESGCM_SHA256",gt=32,Oo=16,vo=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),ft=class n{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(jo),t=new Uint8Array(32);return t.set(e),new n(t)}async mixHash(e){this.h=await So(f(this.h,e))}async mixKey(e){let[t,o]=await an(this.ck,e);this.ck=t,this.k=await crypto.subtle.importKey("raw",o,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let t=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:sn(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(t),t}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let t=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:sn(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),t}split(){return an(this.ck,new Uint8Array)}};async function pn(n,e,t){let o=await ft.initialize();await o.mixHash(e),await o.mixHash(n);let r=await re(t);return await o.mixHash(r.publicKey),await o.mixKey(await ge(r.privateKey,n)),{message1:f(r.publicKey,await o.encryptAndHash(new Uint8Array)),async finish(a){if(a.length<gt+Oo)throw new Error("Noise: message 2 is too short");let i=a.slice(0,gt);return await o.mixHash(i),await o.mixKey(await ge(r.privateKey,i)),{payload:await o.decryptAndHash(a.slice(gt)),split:await o.split()}}}}async function re(n){if(!n){let o;try{o=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 r=new Uint8Array(await crypto.subtle.exportKey("raw",o.publicKey));return{privateKey:o.privateKey,publicKey:r}}let e=await crypto.subtle.importKey("pkcs8",f(vo,n),{name:"X25519"},!0,["deriveBits"]),t=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:xo(t.x)}}async function ge(n,e){let t=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:t},n,256))}function sn(n){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(n),!1),e}async function So(n){return new Uint8Array(await crypto.subtle.digest("SHA-256",n))}async function ht(n,e){let t=await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",t,e))}async function an(n,e){let t=await ht(n,e),o=await ht(t,new Uint8Array([1])),r=await ht(t,f(o,new Uint8Array([2])));return[o,r]}function xo(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(t,o=>o.charCodeAt(0))}var un="/sealed/v2/handshake",yn="/sealed/v2",fe="application/vnd.calimero.sealed",wt=2,Uo=new TextEncoder().encode("calimero/sealed-http/v2"),he=16,Co=1+he+8,Bo=0,qo=1,No=2,Mo=1+64*1024+16,Do=1024,Io=6e4,Vo="calimero.tee-attest.transport-key.v1",Lo=[101,204,205,304],mn=new TextEncoder,we=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},V=class extends Error{constructor(t,o,r,s){super(r);this.status=t;this.code=o;this.retryAfterMs=s;this.name="SealedTransportError"}};async function bt(n,e){let t=await crypto.subtle.digest("SHA-256",f(mn.encode(Vo),n,e));return new Uint8Array(t)}function Pt(n){let e=new URL(n.baseUrl),t=e.pathname.replace(/\/+$/,""),o=`${e.origin}${t}`,r=n.fetch??((l,u)=>fetch(l,u)),s=typeof n.transportPublicKey=="function"?n.transportPublicKey:void 0,a=s?Promise.resolve().then(s):Promise.resolve(n.transportPublicKey);a.catch(()=>{});let i,c=async()=>{try{return await ln(r,o,await cn(a))}catch(l){if(!(l instanceof we)||!s)throw l;return a=Promise.resolve().then(s),ln(r,o,await cn(a))}},y=async()=>{let l=i??d(void 0),u=await l;if(Date.now()<u.renewAt)return[u,l];let m=d(l);return[await m,m]},d=l=>{if(i===l){let u=c();i=u,u.catch(()=>{i===u&&(i=void 0)})}return i};return async(l,u)=>{let m=new Request(l,u),g=new URL(m.url);if(g.origin!==e.origin||!g.pathname.startsWith(`${t}/`))throw new Error(`Refusing to send ${g.href} outside the sealed node at ${n.baseUrl}`);let _=[];m.headers.forEach((v,B)=>_.push([B,v]));let S={method:m.method,path:g.pathname.slice(t.length)+g.search,headers:_},R=new Uint8Array(await m.arrayBuffer()),A=u?.signal??(l instanceof Request?l.signal:void 0),O=async v=>{let{requestId:B,header:z,envelope:M}=await Ko(v,S,R),x=await r(`${o}${yn}`,{method:"POST",headers:{"content-type":fe},body:M,signal:A});if(x.headers.get("content-type")!==fe)throw await hn(x);return Ho(x,v.responseKey,z,B)},[N,oe]=await y();try{return await O(N)}catch(v){if(!(v instanceof V)||v.code!=="unknown_session")throw v;return O(await d(oe))}}}async function cn(n){let e=await n;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function ln(n,e,t){try{return await dn(n,e,t)}catch(o){if(!(o instanceof V)||o.code!=="busy")throw o;return await new Promise(r=>setTimeout(r,o.retryAfterMs??1e3)),dn(n,e,t)}}async function dn(n,e,t){let o=await pn(t,Uo),r=await n(`${e}${un}`,{method:"POST",headers:{"content-type":fe},body:f(new Uint8Array([wt]),t,o.message1)});if(r.headers.get("content-type")!==fe)throw await hn(r);let s=await Qo(r,Do);return $o(o,s)}async function $o(n,e){if(e[0]!==wt)throw new Error("The handshake reply is malformed");let t;try{t=await n.finish(e.slice(1))}catch{throw new Error("The handshake reply did not open: it did not come from the attested node")}let{payload:o,split:r}=t;if(o.length!==he+4)throw new Error("The handshake reply is malformed");let s=o.slice(0,he),a=new DataView(o.buffer,o.byteOffset).getUint32(he,!1),[i,c]=await Promise.all([crypto.subtle.importKey("raw",r[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",r[1],"AES-GCM",!1,["decrypt"])]);return r[0].fill(0),r[1].fill(0),{requestKey:i,responseKey:c,nextRequestId:1,renewAt:Date.now()+a*1e3-Io,header(y){let d=new Uint8Array(Co);return d[0]=wt,d.set(s,1),new DataView(d.buffer).setBigUint64(1+he,BigInt(y),!1),d}}}async function Ko(n,e,t){let o=n.nextRequestId;n.nextRequestId+=1;let r=n.header(o),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:gn(o,0),additionalData:r},n.requestKey,Go(e,t));return{requestId:o,header:r,envelope:f(r,new Uint8Array(s))}}function gn(n,e){let t=new Uint8Array(12),o=new DataView(t.buffer);return o.setBigUint64(0,BigInt(n),!1),o.setUint32(8,e,!1),t}function Go(n,e){let t=mn.encode(JSON.stringify(n)),o=new Uint8Array(4);return new DataView(o.buffer).setUint32(0,t.length,!1),f(o,t,e)}async function Ho(n,e,t,o){if(!n.body)throw new Error("The sealed response has no body");let r=Fo(n.body.getReader()),s=0,a=async()=>{let d=await r.next();if(!d)return null;let l;try{l=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:gn(o,s),additionalData:t},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:l[0],data:l.slice(1)}},i=await a();if(!i||i.kind!==Bo)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(i.data));if(Lo.includes(c.status))return await r.cancel(),new Response(null,{status:c.status,headers:c.headers});let y=new ReadableStream({async pull(d){try{let l=await a();l?l.kind===qo?d.enqueue(l.data):l.kind===No?(d.close(),await r.cancel()):d.error(new Error("The sealed response is malformed")):d.error(new Error("The sealed response was cut short"))}catch(l){d.error(l)}},cancel(){return r.cancel()}});return new Response(y,{status:c.status,headers:c.headers})}function Fo(n){let e=new Uint8Array,t=async o=>{for(;e.length<o;){let{done:r,value:s}=await n.read();if(r)return!1;e=f(e,s)}return!0};return{async next(){if(!await t(4))return null;let o=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(o>Mo)throw await n.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await t(4+o))return null;let r=e.slice(4,4+o);return e=e.slice(4+o),r},cancel:()=>n.cancel()}}async function Qo(n,e){if(!n.body)return new Uint8Array;let t=n.body.getReader(),o=new Uint8Array;for(;;){let{done:r,value:s}=await t.read();if(r)return o;if(o=f(o,s),o.length>e)throw await t.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function hn(n){let e,t=`Sealed request refused: HTTP ${n.status}`;try{let s=await n.json();e=s?.error?.code,s?.error?.message&&(t=`Sealed request refused: ${s.error.message}`)}catch{}if(e==="stale_transport_key")return new we;let o=Number(n.headers.get("retry-after")),r=Number.isFinite(o)&&o>0?Math.min(o,5)*1e3:void 0;return new V(n.status,e,t,r)}var fn=[{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"]}],wn=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var zo="1.2.840.10045.2.1",Jo={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},Yo={"P-256":32,"P-384":48},Wo={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function bn(n,e,t){if(e+2>t)throw new Error("it is truncated");let o=n[e];if((o&31)===31)throw new Error("it uses a tag this parser does not read");let r=n[e+1],s=e+2;if(r&128){let i=r&127;if(i===0||i>4||s+i>t)throw new Error("it has a length this parser does not read");r=0;for(let c=0;c<i;c+=1)r=r*256+n[s+c];s+=i}let a=s+r;if(a>t)throw new Error("it is truncated");return{tag:o,bytes:n,offset:e,start:s,end:a}}function ae(n){let e=bn(n,0,n.length);if(e.end!==n.length)throw new Error("it has trailing bytes");return e}function E(n){let e=[];for(let t=n.start;t<n.end;){let o=bn(n.bytes,t,n.end);e.push(o),t=o.end}return e}function w(n,e,t){if(!n||n.tag!==e)throw new Error(`${t} is not where it should be`);return n}function L(n){return n.bytes.slice(n.start,n.end)}function Me(n){return n.bytes.slice(n.offset,n.end)}function se(n){let e=L(w(n,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let t=[],o=0;for(let a of e)o=o*128+(a&127),a&128||(t.push(o),o=0);let r=t.shift();return[...r<80?[Math.floor(r/40),r%40]:[2,r-80],...t].join(".")}function Zo(n){let e=new TextDecoder().decode(L(n)),t=n.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,o=n.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,r=t??o;if(!r)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let s=Number(r[1]);t&&(s+=s<50?2e3:1900);let[a,i,c,y,d]=r.slice(2).map(Number);return Date.UTC(s,a-1,i,c,y,d)}function _t(n){try{let[e,t,o,...r]=E(w(ae(n),48,"The certificate"));if(r.length>0)throw new Error("it has fields after its signature");let s=E(w(e,48,"The signed part")),a=s[0]?.tag===160?1:0,[i,c,y,d,l,u,...m]=s.slice(a);w(i,2,"The serial number");let g=se(E(w(t,48,"The signature algorithm"))[0]);if(se(E(w(c,48,"The signature algorithm"))[0])!==g)throw new Error("it names two different signature algorithms");let S=Wo[g];if(!S)throw new Error(`it is signed with ${g}, not ECDSA with SHA-256 or SHA-384`);let[R,A]=E(w(d,48,"The validity")).map(Zo);if(A===void 0)throw new Error("its validity is incomplete");let[O,N]=E(w(u,48,"The public key"));w(N,3,"The public key");let[oe,v]=E(w(O,48,"The key algorithm"));if(se(oe)!==zo)throw new Error("its key is not an elliptic-curve key");let B=Jo[se(v)];if(!B)throw new Error("its key is on a curve other than P-256 or P-384");let z=new Map,M=m.find(J=>J.tag===163);if(M){let[J]=E(M);for(let Ue of E(w(J,48,"The extensions"))){let U=E(w(Ue,48,"An extension"));if(U.length===3)w(U[1],1,"An extension's critical flag");else if(U.length!==2)throw new Error("it has a malformed extension");let ye=se(U[0]);if(z.has(ye))throw new Error(`it has extension ${ye} twice`);z.set(ye,L(w(U[U.length-1],4,"An extension value")))}}let x=L(w(o,3,"The signature"));if(x[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:n,tbs:Me(e),signatureHash:S,signature:x.slice(1),issuer:Me(w(y,48,"The issuer")),subject:Me(w(l,48,"The subject")),notBefore:R,notAfter:A,spki:Me(u),curve:B,extensions:z}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function Pn(n){return E(w(ae(n),48,"The list")).map(se)}function Xo(n,e){let t=Yo[e],o=E(w(ae(n),48,"The signature"));if(o.length!==2)throw new Error("The signature is not an ECDSA signature");let r=new Uint8Array(t*2);return o.forEach((s,a)=>{let i=L(w(s,2,"The signature"));if(i.length===0||i[0]&128)throw new Error("The signature is not an ECDSA signature");for(;i.length>1&&i[0]===0;)i=i.subarray(1);if(i.length>t)throw new Error("The signature is not an ECDSA signature");r.set(i,a*t+t-i.length)}),r}async function De(n,e,t,o,r){let s;try{s=Xo(o,e)}catch{return!1}let a=await crypto.subtle.importKey("spki",n,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:t},a,s,r)}function C(n,e){let t=n.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t)||t.length%4!==0)throw new Error(`${e} is not base64`);let o=atob(t),r=new Uint8Array(o.length);for(let s=0;s<o.length;s+=1)r[s]=o.charCodeAt(s);return r}function Rt(n,e){let t=[...n.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(t.length!==1||n.replace(t[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return C(t[0][1],e)}var er="2.5.29.17",tr="2.5.29.37",nr="1.3.6.1.5.5.7.3.3",or="1.3.6.1.4.1.57264.1.8",rr="1.3.6.1.4.1.57264.1.1",sr=134,ar=12,ir=48,pr=new TextEncoder,ie=n=>new TextDecoder().decode(n);async function Ie(n,e,t,o){let{base64Signature:r,cert:s,rekorBundle:a}=ur(e),i=a.Payload;if(o!==void 0&&o.trim()!==r.trim())throw new Error("The detached signature is not the one in the bundle");let c=C(r,"The bundle signature"),y=Rt(ie(C(s,"The bundle certificate")),"The bundle certificate"),d=_t(y),l=wn.find(A=>A.logId===i.logID.toLowerCase());if(!l)throw new Error(`The bundle names Rekor log ${i.logID}, which the Sigstore trust root does not know`);let u=pr.encode(`{"body":${JSON.stringify(i.body)},"integratedTime":${i.integratedTime},"logID":${JSON.stringify(i.logID)},"logIndex":${i.logIndex}}`);if(!await De(C(l.publicKey,"The Rekor key"),"P-256","SHA-256",C(a.SignedEntryTimestamp,"The signed entry timestamp"),u))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let g=i.integratedTime*1e3;if(!An(g,l.validFor))throw new Error(`Rekor log ${l.baseUrl} was not in use at ${be(g)}, when the entry says it was logged`);let _=yr(i.body),S=T(new Uint8Array(await crypto.subtle.digest("SHA-256",n)));if(_.hash!==S)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!At(C(_.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let R=Rt(ie(C(_.publicKey,"The logged certificate")),"The logged certificate");if(!At(R,y))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await De(d.spki,"P-256","SHA-256",c,n))throw new Error("The signature over the file does not verify with the bundle's certificate");return await cr(d,g),dr(d,t),{integratedTime:i.integratedTime}}async function cr(n,e){if(!Rn(n,e))throw new Error(`The signing certificate was valid ${be(n.notBefore)} to ${be(n.notAfter)}, not at ${be(e)} when Rekor logged it`);let t=[];for(let o of fn){let r=o.certChain.map(a=>_t(C(a,"A Fulcio certificate")));if(!await _n(n,r[0]))continue;let s=await lr(r,o.validFor,e);if(!s)return;t.push(`${o.uri} (valid from ${o.validFor.start}): ${s}`)}throw new Error(t.length>0?`The signing certificate's CA is not trusted at ${be(e)}: ${t.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function lr(n,e,t){if(!An(t,e))return"the trust root says it was not issuing certificates then";for(let[o,r]of n.entries()){if(!Rn(r,t))return`its certificate ${o} was not valid then`;let s=n[o+1]??r;if(!await _n(r,s))return`its certificate ${o} is not signed by the next`}}async function _n(n,e){return At(n.issuer,e.subject)?De(e.spki,e.curve,n.signatureHash,n.signature,n.tbs):!1}function dr(n,e){let t=n.extensions.get(er);if(!t)throw new Error("The signing certificate names no identity");let o=E(w(ae(t),ir,"The subject alternative name")),r=o.filter(y=>y.tag===sr).map(y=>ie(L(y)));if(r.length!==1||o.length!==1||r[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(r.length===1?r[0]:r)}, not by ${e.identity}`);let s=n.extensions.get(or),a=n.extensions.get(rr),i=s?ie(L(w(ae(s),ar,"The OIDC issuer"))):a?ie(a):void 0;if(i!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${i===void 0?"missing":JSON.stringify(i)}, not ${e.issuer}`);let c=n.extensions.get(tr);if(!c||!Pn(c).includes(nr))throw new Error("The signing certificate is not for code signing")}function ur(n){let e=n;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let t=e,o=t?.rekorBundle?.Payload;if(!(typeof t?.base64Signature=="string"&&typeof t.cert=="string"&&typeof t.rekorBundle?.SignedEntryTimestamp=="string"&&typeof o?.body=="string"&&typeof o.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(o.logID)&&Number.isSafeInteger(o.integratedTime)&&o.integratedTime>=0&&Number.isSafeInteger(o.logIndex)&&o.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return t}function yr(n){let e;try{e=JSON.parse(ie(C(n,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let t=e?.spec?.data?.hash,o=e?.spec?.signature;if(e?.kind!=="hashedrekord"||t?.algorithm!=="sha256"||typeof t.value!="string"||typeof o?.content!="string"||typeof o.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:t.value.toLowerCase(),signature:o.content,publicKey:o.publicKey.content}}function Rn(n,e){return n.notBefore<=e&&e<=n.notAfter}function An(n,e){return Date.parse(e.start)<=n&&(e.end===void 0||n<=Date.parse(e.end))}function be(n){return new Date(n).toISOString()}function At(n,e){return n.length===e.length&&n.every((t,o)=>t===e[o])}var mr=/^[0-9a-f]{96}$/,gr=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function Z(n){let e=pe(n.allowedMrtd??[],"allowedMrtd"),t=(n.allowedMeasurements??[]).map((i,c)=>{let y=`allowedMeasurements[${c}]`;return gr.map(d=>pe([i?.[d]??""],`${y}.${d}`)[0]).join()}),o=[pe(n.allowedRtmr0??[],"allowedRtmr0"),pe(n.allowedRtmr1??[],"allowedRtmr1"),pe(n.allowedRtmr2??[],"allowedRtmr2"),pe(n.allowedRtmr3??[],"allowedRtmr3")];if(n.allowedMeasurements!==void 0&&t.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(t.length===0){if(e.length===0)throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");if(o.slice(1).some(i=>i.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 r=n.allowedTcbStatuses??["UpToDate"],s=n.now??Date.now;return Object.assign(async({quoteB64:i,nonce:c,reportDataSuffix:y,collateral:d})=>{let l=fr(i),u=d??await n.fetchCollateral?.(l);if(!u)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let m;try{m=n.dcapVerify(l,u,Math.floor(s()/1e3))}catch(R){throw new Error(`The quote did not verify: ${R?.message??String(R)}`)}if(m.status==="Revoked"||!r.includes(m.status))throw new Error(`The platform's TCB status is ${m.status}, which is not accepted`);let g=hr(m.report);if(g.tdAttributes?.length!==8||(g.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let _=[g.mrTd,g.rtMr0,g.rtMr1,g.rtMr2,g.rtMr3].map(R=>T(R));if(t.length>0&&!t.includes(_.join()))throw new Error(`The measurements (MRTD ${_[0]}, RTMR0-3 ${_.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(_[0]))throw new Error(`MRTD ${_[0]} is not an image this verifier trusts`);if([g.rtMr0,g.rtMr1,g.rtMr2,g.rtMr3].forEach((R,A)=>{let O=o[A];if(O.length>0&&!O.includes(T(R)))throw new Error(`RTMR${A} ${T(R)} is not one this verifier trusts`)}),T(g.reportData)!==`${c}${y}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function pe(n,e){return n.map(t=>{let o=t.trim().toLowerCase();if(!mr.test(o))throw new Error(`${e} holds ${JSON.stringify(t)}, which is not a 48-byte hex measurement`);return o})}function hr(n){let e=n.data;if(n.type==="td10"&&e)return e;if(n.type==="td15"&&e?.base)return e.base;throw new Error(`The quote is a ${n.type} quote, not a TDX one`)}function fr(n){let e=atob(n),t=new Uint8Array(e.length);for(let o=0;o<e.length;o+=1)t[o]=e.charCodeAt(o);return t}var wr=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],W="locked-read-only";function kt(n,{profile:e,allowDebugProfile:t=!1}){if(n.length===0)throw new Error("No release given, so no image would be trusted");let o,r=n.map((s,a)=>{let i=s?.tag??`releases[${a}]`;if(s?.role!==void 0&&s.role!=="node")throw new Error(`${i} 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(`${i} has no profile ${JSON.stringify(e)} (it has: ${d})`)}if(e!==W&&!t)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(W)}, or pass allowDebugProfile to test`);let y=(c.allowed_tcb_statuses??["uptodate"]).map(d=>br(d,i));return o=o===void 0?y:o.filter(d=>y.includes(d)),{mrtd:c.mrtd,rtmr0:c.rtmr0,rtmr1:c.rtmr1,rtmr2:c.rtmr2,rtmr3:c.rtmr3}});if(!o||o.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:r,allowedTcbStatuses:o}}function br(n,e){let t=wr.find(o=>o.toLowerCase()===String(n).toLowerCase());if(!t)throw new Error(`${e} accepts TCB status ${JSON.stringify(n)}, which this verifier does not know`);return t}var Et=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"}),Pr=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],Ve="https://cloud.calimero.network",Tt=`${Ve}/api/tee/pcs`;async function En(n,e,t={}){let o=typeof n=="string"?new TextEncoder().encode(n):n;await Ie(o,e,{identity:t.identity??Et.identity,issuer:t.issuer??Et.issuer},t.signature);let r;try{r=JSON.parse(new TextDecoder().decode(o))}catch{throw new Error("The signed release is not JSON")}if(r?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(r?.role)} release, not a node one`);let s=Object.values(r.profiles??{}),a=i=>Pr.every(c=>/^[0-9a-f]{96}$/i.test(String(i?.[c])));if(typeof r.tag!="string"||s.length===0||!s.every(a))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(t.expectedVersion!==void 0&&r.tag!==t.expectedVersion)throw new Error(`The signed release is ${r.tag}, not ${t.expectedVersion}`);return r}async function jt(n,e={}){let t=await(e.fetch??fetch)(n,{headers:{accept:"application/json"}});if(!t.ok)throw new Error(`Fetching the node release from ${n} failed: HTTP ${t.status}`);let o;try{o=(await t.json())?.data}catch{throw new Error(`${n} did not answer with JSON`)}if(typeof o?.version!="string"||typeof o.publishedMrtds!="string"||typeof o.bundle!="string")throw new Error(`${n} did not answer with a signed node release`);return{version:o.version,publishedMrtds:o.publishedMrtds,bundle:o.bundle}}var Tn="https://github.com/calimero-network/mero-tee/releases/download";async function Ot(n,e={}){let t=`mero-tee-v${$(n,"version")}`,o=`${(e.base??Tn).replace(/\/+$/,"")}/${t}/published-mrtds.json`,r=async i=>{let c=await(e.fetch??fetch)(i);if(!c.ok)throw new Error(`Fetching ${i} failed: HTTP ${c.status}`);return c.text()},[s,a]=await Promise.all([r(o),r(`${o}.bundle.json`)]);return{version:n,publishedMrtds:s,bundle:a}}function vt(n,e){return`${n.replace(/\/+$/,"")}/api/tee/node-releases/${$(e,"version")}`}async function Le(n){let e=$(n.minReleaseVersion,"minReleaseVersion"),t=$(n.release?.version,"The release version"),o=await En(n.release.publishedMrtds,n.release.bundle,{expectedVersion:t,identity:n.identity,issuer:n.issuer});if(Pe(t,e)<0)throw new Error(`Release ${t} is older than the minimum trusted, ${e}`);return kt([o],{profile:n.profile,allowDebugProfile:n.allowDebugProfile})}function _r(n){return $(n.minReleaseVersion,"minReleaseVersion"),Object.assign(async t=>{let o=await Le({release:await n.release(),profile:n.profile,allowDebugProfile:n.allowDebugProfile,minReleaseVersion:n.minReleaseVersion,identity:n.identity,issuer:n.issuer});return Z({dcapVerify:n.dcapVerify,fetchCollateral:n.fetchCollateral,now:n.now,...o})(t)},{includeCollateral:!0})}var jn=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function $(n,e){let t=typeof n=="string"?jn.exec(n):null,o=t?.[4];if(!t||o!==void 0&&o.split(".").some(r=>r===""))throw new Error(`${e} is ${JSON.stringify(n)}, not a release version like 2.3.87`);return n}function Pe(n,e){let[t,o]=kn(n),[r,s]=kn(e);for(let c=0;c<3;c+=1)if(t[c]!==r[c])return t[c]<r[c]?-1:1;if(o===void 0||s===void 0)return o===s?0:o===void 0?1:-1;let a=o.split("."),i=s.split(".");for(let c=0;c<Math.max(a.length,i.length);c+=1){let[y,d]=[a[c],i[c]];if(y===void 0||d===void 0)return y===void 0?-1:1;let[l,u]=[/^\d+$/.test(y),/^\d+$/.test(d)],m=l&&u?Math.sign(Number(y)-Number(d)):l!==u?l?-1:1:y<d?-1:y>d?1:0;if(m!==0)return m}return 0}function kn(n){let e=jn.exec(n);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var vn="MOCK_TDX_QUOTE_V1";function Rr(n){let e=atob(n),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);return t}function St(n,e){if(n.length!==e.length)return!1;let t=0;for(let o=0;o<n.length;o++)t|=n[o]^e[o];return t===0}var On;async function xt(n){On??(On=import("@phala/dcap-qvl"));let e=await On,t=typeof e[n]=="function"?e[n]:e.default?.[n];if(typeof t!="function")throw new TypeError(`@phala/dcap-qvl loaded without ${n}`);return t}function Sn(n,e){let t=$(e,"minReleaseVersion"),o=String(n.release?.version??"").trim().replace(/^mero-tee-v/,"").replace(/^v/,""),r=$(o,"The release the node names");if(Pe(r,t)<0)throw new Error(`mero-tee release ${r} is older than the minimum ${t}`);return r}async function Ar(n,e,t){let o=e.releaseSource;return typeof o=="function"?o(n):o==="github"?Ot(n,{fetch:t}):jt(vt(o??Ve,n),{fetch:t})}function kr(n){let e=n.collateralSource??Tt;return e==="intel"?async t=>(await xt("getCollateralFromPcs"))(t):async t=>(await xt("getCollateral"))(e,t)}function xn(n,e){let t=e.maxCollateralAgeDays;return t===void 0?n:async o=>{let r=await n(o),s;try{s=Date.parse(JSON.parse(r.tcb_info).issueDate??"")}catch{s=Number.NaN}if(!Number.isFinite(s))throw new Error("The quote's collateral names no TCB info issue date");let a=((e.now??Date.now)()-s)/864e5;if(a>t)throw new Error(`The quote's collateral was issued ${Math.floor(a)} days ago, more than the ${t} this client accepts`);return r}}async function Er(n,e,t,o){let r=Sn(n,t.minReleaseVersion),s=await Le({release:await Ar(r,t,o),profile:t.profile??W,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer}),a=xn(t.fetchCollateral??kr(t),t);return Z({dcapVerify:t.dcapVerify??await xt("verify"),fetchCollateral:a,now:t.now,...s})(e)}async function Ut(n,e,t=(o,r)=>fetch(o,r)){let o=T(crypto.getRandomValues(new Uint8Array(32))),r=new URL(`${n.replace(/\/+$/,"")}/attestation`);r.searchParams.set("nonce",o),e.appHash&&r.searchParams.set("appHash",e.appHash);let s=await t(r.toString());if(!s.ok)throw new Error(`The node refused to attest: HTTP ${s.status}`);let a=await s.json(),i=Ne(a.transportKey,"transportKey",32),c=e.appHash?Ne(e.appHash,"appHash",32):new Uint8Array(32),y=await bt(c,i),d=Rr(a.quote),l=new TextEncoder().encode(vn);if(St(d.slice(0,l.length),l)){if(!e.allowMock)throw new Error("mock quote refused: this client only trusts real TEEs");let g=d.slice(l.length,l.length+64);if(!St(g.slice(0,32),Ne(o,"nonce",32))||!St(g.slice(32),y))throw new Error("the quote does not bind this transport key, app and nonce");return i}let u={quoteB64:a.quote,nonce:o,reportDataSuffix:T(y)},m;if(e.verifyQuote)m=await e.verifyQuote(u);else if(e.release)m=await Er(a,u,e.release,t);else throw new Error("real quote refused: this client trusts no TD image (set policy.release)");if(!m)throw new Error("The attestation did not verify, so its transport key is not trusted");return i}var Ct="https://manager.cloud.calimero.network/api/v2/directory";var q=class extends Error{constructor(t,o,r,s,a){super(`directory for cluster ${t}: ${r}`);this.cluster=t;this.reason=o;this.status=s;this.cause=a;this.name="DirectoryError"}};function Tr(n,e){return`${n.replace(/\/+$/,"")}/${encodeURIComponent(e)}`}async function Bt(n,e,t){let o;try{o=await t(Tr(n,e),{method:"GET",headers:{accept:"application/json"}})}catch(d){throw new q(e,"unreachable",`could not be reached: ${String(d)}`,void 0,d)}if(o.status===404)throw new q(e,"not-found","unknown cluster",404);if(!o.ok)throw new q(e,"unreachable",`answered ${o.status}`,o.status);let r;try{r=await o.json()}catch(d){throw new q(e,"bad-response","answered something other than JSON",o.status,d)}let s=r;if(!s||typeof s!="object"||!Array.isArray(s.nodes))throw new q(e,"bad-response","answered no node list",o.status);let a=[],i=new Set;for(let d of s.nodes){let l=jr(d);l&&!i.has(l.url)&&(i.add(l.url),a.push(l))}if(a.length===0)throw new q(e,"empty","lists no usable node",o.status);let c=s.refreshAfterSeconds,y=typeof c=="number"&&Number.isFinite(c)&&c>=1?c:60;return{nodes:a,refreshAfterSeconds:y}}function jr(n){if(!n||typeof n!="object")return;let{url:e,zone:t,weight:o}=n;if(typeof e!="string"||typeof o!="number"||!Number.isInteger(o)||o<1)return;let r;try{r=new URL(e)}catch{return}if(!(r.protocol!=="https:"&&r.protocol!=="http:"))return{url:e.replace(/\/+$/,""),zone:typeof t=="string"?t:void 0,weight:o}}function qt(n,e,t){let o=e===void 0?[]:n.filter(s=>s.zone===e),r=e===void 0?n:n.filter(s=>s.zone!==e);return[...Un(o,t),...Un(r,t)]}function Un(n,e){let t=[...n],o=[];for(;t.length>0;){let r=e()*t.reduce((a,i)=>a+i.weight,0),s=0;for(;s<t.length-1&&r>=t[s].weight;)r-=t[s++].weight;o.push(t.splice(s,1)[0].url)}return o}var h=class extends Error{constructor(t,o,r,s={}){super(`${t} ${o}: ${r}`);this.status=t;this.code=o;this.details=s;this.name="CalimeroError"}},K=class extends h{constructor(e,t={}){super(401,"UNAUTHENTICATED",e,t),this.name="LoginRequired"}},$e=class extends h{constructor(e,t={}){super(401,"PASSKEY_UNKNOWN_HERE",e||"this passkey belongs to another Calimero cluster or was removed from this one",t),this.name="PasskeyUnknownHere"}},X=class extends h{constructor(e,t={}){super(421,"WRONG_NODE",e,t),this.name="WrongNode"}},Ke=class extends h{constructor(e,t={}){super(404,"NOT_FOUND",e,t),this.name="NotFound"}},ce=class extends h{constructor(e,t={}){super(412,"CONFIRM_REQUIRED",e,t),this.name="ConfirmRequired"}},_e=class extends Error{constructor(t){super("the passkey confirmation was cancelled");this.cause=t;this.name="ConfirmCancelled"}},Re=class extends Error{constructor(t){super("the passkey prompt was blocked by the browser or a password manager");this.cause=t;this.name="ConfirmPromptBlocked"}},Ge=class extends h{constructor(e,t={}){super(413,"ARGS_TOO_LARGE",e,t),this.name="ArgsTooLarge"}},He=class extends h{constructor(e,t={}){super(409,"IDEMPOTENCY_MISMATCH",e,t),this.name="IdempotencyMismatch"}},Fe=class extends h{constructor(e,t={}){super(409,"RELEASE_DEADLINE",e,t),this.name="ReleaseDeadlineError",this.release=typeof t.release=="string"?t.release:"",this.after=typeof t.after=="string"?t.after:""}},Qe=class extends h{constructor(e,t={}){super(409,"RUNTIME_TOO_OLD",e,t),this.name="RuntimeTooOld",this.minRuntimeVersion=typeof t.minRuntimeVersion=="string"?t.minRuntimeVersion:"",this.nodes=Array.isArray(t.nodes)?t.nodes:[]}},ze=class extends h{constructor(e,t={}){super(409,"CONSENT_STALE",e,t),this.name="ConsentStale"}},ee=class extends h{constructor(e,t={}){let o=typeof t.origin=="string"?t.origin:"",r=typeof t.package=="string"?t.package:"",s=o?`this site (${o})`:"this site";super(403,"ORIGIN_NOT_REGISTERED",`${s} is not registered for ${r||"any package"}${e?` (${e})`:""}`,t),this.name="OriginNotRegistered",this.origin=o,this.package=r,this.nodeMessage=e}},Je=class extends h{constructor(e,t,o={}){super(400,e,t,o),this.name="BadOrigin"}},Ye=class extends h{constructor(e,t={}){super(409,"ORIGIN_TAKEN",e,t),this.name="OriginTaken"}},We=class extends h{constructor(e,t={}){super(400,"NOT_SERVING",e,t),this.name="NotServing"}},Ze=class extends h{constructor(e,t={}){super(409,"CLUSTER_NOT_UPGRADED",e,t),this.name="ClusterNotUpgraded"}},Xe=class extends h{constructor(e,t={}){super(409,"FEATURE_NOT_ACTIVE",e,t),this.name="FeatureNotActive",this.feature=typeof t.feature=="string"?t.feature:"",this.needs=typeof t.needs=="string"?t.needs:"",this.active=typeof t.active=="string"?t.active:""}},et=class extends h{constructor(e,t={}){super(409,"RECOVERY_NOT_READY",e,t),this.name="RecoveryNotReady",this.readyAt=typeof t.readyAt=="number"?t.readyAt:void 0}},Ae=class extends h{constructor(e,t={}){super(401,"UNAUTHENTICATED",e||"unknown or used recovery code",t),this.name="WrongRecoveryCode"}},tt=class extends h{constructor(e,t={}){super(403,"SIGN_UP_REFUSED",e,t),this.name="SignUpRefused",this.reason=Or(e)}};function Or(n){return/invite only/.test(n)?"invite-only":/pre-authorized|sign-up invite/.test(n)?"closed":/unknown invite/.test(n)?"unknown-invite":/invite has expired/.test(n)?"expired-invite":/organization is gone/.test(n)?"org-gone":"other"}var nt=class extends h{constructor(e,t={}){super(429,"QUOTA_EXCEEDED",e,t),this.name="QuotaExceeded"}},ot=class extends h{constructor(e,t={}){super(422,"APP_ERROR",e,t),this.name="AppError";let{appCode:o,fields:r}=vr(t);this.appCode=o,this.fields=r}},rt=class extends h{constructor(e,t={}){super(422,"TRAP",e,t),this.name="TrapError",this.kind=typeof t.kind=="string"?t.kind:""}},le=class extends h{constructor(e,t,o={},r,s){super(503,e,t,o),this.name="UnavailableError",this.reason=e.toLowerCase(),this.committed=e==="TIMEOUT"||e==="MIGRATING"?!1:"unknown",this.retryAfter=r,this.cause=s}};function st(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function vr(n){let e=typeof n.code=="string"?n:st(n.error);return{appCode:typeof e.code=="string"?e.code:"",fields:{...st(e.fields)}}}function Sr(n,e){for(let t of[n.retryAfter,e==null?void 0:Number(e)])if(typeof t=="number"&&Number.isFinite(t)&&t>=0)return t}function de(n,e,t){let o=st(e),r=typeof o.error=="string"?o.error:"ERROR",s=typeof o.message=="string"?o.message:"",a=st(o.details);if(n===503)return new le(r,s,a,Sr(a,t));switch(`${n} ${r}`){case"401 UNAUTHENTICATED":return new K(s,a);case"401 PASSKEY_UNKNOWN_HERE":return new $e(s,a);case"421 WRONG_NODE":return new X(s,a);case"404 NOT_FOUND":return new Ke(s,a);case"409 IDEMPOTENCY_MISMATCH":return new He(s,a);case"409 RELEASE_DEADLINE":return new Fe(s,a);case"409 RUNTIME_TOO_OLD":return new Qe(s,a);case"409 CONSENT_STALE":return new ze(s,a);case"403 ORIGIN_NOT_REGISTERED":return new ee(s,a);case"400 BAD_ORIGIN":case"400 BAD_RP_ID":return new Je(r,s,a);case"409 ORIGIN_TAKEN":return new Ye(s,a);case"400 NOT_SERVING":return new We(s,a);case"409 CLUSTER_NOT_UPGRADED":return new Ze(s,a);case"409 FEATURE_NOT_ACTIVE":return new Xe(s,a);case"429 QUOTA_EXCEEDED":return new nt(s,a);case"409 RECOVERY_NOT_READY":return new et(s,a);case"403 SIGN_UP_REFUSED":return new tt(s,a);case"412 CONFIRM_REQUIRED":return new ce(s,a);case"413 ARGS_TOO_LARGE":return new Ge(s,a);case"422 APP_ERROR":return new ot(s,a);case"422 TRAP":return new rt(s,a);default:return new h(n,r,s,a)}}function j(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function G(n){let e=n.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((n.length+3)%4),t=atob(e),o=new Uint8Array(t.length);for(let r=0;r<t.length;r++)o[r]=t.charCodeAt(r);return o}var ke=n=>n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);function Nt(n){let e=new Error(n);return e.name="NotAllowedError",e}async function Cn(n,e,t,o){let r=navigator.credentials,a=globalThis.CredentialsContainer?.prototype?.[n]??r[n];try{return await a.call(r,t?{...e,signal:t}:e)}catch(i){throw t?.aborted||i?.name==="AbortError"?Object.assign(Nt(`${o} was cancelled`),{cause:i}):i}}function xr(n){let e=n.filter(t=>t.alg===-7);return e.length?e:n}function Ur(){return{async create(n,e){let t=n,o=await Cn("create",{publicKey:{challenge:ke(G(t.challenge)),rp:t.rp,user:{...t.user,id:ke(G(t.user.id))},pubKeyCredParams:xr(t.pubKeyCredParams),excludeCredentials:(t.excludeCredentials??[]).map(s=>({type:s.type,id:ke(G(s.id))})),authenticatorSelection:t.authenticatorSelection,attestation:"none",timeout:t.timeout}},e?.signal,"passkey creation");if(!o)throw Nt("passkey creation was cancelled");let r=o.response;return{attestationObject:j(new Uint8Array(r.attestationObject)),clientDataJson:j(new Uint8Array(r.clientDataJSON))}},async get(n,e,t,o){let r=await Cn("get",{publicKey:{challenge:ke(n),rpId:e,userVerification:o?.userVerification??"preferred",allowCredentials:(t??[]).map(a=>({type:"public-key",id:ke(G(a))}))}},o?.signal,"passkey sign-in");if(!r)throw Nt("passkey sign-in was cancelled");let s=r.response;return{credentialId:j(new Uint8Array(r.rawId)),authenticatorData:j(new Uint8Array(s.authenticatorData)),clientDataJson:j(new Uint8Array(s.clientDataJSON)),signature:j(new Uint8Array(s.signature))}}}}function Cr(n,e){return n==="required"||n==="preferred"||n==="discouraged"?n:e}function Br(n){let e=n,t=e?.name,o=typeof e?.message=="string"?e.message:"";return t==="InvalidStateError"||/not focused|already pending/i.test(o)?new Re(n):t==="NotAllowedError"||t==="AbortError"?new _e(n):n}function Ee(n,e={}){return async t=>{try{return await n.get(G(t.challenge),t.rpId,t.allowCredentials,{userVerification:Cr(t.userVerification,e.userVerification??"required"),...e.signal?{signal:e.signal}:{}})}catch(o){throw Br(o)}}}var Dt={retries:6,baseDelayMs:200,maxDelayMs:2e3};function It(n,e){return Math.min(e.baseDelayMs*2**n,e.maxDelayMs)}function qr(n){return n instanceof V&&n.status===413?de(413,{error:"TOO_LARGE",message:n.message.replace(/^Sealed request refused: /,"")}):n}async function H(n){let e=await n.text().catch(()=>""),t={};try{t=e?JSON.parse(e):{}}catch{t={message:e}}return de(n.status,t,n.headers.get("retry-after"))}async function*qn(n){let e=n.getReader(),t=new TextDecoder,o="";for(;;){let{value:r,done:s}=await e.read();if(s)return;o+=t.decode(r,{stream:!0});let a;for(;(a=o.indexOf(`
1
+ function R(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function B(n,e,t){let o=n.trim();if(!/^[0-9a-fA-F]*$/.test(o)||o.length!==t*2)throw new Error(`${e} must be ${t*2} hex characters, got ${o.length}`);let r=new Uint8Array(t);for(let s=0;s<t;s+=1)r[s]=Number.parseInt(o.slice(s*2,s*2+2),16);return r}function h(...n){let e=new Uint8Array(n.reduce((o,r)=>o+r.length,0)),t=0;for(let o of n)e.set(o,t),t+=o.length;return e}var Ko="Noise_NK_25519_AESGCM_SHA256",_t=32,Lo=16,$o=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),At=class n{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(Ko),t=new Uint8Array(32);return t.set(e),new n(t)}async mixHash(e){this.h=await Go(h(this.h,e))}async mixKey(e){let[t,o]=await gn(this.ck,e);this.ck=t,this.k=await crypto.subtle.importKey("raw",o,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let t=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:mn(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(t),t}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let t=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:mn(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),t}split(){return gn(this.ck,new Uint8Array)}};async function hn(n,e,t){let o=await At.initialize();await o.mixHash(e),await o.mixHash(n);let r=await M(t);return await o.mixHash(r.publicKey),await o.mixKey(await te(r.privateKey,n)),{message1:h(r.publicKey,await o.encryptAndHash(new Uint8Array)),async finish(a){if(a.length<_t+Lo)throw new Error("Noise: message 2 is too short");let i=a.slice(0,_t);return await o.mixHash(i),await o.mixKey(await te(r.privateKey,i)),{payload:await o.decryptAndHash(a.slice(_t)),split:await o.split()}}}}async function M(n){if(!n){let o;try{o=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 r=new Uint8Array(await crypto.subtle.exportKey("raw",o.publicKey));return{privateKey:o.privateKey,publicKey:r}}let e=await crypto.subtle.importKey("pkcs8",h($o,n),{name:"X25519"},!0,["deriveBits"]),t=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Ho(t.x)}}async function te(n,e){let t=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:t},n,256))}function mn(n){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(n),!1),e}async function Go(n){return new Uint8Array(await crypto.subtle.digest("SHA-256",n))}async function Rt(n,e){let t=await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",t,e))}async function gn(n,e){let t=await Rt(n,e),o=await Rt(t,new Uint8Array([1])),r=await Rt(t,h(o,new Uint8Array([2])));return[o,r]}function Ho(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(t,o=>o.charCodeAt(0))}var Pn="/sealed/v2/handshake",_n="/sealed/v2",Pe="application/vnd.calimero.sealed",kt=2,Fo=new TextEncoder().encode("calimero/sealed-http/v2"),be=16,Qo=1+be+8,zo=0,Jo=1,Yo=2,Wo=1+64*1024+16,Zo=1024,Xo=6e4,er="calimero.tee-attest.transport-key.v1",tr=[101,204,205,304],Rn=new TextEncoder,_e=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},$=class extends Error{constructor(t,o,r,s){super(r);this.status=t;this.code=o;this.retryAfterMs=s;this.name="SealedTransportError"}};async function Et(n,e){let t=await crypto.subtle.digest("SHA-256",h(Rn.encode(er),n,e));return new Uint8Array(t)}function Tt(n){let e=new URL(n.baseUrl),t=e.pathname.replace(/\/+$/,""),o=`${e.origin}${t}`,r=n.fetch??((l,y)=>fetch(l,y)),s=typeof n.transportPublicKey=="function"?n.transportPublicKey:void 0,a=s?Promise.resolve().then(s):Promise.resolve(n.transportPublicKey);a.catch(()=>{});let i,c=async()=>{try{return await wn(r,o,await fn(a))}catch(l){if(!(l instanceof _e)||!s)throw l;return a=Promise.resolve().then(s),wn(r,o,await fn(a))}},u=async()=>{let l=i??d(void 0),y=await l;if(Date.now()<y.renewAt)return[y,l];let m=d(l);return[await m,m]},d=l=>{if(i===l){let y=c();i=y,y.catch(()=>{i===y&&(i=void 0)})}return i};return async(l,y)=>{let m=new Request(l,y),g=new URL(m.url);if(g.origin!==e.origin||!g.pathname.startsWith(`${t}/`))throw new Error(`Refusing to send ${g.href} outside the sealed node at ${n.baseUrl}`);let b=[];m.headers.forEach((O,N)=>b.push([N,O]));let U={method:m.method,path:g.pathname.slice(t.length)+g.search,headers:b},A=new Uint8Array(await m.arrayBuffer()),k=y?.signal??(l instanceof Request?l.signal:void 0),v=async O=>{let{requestId:N,header:Z,envelope:V}=await or(O,U,A),x=await r(`${o}${_n}`,{method:"POST",headers:{"content-type":Pe},body:V,signal:k});if(x.headers.get("content-type")!==Pe)throw await kn(x);return sr(x,O.responseKey,Z,N)},[I,pe]=await u();try{return await v(I)}catch(O){if(!(O instanceof $)||O.code!=="unknown_session")throw O;return v(await d(pe))}}}async function fn(n){let e=await n;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function wn(n,e,t){try{return await bn(n,e,t)}catch(o){if(!(o instanceof $)||o.code!=="busy")throw o;return await new Promise(r=>setTimeout(r,o.retryAfterMs??1e3)),bn(n,e,t)}}async function bn(n,e,t){let o=await hn(t,Fo),r=await n(`${e}${Pn}`,{method:"POST",headers:{"content-type":Pe},body:h(new Uint8Array([kt]),t,o.message1)});if(r.headers.get("content-type")!==Pe)throw await kn(r);let s=await ir(r,Zo);return nr(o,s)}async function nr(n,e){if(e[0]!==kt)throw new Error("The handshake reply is malformed");let t;try{t=await n.finish(e.slice(1))}catch{throw new Error("The handshake reply did not open: it did not come from the attested node")}let{payload:o,split:r}=t;if(o.length!==be+4)throw new Error("The handshake reply is malformed");let s=o.slice(0,be),a=new DataView(o.buffer,o.byteOffset).getUint32(be,!1),[i,c]=await Promise.all([crypto.subtle.importKey("raw",r[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",r[1],"AES-GCM",!1,["decrypt"])]);return r[0].fill(0),r[1].fill(0),{requestKey:i,responseKey:c,nextRequestId:1,renewAt:Date.now()+a*1e3-Xo,header(u){let d=new Uint8Array(Qo);return d[0]=kt,d.set(s,1),new DataView(d.buffer).setBigUint64(1+be,BigInt(u),!1),d}}}async function or(n,e,t){let o=n.nextRequestId;n.nextRequestId+=1;let r=n.header(o),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:An(o,0),additionalData:r},n.requestKey,rr(e,t));return{requestId:o,header:r,envelope:h(r,new Uint8Array(s))}}function An(n,e){let t=new Uint8Array(12),o=new DataView(t.buffer);return o.setBigUint64(0,BigInt(n),!1),o.setUint32(8,e,!1),t}function rr(n,e){let t=Rn.encode(JSON.stringify(n)),o=new Uint8Array(4);return new DataView(o.buffer).setUint32(0,t.length,!1),h(o,t,e)}async function sr(n,e,t,o){if(!n.body)throw new Error("The sealed response has no body");let r=ar(n.body.getReader()),s=0,a=async()=>{let d=await r.next();if(!d)return null;let l;try{l=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:An(o,s),additionalData:t},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:l[0],data:l.slice(1)}},i=await a();if(!i||i.kind!==zo)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(i.data));if(tr.includes(c.status))return await r.cancel(),new Response(null,{status:c.status,headers:c.headers});let u=new ReadableStream({async pull(d){try{let l=await a();l?l.kind===Jo?d.enqueue(l.data):l.kind===Yo?(d.close(),await r.cancel()):d.error(new Error("The sealed response is malformed")):d.error(new Error("The sealed response was cut short"))}catch(l){d.error(l)}},cancel(){return r.cancel()}});return new Response(u,{status:c.status,headers:c.headers})}function ar(n){let e=new Uint8Array,t=async o=>{for(;e.length<o;){let{done:r,value:s}=await n.read();if(r)return!1;e=h(e,s)}return!0};return{async next(){if(!await t(4))return null;let o=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(o>Wo)throw await n.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await t(4+o))return null;let r=e.slice(4,4+o);return e=e.slice(4+o),r},cancel:()=>n.cancel()}}async function ir(n,e){if(!n.body)return new Uint8Array;let t=n.body.getReader(),o=new Uint8Array;for(;;){let{done:r,value:s}=await t.read();if(r)return o;if(o=h(o,s),o.length>e)throw await t.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function kn(n){let e,t=`Sealed request refused: HTTP ${n.status}`;try{let s=await n.json();e=s?.error?.code,s?.error?.message&&(t=`Sealed request refused: ${s.error.message}`)}catch{}if(e==="stale_transport_key")return new _e;let o=Number(n.headers.get("retry-after")),r=Number.isFinite(o)&&o>0?Math.min(o,5)*1e3:void 0;return new $(n.status,e,t,r)}var En=[{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"]}],Tn=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var pr="1.2.840.10045.2.1",cr={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},lr={"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 jn(n,e,t){if(e+2>t)throw new Error("it is truncated");let o=n[e];if((o&31)===31)throw new Error("it uses a tag this parser does not read");let r=n[e+1],s=e+2;if(r&128){let i=r&127;if(i===0||i>4||s+i>t)throw new Error("it has a length this parser does not read");r=0;for(let c=0;c<i;c+=1)r=r*256+n[s+c];s+=i}let a=s+r;if(a>t)throw new Error("it is truncated");return{tag:o,bytes:n,offset:e,start:s,end:a}}function le(n){let e=jn(n,0,n.length);if(e.end!==n.length)throw new Error("it has trailing bytes");return e}function T(n){let e=[];for(let t=n.start;t<n.end;){let o=jn(n.bytes,t,n.end);e.push(o),t=o.end}return e}function w(n,e,t){if(!n||n.tag!==e)throw new Error(`${t} is not where it should be`);return n}function G(n){return n.bytes.slice(n.start,n.end)}function Le(n){return n.bytes.slice(n.offset,n.end)}function ce(n){let e=G(w(n,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let t=[],o=0;for(let a of e)o=o*128+(a&127),a&128||(t.push(o),o=0);let r=t.shift();return[...r<80?[Math.floor(r/40),r%40]:[2,r-80],...t].join(".")}function ur(n){let e=new TextDecoder().decode(G(n)),t=n.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,o=n.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,r=t??o;if(!r)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let s=Number(r[1]);t&&(s+=s<50?2e3:1900);let[a,i,c,u,d]=r.slice(2).map(Number);return Date.UTC(s,a-1,i,c,u,d)}function jt(n){try{let[e,t,o,...r]=T(w(le(n),48,"The certificate"));if(r.length>0)throw new Error("it has fields after its signature");let s=T(w(e,48,"The signed part")),a=s[0]?.tag===160?1:0,[i,c,u,d,l,y,...m]=s.slice(a);w(i,2,"The serial number");let g=ce(T(w(t,48,"The signature algorithm"))[0]);if(ce(T(w(c,48,"The signature algorithm"))[0])!==g)throw new Error("it names two different signature algorithms");let U=dr[g];if(!U)throw new Error(`it is signed with ${g}, not ECDSA with SHA-256 or SHA-384`);let[A,k]=T(w(d,48,"The validity")).map(ur);if(k===void 0)throw new Error("its validity is incomplete");let[v,I]=T(w(y,48,"The public key"));w(I,3,"The public key");let[pe,O]=T(w(v,48,"The key algorithm"));if(ce(pe)!==pr)throw new Error("its key is not an elliptic-curve key");let N=cr[ce(O)];if(!N)throw new Error("its key is on a curve other than P-256 or P-384");let Z=new Map,V=m.find(X=>X.tag===163);if(V){let[X]=T(V);for(let De of T(w(X,48,"The extensions"))){let C=T(w(De,48,"An extension"));if(C.length===3)w(C[1],1,"An extension's critical flag");else if(C.length!==2)throw new Error("it has a malformed extension");let fe=ce(C[0]);if(Z.has(fe))throw new Error(`it has extension ${fe} twice`);Z.set(fe,G(w(C[C.length-1],4,"An extension value")))}}let x=G(w(o,3,"The signature"));if(x[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:n,tbs:Le(e),signatureHash:U,signature:x.slice(1),issuer:Le(w(u,48,"The issuer")),subject:Le(w(l,48,"The subject")),notBefore:A,notAfter:k,spki:Le(y),curve:N,extensions:Z}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function vn(n){return T(w(le(n),48,"The list")).map(ce)}function yr(n,e){let t=lr[e],o=T(w(le(n),48,"The signature"));if(o.length!==2)throw new Error("The signature is not an ECDSA signature");let r=new Uint8Array(t*2);return o.forEach((s,a)=>{let i=G(w(s,2,"The signature"));if(i.length===0||i[0]&128)throw new Error("The signature is not an ECDSA signature");for(;i.length>1&&i[0]===0;)i=i.subarray(1);if(i.length>t)throw new Error("The signature is not an ECDSA signature");r.set(i,a*t+t-i.length)}),r}async function $e(n,e,t,o,r){let s;try{s=yr(o,e)}catch{return!1}let a=await crypto.subtle.importKey("spki",n,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:t},a,s,r)}function q(n,e){let t=n.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t)||t.length%4!==0)throw new Error(`${e} is not base64`);let o=atob(t),r=new Uint8Array(o.length);for(let s=0;s<o.length;s+=1)r[s]=o.charCodeAt(s);return r}function vt(n,e){let t=[...n.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(t.length!==1||n.replace(t[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return q(t[0][1],e)}var mr="2.5.29.17",gr="2.5.29.37",hr="1.3.6.1.5.5.7.3.3",fr="1.3.6.1.4.1.57264.1.8",wr="1.3.6.1.4.1.57264.1.1",br=134,Pr=12,_r=48,Rr=new TextEncoder,de=n=>new TextDecoder().decode(n);async function Ge(n,e,t,o){let{base64Signature:r,cert:s,rekorBundle:a}=Tr(e),i=a.Payload;if(o!==void 0&&o.trim()!==r.trim())throw new Error("The detached signature is not the one in the bundle");let c=q(r,"The bundle signature"),u=vt(de(q(s,"The bundle certificate")),"The bundle certificate"),d=jt(u),l=Tn.find(k=>k.logId===i.logID.toLowerCase());if(!l)throw new Error(`The bundle names Rekor log ${i.logID}, which the Sigstore trust root does not know`);let y=Rr.encode(`{"body":${JSON.stringify(i.body)},"integratedTime":${i.integratedTime},"logID":${JSON.stringify(i.logID)},"logIndex":${i.logIndex}}`);if(!await $e(q(l.publicKey,"The Rekor key"),"P-256","SHA-256",q(a.SignedEntryTimestamp,"The signed entry timestamp"),y))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let g=i.integratedTime*1e3;if(!Un(g,l.validFor))throw new Error(`Rekor log ${l.baseUrl} was not in use at ${Re(g)}, when the entry says it was logged`);let b=jr(i.body),U=R(new Uint8Array(await crypto.subtle.digest("SHA-256",n)));if(b.hash!==U)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!Ot(q(b.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let A=vt(de(q(b.publicKey,"The logged certificate")),"The logged certificate");if(!Ot(A,u))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await $e(d.spki,"P-256","SHA-256",c,n))throw new Error("The signature over the file does not verify with the bundle's certificate");return await Ar(d,g),Er(d,t),{integratedTime:i.integratedTime}}async function Ar(n,e){if(!Sn(n,e))throw new Error(`The signing certificate was valid ${Re(n.notBefore)} to ${Re(n.notAfter)}, not at ${Re(e)} when Rekor logged it`);let t=[];for(let o of En){let r=o.certChain.map(a=>jt(q(a,"A Fulcio certificate")));if(!await On(n,r[0]))continue;let s=await kr(r,o.validFor,e);if(!s)return;t.push(`${o.uri} (valid from ${o.validFor.start}): ${s}`)}throw new Error(t.length>0?`The signing certificate's CA is not trusted at ${Re(e)}: ${t.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function kr(n,e,t){if(!Un(t,e))return"the trust root says it was not issuing certificates then";for(let[o,r]of n.entries()){if(!Sn(r,t))return`its certificate ${o} was not valid then`;let s=n[o+1]??r;if(!await On(r,s))return`its certificate ${o} is not signed by the next`}}async function On(n,e){return Ot(n.issuer,e.subject)?$e(e.spki,e.curve,n.signatureHash,n.signature,n.tbs):!1}function Er(n,e){let t=n.extensions.get(mr);if(!t)throw new Error("The signing certificate names no identity");let o=T(w(le(t),_r,"The subject alternative name")),r=o.filter(u=>u.tag===br).map(u=>de(G(u)));if(r.length!==1||o.length!==1||r[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(r.length===1?r[0]:r)}, not by ${e.identity}`);let s=n.extensions.get(fr),a=n.extensions.get(wr),i=s?de(G(w(le(s),Pr,"The OIDC issuer"))):a?de(a):void 0;if(i!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${i===void 0?"missing":JSON.stringify(i)}, not ${e.issuer}`);let c=n.extensions.get(gr);if(!c||!vn(c).includes(hr))throw new Error("The signing certificate is not for code signing")}function Tr(n){let e=n;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let t=e,o=t?.rekorBundle?.Payload;if(!(typeof t?.base64Signature=="string"&&typeof t.cert=="string"&&typeof t.rekorBundle?.SignedEntryTimestamp=="string"&&typeof o?.body=="string"&&typeof o.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(o.logID)&&Number.isSafeInteger(o.integratedTime)&&o.integratedTime>=0&&Number.isSafeInteger(o.logIndex)&&o.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return t}function jr(n){let e;try{e=JSON.parse(de(q(n,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let t=e?.spec?.data?.hash,o=e?.spec?.signature;if(e?.kind!=="hashedrekord"||t?.algorithm!=="sha256"||typeof t.value!="string"||typeof o?.content!="string"||typeof o.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:t.value.toLowerCase(),signature:o.content,publicKey:o.publicKey.content}}function Sn(n,e){return n.notBefore<=e&&e<=n.notAfter}function Un(n,e){return Date.parse(e.start)<=n&&(e.end===void 0||n<=Date.parse(e.end))}function Re(n){return new Date(n).toISOString()}function Ot(n,e){return n.length===e.length&&n.every((t,o)=>t===e[o])}var vr=/^[0-9a-f]{96}$/,Or=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function oe(n){let e=ue(n.allowedMrtd??[],"allowedMrtd"),t=(n.allowedMeasurements??[]).map((i,c)=>{let u=`allowedMeasurements[${c}]`;return Or.map(d=>ue([i?.[d]??""],`${u}.${d}`)[0]).join()}),o=[ue(n.allowedRtmr0??[],"allowedRtmr0"),ue(n.allowedRtmr1??[],"allowedRtmr1"),ue(n.allowedRtmr2??[],"allowedRtmr2"),ue(n.allowedRtmr3??[],"allowedRtmr3")];if(n.allowedMeasurements!==void 0&&t.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(t.length===0){if(e.length===0)throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");if(o.slice(1).some(i=>i.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 r=n.allowedTcbStatuses??["UpToDate"],s=n.now??Date.now;return Object.assign(async({quoteB64:i,nonce:c,reportDataSuffix:u,collateral:d})=>{let l=Ur(i),y=d??await n.fetchCollateral?.(l);if(!y)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let m;try{m=n.dcapVerify(l,y,Math.floor(s()/1e3))}catch(A){throw new Error(`The quote did not verify: ${A?.message??String(A)}`)}if(m.status==="Revoked"||!r.includes(m.status))throw new Error(`The platform's TCB status is ${m.status}, which is not accepted`);let g=Sr(m.report);if(g.tdAttributes?.length!==8||(g.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let b=[g.mrTd,g.rtMr0,g.rtMr1,g.rtMr2,g.rtMr3].map(A=>R(A));if(t.length>0&&!t.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([g.rtMr0,g.rtMr1,g.rtMr2,g.rtMr3].forEach((A,k)=>{let v=o[k];if(v.length>0&&!v.includes(R(A)))throw new Error(`RTMR${k} ${R(A)} is not one this verifier trusts`)}),R(g.reportData)!==`${c}${u}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function ue(n,e){return n.map(t=>{let o=t.trim().toLowerCase();if(!vr.test(o))throw new Error(`${e} holds ${JSON.stringify(t)}, which is not a 48-byte hex measurement`);return o})}function Sr(n){let e=n.data;if(n.type==="td10"&&e)return e;if(n.type==="td15"&&e?.base)return e.base;throw new Error(`The quote is a ${n.type} quote, not a TDX one`)}function Ur(n){let e=atob(n),t=new Uint8Array(e.length);for(let o=0;o<e.length;o+=1)t[o]=e.charCodeAt(o);return t}var xr=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],ne="locked-read-only";function St(n,{profile:e,allowDebugProfile:t=!1}){if(n.length===0)throw new Error("No release given, so no image would be trusted");let o,r=n.map((s,a)=>{let i=s?.tag??`releases[${a}]`;if(s?.role!==void 0&&s.role!=="node")throw new Error(`${i} 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(`${i} has no profile ${JSON.stringify(e)} (it has: ${d})`)}if(e!==ne&&!t)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(ne)}, or pass allowDebugProfile to test`);let u=(c.allowed_tcb_statuses??["uptodate"]).map(d=>Cr(d,i));return o=o===void 0?u:o.filter(d=>u.includes(d)),{mrtd:c.mrtd,rtmr0:c.rtmr0,rtmr1:c.rtmr1,rtmr2:c.rtmr2,rtmr3:c.rtmr3}});if(!o||o.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:r,allowedTcbStatuses:o}}function Cr(n,e){let t=xr.find(o=>o.toLowerCase()===String(n).toLowerCase());if(!t)throw new Error(`${e} accepts TCB status ${JSON.stringify(n)}, which this verifier does not know`);return t}var Ut=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"}),Br=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],He="https://cloud.calimero.network",xt=`${He}/api/tee/pcs`;async function Cn(n,e,t={}){let o=typeof n=="string"?new TextEncoder().encode(n):n;await Ge(o,e,{identity:t.identity??Ut.identity,issuer:t.issuer??Ut.issuer},t.signature);let r;try{r=JSON.parse(new TextDecoder().decode(o))}catch{throw new Error("The signed release is not JSON")}if(r?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(r?.role)} release, not a node one`);let s=Object.values(r.profiles??{}),a=i=>Br.every(c=>/^[0-9a-f]{96}$/i.test(String(i?.[c])));if(typeof r.tag!="string"||s.length===0||!s.every(a))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(t.expectedVersion!==void 0&&r.tag!==t.expectedVersion)throw new Error(`The signed release is ${r.tag}, not ${t.expectedVersion}`);return r}async function Ct(n,e={}){let t=await(e.fetch??fetch)(n,{headers:{accept:"application/json"}});if(!t.ok)throw new Error(`Fetching the node release from ${n} failed: HTTP ${t.status}`);let o;try{o=(await t.json())?.data}catch{throw new Error(`${n} did not answer with JSON`)}if(typeof o?.version!="string"||typeof o.publishedMrtds!="string"||typeof o.bundle!="string")throw new Error(`${n} did not answer with a signed node release`);return{version:o.version,publishedMrtds:o.publishedMrtds,bundle:o.bundle}}var Bn="https://github.com/calimero-network/mero-tee/releases/download";async function Bt(n,e={}){let t=`mero-tee-v${H(n,"version")}`,o=`${(e.base??Bn).replace(/\/+$/,"")}/${t}/published-mrtds.json`,r=async i=>{let c=await(e.fetch??fetch)(i);if(!c.ok)throw new Error(`Fetching ${i} failed: HTTP ${c.status}`);return c.text()},[s,a]=await Promise.all([r(o),r(`${o}.bundle.json`)]);return{version:n,publishedMrtds:s,bundle:a}}function qt(n,e){return`${n.replace(/\/+$/,"")}/api/tee/node-releases/${H(e,"version")}`}async function Fe(n){let e=H(n.minReleaseVersion,"minReleaseVersion"),t=H(n.release?.version,"The release version"),o=await Cn(n.release.publishedMrtds,n.release.bundle,{expectedVersion:t,identity:n.identity,issuer:n.issuer});if(Ae(t,e)<0)throw new Error(`Release ${t} is older than the minimum trusted, ${e}`);return St([o],{profile:n.profile,allowDebugProfile:n.allowDebugProfile})}function qr(n){return H(n.minReleaseVersion,"minReleaseVersion"),Object.assign(async t=>{let o=await Fe({release:await n.release(),profile:n.profile,allowDebugProfile:n.allowDebugProfile,minReleaseVersion:n.minReleaseVersion,identity:n.identity,issuer:n.issuer});return oe({dcapVerify:n.dcapVerify,fetchCollateral:n.fetchCollateral,now:n.now,...o})(t)},{includeCollateral:!0})}var qn=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function H(n,e){let t=typeof n=="string"?qn.exec(n):null,o=t?.[4];if(!t||o!==void 0&&o.split(".").some(r=>r===""))throw new Error(`${e} is ${JSON.stringify(n)}, not a release version like 2.3.87`);return n}function Ae(n,e){let[t,o]=xn(n),[r,s]=xn(e);for(let c=0;c<3;c+=1)if(t[c]!==r[c])return t[c]<r[c]?-1:1;if(o===void 0||s===void 0)return o===s?0:o===void 0?1:-1;let a=o.split("."),i=s.split(".");for(let c=0;c<Math.max(a.length,i.length);c+=1){let[u,d]=[a[c],i[c]];if(u===void 0||d===void 0)return u===void 0?-1:1;let[l,y]=[/^\d+$/.test(u),/^\d+$/.test(d)],m=l&&y?Math.sign(Number(u)-Number(d)):l!==y?l?-1:1:u<d?-1:u>d?1:0;if(m!==0)return m}return 0}function xn(n){let e=qn.exec(n);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var Mn="MOCK_TDX_QUOTE_V1";function Nr(n){let e=atob(n),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);return t}function Nt(n,e){if(n.length!==e.length)return!1;let t=0;for(let o=0;o<n.length;o++)t|=n[o]^e[o];return t===0}var Nn;async function Mt(n){Nn??(Nn=import("@phala/dcap-qvl"));let e=await Nn,t=typeof e[n]=="function"?e[n]:e.default?.[n];if(typeof t!="function")throw new TypeError(`@phala/dcap-qvl loaded without ${n}`);return t}function Dn(n,e){let t=H(e,"minReleaseVersion"),o=String(n.release?.version??"").trim().replace(/^mero-tee-v/,"").replace(/^v/,""),r=H(o,"The release the node names");if(Ae(r,t)<0)throw new Error(`mero-tee release ${r} is older than the minimum ${t}`);return r}async function Mr(n,e,t){let o=e.releaseSource;return typeof o=="function"?o(n):o==="github"?Bt(n,{fetch:t}):Ct(qt(o??He,n),{fetch:t})}function Dr(n){let e=n.collateralSource??xt;return e==="intel"?async t=>(await Mt("getCollateralFromPcs"))(t):async t=>(await Mt("getCollateral"))(e,t)}function In(n,e){let t=e.maxCollateralAgeDays;return t===void 0?n:async o=>{let r=await n(o),s;try{s=Date.parse(JSON.parse(r.tcb_info).issueDate??"")}catch{s=Number.NaN}if(!Number.isFinite(s))throw new Error("The quote's collateral names no TCB info issue date");let a=((e.now??Date.now)()-s)/864e5;if(a>t)throw new Error(`The quote's collateral was issued ${Math.floor(a)} days ago, more than the ${t} this client accepts`);return r}}async function Ir(n,e,t,o){let r=Dn(n,t.minReleaseVersion),s=await Fe({release:await Mr(r,t,o),profile:t.profile??ne,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer}),a=In(t.fetchCollateral??Dr(t),t);return oe({dcapVerify:t.dcapVerify??await Mt("verify"),fetchCollateral:a,now:t.now,...s})(e)}async function Dt(n,e,t=(o,r)=>fetch(o,r)){let o=R(crypto.getRandomValues(new Uint8Array(32))),r=new URL(`${n.replace(/\/+$/,"")}/attestation`);r.searchParams.set("nonce",o),e.appHash&&r.searchParams.set("appHash",e.appHash);let s=await t(r.toString());if(!s.ok)throw new Error(`The node refused to attest: HTTP ${s.status}`);let a=await s.json(),i=B(a.transportKey,"transportKey",32),c=e.appHash?B(e.appHash,"appHash",32):new Uint8Array(32),u=await Et(c,i),d=Nr(a.quote),l=new TextEncoder().encode(Mn);if(Nt(d.slice(0,l.length),l)){if(!e.allowMock)throw new Error("mock quote refused: this client only trusts real TEEs");let g=d.slice(l.length,l.length+64);if(!Nt(g.slice(0,32),B(o,"nonce",32))||!Nt(g.slice(32),u))throw new Error("the quote does not bind this transport key, app and nonce");return i}let y={quoteB64:a.quote,nonce:o,reportDataSuffix:R(u)},m;if(e.verifyQuote)m=await e.verifyQuote(y);else if(e.release)m=await Ir(a,y,e.release,t);else throw new Error("real quote refused: this client trusts no TD image (set policy.release)");if(!m)throw new Error("The attestation did not verify, so its transport key is not trusted");return i}var It="https://manager.cloud.calimero.network/api/v2/directory";var D=class extends Error{constructor(t,o,r,s,a){super(`directory for cluster ${t}: ${r}`);this.cluster=t;this.reason=o;this.status=s;this.cause=a;this.name="DirectoryError"}};function Vr(n,e){return`${n.replace(/\/+$/,"")}/${encodeURIComponent(e)}`}async function Vt(n,e,t){let o;try{o=await t(Vr(n,e),{method:"GET",headers:{accept:"application/json"}})}catch(d){throw new D(e,"unreachable",`could not be reached: ${String(d)}`,void 0,d)}if(o.status===404)throw new D(e,"not-found","unknown cluster",404);if(!o.ok)throw new D(e,"unreachable",`answered ${o.status}`,o.status);let r;try{r=await o.json()}catch(d){throw new D(e,"bad-response","answered something other than JSON",o.status,d)}let s=r;if(!s||typeof s!="object"||!Array.isArray(s.nodes))throw new D(e,"bad-response","answered no node list",o.status);let a=[],i=new Set;for(let d of s.nodes){let l=Kr(d);l&&!i.has(l.url)&&(i.add(l.url),a.push(l))}if(a.length===0)throw new D(e,"empty","lists no usable node",o.status);let c=s.refreshAfterSeconds,u=typeof c=="number"&&Number.isFinite(c)&&c>=1?c:60;return{nodes:a,refreshAfterSeconds:u}}function Kr(n){if(!n||typeof n!="object")return;let{url:e,zone:t,weight:o}=n;if(typeof e!="string"||typeof o!="number"||!Number.isInteger(o)||o<1)return;let r;try{r=new URL(e)}catch{return}if(!(r.protocol!=="https:"&&r.protocol!=="http:"))return{url:e.replace(/\/+$/,""),zone:typeof t=="string"?t:void 0,weight:o}}function Kt(n,e,t){let o=e===void 0?[]:n.filter(s=>s.zone===e),r=e===void 0?n:n.filter(s=>s.zone!==e);return[...Vn(o,t),...Vn(r,t)]}function Vn(n,e){let t=[...n],o=[];for(;t.length>0;){let r=e()*t.reduce((a,i)=>a+i.weight,0),s=0;for(;s<t.length-1&&r>=t[s].weight;)r-=t[s++].weight;o.push(t.splice(s,1)[0].url)}return o}var f=class extends Error{constructor(t,o,r,s={}){super(`${t} ${o}: ${r}`);this.status=t;this.code=o;this.details=s;this.name="CalimeroError"}},F=class extends f{constructor(e,t={}){super(401,"UNAUTHENTICATED",e,t),this.name="LoginRequired"}},Qe=class extends f{constructor(e,t={}){super(401,"PASSKEY_UNKNOWN_HERE",e||"this passkey belongs to another Calimero cluster or was removed from this one",t),this.name="PasskeyUnknownHere"}},re=class extends f{constructor(e,t={}){super(421,"WRONG_NODE",e,t),this.name="WrongNode"}},ze=class extends f{constructor(e,t={}){super(404,"NOT_FOUND",e,t),this.name="NotFound"}},ye=class extends f{constructor(e,t={}){super(412,"CONFIRM_REQUIRED",e,t),this.name="ConfirmRequired"}},ke=class extends Error{constructor(t){super("the passkey confirmation was cancelled");this.cause=t;this.name="ConfirmCancelled"}},Ee=class extends Error{constructor(t){super("the passkey prompt was blocked by the browser or a password manager");this.cause=t;this.name="ConfirmPromptBlocked"}},Je=class extends f{constructor(e,t={}){super(413,"ARGS_TOO_LARGE",e,t),this.name="ArgsTooLarge"}},Ye=class extends f{constructor(e,t={}){super(409,"IDEMPOTENCY_MISMATCH",e,t),this.name="IdempotencyMismatch"}},We=class extends f{constructor(e,t={}){super(409,"RELEASE_DEADLINE",e,t),this.name="ReleaseDeadlineError",this.release=typeof t.release=="string"?t.release:"",this.after=typeof t.after=="string"?t.after:""}},Ze=class extends f{constructor(e,t={}){super(409,"RUNTIME_TOO_OLD",e,t),this.name="RuntimeTooOld",this.minRuntimeVersion=typeof t.minRuntimeVersion=="string"?t.minRuntimeVersion:"",this.nodes=Array.isArray(t.nodes)?t.nodes:[]}},Xe=class extends f{constructor(e,t={}){super(409,"CONSENT_STALE",e,t),this.name="ConsentStale"}},se=class extends f{constructor(e,t={}){let o=typeof t.origin=="string"?t.origin:"",r=typeof t.package=="string"?t.package:"",s=o?`this site (${o})`:"this site";super(403,"ORIGIN_NOT_REGISTERED",`${s} is not registered for ${r||"any package"}${e?` (${e})`:""}`,t),this.name="OriginNotRegistered",this.origin=o,this.package=r,this.nodeMessage=e}},et=class extends f{constructor(e,t,o={}){super(400,e,t,o),this.name="BadOrigin"}},tt=class extends f{constructor(e,t={}){super(409,"ORIGIN_TAKEN",e,t),this.name="OriginTaken"}},nt=class extends f{constructor(e,t={}){super(400,"NOT_SERVING",e,t),this.name="NotServing"}},ot=class extends f{constructor(e,t={}){super(409,"CLUSTER_NOT_UPGRADED",e,t),this.name="ClusterNotUpgraded"}},rt=class extends f{constructor(e,t={}){super(409,"FEATURE_NOT_ACTIVE",e,t),this.name="FeatureNotActive",this.feature=typeof t.feature=="string"?t.feature:"",this.needs=typeof t.needs=="string"?t.needs:"",this.active=typeof t.active=="string"?t.active:""}},st=class extends f{constructor(e,t={}){super(409,"RECOVERY_NOT_READY",e,t),this.name="RecoveryNotReady",this.readyAt=typeof t.readyAt=="number"?t.readyAt:void 0}},Te=class extends f{constructor(e,t={}){super(401,"UNAUTHENTICATED",e||"unknown or used recovery code",t),this.name="WrongRecoveryCode"}},at=class extends f{constructor(e,t={}){super(403,"SIGN_UP_REFUSED",e,t),this.name="SignUpRefused",this.reason=Lr(e)}};function Lr(n){return/invite only/.test(n)?"invite-only":/pre-authorized|sign-up invite/.test(n)?"closed":/unknown invite/.test(n)?"unknown-invite":/invite has expired/.test(n)?"expired-invite":/organization is gone/.test(n)?"org-gone":"other"}var it=class extends f{constructor(e,t={}){super(429,"QUOTA_EXCEEDED",e,t),this.name="QuotaExceeded"}},pt=class extends f{constructor(e,t={}){super(422,"APP_ERROR",e,t),this.name="AppError";let{appCode:o,fields:r}=$r(t);this.appCode=o,this.fields=r}},ct=class extends f{constructor(e,t={}){super(422,"TRAP",e,t),this.name="TrapError",this.kind=typeof t.kind=="string"?t.kind:""}},Q=class extends f{constructor(e,t,o={},r,s){super(503,e,t,o),this.name="UnavailableError",this.reason=e.toLowerCase(),this.committed=e==="TIMEOUT"||e==="MIGRATING"?!1:"unknown",this.retryAfter=r,this.cause=s}};function lt(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function $r(n){let e=typeof n.code=="string"?n:lt(n.error);return{appCode:typeof e.code=="string"?e.code:"",fields:{...lt(e.fields)}}}function Gr(n,e){for(let t of[n.retryAfter,e==null?void 0:Number(e)])if(typeof t=="number"&&Number.isFinite(t)&&t>=0)return t}function me(n,e,t){let o=lt(e),r=typeof o.error=="string"?o.error:"ERROR",s=typeof o.message=="string"?o.message:"",a=lt(o.details);if(n===503)return new Q(r,s,a,Gr(a,t));switch(`${n} ${r}`){case"401 UNAUTHENTICATED":return new F(s,a);case"401 PASSKEY_UNKNOWN_HERE":return new Qe(s,a);case"421 WRONG_NODE":return new re(s,a);case"404 NOT_FOUND":return new ze(s,a);case"409 IDEMPOTENCY_MISMATCH":return new Ye(s,a);case"409 RELEASE_DEADLINE":return new We(s,a);case"409 RUNTIME_TOO_OLD":return new Ze(s,a);case"409 CONSENT_STALE":return new Xe(s,a);case"403 ORIGIN_NOT_REGISTERED":return new se(s,a);case"400 BAD_ORIGIN":case"400 BAD_RP_ID":return new et(r,s,a);case"409 ORIGIN_TAKEN":return new tt(s,a);case"400 NOT_SERVING":return new nt(s,a);case"409 CLUSTER_NOT_UPGRADED":return new ot(s,a);case"409 FEATURE_NOT_ACTIVE":return new rt(s,a);case"429 QUOTA_EXCEEDED":return new it(s,a);case"409 RECOVERY_NOT_READY":return new st(s,a);case"403 SIGN_UP_REFUSED":return new at(s,a);case"412 CONFIRM_REQUIRED":return new ye(s,a);case"413 ARGS_TOO_LARGE":return new Je(s,a);case"422 APP_ERROR":return new pt(s,a);case"422 TRAP":return new ct(s,a);default:return new f(n,r,s,a)}}function j(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function z(n){let e=n.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((n.length+3)%4),t=atob(e),o=new Uint8Array(t.length);for(let r=0;r<t.length;r++)o[r]=t.charCodeAt(r);return o}var je=n=>n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);function Lt(n){let e=new Error(n);return e.name="NotAllowedError",e}async function Kn(n,e,t,o){let r=navigator.credentials,a=globalThis.CredentialsContainer?.prototype?.[n]??r[n];try{return await a.call(r,t?{...e,signal:t}:e)}catch(i){throw t?.aborted||i?.name==="AbortError"?Object.assign(Lt(`${o} was cancelled`),{cause:i}):i}}function Hr(n){let e=n.filter(t=>t.alg===-7);return e.length?e:n}function Fr(){return{async create(n,e){let t=n,o=await Kn("create",{publicKey:{challenge:je(z(t.challenge)),rp:t.rp,user:{...t.user,id:je(z(t.user.id))},pubKeyCredParams:Hr(t.pubKeyCredParams),excludeCredentials:(t.excludeCredentials??[]).map(s=>({type:s.type,id:je(z(s.id))})),authenticatorSelection:t.authenticatorSelection,attestation:"none",timeout:t.timeout}},e?.signal,"passkey creation");if(!o)throw Lt("passkey creation was cancelled");let r=o.response;return{attestationObject:j(new Uint8Array(r.attestationObject)),clientDataJson:j(new Uint8Array(r.clientDataJSON))}},async get(n,e,t,o){let r=await Kn("get",{publicKey:{challenge:je(n),rpId:e,userVerification:o?.userVerification??"preferred",allowCredentials:(t??[]).map(a=>({type:"public-key",id:je(z(a))}))}},o?.signal,"passkey sign-in");if(!r)throw Lt("passkey sign-in was cancelled");let s=r.response;return{credentialId:j(new Uint8Array(r.rawId)),authenticatorData:j(new Uint8Array(s.authenticatorData)),clientDataJson:j(new Uint8Array(s.clientDataJSON)),signature:j(new Uint8Array(s.signature))}}}}function Qr(n,e){return n==="required"||n==="preferred"||n==="discouraged"?n:e}function zr(n){let e=n,t=e?.name,o=typeof e?.message=="string"?e.message:"";return t==="InvalidStateError"||/not focused|already pending/i.test(o)?new Ee(n):t==="NotAllowedError"||t==="AbortError"?new ke(n):n}function ve(n,e={}){return async t=>{try{return await n.get(z(t.challenge),t.rpId,t.allowCredentials,{userVerification:Qr(t.userVerification,e.userVerification??"required"),...e.signal?{signal:e.signal}:{}})}catch(o){throw zr(o)}}}var Gt={retries:6,baseDelayMs:200,maxDelayMs:2e3};function Se(n,e){return Math.min(e.baseDelayMs*2**n,e.maxDelayMs)}function Jr(n){return n instanceof $&&n.status===413?me(413,{error:"TOO_LARGE",message:n.message.replace(/^Sealed request refused: /,"")}):n}async function J(n){let e=await n.text().catch(()=>""),t={};try{t=e?JSON.parse(e):{}}catch{t={message:e}}return me(n.status,t,n.headers.get("retry-after"))}async function*$n(n){let e=n.getReader(),t=new TextDecoder,o="";for(;;){let{value:r,done:s}=await e.read();if(s)return;o+=t.decode(r,{stream:!0});let a;for(;(a=o.indexOf(`
2
2
 
3
- `))>=0;){let i=o.slice(0,a);o=o.slice(a+2);let c="",y="",d="";for(let u of i.split(`
4
- `))u.startsWith("id:")?c=u.slice(3).trim():u.startsWith("event:")?y=u.slice(6).trim():u.startsWith("data:")&&(d+=u.slice(5).trim());if(!y&&!d)continue;let l=d;try{l=JSON.parse(d)}catch{}yield{id:c,kind:y,data:l}}}}function Vt(){return`node:c-${j(crypto.getRandomValues(new Uint8Array(16)))}`}function at(n,e={}){return n.replace(/\{([^}]+)\}/g,(t,o)=>{let r=e[o];if(r===void 0)throw new Error(`no value for path parameter ${o} of ${n}`);return encodeURIComponent(String(r))})}function Mt(n){if(!n)return"";let e=new URLSearchParams;for(let[o,r]of Object.entries(n))for(let s of Array.isArray(r)?r:[r])s!=null&&e.append(o,String(s));let t=e.toString();return t?`?${t}`:""}function Bn(n){return n==="auth/refresh"||n.startsWith("auth/passkey/")||Nr.has(n)}var Nr=new Set(["auth/recovery/begin","auth/recovery/start","auth/recovery/finish"]);function Te(n){return n.replace(/^\/+/,"")}var te=class{constructor(e){this.at=0;this.channels=new Map;this.networkFailures=new WeakSet;let t=s=>s.replace(/\/+$/,"");this.nodeUrls=[...new Set([e.baseUrl,...e.nodes??[]].map(t))],this.policy=e.policy,this.retry={...Dt,...e.retry};let o=e.fetch??((s,a)=>fetch(s,a)),r=async(s,a)=>{try{return await o(s,a)}catch(i){throw i instanceof TypeError&&this.networkFailures.add(i),i}};this.raw=r}useDirectory(e){this.source=e}get nodeUrl(){return this.nodeUrls[this.at]}get nodes(){return[...this.nodeUrls]}useApiKey(e){this.auth=e,this.current=void 0}useSession(e){this.auth=e.sessionToken,this.current=e}signOut(){this.auth=void 0,this.current=void 0}get session(){return this.current}channel(e){let t=this.channels.get(e);return t||(t=Pt({baseUrl:e,transportPublicKey:()=>Ut(e,this.policy,this.raw),fetch:this.raw}),this.channels.set(e,t)),t}moveOn(e){return this.nodeUrls.length<2?!1:(this.nodeUrl===e&&(this.at=(this.at+1)%this.nodeUrls.length),!0)}failOver(e,t){if(this.nodeUrl!==e&&!t.has(this.nodeUrl))return!0;let o=this.nodeUrls.length;for(let r=1;r<o;r++){let s=(this.at+r)%o;if(!t.has(this.nodeUrls[s]))return this.at=s,this.reread(),!0}return!1}reread(){let e=this.source;!e||e.reading||(e.reading=Bt(e.directory,e.cluster,this.raw).then(t=>{let o=this.nodeUrl,r=qt(t.nodes,e.zone,e.random);this.nodeUrls=[o,...r.filter(s=>s!==o)],this.at=0,e.due=Date.now()+t.refreshAfterSeconds*1e3}).catch(()=>{}).finally(()=>{e.reading=void 0}))}async once(e,t,o){let r={};this.auth&&(r.authorization=`Bearer ${this.auth}`);let s;o.bytes?(r["content-type"]=o.contentType??"application/wasm",s=o.bytes):o.body!==void 0&&(r["content-type"]="application/json",s=JSON.stringify(o.body)),this.source&&Date.now()>=this.source.due&&this.reread();let a=this.nodeUrl;try{return await this.channel(a)(`${a}/${t}${Mt(o.query)}`,{method:e,headers:r,body:s,signal:o.signal})}catch(i){throw qr(i)}}async send(e,t,o){let r=await this.answer(e,t,o);if(!r.ok)throw await H(r);return r}async answer(e,t,o){let r=!1,s=!1;for(;;){let[a,i]=[this.auth,this.nodeUrl],c=await this.once(e,t,o);if(c.ok||c.status!==401&&c.status!==421)return c;let y=await H(c.clone());if(y instanceof X&&!s){if(s=!0,this.moveOn(i)&&!Bn(t))continue}else if(y instanceof K&&!r&&this.mayRefresh(a,t)){r=!0,await this.renew(a);continue}return c}}mayRefresh(e,t){return e!==void 0&&this.current!==void 0&&!Bn(t)}async renew(e){this.auth===e&&await this.refresh()}async read(e,t,o){let s=await(await this.send(e,t,o)).text();return s?JSON.parse(s):{}}async retried(e,t,o,r){let s=await this.answerRetried(e,t,o,r);if(!s.ok)throw await H(s);let a=await s.text();return a?JSON.parse(a):{}}async answerRetried(e,t,o,r){let s=r?0:this.retry.retries,a=new Set;for(;;){let i,c,y=this.nodeUrl;for(let d=0;;d++){y=this.nodeUrl,a.add(y);try{let u=await this.answer(e,t,o);if(u.status!==503)return u;c=u,i=await H(u.clone())}catch(u){if(u instanceof TypeError&&this.networkFailures.has(u))c=void 0,i=new le("NETWORK",`the node could not be reached: ${u.message}`,{},void 0,u);else throw u}if(d>=s)break;let l=It(d,this.retry);await new Promise(u=>setTimeout(u,Math.max(l,(i.retryAfter??0)*1e3)))}if(r||!this.failOver(y,a)){if(c)return c;throw i}}}exchange(e,t,o={}){let r=Te(t);return o.retry?this.answerRetried(e,r,o,o.retry==="once"):this.answer(e,r,o)}attempt(e,t,o){if(!o.retry)return this.read(e,t,o);let r=o.body?.confirm!==void 0;return this.retried(e,t,o,o.retry==="once"||r)}async confirmed(e,t,o){let{passkey:r}=o;try{return await this.attempt(e,t,o)}catch(s){if(!(s instanceof ce)||!r)throw s;let a=s.details,i=await Ee(r,{userVerification:o.userVerification,signal:o.promptSignal??o.signal})(a,{request:new Request(`${this.nodeUrl}/${t}`,{method:e})}),c={...o.body,confirm:{challengeId:a.challengeId,assertion:i}};return this.attempt(e,t,{...o,body:c})}}request(e,t,o={}){return this.send(e,Te(t),o)}json(e,t,o={}){return this.confirmed(e,Te(t),o)}async*events(e,t={}){let o=await this.send("GET",Te(e),t);if(!o.body)throw new h(o.status,"EVENTS","the event stream has no body");yield*qn(o.body)}async unsealed(e,t={}){let o=await this.inTheClear(e,t);if(!o.ok)throw await H(o);return o}inTheClear(e,t={}){return this.raw(`${this.nodeUrl}/${Te(e)}${Mt(t.query)}`,{signal:t.signal})}refresh(){if(!this.refreshing){let e=this.exchangeRefresh();this.refreshing=e;let t=()=>{this.refreshing===e&&(this.refreshing=void 0)};e.then(t,t)}return this.refreshing}async exchangeRefresh(){let e=this.current;if(!e)throw new Error("no session to refresh");let t;for(let o=1;t===void 0;o++)try{t=await this.json("POST","auth/refresh",{body:{refreshToken:e.refreshToken}})}catch(r){if(!(r instanceof X)||o>=this.nodeUrls.length)throw r}return this.current===e&&this.useSession(t),t}};async function Lt(n){let e=n.random??Math.random,t=n.fetch??((i,c)=>fetch(i,c)),o=await Bt(n.directory,n.cluster,t),[r,...s]=qt(o.nodes,n.zone,e),a=new te({baseUrl:r,nodes:s,policy:n.policy,fetch:n.fetch,retry:n.retry});return a.useDirectory({directory:n.directory,cluster:n.cluster,zone:n.zone,random:e,due:Date.now()+o.refreshAfterSeconds*1e3}),a}var Mr=/\{[^{}]+\}/g,Dr=()=>typeof process=="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici;function Ir(){return Math.random().toString(36).slice(2,11)}function In(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:o=globalThis.fetch,querySerializer:r,bodySerializer:s,pathSerializer:a,headers:i,requestInitExt:c=void 0,...y}={...n};c=Dr()?c:void 0,e=Dn(e);let d=[];async function l(u,m){let{baseUrl:g,fetch:_=o,Request:S=t,headers:R,params:A={},parseAs:O="json",querySerializer:N,bodySerializer:oe=s??Lr,pathSerializer:v,body:B,middleware:z=[],...M}=m||{},x=e;g&&(x=Dn(g)??e);let J=typeof r=="function"?r:Nn(r);N&&(J=typeof N=="function"?N:Nn({...typeof r=="object"?r:{},...N}));let Ue=v||a||Vr,U=B===void 0?void 0:oe(B,Mn(i,R,A.header)),ye=Mn(U===void 0||U instanceof FormData?{}:{"Content-Type":"application/json"},i,R,A.header),D=[...d,...z],To={redirect:"follow",...y,...M,body:U,headers:ye},Ce,Be,I=new S($r(u,{baseUrl:x,params:A,querySerializer:J,pathSerializer:Ue}),To),b;for(let k in M)k in I||(I[k]=M[k]);if(D.length){Ce=Ir(),Be=Object.freeze({baseUrl:x,fetch:_,parseAs:O,querySerializer:J,bodySerializer:oe,pathSerializer:Ue});for(let k of D)if(k&&typeof k=="object"&&typeof k.onRequest=="function"){let P=await k.onRequest({request:I,schemaPath:u,params:A,options:Be,id:Ce});if(P)if(P instanceof S)I=P;else if(P instanceof Response){b=P;break}else throw new Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!b){try{b=await _(I,c)}catch(k){let P=k;if(D.length)for(let Y=D.length-1;Y>=0;Y--){let qe=D[Y];if(qe&&typeof qe=="object"&&typeof qe.onError=="function"){let me=await qe.onError({request:I,error:P,schemaPath:u,params:A,options:Be,id:Ce});if(me){if(me instanceof Response){P=void 0,b=me;break}if(me instanceof Error){P=me;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(P)throw P}if(D.length)for(let k=D.length-1;k>=0;k--){let P=D[k];if(P&&typeof P=="object"&&typeof P.onResponse=="function"){let Y=await P.onResponse({request:I,response:b,schemaPath:u,params:A,options:Be,id:Ce});if(Y){if(!(Y instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");b=Y}}}}let rn=b.headers.get("Content-Length");if(b.status===204||I.method==="HEAD"||rn==="0"&&!b.headers.get("Transfer-Encoding")?.includes("chunked"))return b.ok?{data:void 0,response:b}:{error:void 0,response:b};if(b.ok)return{data:await(async()=>{if(O==="stream")return b.body;if(O==="json"&&!rn){let P=await b.text();return P?JSON.parse(P):void 0}return await b[O]()})(),response:b};let mt=await b.text();try{mt=JSON.parse(mt)}catch{}return{error:mt,response:b}}return{request(u,m,g){return l(m,{...g,method:u.toUpperCase()})},GET(u,m){return l(u,{...m,method:"GET"})},PUT(u,m){return l(u,{...m,method:"PUT"})},POST(u,m){return l(u,{...m,method:"POST"})},DELETE(u,m){return l(u,{...m,method:"DELETE"})},OPTIONS(u,m){return l(u,{...m,method:"OPTIONS"})},HEAD(u,m){return l(u,{...m,method:"HEAD"})},PATCH(u,m){return l(u,{...m,method:"PATCH"})},TRACE(u,m){return l(u,{...m,method:"TRACE"})},use(...u){for(let m of u)if(m){if(typeof m!="object"||!("onRequest"in m||"onResponse"in m||"onError"in m))throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");d.push(m)}},eject(...u){for(let m of u){let g=d.indexOf(m);g!==-1&&d.splice(g,1)}}}}function it(n,e,t){if(e==null)return"";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${n}=${t?.allowReserved===!0?e:encodeURIComponent(e)}`}function Vn(n,e,t){if(!e||typeof e!="object")return"";let o=[],r={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(let i in e)o.push(i,t.allowReserved===!0?e[i]:encodeURIComponent(e[i]));let a=o.join(",");switch(t.style){case"form":return`${n}=${a}`;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return a}}for(let a in e){let i=t.style==="deepObject"?`${n}[${a}]`:a;o.push(it(i,e[a],t))}let s=o.join(r);return t.style==="label"||t.style==="matrix"?`${r}${s}`:s}function Ln(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){let s={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",a=(t.allowReserved===!0?e:e.map(i=>encodeURIComponent(i))).join(s);switch(t.style){case"simple":return a;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return`${n}=${a}`}}let o={simple:",",label:".",matrix:";"}[t.style]||"&",r=[];for(let s of e)t.style==="simple"||t.style==="label"?r.push(t.allowReserved===!0?s:encodeURIComponent(s)):r.push(it(n,s,t));return t.style==="label"||t.style==="matrix"?`${o}${r.join(o)}`:r.join(o)}function Nn(n){return function(t){let o=[];if(t&&typeof t=="object")for(let r in t){let s=t[r];if(s!=null){if(Array.isArray(s)){if(s.length===0)continue;o.push(Ln(r,s,{style:"form",explode:!0,...n?.array,allowReserved:n?.allowReserved||!1}));continue}if(typeof s=="object"){o.push(Vn(r,s,{style:"deepObject",explode:!0,...n?.object,allowReserved:n?.allowReserved||!1}));continue}o.push(it(r,s,n))}}return o.join("&")}}function Vr(n,e){let t=n;for(let o of n.match(Mr)??[]){let r=o.substring(1,o.length-1),s=!1,a="simple";if(r.endsWith("*")&&(s=!0,r=r.substring(0,r.length-1)),r.startsWith(".")?(a="label",r=r.substring(1)):r.startsWith(";")&&(a="matrix",r=r.substring(1)),!e||e[r]===void 0||e[r]===null)continue;let i=e[r];if(Array.isArray(i)){t=t.replace(o,Ln(r,i,{style:a,explode:s}));continue}if(typeof i=="object"){t=t.replace(o,Vn(r,i,{style:a,explode:s}));continue}if(a==="matrix"){t=t.replace(o,`;${it(r,i)}`);continue}t=t.replace(o,a==="label"?`.${encodeURIComponent(i)}`:encodeURIComponent(i))}return t}function Lr(n,e){return n instanceof FormData?n:e&&(e.get instanceof Function?e.get("Content-Type")??e.get("content-type"):e["Content-Type"]??e["content-type"])==="application/x-www-form-urlencoded"?new URLSearchParams(n).toString():JSON.stringify(n)}function $r(n,e){let t=`${e.baseUrl}${n}`;e.params?.path&&(t=e.pathSerializer(t,e.params.path));let o=e.querySerializer(e.params.query??{});return o.startsWith("?")&&(o=o.substring(1)),o&&(t+=`?${o}`),t}function Mn(...n){let e=new Headers;for(let t of n){if(!t||typeof t!="object")continue;let o=t instanceof Headers?t.entries():Object.entries(t);for(let[r,s]of o)if(s===null)e.delete(r);else if(Array.isArray(s))for(let a of s)e.append(r,a);else s!==void 0&&e.set(r,s)}return e}function Dn(n){return n.endsWith("/")?n.substring(0,n.length-1):n}function $n(n,e,t){let o=new Map;return{onRequest({request:r,id:s}){let a=r.headers.get("content-type");(a===null||a.startsWith("application/json"))&&r.method!=="GET"&&r.method!=="HEAD"&&o.set(s,r.clone())},async onResponse({response:r,id:s,options:a}){let i=o.get(s);if(o.delete(s),r.status!==n||!i)return;let c=await r.clone().json().catch(()=>{});if(c?.error!==e)return;let y=await t(c.details??{},i),d=await i.text(),l=d?JSON.parse(d):{},u=new Headers(i.headers);u.set("content-type","application/json");let m=new Request(i.url,{method:i.method,headers:u,body:JSON.stringify({...l,...y}),signal:i.signal});return a.fetch(m)},onError({id:r}){o.delete(r)}}}function pt(n){return $n(412,"CONFIRM_REQUIRED",async(e,t)=>({confirm:{challengeId:e.challengeId,assertion:await n(e,{request:t})}}))}function ct(n){return $n(428,"OPERATOR_SIGNATURE_REQUIRED",async(e,t)=>({operatorProof:await n(e,{request:t})}))}async function p(n,e,t,o={}){let r=t??{},s={},a={},i={};for(let[l,u]of Object.entries(r))e.pathParams.includes(l)?s[l]=u:e.queryWhole&&l==="query"?Object.assign(a,u):!e.queryWhole&&e.query.includes(l)?a[l]=u:i[l]=u;for(let l of e.pathParams)if(s[l]===void 0)throw new TypeError(`${e.method} ${e.path}: no value for ${l}`);let c={params:{path:s,query:a}};e.body==="fields"?Object.values(i).every(u=>u===void 0)&&e.optionalBody||(c.body=i):e.body==="whole"?(i.body!==void 0||!e.optionalBody)&&(c.body=i.body):e.body==="raw"&&(c.body=i.body,c.bodySerializer=l=>l,c.headers={"Content-Type":i.contentType??e.media??"application/octet-stream"}),e.reply==="bytes"?c.parseAs="blob":e.reply==="text"&&(c.parseAs="text");let y=[];if(o.confirm){let l=o.confirm,u=e.userVerification?(m,g)=>l({userVerification:e.userVerification,...m},g):l;y.push(pt(u))}o.operatorProof&&y.push(ct(o.operatorProof)),y.length&&(c.middleware=y),o.signal&&(c.signal=o.signal);let d=n.request;return Kn(d(e.method.toLowerCase(),e.path,c))}function $t(n){return{apps:{abi:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/abi",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),access:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/access",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),attestation:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/attestation",pathParams:["app"],query:["nonce"],body:"none",optionalBody:!1,reply:"json"},e,t),blobDelete:(e,t)=>p(n,{method:"DELETE",path:"/apps/{app}/blobs/{id}",pathParams:["app","id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),blobDownload:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/blobs/{id}",pathParams:["app","id"],query:["grant"],body:"none",optionalBody:!1,reply:"bytes"},e,t),blobInfo:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/blobs/{id}/info",pathParams:["app","id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),blobList:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/blobs",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),blobRevoke:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/blobs/{id}/revoke",pathParams:["app","id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),blobUpload:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/blobs",pathParams:["app"],query:["sealed"],body:"raw",optionalBody:!1,media:"application/octet-stream",reply:"json"},e,t),call:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/intents",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),create:(e={},t)=>p(n,{method:"POST",path:"/apps",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),delete:(e,t)=>p(n,{method:"DELETE",path:"/apps/{app}",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),fileInfo:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/files/{id}",pathParams:["app","id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),filesList:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/files",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),filesUpload:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/files",pathParams:["app"],query:[],body:"raw",optionalBody:!1,media:"application/octet-stream",reply:"json"},e,t),get:(e,t)=>p(n,{method:"GET",path:"/apps/{app}",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),list:(e={},t)=>p(n,{method:"GET",path:"/apps",pathParams:[],query:["package","bundle"],body:"none",optionalBody:!1,reply:"json"},e,t),metadata:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/metadata",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),method:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/methods/{method}",pathParams:["app","method"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),move:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/move",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),openapi:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/openapi.json",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),presenceGet:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/presence",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),presencePublish:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/presence",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),run:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/runs/{run}",pathParams:["app","run"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),runs:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/runs",pathParams:["app"],query:["limit","before"],body:"none",optionalBody:!1,reply:"json"},e,t),storage:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/storage",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),transfer:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/transfer",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),upgrade:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/upgrade",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),uploadAbort:(e,t)=>p(n,{method:"DELETE",path:"/apps/{app}/files/uploads/{upload}",pathParams:["app","upload"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),uploadBegin:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/files/uploads",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),uploadComplete:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/files/uploads/{upload}/complete",pathParams:["app","upload"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),uploadPart:(e,t)=>p(n,{method:"PUT",path:"/apps/{app}/files/uploads/{upload}/parts/{k}",pathParams:["app","upload","k"],query:[],body:"raw",optionalBody:!1,media:"application/octet-stream",reply:"json"},e,t),uploadStatus:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/files/uploads/{upload}",pathParams:["app","upload"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),usage:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/usage",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),view:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/views",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),xcalls:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/xcalls",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},auth:{accountApps:(e={},t)=>p(n,{method:"GET",path:"/auth/apps",pathParams:[],query:["after","limit"],body:"none",optionalBody:!1,reply:"json"},e,t),accountOutboundApproval:(e,t)=>p(n,{method:"POST",path:"/auth/outbound",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),accountProofProve:(e,t)=>p(n,{method:"POST",path:"/auth/account-proof",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),accountRecoveryBegin:(e,t)=>p(n,{method:"POST",path:"/auth/recovery/begin",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),accountRecoveryCancel:(e={},t)=>p(n,{method:"POST",path:"/auth/recovery/cancel",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),accountRecoveryFinish:(e={},t)=>p(n,{method:"POST",path:"/auth/recovery/finish",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),accountRecoveryStart:(e,t)=>p(n,{method:"POST",path:"/auth/recovery/start",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),accountReleaseApproval:(e,t)=>p(n,{method:"POST",path:"/auth/releases",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),activityList:(e={},t)=>p(n,{method:"GET",path:"/auth/activity",pathParams:[],query:["after"],body:"none",optionalBody:!1,reply:"json"},e,t),aliasDelete:(e,t)=>p(n,{method:"DELETE",path:"/auth/aliases/{alias}",pathParams:["alias"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),aliasGet:(e,t)=>p(n,{method:"GET",path:"/auth/aliases/{alias}",pathParams:["alias"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),aliasList:(e={},t)=>p(n,{method:"GET",path:"/auth/aliases",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),aliasSet:(e,t)=>p(n,{method:"PUT",path:"/auth/aliases/{alias}",pathParams:["alias"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),apikeyCreate:(e={},t)=>p(n,{method:"POST",path:"/auth/apikeys",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),apikeyList:(e={},t)=>p(n,{method:"GET",path:"/auth/apikeys",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),apikeyRevoke:(e,t)=>p(n,{method:"DELETE",path:"/auth/apikeys/{key}",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),loginBegin:(e={},t)=>p(n,{method:"POST",path:"/auth/passkey/login/begin",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json"},e,t),loginFinish:(e,t)=>p(n,{method:"POST",path:"/auth/passkey/login/finish",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),logout:(e={},t)=>p(n,{method:"POST",path:"/auth/logout",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),logoutAll:(e={},t)=>p(n,{method:"POST",path:"/auth/logout-all",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),me:(e={},t)=>p(n,{method:"GET",path:"/auth/me",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),passkeyAddBegin:(e={},t)=>p(n,{method:"POST",path:"/auth/passkeys/add/begin",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),passkeyAddFinish:(e,t)=>p(n,{method:"POST",path:"/auth/passkeys/add/finish",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),passkeyLabel:(e,t)=>p(n,{method:"POST",path:"/auth/passkeys/{cred}",pathParams:["cred"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),passkeyRemove:(e,t)=>p(n,{method:"DELETE",path:"/auth/passkeys/{cred}",pathParams:["cred"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),recoveryCreate:(e={},t)=>p(n,{method:"POST",path:"/auth/recovery",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),recoveryRemove:(e={},t)=>p(n,{method:"DELETE",path:"/auth/recovery",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),refresh:(e,t)=>p(n,{method:"POST",path:"/auth/refresh",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),registerBegin:(e={},t)=>p(n,{method:"POST",path:"/auth/passkey/register/begin",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),registerFinish:(e,t)=>p(n,{method:"POST",path:"/auth/passkey/register/finish",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"preferred"},e,t),sessionRevoke:(e,t)=>p(n,{method:"DELETE",path:"/auth/sessions/{session}",pathParams:["session"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),sessionsList:(e={},t)=>p(n,{method:"GET",path:"/auth/sessions",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),usage:(e={},t)=>p(n,{method:"GET",path:"/auth/usage",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},consent:{pageCreate:(e,t)=>p(n,{method:"POST",path:"/consent/requests",pathParams:[],query:[],body:"whole",optionalBody:!1,reply:"json"},e,t),pageResult:(e,t)=>p(n,{method:"GET",path:"/consent/{request}/result",pathParams:["request"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},deployments:{create:(e,t)=>p(n,{method:"POST",path:"/deployments",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),delete:(e,t)=>p(n,{method:"DELETE",path:"/deployments/{id}",pathParams:["id"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),deployerGrant:(e,t)=>p(n,{method:"POST",path:"/deployers",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),deployerList:(e={},t)=>p(n,{method:"GET",path:"/deployers",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),deployerRevoke:(e,t)=>p(n,{method:"DELETE",path:"/deployers/{key}",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),get:(e,t)=>p(n,{method:"GET",path:"/deployments/{id}",pathParams:["id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),list:(e={},t)=>p(n,{method:"GET",path:"/deployments",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),offer:(e,t)=>p(n,{method:"POST",path:"/deployments/{id}/apps",pathParams:["id"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),orgs:(e,t)=>p(n,{method:"GET",path:"/deployments/{id}/orgs",pathParams:["id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),signUpInviteCreate:(e={},t)=>p(n,{method:"POST",path:"/sign-up/invites",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),signUpInviteList:(e={},t)=>p(n,{method:"GET",path:"/sign-up/invites",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),signUpInviteRevoke:(e,t)=>p(n,{method:"DELETE",path:"/sign-up/invites/{key}",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),signUpPublic:(e={},t)=>p(n,{method:"GET",path:"/sign-up",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),signUpSet:(e,t)=>p(n,{method:"POST",path:"/sign-up",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),withdraw:(e,t)=>p(n,{method:"DELETE",path:"/deployments/{id}/apps/{app}",pathParams:["id","app"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t)},ops:{apps:(e={},t)=>p(n,{method:"GET",path:"/ops/apps",pathParams:[],query:["after","limit"],body:"none",optionalBody:!1,reply:"json"},e,t),backup:(e={},t)=>p(n,{method:"POST",path:"/ops/backup",pathParams:[],query:["all"],body:"none",optionalBody:!1,reply:"json"},e,t),cluster:(e={},t)=>p(n,{method:"GET",path:"/ops/cluster",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),clusterOwner:(e,t)=>p(n,{method:"POST",path:"/ops/cluster-owner",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),deployerGrant:(e,t)=>p(n,{method:"POST",path:"/ops/deployers",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),deployerRevokeDelete:(e,t)=>p(n,{method:"DELETE",path:"/ops/deployers/{key}",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),deployerRevokePost:(e,t)=>p(n,{method:"POST",path:"/ops/deployers/{key}/revoke",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),deploymentsGranted:(e={},t)=>p(n,{method:"POST",path:"/ops/deployments/granted",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),metrics:(e={},t)=>p(n,{method:"GET",path:"/ops/metrics",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"text"},e,t),orgs:(e={},t)=>p(n,{method:"GET",path:"/ops/orgs",pathParams:[],query:["after","limit"],body:"none",optionalBody:!1,reply:"json"},e,t),orgUpgrade:(e,t)=>p(n,{method:"POST",path:"/ops/orgs/{org}/upgrade",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),outbound:(e,t)=>p(n,{method:"POST",path:"/ops/outbound",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),packageInstall:(e,t)=>p(n,{method:"POST",path:"/ops/packages/install",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),packageList:(e={},t)=>p(n,{method:"GET",path:"/ops/packages",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),packageUninstall:(e,t)=>p(n,{method:"DELETE",path:"/ops/packages/{package}",pathParams:["package"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),packageUpload:(e,t)=>p(n,{method:"POST",path:"/ops/packages",pathParams:[],query:[],body:"raw",optionalBody:!1,media:"application/octet-stream",reply:"json"},e,t),packageVersionUninstall:(e,t)=>p(n,{method:"DELETE",path:"/ops/packages/{package}/{version}",pathParams:["package","version"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),placement:(e={},t)=>p(n,{method:"GET",path:"/ops/placement",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),poolsGet:(e={},t)=>p(n,{method:"GET",path:"/ops/pools",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),poolsSet:(e,t)=>p(n,{method:"POST",path:"/ops/pools",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),quotasGet:(e={},t)=>p(n,{method:"GET",path:"/ops/quotas",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),quotasSet:(e={},t)=>p(n,{method:"POST",path:"/ops/quotas",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),receiptKey:(e,t)=>p(n,{method:"GET",path:"/ops/nodes/{id}/receipt-key",pathParams:["id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),registerNode:(e,t)=>p(n,{method:"POST",path:"/ops/nodes",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),release:(e,t)=>p(n,{method:"POST",path:"/ops/releases",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),releaseDeadline:(e,t)=>p(n,{method:"POST",path:"/ops/releases/{version}/deadline",pathParams:["version"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),releaseDeadlineLift:(e,t)=>p(n,{method:"DELETE",path:"/ops/releases/{version}/deadline",pathParams:["version"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),removeNode:(e,t)=>p(n,{method:"DELETE",path:"/ops/nodes/{id}",pathParams:["id"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),restore:(e,t)=>p(n,{method:"POST",path:"/ops/apps/{app}/restore",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),served:(e={},t)=>p(n,{method:"GET",path:"/ops/served-origins",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),setReplicas:(e,t)=>p(n,{method:"POST",path:"/ops/apps/{app}/replicas",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),signUpInviteCreate:(e,t)=>p(n,{method:"POST",path:"/ops/sign-up/invites",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),signUpInviteList:(e={},t)=>p(n,{method:"GET",path:"/ops/sign-up/invites",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),signUpInviteRevokeDelete:(e,t)=>p(n,{method:"DELETE",path:"/ops/sign-up/invites/{key}",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),signUpInviteRevokePost:(e,t)=>p(n,{method:"POST",path:"/ops/sign-up/invites/{key}/revoke",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),signUpSet:(e,t)=>p(n,{method:"POST",path:"/ops/sign-up",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),status:(e={},t)=>p(n,{method:"GET",path:"/ops/status",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),upgrade:(e,t)=>p(n,{method:"POST",path:"/ops/apps/{app}/upgrade",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t)},orgs:{allApps:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/all-apps",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),apps:(e,t)=>p(n,{method:"GET",path:"/orgs/{org}/apps",pathParams:["org"],query:["after","limit"],body:"none",optionalBody:!1,reply:"json"},e,t),appTeamList:(e,t)=>p(n,{method:"GET",path:"/orgs/{org}/app-teams",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),appTeamsScope:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/app-teams",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),capabilities:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/capabilities",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),create:(e,t)=>p(n,{method:"POST",path:"/orgs",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),delete:(e,t)=>p(n,{method:"DELETE",path:"/orgs/{org}",pathParams:["org"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),get:(e,t)=>p(n,{method:"GET",path:"/orgs/{org}",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),inviteCreate:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/invites",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),inviteList:(e,t)=>p(n,{method:"GET",path:"/orgs/{org}/invites",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),inviteRedeem:(e,t)=>p(n,{method:"POST",path:"/invites/{token}/redeem",pathParams:["token"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),inviteRevoke:(e,t)=>p(n,{method:"DELETE",path:"/orgs/{org}/invites/{key}",pathParams:["org","key"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),memberMetadata:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/members/{account}/metadata",pathParams:["org","account"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),memberRemoveTeams:(e,t)=>p(n,{method:"DELETE",path:"/orgs/{org}/members/{account}/teams",pathParams:["org","account"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),members:(e,t)=>p(n,{method:"GET",path:"/orgs/{org}/members",pathParams:["org"],query:["detail"],body:"none",optionalBody:!1,reply:"json"},e,t),memberSetTeams:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/members/{account}/teams",pathParams:["org","account"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),metadata:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/metadata",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),outboundApproval:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/outbound",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),publisher:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/publishers",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),publisherUpgrade:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/packages/{package}/upgrade",pathParams:["org","package"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),recoveryCancel:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/recovery/cancel",pathParams:["org"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),recoveryFinish:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/recovery/finish",pathParams:["org"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),recoverySet:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/recovery",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),recoveryStart:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/recovery/start",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),releaseApproval:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/releases",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),removeMember:(e,t)=>p(n,{method:"DELETE",path:"/orgs/{org}/members/{account}",pathParams:["org","account"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),rename:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/name",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),setMember:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/members",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),teamCreate:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/teams",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),teamDelete:(e,t)=>p(n,{method:"DELETE",path:"/orgs/{org}/teams/{team}",pathParams:["org","team"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),teamGet:(e,t)=>p(n,{method:"GET",path:"/orgs/{org}/teams/{team}",pathParams:["org","team"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),teamRemoveMember:(e,t)=>p(n,{method:"DELETE",path:"/orgs/{org}/teams/{team}/members/{account}",pathParams:["org","team","account"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),teamSetMember:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/teams/{team}/members",pathParams:["org","team"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),teamUpdate:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/teams/{team}",pathParams:["org","team"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),upgrade:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/upgrade",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),upgradeRetry:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/upgrades/{run}/retry",pathParams:["org","run"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required",operator:!0},e,t),upgradeStatus:(e,t)=>p(n,{method:"GET",path:"/orgs/{org}/upgrades/{run}",pathParams:["org","run"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),usage:(e,t)=>p(n,{method:"GET",path:"/orgs/{org}/usage",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},packages:{bundlePut:(e,t)=>p(n,{method:"POST",path:"/bundles",pathParams:[],query:[],body:"raw",optionalBody:!1,media:"application/wasm",reply:"json"},e,t),get:(e,t)=>p(n,{method:"GET",path:"/packages/{package}",pathParams:["package"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),install:(e,t)=>p(n,{method:"POST",path:"/packages/install",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),list:(e={},t)=>p(n,{method:"GET",path:"/packages",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),originsAdd:(e,t)=>p(n,{method:"POST",path:"/package-origins/{package}",pathParams:["package"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),originsList:(e,t)=>p(n,{method:"GET",path:"/package-origins/{package}",pathParams:["package"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),originsRemove:(e,t)=>p(n,{method:"DELETE",path:"/package-origins/{package}",pathParams:["package"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),uninstall:(e,t)=>p(n,{method:"DELETE",path:"/packages/{package}",pathParams:["package"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),upload:(e,t)=>p(n,{method:"POST",path:"/packages",pathParams:[],query:[],body:"raw",optionalBody:!1,media:"application/octet-stream",reply:"json"},e,t),versionUninstall:(e,t)=>p(n,{method:"DELETE",path:"/packages/{package}/{version}",pathParams:["package","version"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},public:{attestation:(e,t)=>p(n,{method:"GET",path:"/attestation",pathParams:[],query:["nonce","app","appHash","purpose"],body:"none",optionalBody:!1,reply:"json"},e,t),health:(e={},t)=>p(n,{method:"GET",path:"/health",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),publisherBinding:(e,t)=>p(n,{method:"GET",path:"/publishers/{signer}",pathParams:["signer"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),releasesPublic:(e={},t)=>p(n,{method:"GET",path:"/releases",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)}}}var Kt=[{method:"POST",path:"/apps/{app}/intents",requires:"idempotencyKey"},{method:"POST",path:"/apps/{app}/methods/{method}",requires:"idempotencyKey"},{method:"POST",path:"/apps/{app}/views"}];var Gn="https://calimero-node.invalid",Kr=new Set(["attestation","health"]),Gr=Kt.map(n=>({method:n.method,pattern:new RegExp(`^${n.path.replace(/^\//,"").replace(/\{[^}]+\}/g,"[^/]+")}$`)})),Hr=new Set(Kt.filter(n=>n.requires==="idempotencyKey").map(n=>`${n.method} ${n.path}`));function Fr(n){return async e=>{if(!e.url.startsWith(`${Gn}/`))throw new Error(`not a route of the generated client: ${e.url}`);let t=new URL(e.url),o=t.pathname.replace(/^\/+/,""),r={};for(let[d,l]of t.searchParams)(r[d]??(r[d]=[])).push(l);let s=e.method;if(s==="GET"&&Kr.has(o)&&n.inTheClear)return n.inTheClear(o,{query:r,signal:e.signal});let a=e.headers.get("content-type")??void 0,i=s==="GET"?void 0:new Uint8Array(await e.arrayBuffer()),c=i&&i.length>0?i:void 0,y=!1;return Gr.some(d=>d.method===s&&d.pattern.test(o))&&(y=(c?JSON.parse(new TextDecoder().decode(c)):{}).confirm===void 0?!0:"once"),n.exchange(s,o,{query:r,...c?{bytes:c,contentType:a??"application/octet-stream"}:{},retry:y,signal:e.signal})}}var Qr={async onRequest({request:n,schemaPath:e}){if(!Hr.has(`${n.method} ${e}`))return;let t=await n.clone().text(),o=t?JSON.parse(t):{};if(o.idempotencyKey===void 0)return new Request(n,{body:JSON.stringify({...o,idempotencyKey:Vt()})})}};function Gt(n,e={}){let t=In({baseUrl:Gn,fetch:Fr(n)});return t.use(Qr),e.confirm&&t.use(pt(e.confirm)),e.operatorProof&&t.use(ct(e.operatorProof)),t}async function Kn(n){let{data:e,error:t,response:o}=await n;if(!o.ok)throw zr(o,t);return e??{}}function zr(n,e){let t=typeof e=="string"?e?{message:e}:{}:e;return de(n.status,t,n.headers.get("retry-after"))}var Hn="calimero.org-recovery.v1\0",Ft=64,Ht=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function Jr(){return crypto.getRandomValues(new Uint8Array(32))}function Yr(n){Qn(n);let e=Array.from(n,o=>o.toString(16).padStart(2,"0")).join(""),t=[];for(let o=0;o<e.length;o+=8)t.push(e.slice(o,o+8));return t.join("-")}function Wr(n){let e=n.replace(/[-\s]/g,"");if(!/^[0-9a-fA-F]{64}$/.test(e))throw new Error("a recovery seed is 64 hex digits");return Uint8Array.from({length:32},(t,o)=>parseInt(e.slice(2*o,2*o+2),16))}function Fn(n,e,t){return new TextEncoder().encode(`${Hn}${n}\0${e}\0${t}`)}async function Zr(n){let e=await zn(n,!0),t=await crypto.subtle.exportKey("jwk",e);if(!t.x)throw new Error("this runtime cannot export an Ed25519 public key");return t.x}async function Qt(n,e,t,o){let r=new TextEncoder().encode(o).length;if(r===0||r>Ft)throw new Error(`a recovery nonce is 1 to ${Ft} bytes`);let s=await zn(n,!1),a=await crypto.subtle.sign("Ed25519",s,Jn(Fn(e,t,o)));return j(new Uint8Array(a))}function Qn(n){if(n.length!==32)throw new Error("a recovery seed is 32 bytes")}function zn(n,e){Qn(n);let t=new Uint8Array(Ht.length+32);return t.set(Ht),t.set(n,Ht.length),crypto.subtle.importKey("pkcs8",Jn(t),{name:"Ed25519"},e,["sign"])}var Jn=n=>n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);var zt=100;function Jt(n={}){let e=new URLSearchParams;if(n.after!==void 0&&e.set("after",n.after),n.limit!==void 0){if(!Number.isInteger(n.limit)||n.limit<1||n.limit>zt)throw new RangeError(`limit is 1 to ${zt}`);e.set("limit",String(n.limit))}let t=e.toString();return t?`?${t}`:""}function je(n,e){try{return Pe(n,e)}catch{return n<e?-1:n>e?1:0}}function Yn(n,e,t=Date.now()/1e3){if(n===null||n.length===0)return null;let o=n.reduce((s,a)=>je(s,a)>=0?s:a),r=null;for(let s of e)s.afterSecs<=t&&je(o,s.version)<0&&(r===null||je(s.version,r.version)>0)&&(r=s);return r}function Wn(n,e,t,o){return`calimero-publisher-binding/v1
3
+ `))>=0;){let i=o.slice(0,a);o=o.slice(a+2);let c="",u="",d="";for(let y of i.split(`
4
+ `))y.startsWith("id:")?c=y.slice(3).trim():y.startsWith("event:")?u=y.slice(6).trim():y.startsWith("data:")&&(d+=y.slice(5).trim());if(!u&&!d)continue;let l=d;try{l=JSON.parse(d)}catch{}yield{id:c,kind:u,data:l}}}}function Ht(){return`node:c-${j(crypto.getRandomValues(new Uint8Array(16)))}`}function dt(n,e={}){return n.replace(/\{([^}]+)\}/g,(t,o)=>{let r=e[o];if(r===void 0)throw new Error(`no value for path parameter ${o} of ${n}`);return encodeURIComponent(String(r))})}function $t(n){if(!n)return"";let e=new URLSearchParams;for(let[o,r]of Object.entries(n))for(let s of Array.isArray(r)?r:[r])s!=null&&e.append(o,String(s));let t=e.toString();return t?`?${t}`:""}function Ln(n){return n==="auth/refresh"||n.startsWith("auth/passkey/")||Yr.has(n)}var Yr=new Set(["auth/recovery/begin","auth/recovery/start","auth/recovery/finish"]);function Oe(n){return n.replace(/^\/+/,"")}var ae=class{constructor(e){this.at=0;this.channels=new Map;this.networkFailures=new WeakSet;let t=s=>s.replace(/\/+$/,"");this.nodeUrls=[...new Set([e.baseUrl,...e.nodes??[]].map(t))],this.policy=e.policy,this.retry={...Gt,...e.retry};let o=e.fetch??((s,a)=>fetch(s,a)),r=async(s,a)=>{try{return await o(s,a)}catch(i){throw i instanceof TypeError&&this.networkFailures.add(i),i}};this.raw=r}isNetworkFailure(e){return e instanceof TypeError&&this.networkFailures.has(e)}useDirectory(e){this.source=e}get nodeUrl(){return this.nodeUrls[this.at]}get nodes(){return[...this.nodeUrls]}useApiKey(e){this.auth=e,this.current=void 0}useSession(e){this.auth=e.sessionToken,this.current=e}signOut(){this.auth=void 0,this.current=void 0}get session(){return this.current}channel(e){let t=this.channels.get(e);return t||(t=Tt({baseUrl:e,transportPublicKey:()=>Dt(e,this.policy,this.raw),fetch:this.raw}),this.channels.set(e,t)),t}moveOn(e){return this.nodeUrls.length<2?!1:(this.nodeUrl===e&&(this.at=(this.at+1)%this.nodeUrls.length),!0)}failOver(e,t){if(this.nodeUrl!==e&&!t.has(this.nodeUrl))return!0;let o=this.nodeUrls.length;for(let r=1;r<o;r++){let s=(this.at+r)%o;if(!t.has(this.nodeUrls[s]))return this.at=s,this.reread(),!0}return!1}reread(){let e=this.source;!e||e.reading||(e.reading=Vt(e.directory,e.cluster,this.raw).then(t=>{let o=this.nodeUrl,r=Kt(t.nodes,e.zone,e.random);this.nodeUrls=[o,...r.filter(s=>s!==o)],this.at=0,e.due=Date.now()+t.refreshAfterSeconds*1e3}).catch(()=>{}).finally(()=>{e.reading=void 0}))}async once(e,t,o){let r={};this.auth&&(r.authorization=`Bearer ${this.auth}`);let s;o.bytes?(r["content-type"]=o.contentType??"application/wasm",s=o.bytes):o.body!==void 0&&(r["content-type"]="application/json",s=JSON.stringify(o.body)),this.source&&Date.now()>=this.source.due&&this.reread();let a=this.nodeUrl;try{return await this.channel(a)(`${a}/${t}${$t(o.query)}`,{method:e,headers:r,body:s,signal:o.signal})}catch(i){throw Jr(i)}}async send(e,t,o){let r=await this.answer(e,t,o);if(!r.ok)throw await J(r);return r}async answer(e,t,o){let r=!1,s=!1;for(;;){let[a,i]=[this.auth,this.nodeUrl],c=await this.once(e,t,o);if(c.ok||c.status!==401&&c.status!==421)return c;let u=await J(c.clone());if(u instanceof re&&!s){if(s=!0,this.moveOn(i)&&!Ln(t))continue}else if(u instanceof F&&!r&&this.mayRefresh(a,t)){r=!0,await this.renew(a);continue}return c}}mayRefresh(e,t){return e!==void 0&&this.current!==void 0&&!Ln(t)}async renew(e){this.auth===e&&await this.refresh()}async read(e,t,o){let s=await(await this.send(e,t,o)).text();return s?JSON.parse(s):{}}async retried(e,t,o,r){let s=await this.answerRetried(e,t,o,r);if(!s.ok)throw await J(s);let a=await s.text();return a?JSON.parse(a):{}}async answerRetried(e,t,o,r){let s=r?0:this.retry.retries,a=new Set;for(;;){let i,c,u=this.nodeUrl;for(let d=0;;d++){u=this.nodeUrl,a.add(u);try{let y=await this.answer(e,t,o);if(y.status!==503)return y;c=y,i=await J(y.clone())}catch(y){if(y instanceof TypeError&&this.networkFailures.has(y))c=void 0,i=new Q("NETWORK",`the node could not be reached: ${y.message}`,{},void 0,y);else throw y}if(d>=s)break;let l=Se(d,this.retry);await new Promise(y=>setTimeout(y,Math.max(l,(i.retryAfter??0)*1e3)))}if(r||!this.failOver(u,a)){if(c)return c;throw i}}}exchange(e,t,o={}){let r=Oe(t);return o.retry?this.answerRetried(e,r,o,o.retry==="once"):this.answer(e,r,o)}attempt(e,t,o){if(!o.retry)return this.read(e,t,o);let r=o.body?.confirm!==void 0;return this.retried(e,t,o,o.retry==="once"||r)}async confirmed(e,t,o){let{passkey:r}=o;try{return await this.attempt(e,t,o)}catch(s){if(!(s instanceof ye)||!r)throw s;let a=s.details,i=await ve(r,{userVerification:o.userVerification,signal:o.promptSignal??o.signal})(a,{request:new Request(`${this.nodeUrl}/${t}`,{method:e})}),c={...o.body,confirm:{challengeId:a.challengeId,assertion:i}};return this.attempt(e,t,{...o,body:c})}}request(e,t,o={}){return this.send(e,Oe(t),o)}json(e,t,o={}){return this.confirmed(e,Oe(t),o)}async*events(e,t={}){let o=await this.send("GET",Oe(e),t);if(!o.body)throw new f(o.status,"EVENTS","the event stream has no body");yield*$n(o.body)}async unsealed(e,t={}){let o=await this.inTheClear(e,t);if(!o.ok)throw await J(o);return o}inTheClear(e,t={}){return this.raw(`${this.nodeUrl}/${Oe(e)}${$t(t.query)}`,{signal:t.signal})}refresh(){if(!this.refreshing){let e=this.exchangeRefresh();this.refreshing=e;let t=()=>{this.refreshing===e&&(this.refreshing=void 0)};e.then(t,t)}return this.refreshing}async exchangeRefresh(){let e=this.current;if(!e)throw new Error("no session to refresh");let t;for(let o=1;t===void 0;o++)try{t=await this.json("POST","auth/refresh",{body:{refreshToken:e.refreshToken}})}catch(r){if(!(r instanceof re)||o>=this.nodeUrls.length)throw r}return this.current===e&&this.useSession(t),t}};async function Ft(n){let e=n.random??Math.random,t=n.fetch??((i,c)=>fetch(i,c)),o=await Vt(n.directory,n.cluster,t),[r,...s]=Kt(o.nodes,n.zone,e),a=new ae({baseUrl:r,nodes:s,policy:n.policy,fetch:n.fetch,retry:n.retry});return a.useDirectory({directory:n.directory,cluster:n.cluster,zone:n.zone,random:e,due:Date.now()+o.refreshAfterSeconds*1e3}),a}var Wr=/\{[^{}]+\}/g,Zr=()=>typeof process=="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici;function Xr(){return Math.random().toString(36).slice(2,11)}function Qn(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:o=globalThis.fetch,querySerializer:r,bodySerializer:s,pathSerializer:a,headers:i,requestInitExt:c=void 0,...u}={...n};c=Zr()?c:void 0,e=Fn(e);let d=[];async function l(y,m){let{baseUrl:g,fetch:b=o,Request:U=t,headers:A,params:k={},parseAs:v="json",querySerializer:I,bodySerializer:pe=s??ts,pathSerializer:O,body:N,middleware:Z=[],...V}=m||{},x=e;g&&(x=Fn(g)??e);let X=typeof r=="function"?r:Gn(r);I&&(X=typeof I=="function"?I:Gn({...typeof r=="object"?r:{},...I}));let De=O||a||es,C=N===void 0?void 0:pe(N,Hn(i,A,k.header)),fe=Hn(C===void 0||C instanceof FormData?{}:{"Content-Type":"application/json"},i,A,k.header),K=[...d,...Z],Vo={redirect:"follow",...u,...V,body:C,headers:fe},Ie,Ve,L=new U(ns(y,{baseUrl:x,params:k,querySerializer:X,pathSerializer:De}),Vo),P;for(let E in V)E in L||(L[E]=V[E]);if(K.length){Ie=Xr(),Ve=Object.freeze({baseUrl:x,fetch:b,parseAs:v,querySerializer:X,bodySerializer:pe,pathSerializer:De});for(let E of K)if(E&&typeof E=="object"&&typeof E.onRequest=="function"){let _=await E.onRequest({request:L,schemaPath:y,params:k,options:Ve,id:Ie});if(_)if(_ instanceof U)L=_;else if(_ instanceof Response){P=_;break}else throw new Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!P){try{P=await b(L,c)}catch(E){let _=E;if(K.length)for(let ee=K.length-1;ee>=0;ee--){let Ke=K[ee];if(Ke&&typeof Ke=="object"&&typeof Ke.onError=="function"){let we=await Ke.onError({request:L,error:_,schemaPath:y,params:k,options:Ve,id:Ie});if(we){if(we instanceof Response){_=void 0,P=we;break}if(we instanceof Error){_=we;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(_)throw _}if(K.length)for(let E=K.length-1;E>=0;E--){let _=K[E];if(_&&typeof _=="object"&&typeof _.onResponse=="function"){let ee=await _.onResponse({request:L,response:P,schemaPath:y,params:k,options:Ve,id:Ie});if(ee){if(!(ee instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");P=ee}}}}let yn=P.headers.get("Content-Length");if(P.status===204||L.method==="HEAD"||yn==="0"&&!P.headers.get("Transfer-Encoding")?.includes("chunked"))return P.ok?{data:void 0,response:P}:{error:void 0,response:P};if(P.ok)return{data:await(async()=>{if(v==="stream")return P.body;if(v==="json"&&!yn){let _=await P.text();return _?JSON.parse(_):void 0}return await P[v]()})(),response:P};let Pt=await P.text();try{Pt=JSON.parse(Pt)}catch{}return{error:Pt,response:P}}return{request(y,m,g){return l(m,{...g,method:y.toUpperCase()})},GET(y,m){return l(y,{...m,method:"GET"})},PUT(y,m){return l(y,{...m,method:"PUT"})},POST(y,m){return l(y,{...m,method:"POST"})},DELETE(y,m){return l(y,{...m,method:"DELETE"})},OPTIONS(y,m){return l(y,{...m,method:"OPTIONS"})},HEAD(y,m){return l(y,{...m,method:"HEAD"})},PATCH(y,m){return l(y,{...m,method:"PATCH"})},TRACE(y,m){return l(y,{...m,method:"TRACE"})},use(...y){for(let m of y)if(m){if(typeof m!="object"||!("onRequest"in m||"onResponse"in m||"onError"in m))throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");d.push(m)}},eject(...y){for(let m of y){let g=d.indexOf(m);g!==-1&&d.splice(g,1)}}}}function ut(n,e,t){if(e==null)return"";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${n}=${t?.allowReserved===!0?e:encodeURIComponent(e)}`}function zn(n,e,t){if(!e||typeof e!="object")return"";let o=[],r={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(let i in e)o.push(i,t.allowReserved===!0?e[i]:encodeURIComponent(e[i]));let a=o.join(",");switch(t.style){case"form":return`${n}=${a}`;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return a}}for(let a in e){let i=t.style==="deepObject"?`${n}[${a}]`:a;o.push(ut(i,e[a],t))}let s=o.join(r);return t.style==="label"||t.style==="matrix"?`${r}${s}`:s}function Jn(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){let s={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",a=(t.allowReserved===!0?e:e.map(i=>encodeURIComponent(i))).join(s);switch(t.style){case"simple":return a;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return`${n}=${a}`}}let o={simple:",",label:".",matrix:";"}[t.style]||"&",r=[];for(let s of e)t.style==="simple"||t.style==="label"?r.push(t.allowReserved===!0?s:encodeURIComponent(s)):r.push(ut(n,s,t));return t.style==="label"||t.style==="matrix"?`${o}${r.join(o)}`:r.join(o)}function Gn(n){return function(t){let o=[];if(t&&typeof t=="object")for(let r in t){let s=t[r];if(s!=null){if(Array.isArray(s)){if(s.length===0)continue;o.push(Jn(r,s,{style:"form",explode:!0,...n?.array,allowReserved:n?.allowReserved||!1}));continue}if(typeof s=="object"){o.push(zn(r,s,{style:"deepObject",explode:!0,...n?.object,allowReserved:n?.allowReserved||!1}));continue}o.push(ut(r,s,n))}}return o.join("&")}}function es(n,e){let t=n;for(let o of n.match(Wr)??[]){let r=o.substring(1,o.length-1),s=!1,a="simple";if(r.endsWith("*")&&(s=!0,r=r.substring(0,r.length-1)),r.startsWith(".")?(a="label",r=r.substring(1)):r.startsWith(";")&&(a="matrix",r=r.substring(1)),!e||e[r]===void 0||e[r]===null)continue;let i=e[r];if(Array.isArray(i)){t=t.replace(o,Jn(r,i,{style:a,explode:s}));continue}if(typeof i=="object"){t=t.replace(o,zn(r,i,{style:a,explode:s}));continue}if(a==="matrix"){t=t.replace(o,`;${ut(r,i)}`);continue}t=t.replace(o,a==="label"?`.${encodeURIComponent(i)}`:encodeURIComponent(i))}return t}function ts(n,e){return n instanceof FormData?n:e&&(e.get instanceof Function?e.get("Content-Type")??e.get("content-type"):e["Content-Type"]??e["content-type"])==="application/x-www-form-urlencoded"?new URLSearchParams(n).toString():JSON.stringify(n)}function ns(n,e){let t=`${e.baseUrl}${n}`;e.params?.path&&(t=e.pathSerializer(t,e.params.path));let o=e.querySerializer(e.params.query??{});return o.startsWith("?")&&(o=o.substring(1)),o&&(t+=`?${o}`),t}function Hn(...n){let e=new Headers;for(let t of n){if(!t||typeof t!="object")continue;let o=t instanceof Headers?t.entries():Object.entries(t);for(let[r,s]of o)if(s===null)e.delete(r);else if(Array.isArray(s))for(let a of s)e.append(r,a);else s!==void 0&&e.set(r,s)}return e}function Fn(n){return n.endsWith("/")?n.substring(0,n.length-1):n}function Yn(n,e,t){let o=new Map;return{onRequest({request:r,id:s}){let a=r.headers.get("content-type");(a===null||a.startsWith("application/json"))&&r.method!=="GET"&&r.method!=="HEAD"&&o.set(s,r.clone())},async onResponse({response:r,id:s,options:a}){let i=o.get(s);if(o.delete(s),r.status!==n||!i)return;let c=await r.clone().json().catch(()=>{});if(c?.error!==e)return;let u=await t(c.details??{},i),d=await i.text(),l=d?JSON.parse(d):{},y=new Headers(i.headers);y.set("content-type","application/json");let m=new Request(i.url,{method:i.method,headers:y,body:JSON.stringify({...l,...u}),signal:i.signal});return a.fetch(m)},onError({id:r}){o.delete(r)}}}function yt(n){return Yn(412,"CONFIRM_REQUIRED",async(e,t)=>({confirm:{challengeId:e.challengeId,assertion:await n(e,{request:t})}}))}function mt(n){return Yn(428,"OPERATOR_SIGNATURE_REQUIRED",async(e,t)=>({operatorProof:await n(e,{request:t})}))}async function p(n,e,t,o={}){let r=t??{},s={},a={},i={};for(let[l,y]of Object.entries(r))e.pathParams.includes(l)?s[l]=y:e.queryWhole&&l==="query"?Object.assign(a,y):!e.queryWhole&&e.query.includes(l)?a[l]=y:i[l]=y;for(let l of e.pathParams)if(s[l]===void 0)throw new TypeError(`${e.method} ${e.path}: no value for ${l}`);let c={params:{path:s,query:a}};e.body==="fields"?Object.values(i).every(y=>y===void 0)&&e.optionalBody||(c.body=i):e.body==="whole"?(i.body!==void 0||!e.optionalBody)&&(c.body=i.body):e.body==="raw"&&(c.body=i.body,c.bodySerializer=l=>l,c.headers={"Content-Type":i.contentType??e.media??"application/octet-stream"}),e.reply==="bytes"?c.parseAs="blob":e.reply==="text"&&(c.parseAs="text");let u=[];if(o.confirm){let l=o.confirm,y=e.userVerification?(m,g)=>l({userVerification:e.userVerification,...m},g):l;u.push(yt(y))}o.operatorProof&&u.push(mt(o.operatorProof)),u.length&&(c.middleware=u),o.signal&&(c.signal=o.signal);let d=n.request;return Wn(d(e.method.toLowerCase(),e.path,c))}function Qt(n){return{apps:{abi:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/abi",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),access:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/access",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),attestation:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/attestation",pathParams:["app"],query:["nonce"],body:"none",optionalBody:!1,reply:"json"},e,t),blobDelete:(e,t)=>p(n,{method:"DELETE",path:"/apps/{app}/blobs/{id}",pathParams:["app","id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),blobDownload:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/blobs/{id}",pathParams:["app","id"],query:["grant"],body:"none",optionalBody:!1,reply:"bytes"},e,t),blobInfo:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/blobs/{id}/info",pathParams:["app","id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),blobList:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/blobs",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),blobRevoke:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/blobs/{id}/revoke",pathParams:["app","id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),blobUpload:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/blobs",pathParams:["app"],query:["sealed"],body:"raw",optionalBody:!1,media:"application/octet-stream",reply:"json"},e,t),call:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/intents",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),create:(e={},t)=>p(n,{method:"POST",path:"/apps",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),delete:(e,t)=>p(n,{method:"DELETE",path:"/apps/{app}",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),fileInfo:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/files/{id}",pathParams:["app","id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),filesList:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/files",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),filesUpload:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/files",pathParams:["app"],query:[],body:"raw",optionalBody:!1,media:"application/octet-stream",reply:"json"},e,t),get:(e,t)=>p(n,{method:"GET",path:"/apps/{app}",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),list:(e={},t)=>p(n,{method:"GET",path:"/apps",pathParams:[],query:["package","bundle"],body:"none",optionalBody:!1,reply:"json"},e,t),metadata:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/metadata",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),method:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/methods/{method}",pathParams:["app","method"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),move:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/move",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),openapi:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/openapi.json",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),presenceGet:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/presence",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),presencePublish:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/presence",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),run:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/runs/{run}",pathParams:["app","run"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),runs:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/runs",pathParams:["app"],query:["limit","before"],body:"none",optionalBody:!1,reply:"json"},e,t),storage:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/storage",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),transfer:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/transfer",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),upgrade:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/upgrade",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),uploadAbort:(e,t)=>p(n,{method:"DELETE",path:"/apps/{app}/files/uploads/{upload}",pathParams:["app","upload"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),uploadBegin:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/files/uploads",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),uploadComplete:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/files/uploads/{upload}/complete",pathParams:["app","upload"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),uploadPart:(e,t)=>p(n,{method:"PUT",path:"/apps/{app}/files/uploads/{upload}/parts/{k}",pathParams:["app","upload","k"],query:[],body:"raw",optionalBody:!1,media:"application/octet-stream",reply:"json"},e,t),uploadStatus:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/files/uploads/{upload}",pathParams:["app","upload"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),usage:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/usage",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),view:(e,t)=>p(n,{method:"POST",path:"/apps/{app}/views",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),xcalls:(e,t)=>p(n,{method:"GET",path:"/apps/{app}/xcalls",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},auth:{accountApps:(e={},t)=>p(n,{method:"GET",path:"/auth/apps",pathParams:[],query:["after","limit"],body:"none",optionalBody:!1,reply:"json"},e,t),accountOutboundApproval:(e,t)=>p(n,{method:"POST",path:"/auth/outbound",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),accountProofProve:(e,t)=>p(n,{method:"POST",path:"/auth/account-proof",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),accountRecoveryBegin:(e,t)=>p(n,{method:"POST",path:"/auth/recovery/begin",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),accountRecoveryCancel:(e={},t)=>p(n,{method:"POST",path:"/auth/recovery/cancel",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),accountRecoveryFinish:(e={},t)=>p(n,{method:"POST",path:"/auth/recovery/finish",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),accountRecoveryStart:(e,t)=>p(n,{method:"POST",path:"/auth/recovery/start",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),accountReleaseApproval:(e,t)=>p(n,{method:"POST",path:"/auth/releases",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),activityList:(e={},t)=>p(n,{method:"GET",path:"/auth/activity",pathParams:[],query:["after"],body:"none",optionalBody:!1,reply:"json"},e,t),aliasDelete:(e,t)=>p(n,{method:"DELETE",path:"/auth/aliases/{alias}",pathParams:["alias"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),aliasGet:(e,t)=>p(n,{method:"GET",path:"/auth/aliases/{alias}",pathParams:["alias"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),aliasList:(e={},t)=>p(n,{method:"GET",path:"/auth/aliases",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),aliasSet:(e,t)=>p(n,{method:"PUT",path:"/auth/aliases/{alias}",pathParams:["alias"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),apikeyCreate:(e={},t)=>p(n,{method:"POST",path:"/auth/apikeys",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),apikeyList:(e={},t)=>p(n,{method:"GET",path:"/auth/apikeys",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),apikeyRevoke:(e,t)=>p(n,{method:"DELETE",path:"/auth/apikeys/{key}",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),loginBegin:(e={},t)=>p(n,{method:"POST",path:"/auth/passkey/login/begin",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json"},e,t),loginFinish:(e,t)=>p(n,{method:"POST",path:"/auth/passkey/login/finish",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),logout:(e={},t)=>p(n,{method:"POST",path:"/auth/logout",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),logoutAll:(e={},t)=>p(n,{method:"POST",path:"/auth/logout-all",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),me:(e={},t)=>p(n,{method:"GET",path:"/auth/me",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),passkeyAddBegin:(e={},t)=>p(n,{method:"POST",path:"/auth/passkeys/add/begin",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),passkeyAddFinish:(e,t)=>p(n,{method:"POST",path:"/auth/passkeys/add/finish",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),passkeyLabel:(e,t)=>p(n,{method:"POST",path:"/auth/passkeys/{cred}",pathParams:["cred"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),passkeyRemove:(e,t)=>p(n,{method:"DELETE",path:"/auth/passkeys/{cred}",pathParams:["cred"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),recoveryCreate:(e={},t)=>p(n,{method:"POST",path:"/auth/recovery",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),recoveryRemove:(e={},t)=>p(n,{method:"DELETE",path:"/auth/recovery",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),refresh:(e,t)=>p(n,{method:"POST",path:"/auth/refresh",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),registerBegin:(e={},t)=>p(n,{method:"POST",path:"/auth/passkey/register/begin",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),registerFinish:(e,t)=>p(n,{method:"POST",path:"/auth/passkey/register/finish",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"preferred"},e,t),sessionRevoke:(e,t)=>p(n,{method:"DELETE",path:"/auth/sessions/{session}",pathParams:["session"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),sessionsList:(e={},t)=>p(n,{method:"GET",path:"/auth/sessions",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),usage:(e={},t)=>p(n,{method:"GET",path:"/auth/usage",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},consent:{pageCreate:(e,t)=>p(n,{method:"POST",path:"/consent/requests",pathParams:[],query:[],body:"whole",optionalBody:!1,reply:"json"},e,t),pageResult:(e,t)=>p(n,{method:"GET",path:"/consent/{request}/result",pathParams:["request"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},deployments:{create:(e,t)=>p(n,{method:"POST",path:"/deployments",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),delete:(e,t)=>p(n,{method:"DELETE",path:"/deployments/{id}",pathParams:["id"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),deployerGrant:(e,t)=>p(n,{method:"POST",path:"/deployers",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),deployerList:(e={},t)=>p(n,{method:"GET",path:"/deployers",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),deployerRevoke:(e,t)=>p(n,{method:"DELETE",path:"/deployers/{key}",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),get:(e,t)=>p(n,{method:"GET",path:"/deployments/{id}",pathParams:["id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),list:(e={},t)=>p(n,{method:"GET",path:"/deployments",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),offer:(e,t)=>p(n,{method:"POST",path:"/deployments/{id}/apps",pathParams:["id"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),orgs:(e,t)=>p(n,{method:"GET",path:"/deployments/{id}/orgs",pathParams:["id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),signUpInviteCreate:(e={},t)=>p(n,{method:"POST",path:"/sign-up/invites",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),signUpInviteList:(e={},t)=>p(n,{method:"GET",path:"/sign-up/invites",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),signUpInviteRevoke:(e,t)=>p(n,{method:"DELETE",path:"/sign-up/invites/{key}",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),signUpPublic:(e={},t)=>p(n,{method:"GET",path:"/sign-up",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),signUpSet:(e,t)=>p(n,{method:"POST",path:"/sign-up",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),withdraw:(e,t)=>p(n,{method:"DELETE",path:"/deployments/{id}/apps/{app}",pathParams:["id","app"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t)},ops:{apps:(e={},t)=>p(n,{method:"GET",path:"/ops/apps",pathParams:[],query:["after","limit"],body:"none",optionalBody:!1,reply:"json"},e,t),backup:(e={},t)=>p(n,{method:"POST",path:"/ops/backup",pathParams:[],query:["all"],body:"none",optionalBody:!1,reply:"json"},e,t),cluster:(e={},t)=>p(n,{method:"GET",path:"/ops/cluster",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),clusterOwner:(e,t)=>p(n,{method:"POST",path:"/ops/cluster-owner",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),deployerGrant:(e,t)=>p(n,{method:"POST",path:"/ops/deployers",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),deployerRevokeDelete:(e,t)=>p(n,{method:"DELETE",path:"/ops/deployers/{key}",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),deployerRevokePost:(e,t)=>p(n,{method:"POST",path:"/ops/deployers/{key}/revoke",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),deploymentsGranted:(e={},t)=>p(n,{method:"POST",path:"/ops/deployments/granted",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),metrics:(e={},t)=>p(n,{method:"GET",path:"/ops/metrics",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"text"},e,t),orgs:(e={},t)=>p(n,{method:"GET",path:"/ops/orgs",pathParams:[],query:["after","limit"],body:"none",optionalBody:!1,reply:"json"},e,t),orgUpgrade:(e,t)=>p(n,{method:"POST",path:"/ops/orgs/{org}/upgrade",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),outbound:(e,t)=>p(n,{method:"POST",path:"/ops/outbound",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),packageInstall:(e,t)=>p(n,{method:"POST",path:"/ops/packages/install",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),packageList:(e={},t)=>p(n,{method:"GET",path:"/ops/packages",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),packageUninstall:(e,t)=>p(n,{method:"DELETE",path:"/ops/packages/{package}",pathParams:["package"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),packageUpload:(e,t)=>p(n,{method:"POST",path:"/ops/packages",pathParams:[],query:[],body:"raw",optionalBody:!1,media:"application/octet-stream",reply:"json"},e,t),packageVersionUninstall:(e,t)=>p(n,{method:"DELETE",path:"/ops/packages/{package}/{version}",pathParams:["package","version"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),placement:(e={},t)=>p(n,{method:"GET",path:"/ops/placement",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),poolsGet:(e={},t)=>p(n,{method:"GET",path:"/ops/pools",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),poolsSet:(e,t)=>p(n,{method:"POST",path:"/ops/pools",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),quotasGet:(e={},t)=>p(n,{method:"GET",path:"/ops/quotas",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),quotasSet:(e={},t)=>p(n,{method:"POST",path:"/ops/quotas",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),receiptKey:(e,t)=>p(n,{method:"GET",path:"/ops/nodes/{id}/receipt-key",pathParams:["id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),registerNode:(e,t)=>p(n,{method:"POST",path:"/ops/nodes",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),release:(e,t)=>p(n,{method:"POST",path:"/ops/releases",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),releaseDeadline:(e,t)=>p(n,{method:"POST",path:"/ops/releases/{version}/deadline",pathParams:["version"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),releaseDeadlineLift:(e,t)=>p(n,{method:"DELETE",path:"/ops/releases/{version}/deadline",pathParams:["version"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),removeNode:(e,t)=>p(n,{method:"DELETE",path:"/ops/nodes/{id}",pathParams:["id"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),restore:(e,t)=>p(n,{method:"POST",path:"/ops/apps/{app}/restore",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),served:(e={},t)=>p(n,{method:"GET",path:"/ops/served-origins",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),setReplicas:(e,t)=>p(n,{method:"POST",path:"/ops/apps/{app}/replicas",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),signUpInviteCreate:(e,t)=>p(n,{method:"POST",path:"/ops/sign-up/invites",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),signUpInviteList:(e={},t)=>p(n,{method:"GET",path:"/ops/sign-up/invites",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),signUpInviteRevokeDelete:(e,t)=>p(n,{method:"DELETE",path:"/ops/sign-up/invites/{key}",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),signUpInviteRevokePost:(e,t)=>p(n,{method:"POST",path:"/ops/sign-up/invites/{key}/revoke",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),signUpSet:(e,t)=>p(n,{method:"POST",path:"/ops/sign-up",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),status:(e={},t)=>p(n,{method:"GET",path:"/ops/status",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),upgrade:(e,t)=>p(n,{method:"POST",path:"/ops/apps/{app}/upgrade",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t)},orgs:{allApps:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/all-apps",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),apps:(e,t)=>p(n,{method:"GET",path:"/orgs/{org}/apps",pathParams:["org"],query:["after","limit"],body:"none",optionalBody:!1,reply:"json"},e,t),appTeamList:(e,t)=>p(n,{method:"GET",path:"/orgs/{org}/app-teams",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),appTeamsScope:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/app-teams",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),capabilities:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/capabilities",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),create:(e,t)=>p(n,{method:"POST",path:"/orgs",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),delete:(e,t)=>p(n,{method:"DELETE",path:"/orgs/{org}",pathParams:["org"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),get:(e,t)=>p(n,{method:"GET",path:"/orgs/{org}",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),inviteCreate:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/invites",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),inviteList:(e,t)=>p(n,{method:"GET",path:"/orgs/{org}/invites",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),inviteRedeem:(e,t)=>p(n,{method:"POST",path:"/invites/{token}/redeem",pathParams:["token"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),inviteRevoke:(e,t)=>p(n,{method:"DELETE",path:"/orgs/{org}/invites/{key}",pathParams:["org","key"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),memberMetadata:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/members/{account}/metadata",pathParams:["org","account"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),memberRemoveTeams:(e,t)=>p(n,{method:"DELETE",path:"/orgs/{org}/members/{account}/teams",pathParams:["org","account"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),members:(e,t)=>p(n,{method:"GET",path:"/orgs/{org}/members",pathParams:["org"],query:["detail"],body:"none",optionalBody:!1,reply:"json"},e,t),memberSetTeams:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/members/{account}/teams",pathParams:["org","account"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),metadata:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/metadata",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),outboundApproval:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/outbound",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),publisher:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/publishers",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),publisherUpgrade:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/packages/{package}/upgrade",pathParams:["org","package"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),recoveryCancel:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/recovery/cancel",pathParams:["org"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),recoveryFinish:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/recovery/finish",pathParams:["org"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),recoverySet:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/recovery",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),recoveryStart:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/recovery/start",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),releaseApproval:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/releases",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),removeMember:(e,t)=>p(n,{method:"DELETE",path:"/orgs/{org}/members/{account}",pathParams:["org","account"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),rename:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/name",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),setMember:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/members",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),teamCreate:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/teams",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),teamDelete:(e,t)=>p(n,{method:"DELETE",path:"/orgs/{org}/teams/{team}",pathParams:["org","team"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),teamGet:(e,t)=>p(n,{method:"GET",path:"/orgs/{org}/teams/{team}",pathParams:["org","team"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),teamRemoveMember:(e,t)=>p(n,{method:"DELETE",path:"/orgs/{org}/teams/{team}/members/{account}",pathParams:["org","team","account"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),teamSetMember:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/teams/{team}/members",pathParams:["org","team"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),teamUpdate:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/teams/{team}",pathParams:["org","team"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),upgrade:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/upgrade",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),upgradeRetry:(e,t)=>p(n,{method:"POST",path:"/orgs/{org}/upgrades/{run}/retry",pathParams:["org","run"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required",operator:!0},e,t),upgradeStatus:(e,t)=>p(n,{method:"GET",path:"/orgs/{org}/upgrades/{run}",pathParams:["org","run"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),usage:(e,t)=>p(n,{method:"GET",path:"/orgs/{org}/usage",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},packages:{bundlePut:(e,t)=>p(n,{method:"POST",path:"/bundles",pathParams:[],query:[],body:"raw",optionalBody:!1,media:"application/wasm",reply:"json"},e,t),get:(e,t)=>p(n,{method:"GET",path:"/packages/{package}",pathParams:["package"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),install:(e,t)=>p(n,{method:"POST",path:"/packages/install",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),list:(e={},t)=>p(n,{method:"GET",path:"/packages",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),originsAdd:(e,t)=>p(n,{method:"POST",path:"/package-origins/{package}",pathParams:["package"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),originsList:(e,t)=>p(n,{method:"GET",path:"/package-origins/{package}",pathParams:["package"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),originsRemove:(e,t)=>p(n,{method:"DELETE",path:"/package-origins/{package}",pathParams:["package"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),uninstall:(e,t)=>p(n,{method:"DELETE",path:"/packages/{package}",pathParams:["package"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),upload:(e,t)=>p(n,{method:"POST",path:"/packages",pathParams:[],query:[],body:"raw",optionalBody:!1,media:"application/octet-stream",reply:"json"},e,t),versionUninstall:(e,t)=>p(n,{method:"DELETE",path:"/packages/{package}/{version}",pathParams:["package","version"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},public:{attestation:(e,t)=>p(n,{method:"GET",path:"/attestation",pathParams:[],query:["nonce","app","appHash","purpose"],body:"none",optionalBody:!1,reply:"json"},e,t),health:(e={},t)=>p(n,{method:"GET",path:"/health",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),publisherBinding:(e,t)=>p(n,{method:"GET",path:"/publishers/{signer}",pathParams:["signer"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),releasesPublic:(e={},t)=>p(n,{method:"GET",path:"/releases",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)}}}var zt=[{method:"POST",path:"/apps/{app}/intents",requires:"idempotencyKey"},{method:"POST",path:"/apps/{app}/methods/{method}",requires:"idempotencyKey"},{method:"POST",path:"/apps/{app}/views"}];var Zn="https://calimero-node.invalid",os=new Set(["attestation","health"]),rs=zt.map(n=>({method:n.method,pattern:new RegExp(`^${n.path.replace(/^\//,"").replace(/\{[^}]+\}/g,"[^/]+")}$`)})),ss=new Set(zt.filter(n=>n.requires==="idempotencyKey").map(n=>`${n.method} ${n.path}`));function as(n){return async e=>{if(!e.url.startsWith(`${Zn}/`))throw new Error(`not a route of the generated client: ${e.url}`);let t=new URL(e.url),o=t.pathname.replace(/^\/+/,""),r={};for(let[d,l]of t.searchParams)(r[d]??(r[d]=[])).push(l);let s=e.method;if(s==="GET"&&os.has(o)&&n.inTheClear)return n.inTheClear(o,{query:r,signal:e.signal});let a=e.headers.get("content-type")??void 0,i=s==="GET"?void 0:new Uint8Array(await e.arrayBuffer()),c=i&&i.length>0?i:void 0,u=!1;return rs.some(d=>d.method===s&&d.pattern.test(o))&&(u=(c?JSON.parse(new TextDecoder().decode(c)):{}).confirm===void 0?!0:"once"),n.exchange(s,o,{query:r,...c?{bytes:c,contentType:a??"application/octet-stream"}:{},retry:u,signal:e.signal})}}var is={async onRequest({request:n,schemaPath:e}){if(!ss.has(`${n.method} ${e}`))return;let t=await n.clone().text(),o=t?JSON.parse(t):{};if(o.idempotencyKey===void 0)return new Request(n,{body:JSON.stringify({...o,idempotencyKey:Ht()})})}};function Jt(n,e={}){let t=Qn({baseUrl:Zn,fetch:as(n)});return t.use(is),e.confirm&&t.use(yt(e.confirm)),e.operatorProof&&t.use(mt(e.operatorProof)),t}async function Wn(n){let{data:e,error:t,response:o}=await n;if(!o.ok)throw ps(o,t);return e??{}}function ps(n,e){let t=typeof e=="string"?e?{message:e}:{}:e;return me(n.status,t,n.headers.get("retry-after"))}var Xn="calimero.org-recovery.v1\0",Wt=64,Yt=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function cs(){return crypto.getRandomValues(new Uint8Array(32))}function ls(n){to(n);let e=Array.from(n,o=>o.toString(16).padStart(2,"0")).join(""),t=[];for(let o=0;o<e.length;o+=8)t.push(e.slice(o,o+8));return t.join("-")}function ds(n){let e=n.replace(/[-\s]/g,"");if(!/^[0-9a-fA-F]{64}$/.test(e))throw new Error("a recovery seed is 64 hex digits");return Uint8Array.from({length:32},(t,o)=>parseInt(e.slice(2*o,2*o+2),16))}function eo(n,e,t){return new TextEncoder().encode(`${Xn}${n}\0${e}\0${t}`)}async function us(n){let e=await no(n,!0),t=await crypto.subtle.exportKey("jwk",e);if(!t.x)throw new Error("this runtime cannot export an Ed25519 public key");return t.x}async function Zt(n,e,t,o){let r=new TextEncoder().encode(o).length;if(r===0||r>Wt)throw new Error(`a recovery nonce is 1 to ${Wt} bytes`);let s=await no(n,!1),a=await crypto.subtle.sign("Ed25519",s,oo(eo(e,t,o)));return j(new Uint8Array(a))}function to(n){if(n.length!==32)throw new Error("a recovery seed is 32 bytes")}function no(n,e){to(n);let t=new Uint8Array(Yt.length+32);return t.set(Yt),t.set(n,Yt.length),crypto.subtle.importKey("pkcs8",oo(t),{name:"Ed25519"},e,["sign"])}var oo=n=>n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);var Xt=100;function en(n={}){let e=new URLSearchParams;if(n.after!==void 0&&e.set("after",n.after),n.limit!==void 0){if(!Number.isInteger(n.limit)||n.limit<1||n.limit>Xt)throw new RangeError(`limit is 1 to ${Xt}`);e.set("limit",String(n.limit))}let t=e.toString();return t?`?${t}`:""}function Ue(n,e){try{return Ae(n,e)}catch{return n<e?-1:n>e?1:0}}function ro(n,e,t=Date.now()/1e3){if(n===null||n.length===0)return null;let o=n.reduce((s,a)=>Ue(s,a)>=0?s:a),r=null;for(let s of e)s.afterSecs<=t&&Ue(o,s.version)<0&&(r===null||Ue(s.version,r.version)>0)&&(r=s);return r}function so(n,e,t,o){return`calimero-publisher-binding/v1
5
5
  ${n}
6
6
  ${e}
7
7
  ${t}
8
- ${o}`}function Xr(n,e,t,o){return new TextEncoder().encode(Wn(n,e,t,o))}var es="0123456789ABCDEFGHJKMNPQRSTVWXYZ";async function Yt(n){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n))),t=(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0,o="";for(let r=0;r<6;r++)r===3&&(o+="-"),o+=es[t>>>27-5*r&31];return o}function ts(n){let e=typeof n=="string"?new URL(n):n,t=e.searchParams.get("request_id"),o=e.searchParams.get("result");return!t||o!=="approved"&&o!=="declined"?null:{requestId:t,result:o}}var Zn="https://mero-tee.vercel.app";function Xn(n){return`https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(n)}`}function eo(n){return`${Zn}/mero-tee?release_tag=${encodeURIComponent(`mero-tee-v${n}`)}`}function Wt(n,e,t=Date.now()/1e3){let o=c=>e.deadlines.find(y=>y.version===c)??null,r=n.governance.releases==="owner",s=n.governance.appUpgrades==="owner",a=n.clusterReleases.filter(c=>!c.approved).sort((c,y)=>je(y.release,c.release)).map(c=>({version:c.release,nodes:c.nodes,actionable:r,releaseNotesUrl:Xn(c.release),verifyUrl:eo(c.release),deadline:o(c.release)})),i=[];for(let c of n.apps){let y=c.availableVersions??[];if(c.package===null||y.length===0)continue;let d=y[y.length-1],l=c.latestReachable===void 0?d:c.latestReachable;i.push({app:c.app,name:c.name??null,package:c.package.package,from:c.package.version,to:l??d,reachable:l!==null,blocked:c.latestBlocked??null,available:y,actionable:s})}return{scope:n.scope,governance:n.governance,approvedReleases:n.approvedReleases,releases:a,upgrades:i,stalledBy:Yn(n.approvedReleases,e.deadlines,t),actionable:a.some(c=>c.actionable)||i.some(c=>c.actionable)}}function to(n,e,t,o={}){return{kind:"release",scope:n.kind==="org"?{org:n.org}:"account",subject:o.withdraw?{version:e,withdraw:!0}:{version:e},returnTo:t}}function ns(n,e,t){return to(n,e,t,{withdraw:!0})}function os(n,e,t){return{kind:"upgrade",subject:{app:n,toVersion:e},returnTo:t}}function rs(n){return"account"in n?`account:${n.account}`:`org:${n.org}`}async function ss(n,e=fetch){let t=n??globalThis.location?.origin;if(!t)throw new Error("no page origin to read the frontend manifest from; pass `origin`");let o=await e(new URL("/.well-known/calimero.json",t).toString());if(!o.ok)throw await H(o);let r=await o.json();return{...r,deployments:r.deployments??[]}}function as(n){let e=n??globalThis.location?.href;if(!e)return null;try{return new URL(e).searchParams.get("deployment")||null}catch{return null}}function no(n){return Jt(n),{after:n.after,limit:n.limit}}function is(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function ps(n){return n===null?null:is(n)}var Zt=class n{static async connect(e,t={}){let o=await Lt({...e,directory:e.directory??Ct});return new n(o,t)}constructor(e,t={}){this.transport=e instanceof te?e:new te(e);let o=$t(Gt(this.transport,t));this.apps=o.apps,this.auth=o.auth,this.consent=o.consent,this.ops=o.ops,this.orgs=o.orgs,this.public=o.public,this.packages=o.packages,this.deployments=o.deployments}as(e){return e}confirmWith(e,t={}){return e?{confirm:Ee(e,t)}:void 0}get nodeUrl(){return this.transport.nodeUrl}get nodes(){return this.transport.nodes}useApiKey(e){this.transport.useApiKey(e)}useSession(e){this.transport.useSession(e)}get session(){return this.transport.session}json(e,t,o){return this.transport.json(e,t,{body:o})}async signUp(e,t,o={}){let r=this.pageOrigin(o),s=o.invite?{invite:o.invite}:{},a=await this.begin(this.auth.registerBegin({...r===void 0?{name:t,...s}:{name:t,origin:r,...s}}),r),i=o.signal,c=await(i?e.create(a.options,{signal:i}):e.create(a.options)),y=await this.auth.registerFinish({challengeId:a.challengeId,registration:c,...s},this.confirmWith(e,{signal:i}));return this.useSession(y),y}async signIn(e,t={}){let o=this.pageOrigin(t),r=await this.begin(this.auth.loginBegin({...o===void 0?{}:{origin:o}}),o),s=r.options.rpId??r.options.rp?.id??"",a=G(r.options.challenge),i=await(t.signal?e.get(a,s,void 0,{signal:t.signal}):e.get(a,s)),c=await this.auth.loginFinish({challengeId:r.challengeId,assertion:i});return this.useSession(c),c}pageOrigin(e){if(e.origin!==void 0)return e.origin??void 0;let t=globalThis.location?.origin;return!t||t==="null"||new Set(this.transport.nodes.map(r=>{try{return new URL(r).origin}catch{return r}})).has(t)?void 0:t}async begin(e,t){try{return await this.as(e)}catch(o){throw o instanceof ee&&!o.origin&&t!==void 0?new ee(o.nodeMessage,{...o.details,origin:t}):o}}refresh(){return this.transport.refresh()}async signOut(){await this.signingOut(this.auth.logout())}async signOutEverywhere(){await this.signingOut(this.auth.logoutAll())}async signingOut(e){try{await e}finally{this.transport.signOut()}}async addPasskey(e,t){let o=await this.as(this.auth.passkeyAddBegin()),r=await e.create(o.options),{credentialId:s}=await this.auth.passkeyAddFinish({challengeId:o.challengeId,registration:r},this.confirmWith(t));return s}async startAccountRecovery(e,t){try{let o=await this.as(this.auth.accountRecoveryBegin({code:e})),r=await t.create(o.options);return await this.auth.accountRecoveryStart({challengeId:o.challengeId,code:e,registration:r})}catch(o){throw o instanceof K?new Ae(o.message.replace(/^401 UNAUTHENTICATED: /,""),o.details):o}}async finishAccountRecovery(e,t){let o=await this.auth.accountRecoveryFinish({...t?{accountId:t}:{}},this.confirmWith(e));return this.useSession(o),o}async downloadBlob(e,t){return new Uint8Array(await(await this.apps.blobDownload({app:e,id:t})).arrayBuffer())}async downloadBlobGranted(e,t,o){return new Uint8Array(await(await this.apps.blobDownload({app:e,id:t,grant:o})).arrayBuffer())}events(e,t=0,o){return this.transport.events(at("apps/{app}/events",{app:e}),{query:{from:t},signal:o})}presenceStream(e,t){return this.transport.events(at("apps/{app}/presence/stream",{app:e}),{signal:t})}async startRecovery(e,t){let o=(await this.auth.me()).accountId,r=j(crypto.getRandomValues(new Uint8Array(16))),s=await Qt(t,e,o,r);return this.orgs.recoveryStart({org:e,nonce:r,signature:s})}async appsReportAll(e){let t=(a={})=>e===null?this.auth.accountApps(no(a)):this.orgs.apps({org:e,...no(a)}),o=await t(),r=[...o.apps],s=o.next;for(;s!==null;){let a=await t({after:s});r.push(...a.apps),s=a.next}return{...o,apps:r,next:null}}async pendingApprovals(e=null){let[t,o]=await Promise.all([this.appsReportAll(e),this.public.releasesPublic()]);return Wt(t,o)}async openConsentPage(e,t={}){let o=typeof t=="function"?{navigate:t}:t,r=o.navigate??(a=>{let i=globalThis.window;if(!i)throw new Error("no window to open the consent page in; pass `navigate`");i.location.assign(a)}),s=await this.consent.pageCreate({body:e});if(s.code!==void 0){let a=await Yt(s.requestId);if(s.code!==a)throw new h(200,"CONSENT_CODE_MISMATCH","the consent page code does not match the request",{requestId:s.requestId,code:s.code,expected:a})}return o.confirm&&!await o.confirm(s)||r(s.url),s}async waitForConsent(e,t={}){let o=t.intervalMs??2e3;for(;;){let r=await this.consent.pageResult({request:e});if(r.status!=="pending"||t.signal?.aborted||t.expiresAt!==void 0&&Date.now()/1e3>=t.expiresAt)return r;await new Promise(s=>setTimeout(s,o))}}};var Xt={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},cs=Xt.JOIN_OPEN_TEAMS;function ls(...n){return n.reduce((e,t)=>e|Xt[t],0)}function lt(n,e){return(n<<e|n>>>32-e)>>>0}function F(n,e,t,o,r){n[e]=n[e]+n[t]>>>0,n[r]=lt(n[r]^n[e],16),n[o]=n[o]+n[r]>>>0,n[t]=lt(n[t]^n[o],12),n[e]=n[e]+n[t]>>>0,n[r]=lt(n[r]^n[e],8),n[o]=n[o]+n[r]>>>0,n[t]=lt(n[t]^n[o],7)}function oo(n,e){return(n[e]|n[e+1]<<8|n[e+2]<<16|n[e+3]<<24)>>>0}function ao(n,e,t){let o=new Uint32Array(16);o[0]=1634760805,o[1]=857760878,o[2]=2036477234,o[3]=1797285236;for(let a=0;a<8;a+=1)o[4+a]=oo(n,a*4);o[12]=e>>>0;for(let a=0;a<3;a+=1)o[13+a]=oo(t,a*4);let r=o.slice();for(let a=0;a<10;a+=1)F(r,0,4,8,12),F(r,1,5,9,13),F(r,2,6,10,14),F(r,3,7,11,15),F(r,0,5,10,15),F(r,1,6,11,12),F(r,2,7,8,13),F(r,3,4,9,14);let s=new Uint8Array(64);for(let a=0;a<16;a+=1){let i=r[a]+o[a]>>>0;s[a*4]=i&255,s[a*4+1]=i>>>8&255,s[a*4+2]=i>>>16&255,s[a*4+3]=i>>>24&255}return s}function ds(n,e,t,o){let r=new Uint8Array(o.length);for(let s=0,a=e;s<o.length;s+=64,a+=1){let i=ao(n,a,t),c=Math.min(s+64,o.length);for(let y=s;y<c;y+=1)r[y]=o[y]^i[y-s]}return r}function en(n){let e=0n;for(let t=n.length-1;t>=0;t-=1)e=e<<8n|BigInt(n[t]);return e}var us=(1n<<130n)-5n;function ys(n,e){let t=en(n.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,o=en(n.subarray(16,32)),r=0n;for(let i=0;i<e.length;i+=16){let c=e.subarray(i,Math.min(i+16,e.length)),y=en(c)+(1n<<BigInt(8*c.length));r=(r+y)*t%us}let s=r+o&(1n<<128n)-1n,a=new Uint8Array(16);for(let i=0;i<16;i+=1)a[i]=Number(s&0xffn),s>>=8n;return a}function ro(n){return new Uint8Array((16-n%16)%16)}function so(n){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(n),!0),e}function ms(n,e){let t=[n,ro(n.length),e,ro(e.length),so(n.length),so(e.length)],o=new Uint8Array(t.reduce((s,a)=>s+a.length,0)),r=0;for(let s of t)o.set(s,r),r+=s.length;return o}function gs(n,e){if(n.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 io(n,e,t,o=new Uint8Array(0)){gs(n,e);let r=ao(n,0,e).subarray(0,32),s=ds(n,1,e,t),a=ys(r,ms(o,s)),i=new Uint8Array(s.length+16);return i.set(s),i.set(a,s.length),i}var co=32,hs=1,fs=3,ws=2,bs=32,Ps=32,_s=12,ue=n=>new TextEncoder().encode(n),ve=n=>new Uint8Array([n>>8&255,n&255]),po=f(ue("KEM"),ve(co)),Oe=f(ue("HPKE"),ve(co),ve(hs),ve(fs));async function lo(n,e){let t=n.length===0?new Uint8Array(32):n,o=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",o,e))}async function Rs(n,e,t){let o=new Uint8Array(t),r=new Uint8Array(0);for(let s=1,a=0;a<t;s+=1)r=await lo(n,f(r,e,new Uint8Array([s]))),o.set(r.subarray(0,Math.min(r.length,t-a)),a),a+=r.length;return o}function dt(n,e,t,o){return lo(e,f(ue("HPKE-v1"),n,ue(t),o))}function tn(n,e,t,o,r){return Rs(e,f(ve(r),ue("HPKE-v1"),n,ue(t),o),r)}async function As(n,e){let t=await dt(po,new Uint8Array(0),"eae_prk",n);return tn(po,t,"shared_secret",e,bs)}async function ks(n,e){let t=new Uint8Array(0),o=await dt(Oe,t,"psk_id_hash",t),r=await dt(Oe,t,"info_hash",e),s=f(new Uint8Array([ws]),o,r),a=await dt(Oe,n,"secret",t);return{key:await tn(Oe,a,"key",s,Ps),nonce:await tn(Oe,a,"base_nonce",s,_s)}}async function uo(n,e,t,o,r=new Uint8Array(0),s){if(n.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let a=await re(s),i=await re(e),c=f(await ge(a.privateKey,n),await ge(i.privateKey,n)),y=await As(c,f(a.publicKey,n,i.publicKey)),{key:d,nonce:l}=await ks(y,t);return{enc:a.publicKey,ciphertext:io(d,l,o,r)}}var go="mero-agent-gate/attest/v3",ho="mero-agent-gate/provision/v2",Es=/^[a-z0-9][a-z0-9-]{0,62}$/,Ts=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,yo=64,mo=64*1024,Q=class extends Error{constructor(t,o,r){super(t);this.status=o;this.code=r;this.name="AgentGateError"}};function fo(n){if(!Es.test(n))throw new Error(`Agent id ${JSON.stringify(n)} must match [a-z0-9][a-z0-9-]{0,62}`)}function Se(n){return new TextEncoder().encode(n)}function wo(n){let e=Se(n);return f(new Uint8Array([e.length]),e)}function ne(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}function ut(n,e,t){let o;try{o=Uint8Array.from(atob(n.trim()),r=>r.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(t!==void 0&&o.length!==t)throw new Error(`${e} is not ${t} bytes`);return o}async function bo(n,e,t,o){let r=new Uint8Array(32),s=f(Se(go),n,wo(e),t??r,o??r);return new Uint8Array(await crypto.subtle.digest("SHA-256",s))}function Po(n,e){return f(Se(ho),n,wo(e))}async function js(){let n=crypto.getRandomValues(new Uint8Array(32));return{secret:n,publicKey:await yt(n)}}async function yt(n){if(n.length!==32)throw new Error("An owner key is 32 bytes");return ne((await re(n)).publicKey)}function _o(n,e){return`${n.replace(/\/+$/,"")}${e}`}async function Ro(n,e,t){let o=await n(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),r=await o.text(),s;try{s=r?JSON.parse(r):void 0}catch{}if(!o.ok){let a=s;throw new Q(`The gate answered ${o.status}${a?.error?` ${a.error}`:""}: ${a?.details??r.slice(0,200)}`,o.status,a?.error)}return s}async function nn(n){let e=n.agentId??"";e&&fo(e);let t=crypto.getRandomValues(new Uint8Array(32)),o=await Ro(n.fetch??fetch,_o(n.gateUrl,"/attest"),{nonceB64:ne(t),...e?{agentId:e}:{}});if((o?.agentId??"")!==e)throw new Error(`Asked about agent ${JSON.stringify(e)}, the gate answered for ${JSON.stringify(o?.agentId)}`);let r=ut(o.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),s=o.signingPublicKeyB64?ut(o.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,a=o.ownerPublicKeyB64?ut(o.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!s!=!a)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let i=await bo(r,e,s,a);return await n.verifier({quoteB64:o.quoteB64,nonce:T(t),reportDataSuffix:T(i)}),{agentId:e,provisioningPublicKey:ne(r),...s?{signingPublicKey:ne(s)}:{},...a?{ownerPublicKey:ne(a)}:{}}}async function Ao(n,e){let t=await yt(e);if(n.ownerPublicKey&&n.ownerPublicKey!==t)throw new Q(`This agent is claimed by another key (${n.ownerPublicKey}); it is not yours. Send it nothing and do not authorize its signing key`,void 0,"not_yours");return t}function Os(n){let e=Object.keys(n);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>yo)throw new Error(`At most ${yo} secrets at once`);for(let t of e){if(!Ts.test(t))throw new Error(`Secret name ${JSON.stringify(t)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);if(typeof n[t]!="string")throw new Error(`Secret ${t} is not a string`);if(Se(n[t]).length>mo)throw new Error(`Secret ${t} is over ${mo} bytes`)}}async function ko(n,e,t,o,r,s){if(!o.agentId)throw new Error("This quote names no agent; attest with the agent id");let a=await Ao(o,r),i=ut(o.provisioningPublicKey,"provisioningPublicKey",32),c=await uo(i,r,Po(i,o.agentId),Se(JSON.stringify(s)));return Ro(n,_o(e,t),{agentId:o.agentId,provisioningPublicKeyB64:o.provisioningPublicKey,senderPublicKeyB64:a,encappedKeyB64:ne(c.enc),ciphertextB64:ne(c.ciphertext)})}async function vs(n){Os(n.secrets);let e=n.fetch??fetch,t=await ko(e,n.gateUrl,"/provision",n.agent,n.ownerSecret,{secrets:n.secrets}),o=await nn({gateUrl:n.gateUrl,agentId:n.agent.agentId,verifier:n.verifier,fetch:e}),r=await yt(n.ownerSecret);if(o.ownerPublicKey!==r||!o.signingPublicKey)throw new Q("The gate accepted the secrets, but its quote does not name your key as owner");if(n.agent.signingPublicKey&&n.agent.signingPublicKey!==o.signingPublicKey)throw new Q("The agent's signing key changed while provisioning");return{agentId:o.agentId,provisioningPublicKey:o.provisioningPublicKey,signingPublicKey:o.signingPublicKey,ownerPublicKey:r,written:t?.written??[],claimed:t?.claimed===!0}}async function Ss(n){if(!n.agent.ownerPublicKey)throw new Error("This agent is not claimed; there is nothing to release");let e=n.fetch??fetch;if(await ko(e,n.gateUrl,"/release",n.agent,n.ownerSecret,{release:!0}),(await nn({gateUrl:n.gateUrl,agentId:n.agent.agentId,verifier:n.verifier,fetch:e})).ownerPublicKey)throw new Q("The gate says it released the agent, but its quote still names an owner")}var on=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),xs=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function Us(n,e,t={}){let o=typeof n=="string"?new TextEncoder().encode(n):n;await Ie(o,e,{identity:t.identity??on.identity,issuer:t.issuer??on.issuer});let r;try{r=JSON.parse(new TextDecoder().decode(o))}catch{throw new Error("The signed agent policy is not JSON")}let s=t.role??"agent";if(r?.role!==s)throw new Error(`The signed file is a ${JSON.stringify(r?.role)} policy, not an ${s} one`);let a=t.profile??W;if(r.profile!==a)throw new Error(`The signed agent policy is for the ${JSON.stringify(r.profile)} profile, not ${a}`);if(t.expectedVersion!==void 0&&r.version!==t.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(r.version)}, not ${t.expectedVersion}`);return Eo(r),r}function Eo(n){for(let e of xs)if(!Array.isArray(n?.[e])||n[e].length===0)throw new Error(`The agent policy's ${e} is empty, so no agent would be accepted`)}var Cs=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function Bs(n){let e=Cs.find(t=>t.toLowerCase()===n.trim().toLowerCase());if(!e)throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(n)}`);return e}var xe=n=>n.trim().replace(/^0x/i,"");function qs(n,e){return Eo(n),Z({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:n.allowed_tcb_statuses.map(Bs),allowedMrtd:n.allowed_mrtd.map(xe),allowedRtmr0:n.allowed_rtmr0.map(xe),allowedRtmr1:n.allowed_rtmr1.map(xe),allowedRtmr2:n.allowed_rtmr2.map(xe),allowedRtmr3:n.allowed_rtmr3.map(xe)})}export{go as AGENT_ATTEST_DOMAIN,ho as AGENT_PROVISION_INFO_DOMAIN,Q as AgentGateError,ot as AppError,Ge as ArgsTooLarge,Je as BadOrigin,Zt as CalimeroClient,h as CalimeroError,Ze as ClusterNotUpgraded,_e as ConfirmCancelled,Re as ConfirmPromptBlocked,ce as ConfirmRequired,ze as ConsentStale,Tt as DEFAULT_COLLATERAL_MIRROR,Ct as DEFAULT_DIRECTORY,cs as DEFAULT_ORG_CAPABILITIES,Ve as DEFAULT_RELEASE_MIRROR,Dt as DEFAULT_RETRY,q as DirectoryError,Xe as FeatureNotActive,Tn as GITHUB_RELEASES,un as HANDSHAKE_PATH,He as IdempotencyMismatch,on as KMS_RELEASE_SIGNER,K as LoginRequired,Ft as MAX_RECOVERY_NONCE_BYTES,zt as MAX_REPORT_PAGE,vn as MOCK_QUOTE_HEADER,Et as NODE_RELEASE_SIGNER,te as NodeTransport,Ke as NotFound,We as NotServing,Xt as ORG_CAPABILITIES,ee as OriginNotRegistered,Ye as OriginTaken,W as PRODUCTION_PROFILE,$e as PasskeyUnknownHere,nt as QuotaExceeded,Hn as RECOVERY_DOMAIN,Zn as RELEASE_VERIFIER,et as RecoveryNotReady,Fe as ReleaseDeadlineError,Qe as RuntimeTooOld,fe as SEALED_CONTENT_TYPE,yn as SEALED_PATH,V as SealedTransportError,tt as SignUpRefused,we as StaleTransportKeyError,rt as TrapError,le as UnavailableError,X as WrongNode,Ae as WrongRecoveryCode,bo as agentKeyBinding,qs as agentQuoteVerifier,nn as attestAgent,j as b64url,Ur as browserPasskey,Ao as checkOwner,Sn as claimedRelease,vt as cloudNodeReleaseUrl,je as compareVersions,Yt as confirmationCode,ts as consentReturn,Z as createQuoteVerifier,Gt as createRouteClient,$t as createRoutes,Pt as createSealedFetch,_r as createSignedReleaseVerifier,rs as deployerKey,Lt as directoryTransport,de as errorFrom,Ut as fetchAttestedKey,Ot as fetchGithubNodeRelease,jt as fetchNodeRelease,xn as freshCollateral,G as fromB64url,ss as frontendManifest,js as generateOwnerKey,Vt as newIdempotencyKey,Jr as newRecoverySeed,ls as orgCapabilities,yt as ownerPublicKey,as as pageDeployment,Jt as pageQuery,Wr as parseRecoverySeed,Ee as passkeyConfirm,Wt as pendingApprovalsFrom,ps as presenceState,vs as provisionAgent,Po as provisionInfo,Xr as publisherBindingBytes,Wn as publisherBindingMessage,Mt as queryString,Fn as recoveryMessage,Zr as recoveryPublicKey,Yr as recoverySeedText,H as refusal,Ss as releaseAgent,to as releaseConsent,Xn as releaseNotesUrl,It as retryDelayMs,at as routePath,Qt as signRecovery,qn as sseFrames,Yn as stalledBy,bt as transportKeyBinding,Le as trustSignedRelease,kt as trustedMeasurementsFromReleases,os as upgradeConsent,fo as validateAgentId,eo as verifyReleaseUrl,Us as verifySignedAgentPolicy,En as verifySignedNodeRelease,ns as withdrawConsent};
8
+ ${o}`}function ys(n,e,t,o){return new TextEncoder().encode(so(n,e,t,o))}var ms="0123456789ABCDEFGHJKMNPQRSTVWXYZ";async function tn(n){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n))),t=(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0,o="";for(let r=0;r<6;r++)r===3&&(o+="-"),o+=ms[t>>>27-5*r&31];return o}function gs(n){let e=typeof n=="string"?new URL(n):n,t=e.searchParams.get("request_id"),o=e.searchParams.get("result");return!t||o!=="approved"&&o!=="declined"?null:{requestId:t,result:o}}var ao="https://mero-tee.vercel.app";function io(n){return`https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(n)}`}function po(n){return`${ao}/mero-tee?release_tag=${encodeURIComponent(`mero-tee-v${n}`)}`}function nn(n,e,t=Date.now()/1e3){let o=c=>e.deadlines.find(u=>u.version===c)??null,r=n.governance.releases==="owner",s=n.governance.appUpgrades==="owner",a=n.clusterReleases.filter(c=>!c.approved).sort((c,u)=>Ue(u.release,c.release)).map(c=>({version:c.release,nodes:c.nodes,actionable:r,releaseNotesUrl:io(c.release),verifyUrl:po(c.release),deadline:o(c.release)})),i=[];for(let c of n.apps){let u=c.availableVersions??[];if(c.package===null||u.length===0)continue;let d=u[u.length-1],l=c.latestReachable===void 0?d:c.latestReachable;i.push({app:c.app,name:c.name??null,package:c.package.package,from:c.package.version,to:l??d,reachable:l!==null,blocked:c.latestBlocked??null,available:u,actionable:s})}return{scope:n.scope,governance:n.governance,approvedReleases:n.approvedReleases,releases:a,upgrades:i,stalledBy:ro(n.approvedReleases,e.deadlines,t),actionable:a.some(c=>c.actionable)||i.some(c=>c.actionable)}}function co(n,e,t,o={}){return{kind:"release",scope:n.kind==="org"?{org:n.org}:"account",subject:o.withdraw?{version:e,withdraw:!0}:{version:e},returnTo:t}}function hs(n,e,t){return co(n,e,t,{withdraw:!0})}function fs(n,e,t){return{kind:"upgrade",subject:{app:n,toVersion:e},returnTo:t}}var yo=16*1024*1024,ws=1,bs=8,Ps=16,_s=8;function Rs(n){return"account"in n?`account:${n.account}`:`org:${n.org}`}async function As(n,e=fetch){let t=n??globalThis.location?.origin;if(!t)throw new Error("no page origin to read the frontend manifest from; pass `origin`");let o=await e(new URL("/.well-known/calimero.json",t).toString());if(!o.ok)throw await J(o);let r=await o.json();return{...r,deployments:r.deployments??[]}}function ks(n){let e=n??globalThis.location?.href;if(!e)return null;try{return new URL(e).searchParams.get("deployment")||null}catch{return null}}function lo(n){return en(n),{after:n.after,limit:n.limit}}function Es(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function Ts(n){return n===null?null:Es(n)}async function uo(n,e,t){return n instanceof Blob?new Uint8Array(await n.slice(e,t).arrayBuffer()):n instanceof ArrayBuffer?new Uint8Array(n,e,t-e):n.subarray(e,t)}function on(n,e){let t=n?.next;if(typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=e)return t;throw new Error(`the node answered a bad next: ${JSON.stringify(n)}`)}var rn=class n{static async connect(e,t={}){let o=await Ft({...e,directory:e.directory??It});return new n(o,t)}constructor(e,t={}){this.transport=e instanceof ae?e:new ae(e);let o=Qt(Jt(this.transport,t));this.apps=o.apps,this.auth=o.auth,this.consent=o.consent,this.ops=o.ops,this.orgs=o.orgs,this.public=o.public,this.packages=o.packages,this.deployments=o.deployments}as(e){return e}confirmWith(e,t={}){return e?{confirm:ve(e,t)}:void 0}get nodeUrl(){return this.transport.nodeUrl}get nodes(){return this.transport.nodes}useApiKey(e){this.transport.useApiKey(e)}useSession(e){this.transport.useSession(e)}get session(){return this.transport.session}json(e,t,o){return this.transport.json(e,t,{body:o})}async signUp(e,t,o={}){let r=this.pageOrigin(o),s=o.invite?{invite:o.invite}:{},a=await this.begin(this.auth.registerBegin({...r===void 0?{name:t,...s}:{name:t,origin:r,...s}}),r),i=o.signal,c=await(i?e.create(a.options,{signal:i}):e.create(a.options)),u=await this.auth.registerFinish({challengeId:a.challengeId,registration:c,...s},this.confirmWith(e,{signal:i}));return this.useSession(u),u}async signIn(e,t={}){let o=this.pageOrigin(t),r=await this.begin(this.auth.loginBegin({...o===void 0?{}:{origin:o}}),o),s=r.options.rpId??r.options.rp?.id??"",a=z(r.options.challenge),i=await(t.signal?e.get(a,s,void 0,{signal:t.signal}):e.get(a,s)),c=await this.auth.loginFinish({challengeId:r.challengeId,assertion:i});return this.useSession(c),c}pageOrigin(e){if(e.origin!==void 0)return e.origin??void 0;let t=globalThis.location?.origin;return!t||t==="null"||new Set(this.transport.nodes.map(r=>{try{return new URL(r).origin}catch{return r}})).has(t)?void 0:t}async begin(e,t){try{return await this.as(e)}catch(o){throw o instanceof se&&!o.origin&&t!==void 0?new se(o.nodeMessage,{...o.details,origin:t}):o}}refresh(){return this.transport.refresh()}async signOut(){await this.signingOut(this.auth.logout())}async signOutEverywhere(){await this.signingOut(this.auth.logoutAll())}async signingOut(e){try{await e}finally{this.transport.signOut()}}async addPasskey(e,t){let o=await this.as(this.auth.passkeyAddBegin()),r=await e.create(o.options),{credentialId:s}=await this.auth.passkeyAddFinish({challengeId:o.challengeId,registration:r},this.confirmWith(t));return s}async startAccountRecovery(e,t){try{let o=await this.as(this.auth.accountRecoveryBegin({code:e})),r=await t.create(o.options);return await this.auth.accountRecoveryStart({challengeId:o.challengeId,code:e,registration:r})}catch(o){throw o instanceof F?new Te(o.message.replace(/^401 UNAUTHENTICATED: /,""),o.details):o}}async finishAccountRecovery(e,t){let o=await this.auth.accountRecoveryFinish({...t?{accountId:t}:{}},this.confirmWith(e));return this.useSession(o),o}async downloadBlob(e,t){return new Uint8Array(await(await this.apps.blobDownload({app:e,id:t})).arrayBuffer())}async downloadBlobGranted(e,t,o){return new Uint8Array(await(await this.apps.blobDownload({app:e,id:t,grant:o})).arrayBuffer())}async uploadFile(e,t){let o=t instanceof Blob?t.size:t.byteLength;if(o<=yo)return this.apps.filesUpload({app:e,body:await uo(t,0,o)});try{return await this.uploadSession(e,t,o)}catch(r){if(!(r instanceof f)||r.code!=="UPLOAD_UNKNOWN")throw r;return this.uploadSession(e,t,o)}}async uploadSession(e,t,o){let r=await this.untilAvailable(()=>this.apps.uploadBegin({app:e,size:o})),{uploadId:s,partBytes:a,parts:i}=r;if(!s||!a||a<=0||i!==Math.ceil(o/a))throw new Error(`the node began an upload it cannot take: ${JSON.stringify(r)}`);try{return await this.sendParts(e,s,t,o,a,i),await this.untilAvailable(()=>this.apps.uploadComplete({app:e,upload:s}))}catch(c){throw c instanceof f&&c.code==="UPLOAD_UNKNOWN"||await this.apps.uploadAbort({app:e,upload:s}).catch(()=>{}),c}}async sendParts(e,t,o,r,s,a){let[i,c,u]=[0,0,0];for(;i<a;)try{let d=await uo(o,i*s,Math.min((i+1)*s,r));i=on(await this.apps.uploadPart({app:e,upload:t,k:String(i),body:d}),a),c=0;continue}catch(d){if(d instanceof f&&d.code==="PART_OUT_OF_ORDER"){if(u+=1,u>Ps)throw d;i=on(d.details,a);continue}if(!this.isTransient(d)||++c>bs)throw d;if(await new Promise(l=>setTimeout(l,Se(c-1,this.transport.retry))),c>ws)try{let l=on(await this.apps.uploadStatus({app:e,upload:t}),a);l>i&&(c=0),i=l}catch(l){if(!this.isTransient(l))throw l}}}async untilAvailable(e){for(let t=0;;t++)try{return await e()}catch(o){if(!this.isTransient(o)||t>=_s)throw o;await new Promise(r=>setTimeout(r,Se(t,this.transport.retry)))}}isTransient(e){return e instanceof Q||this.transport.isNetworkFailure(e)}events(e,t=0,o){return this.transport.events(dt("apps/{app}/events",{app:e}),{query:{from:t},signal:o})}presenceStream(e,t){return this.transport.events(dt("apps/{app}/presence/stream",{app:e}),{signal:t})}async startRecovery(e,t){let o=(await this.auth.me()).accountId,r=j(crypto.getRandomValues(new Uint8Array(16))),s=await Zt(t,e,o,r);return this.orgs.recoveryStart({org:e,nonce:r,signature:s})}async appsReportAll(e){let t=(a={})=>e===null?this.auth.accountApps(lo(a)):this.orgs.apps({org:e,...lo(a)}),o=await t(),r=[...o.apps],s=o.next;for(;s!==null;){let a=await t({after:s});r.push(...a.apps),s=a.next}return{...o,apps:r,next:null}}async pendingApprovals(e=null){let[t,o]=await Promise.all([this.appsReportAll(e),this.public.releasesPublic()]);return nn(t,o)}async openConsentPage(e,t={}){let o=typeof t=="function"?{navigate:t}:t,r=o.navigate??(a=>{let i=globalThis.window;if(!i)throw new Error("no window to open the consent page in; pass `navigate`");i.location.assign(a)}),s=await this.consent.pageCreate({body:e});if(s.code!==void 0){let a=await tn(s.requestId);if(s.code!==a)throw new f(200,"CONSENT_CODE_MISMATCH","the consent page code does not match the request",{requestId:s.requestId,code:s.code,expected:a})}return o.confirm&&!await o.confirm(s)||r(s.url),s}async waitForConsent(e,t={}){let o=t.intervalMs??2e3;for(;;){let r=await this.consent.pageResult({request:e});if(r.status!=="pending"||t.signal?.aborted||t.expiresAt!==void 0&&Date.now()/1e3>=t.expiresAt)return r;await new Promise(s=>setTimeout(s,o))}}};var sn={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},js=sn.JOIN_OPEN_TEAMS;function vs(...n){return n.reduce((e,t)=>e|sn[t],0)}function gt(n,e){return(n<<e|n>>>32-e)>>>0}function Y(n,e,t,o,r){n[e]=n[e]+n[t]>>>0,n[r]=gt(n[r]^n[e],16),n[o]=n[o]+n[r]>>>0,n[t]=gt(n[t]^n[o],12),n[e]=n[e]+n[t]>>>0,n[r]=gt(n[r]^n[e],8),n[o]=n[o]+n[r]>>>0,n[t]=gt(n[t]^n[o],7)}function mo(n,e){return(n[e]|n[e+1]<<8|n[e+2]<<16|n[e+3]<<24)>>>0}function fo(n,e,t){let o=new Uint32Array(16);o[0]=1634760805,o[1]=857760878,o[2]=2036477234,o[3]=1797285236;for(let a=0;a<8;a+=1)o[4+a]=mo(n,a*4);o[12]=e>>>0;for(let a=0;a<3;a+=1)o[13+a]=mo(t,a*4);let r=o.slice();for(let a=0;a<10;a+=1)Y(r,0,4,8,12),Y(r,1,5,9,13),Y(r,2,6,10,14),Y(r,3,7,11,15),Y(r,0,5,10,15),Y(r,1,6,11,12),Y(r,2,7,8,13),Y(r,3,4,9,14);let s=new Uint8Array(64);for(let a=0;a<16;a+=1){let i=r[a]+o[a]>>>0;s[a*4]=i&255,s[a*4+1]=i>>>8&255,s[a*4+2]=i>>>16&255,s[a*4+3]=i>>>24&255}return s}function Os(n,e,t,o){let r=new Uint8Array(o.length);for(let s=0,a=e;s<o.length;s+=64,a+=1){let i=fo(n,a,t),c=Math.min(s+64,o.length);for(let u=s;u<c;u+=1)r[u]=o[u]^i[u-s]}return r}function an(n){let e=0n;for(let t=n.length-1;t>=0;t-=1)e=e<<8n|BigInt(n[t]);return e}var Ss=(1n<<130n)-5n;function Us(n,e){let t=an(n.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,o=an(n.subarray(16,32)),r=0n;for(let i=0;i<e.length;i+=16){let c=e.subarray(i,Math.min(i+16,e.length)),u=an(c)+(1n<<BigInt(8*c.length));r=(r+u)*t%Ss}let s=r+o&(1n<<128n)-1n,a=new Uint8Array(16);for(let i=0;i<16;i+=1)a[i]=Number(s&0xffn),s>>=8n;return a}function go(n){return new Uint8Array((16-n%16)%16)}function ho(n){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(n),!0),e}function xs(n,e){let t=[n,go(n.length),e,go(e.length),ho(n.length),ho(e.length)],o=new Uint8Array(t.reduce((s,a)=>s+a.length,0)),r=0;for(let s of t)o.set(s,r),r+=s.length;return o}function Cs(n,e){if(n.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 wo(n,e,t,o=new Uint8Array(0)){Cs(n,e);let r=fo(n,0,e).subarray(0,32),s=Os(n,1,e,t),a=Us(r,xs(o,s)),i=new Uint8Array(s.length+16);return i.set(s),i.set(a,s.length),i}var Po=32,Bs=1,qs=3,Ns=2,Ms=32,Ds=32,Is=12,ge=n=>new TextEncoder().encode(n),Ce=n=>new Uint8Array([n>>8&255,n&255]),bo=h(ge("KEM"),Ce(Po)),xe=h(ge("HPKE"),Ce(Po),Ce(Bs),Ce(qs));async function _o(n,e){let t=n.length===0?new Uint8Array(32):n,o=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",o,e))}async function Vs(n,e,t){let o=new Uint8Array(t),r=new Uint8Array(0);for(let s=1,a=0;a<t;s+=1)r=await _o(n,h(r,e,new Uint8Array([s]))),o.set(r.subarray(0,Math.min(r.length,t-a)),a),a+=r.length;return o}function ht(n,e,t,o){return _o(e,h(ge("HPKE-v1"),n,ge(t),o))}function pn(n,e,t,o,r){return Vs(e,h(Ce(r),ge("HPKE-v1"),n,ge(t),o),r)}async function Ks(n,e){let t=await ht(bo,new Uint8Array(0),"eae_prk",n);return pn(bo,t,"shared_secret",e,Ms)}async function Ls(n,e){let t=new Uint8Array(0),o=await ht(xe,t,"psk_id_hash",t),r=await ht(xe,t,"info_hash",e),s=h(new Uint8Array([Ns]),o,r),a=await ht(xe,n,"secret",t);return{key:await pn(xe,a,"key",s,Ds),nonce:await pn(xe,a,"base_nonce",s,Is)}}async function Ro(n,e,t,o,r=new Uint8Array(0),s){if(n.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let a=await M(s),i=await M(e),c=h(await te(a.privateKey,n),await te(i.privateKey,n)),u=await Ks(c,h(a.publicKey,n,i.publicKey)),{key:d,nonce:l}=await Ls(u,t);return{enc:a.publicKey,ciphertext:wo(d,l,o,r)}}var Eo="mero-agent-gate/attest/v3",To="mero-agent-gate/provision/v2",$s=/^[a-z0-9][a-z0-9-]{0,62}$/,Gs=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,Ao=64,ko=64*1024,W=class extends Error{constructor(t,o,r){super(t);this.status=o;this.code=r;this.name="AgentGateError"}};function jo(n){if(!$s.test(n))throw new Error(`Agent id ${JSON.stringify(n)} must match [a-z0-9][a-z0-9-]{0,62}`)}function Be(n){return new TextEncoder().encode(n)}function vo(n){let e=Be(n);return h(new Uint8Array([e.length]),e)}function ie(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}function ft(n,e,t){let o;try{o=Uint8Array.from(atob(n.trim()),r=>r.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(t!==void 0&&o.length!==t)throw new Error(`${e} is not ${t} bytes`);return o}async function Oo(n,e,t,o){let r=new Uint8Array(32),s=h(Be(Eo),n,vo(e),t??r,o??r);return new Uint8Array(await crypto.subtle.digest("SHA-256",s))}function So(n,e){return h(Be(To),n,vo(e))}async function Hs(){let n=crypto.getRandomValues(new Uint8Array(32));return{secret:n,publicKey:await wt(n)}}async function wt(n){if(n.length!==32)throw new Error("An owner key is 32 bytes");return ie((await M(n)).publicKey)}function Uo(n,e){return`${n.replace(/\/+$/,"")}${e}`}async function xo(n,e,t){let o=await n(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),r=await o.text(),s;try{s=r?JSON.parse(r):void 0}catch{}if(!o.ok){let a=s;throw new W(`The gate answered ${o.status}${a?.error?` ${a.error}`:""}: ${a?.details??r.slice(0,200)}`,o.status,a?.error)}return s}async function cn(n){let e=n.agentId??"";e&&jo(e);let t=crypto.getRandomValues(new Uint8Array(32)),o=await xo(n.fetch??fetch,Uo(n.gateUrl,"/attest"),{nonceB64:ie(t),...e?{agentId:e}:{}});if((o?.agentId??"")!==e)throw new Error(`Asked about agent ${JSON.stringify(e)}, the gate answered for ${JSON.stringify(o?.agentId)}`);let r=ft(o.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),s=o.signingPublicKeyB64?ft(o.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,a=o.ownerPublicKeyB64?ft(o.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!s!=!a)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let i=await Oo(r,e,s,a);return await n.verifier({quoteB64:o.quoteB64,nonce:R(t),reportDataSuffix:R(i)}),{agentId:e,provisioningPublicKey:ie(r),...s?{signingPublicKey:ie(s)}:{},...a?{ownerPublicKey:ie(a)}:{}}}async function Co(n,e){let t=await wt(e);if(n.ownerPublicKey&&n.ownerPublicKey!==t)throw new W(`This agent is claimed by another key (${n.ownerPublicKey}); it is not yours. Send it nothing and do not authorize its signing key`,void 0,"not_yours");return t}function Fs(n){let e=Object.keys(n);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>Ao)throw new Error(`At most ${Ao} secrets at once`);for(let t of e){if(!Gs.test(t))throw new Error(`Secret name ${JSON.stringify(t)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);if(typeof n[t]!="string")throw new Error(`Secret ${t} is not a string`);if(Be(n[t]).length>ko)throw new Error(`Secret ${t} is over ${ko} bytes`)}}async function Bo(n,e,t,o,r,s){if(!o.agentId)throw new Error("This quote names no agent; attest with the agent id");let a=await Co(o,r),i=ft(o.provisioningPublicKey,"provisioningPublicKey",32),c=await Ro(i,r,So(i,o.agentId),Be(JSON.stringify(s)));return xo(n,Uo(e,t),{agentId:o.agentId,provisioningPublicKeyB64:o.provisioningPublicKey,senderPublicKeyB64:a,encappedKeyB64:ie(c.enc),ciphertextB64:ie(c.ciphertext)})}async function Qs(n){Fs(n.secrets);let e=n.fetch??fetch,t=await Bo(e,n.gateUrl,"/provision",n.agent,n.ownerSecret,{secrets:n.secrets}),o=await cn({gateUrl:n.gateUrl,agentId:n.agent.agentId,verifier:n.verifier,fetch:e}),r=await wt(n.ownerSecret);if(o.ownerPublicKey!==r||!o.signingPublicKey)throw new W("The gate accepted the secrets, but its quote does not name your key as owner");if(n.agent.signingPublicKey&&n.agent.signingPublicKey!==o.signingPublicKey)throw new W("The agent's signing key changed while provisioning");return{agentId:o.agentId,provisioningPublicKey:o.provisioningPublicKey,signingPublicKey:o.signingPublicKey,ownerPublicKey:r,written:t?.written??[],claimed:t?.claimed===!0}}async function zs(n){if(!n.agent.ownerPublicKey)throw new Error("This agent is not claimed; there is nothing to release");let e=n.fetch??fetch;if(await Bo(e,n.gateUrl,"/release",n.agent,n.ownerSecret,{release:!0}),(await cn({gateUrl:n.gateUrl,agentId:n.agent.agentId,verifier:n.verifier,fetch:e})).ownerPublicKey)throw new W("The gate says it released the agent, but its quote still names an owner")}var ln=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),Js=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function Ys(n,e,t={}){let o=typeof n=="string"?new TextEncoder().encode(n):n;await Ge(o,e,{identity:t.identity??ln.identity,issuer:t.issuer??ln.issuer});let r;try{r=JSON.parse(new TextDecoder().decode(o))}catch{throw new Error("The signed agent policy is not JSON")}let s=t.role??"agent";if(r?.role!==s)throw new Error(`The signed file is a ${JSON.stringify(r?.role)} policy, not an ${s} one`);let a=t.profile??ne;if(r.profile!==a)throw new Error(`The signed agent policy is for the ${JSON.stringify(r.profile)} profile, not ${a}`);if(t.expectedVersion!==void 0&&r.version!==t.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(r.version)}, not ${t.expectedVersion}`);return qo(r),r}function qo(n){for(let e of Js)if(!Array.isArray(n?.[e])||n[e].length===0)throw new Error(`The agent policy's ${e} is empty, so no agent would be accepted`)}var Ws=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function Zs(n){let e=Ws.find(t=>t.toLowerCase()===n.trim().toLowerCase());if(!e)throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(n)}`);return e}var qe=n=>n.trim().replace(/^0x/i,"");function Xs(n,e){return qo(n),oe({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:n.allowed_tcb_statuses.map(Zs),allowedMrtd:n.allowed_mrtd.map(qe),allowedRtmr0:n.allowed_rtmr0.map(qe),allowedRtmr1:n.allowed_rtmr1.map(qe),allowedRtmr2:n.allowed_rtmr2.map(qe),allowedRtmr3:n.allowed_rtmr3.map(qe)})}var No=1,ea=new TextEncoder().encode("calimero.recovery-backup.v1\0"),ta=new TextEncoder().encode("calimero.recovery-backup.v1"),na=new TextEncoder().encode("calimero.recovery-backup.key.v1"),Do=32,oa=1,ra=2,sa=0,S=n=>new TextEncoder().encode(n),Me=n=>new Uint8Array([n>>8&255,n&255]),Mo=h(S("KEM"),Me(Do)),Ne=h(S("HPKE"),Me(Do),Me(oa),Me(ra));function he(n){return n.kind==="operator"?"operator":`${n.kind}:${n.id}`}async function op(){let n=crypto.getRandomValues(new Uint8Array(32));return{secret:n,publicKey:await aa(n)}}async function aa(n){return R((await M(n)).publicKey)}async function ia(n){let e=S(n.header),t=JSON.parse(n.header);if(typeof t.format!="number"||t.format>No)throw new Error(`recovery file format ${t.format} is not one this release reads (${No})`);let o=await crypto.subtle.importKey("raw",B(t.signingKey,"signing key",32),{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify("Ed25519",o,B(n.signature,"signature",64),h(ea,e)))throw new Error("the node's signature over the header does not hold");return t}async function Io(n,e){let t=n.length===0?new Uint8Array(32):n,o=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",o,e))}async function pa(n,e,t){let o=new Uint8Array(t),r=new Uint8Array(0);for(let s=1,a=0;a<t;s+=1)r=await Io(n,h(r,e,new Uint8Array([s]))),o.set(r.subarray(0,Math.min(r.length,t-a)),a),a+=r.length;return o}var bt=(n,e,t,o)=>Io(e,h(S("HPKE-v1"),n,S(t),o)),dn=(n,e,t,o,r)=>pa(e,h(Me(r),S("HPKE-v1"),n,S(t),o),r);async function ca(n,e){let t=await M(e);if(R(t.publicKey)!==n.recipient)throw new Error("this key is not the one the file was sealed to");let o=B(n.enc,"encapsulated key",32),r=await te(t.privateKey,o),s=new Uint8Array(0),a=await bt(Mo,s,"eae_prk",r),i=await dn(Mo,a,"shared_secret",h(o,t.publicKey),32),c=await bt(Ne,s,"psk_id_hash",s),u=await bt(Ne,s,"info_hash",ta),d=h(new Uint8Array([sa]),c,u),l=await bt(Ne,i,"secret",s),y=await dn(Ne,l,"key",d,32),m=await dn(Ne,l,"base_nonce",d,12),g=await crypto.subtle.importKey("raw",y,"AES-GCM",!1,["decrypt"]),b;try{b=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:m,additionalData:na},g,B(n.wrappedKey,"wrapped key",48)))}catch{throw new Error("this key does not open the file")}if(b.length!==32)throw new Error("the data key is not 32 bytes");return b}async function rp(n,e,t,o={}){let r=[];for(let c of[...e].sort((u,d)=>u.name.localeCompare(d.name))){let u=await ia(c);if(o.verifyQuote&&await ua(u,o.verifyQuote),he(u.holder)!==he(n))throw new Error(`${c.name} is ${he(u.holder)}'s, not ${he(n)}'s`);r.push({name:c.name,header:u})}let s=async c=>({file:c.name,key:R(await ca(c.header,t))}),a=r.filter(c=>c.header.kind==="holder").pop();if(!a)throw new Error(`no holder file of ${he(n)}`);let i=new Map;for(let c of r)c.header.kind==="app"&&c.header.app&&(!o.apps||o.apps.includes(c.header.app))&&i.set(c.header.app,c);return{holder:he(n),slice:await s(a),apps:await Promise.all([...i.values()].map(s)),code:await Promise.all(r.filter(c=>c.header.kind==="code").map(s))}}async function un(n){return new Uint8Array(await crypto.subtle.digest("SHA-256",n))}async function la(n,e){let t=S(n),o=new Uint8Array(4);new DataView(o.buffer).setUint32(0,t.length,!1);let r=new Uint8Array(8);return new DataView(r.buffer).setBigUint64(0,BigInt(e),!1),R(await un(h(S("calimero.recovery-backup.attest.v1\0"),o,t,r)))}async function da(n,e){let t=await un(S(JSON.stringify(e)));return R(await un(h(S("calimero.tee-attest.receipt-key.v2"),n,t)))}async function ua(n,e){let t=n.attestation;if(!t||typeof t.quote!="string")throw new Error("the file carries no attestation");if(t.cluster!==n.cluster||t.node!==n.node)throw new Error("the attestation is another node's");if(t.receiptKey!==n.signingKey)throw new Error("the attested key is not the one that signed the file");let o=await la(n.cluster,n.node);if(t.nonce!==o)throw new Error("the attestation is not over the recovery nonce");let r=await da(B(n.signingKey,"signing key",32),t.governance);if(!await e({quoteB64:t.quote,nonce:o,reportDataSuffix:r}))throw new Error("the quote was not accepted")}export{Eo as AGENT_ATTEST_DOMAIN,To as AGENT_PROVISION_INFO_DOMAIN,W as AgentGateError,pt as AppError,Je as ArgsTooLarge,et as BadOrigin,rn as CalimeroClient,f as CalimeroError,ot as ClusterNotUpgraded,ke as ConfirmCancelled,Ee as ConfirmPromptBlocked,ye as ConfirmRequired,Xe as ConsentStale,xt as DEFAULT_COLLATERAL_MIRROR,It as DEFAULT_DIRECTORY,js as DEFAULT_ORG_CAPABILITIES,He as DEFAULT_RELEASE_MIRROR,Gt as DEFAULT_RETRY,D as DirectoryError,yo as FILE_PART_BYTES,rt as FeatureNotActive,Bn as GITHUB_RELEASES,Pn as HANDSHAKE_PATH,na as HPKE_AAD,ta as HPKE_INFO,Ye as IdempotencyMismatch,ln as KMS_RELEASE_SIGNER,F as LoginRequired,Wt as MAX_RECOVERY_NONCE_BYTES,Xt as MAX_REPORT_PAGE,Mn as MOCK_QUOTE_HEADER,Ut as NODE_RELEASE_SIGNER,ae as NodeTransport,ze as NotFound,nt as NotServing,sn as ORG_CAPABILITIES,se as OriginNotRegistered,tt as OriginTaken,ne as PRODUCTION_PROFILE,Qe as PasskeyUnknownHere,it as QuotaExceeded,Xn as RECOVERY_DOMAIN,No as RECOVERY_FORMAT,ao as RELEASE_VERIFIER,st as RecoveryNotReady,We as ReleaseDeadlineError,Ze as RuntimeTooOld,Pe as SEALED_CONTENT_TYPE,_n as SEALED_PATH,ea as SIGNING_LABEL,$ as SealedTransportError,at as SignUpRefused,_e as StaleTransportKeyError,ct as TrapError,Q as UnavailableError,re as WrongNode,Te as WrongRecoveryCode,Oo as agentKeyBinding,Xs as agentQuoteVerifier,cn as attestAgent,j as b64url,aa as backupPublicKey,Fr as browserPasskey,Co as checkOwner,Dn as claimedRelease,qt as cloudNodeReleaseUrl,Ue as compareVersions,tn as confirmationCode,gs as consentReturn,oe as createQuoteVerifier,Jt as createRouteClient,Qt as createRoutes,Tt as createSealedFetch,qr as createSignedReleaseVerifier,Rs as deployerKey,Ft as directoryTransport,me as errorFrom,Dt as fetchAttestedKey,Bt as fetchGithubNodeRelease,Ct as fetchNodeRelease,In as freshCollateral,z as fromB64url,As as frontendManifest,Hs as generateOwnerKey,he as holderKey,rp as holderRecoveryBody,op as newBackupKeyPair,Ht as newIdempotencyKey,cs as newRecoverySeed,ca as openDataKey,vs as orgCapabilities,wt as ownerPublicKey,ks as pageDeployment,en as pageQuery,ds as parseRecoverySeed,ve as passkeyConfirm,nn as pendingApprovalsFrom,Ts as presenceState,Qs as provisionAgent,So as provisionInfo,ys as publisherBindingBytes,so as publisherBindingMessage,$t as queryString,da as receiptKeyBinding,la as recoveryAttestationNonce,eo as recoveryMessage,us as recoveryPublicKey,ls as recoverySeedText,J as refusal,zs as releaseAgent,co as releaseConsent,io as releaseNotesUrl,Se as retryDelayMs,dt as routePath,Zt as signRecovery,$n as sseFrames,ro as stalledBy,Et as transportKeyBinding,Fe as trustSignedRelease,St as trustedMeasurementsFromReleases,fs as upgradeConsent,jo as validateAgentId,ua as verifyRecoveryAttestation,ia as verifyRecoveryHeader,po as verifyReleaseUrl,Ys as verifySignedAgentPolicy,Cn as verifySignedNodeRelease,hs as withdrawConsent};
9
9
  //# sourceMappingURL=index.browser.mjs.map