@calimero-network/mero-js 35.7.0 → 36.0.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
- var Ds=Object.defineProperty;var Is=(n,e,t)=>e in n?Ds(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var E=(n,e,t)=>Is(n,typeof e!="symbol"?e+"":e,t);function m(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function x(n,e,t){let r=n.trim();if(!/^[0-9a-fA-F]*$/.test(r)||r.length!==t*2)throw new Error(`${e} must be ${t*2} hex characters, got ${r.length}`);let o=new Uint8Array(t);for(let s=0;s<t;s+=1)o[s]=Number.parseInt(r.slice(s*2,s*2+2),16);return o}function Rr(n,e){let t=n.trim();if(!/^[0-9a-fA-F]*$/.test(t)||t.length%2!==0)throw new Error(`${e} must be an even number of hex characters`);let r=new Uint8Array(t.length/2);for(let o=0;o<r.length;o+=1)r[o]=Number.parseInt(t.slice(o*2,o*2+2),16);return r}function f(...n){let e=new Uint8Array(n.reduce((r,o)=>r+o.length,0)),t=0;for(let r of n)e.set(r,t),t+=r.length;return e}var Ks="Noise_NK_25519_AESGCM_SHA256",yn=32,$s=16,Ls=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),fn=class n{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(Ks),t=new Uint8Array(32);return t.set(e),new n(t)}async mixHash(e){this.h=await Vs(f(this.h,e))}async mixKey(e){let[t,r]=await Tr(this.ck,e);this.ck=t,this.k=await crypto.subtle.importKey("raw",r,"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:xr(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:xr(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),t}split(){return Tr(this.ck,new Uint8Array)}};async function jr(n,e,t){let r=await fn.initialize();await r.mixHash(e),await r.mixHash(n);let o=await I(t);return await r.mixHash(o.publicKey),await r.mixKey(await z(o.privateKey,n)),{message1:f(o.publicKey,await r.encryptAndHash(new Uint8Array)),async finish(i){if(i.length<yn+$s)throw new Error("Noise: message 2 is too short");let a=i.slice(0,yn);return await r.mixHash(a),await r.mixKey(await z(o.privateKey,a)),{payload:await r.decryptAndHash(i.slice(yn)),split:await r.split()}}}}async function I(n){if(!n){let r;try{r=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 o=new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey));return{privateKey:r.privateKey,publicKey:o}}let e=await crypto.subtle.importKey("pkcs8",f(Ls,n),{name:"X25519"},!0,["deriveBits"]),t=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Hs(t.x)}}async function z(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 xr(n){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(n),!1),e}async function Vs(n){return new Uint8Array(await crypto.subtle.digest("SHA-256",n))}async function hn(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 Tr(n,e){let t=await hn(n,e),r=await hn(t,new Uint8Array([1])),o=await hn(t,f(r,new Uint8Array([2])));return[r,o]}function Hs(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(t,r=>r.charCodeAt(0))}var Ur="/sealed/handshake",Cr="/sealed/v2/handshake",Br="/sealed/v2",Qe="application/vnd.calimero.sealed",gn=2,Gs=new TextEncoder().encode("calimero/sealed-http/v2"),ze=16,Fs=1+ze+8,zs=0,Qs=1,Js=2,Ys=1+64*1024+16,Ws=1024,Xs=6e4,Zs="calimero.tee-attest.transport-key.v1",ei=[101,204,205,304],Nr=new TextEncoder,Je=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},ee=class extends Error{constructor(t,r,o,s){super(o);this.status=t;this.code=r;this.retryAfterMs=s;this.name="SealedTransportError"}};async function mn(n,e){let t=await crypto.subtle.digest("SHA-256",f(Nr.encode(Zs),n,e));return new Uint8Array(t)}function wn(n){let e=new URL(n.baseUrl),t=e.pathname.replace(/\/+$/,""),r=`${e.origin}${t}`,o=n.fetch??((u,y)=>fetch(u,y)),s=typeof n.transportPublicKey=="function"?n.transportPublicKey:void 0,i=s?Promise.resolve().then(s):Promise.resolve(n.transportPublicKey);i.catch(()=>{});let a,p=async()=>{try{return await Or(o,r,await vr(i))}catch(u){if(!(u instanceof Je)||!s)throw u;return i=Promise.resolve().then(s),Or(o,r,await vr(i))}},l=async()=>{let u=a??d(void 0),y=await u;if(Date.now()<y.renewAt)return[y,u];let h=d(u);return[await h,h]},d=u=>{if(a===u){let y=p();a=y,y.catch(()=>{a===y&&(a=void 0)})}return a};return async(u,y)=>{let h=new Request(u,y),g=new URL(h.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 k=[];h.headers.forEach((q,F)=>k.push([F,q]));let B={method:h.method,path:g.pathname.slice(t.length)+g.search,headers:k},v=new Uint8Array(await h.arrayBuffer()),O=y?.signal??(u instanceof Request?u.signal:void 0),M=async q=>{let{requestId:F,header:ue,envelope:W}=await oi(q,B,v),$=await o(`${r}${Br}`,{method:"POST",headers:{"content-type":Qe},body:W,signal:O});if($.headers.get("content-type")!==Qe)throw await qr($);return ii($,q.responseKey,ue,F)},[Y,Re]=await l();try{return await M(Y)}catch(q){if(!(q instanceof ee)||q.code!=="unknown_session")throw q;return M(await d(Re))}}}async function vr(n){let e=await n;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function Or(n,e,t){try{return await Sr(n,e,t)}catch(r){if(!(r instanceof ee)||r.code!=="busy")throw r;return await new Promise(o=>setTimeout(o,r.retryAfterMs??1e3)),Sr(n,e,t)}}async function Sr(n,e,t){let r=await jr(t,Gs),o=await ti(n,e,f(new Uint8Array([gn]),t,r.message1));if(o.headers.get("content-type")!==Qe)throw await qr(o);let s=await pi(o,Ws);return ri(r,s)}async function ti(n,e,t){let r=s=>n(`${e}${s}`,{method:"POST",headers:{"content-type":Qe},body:t}),o=await r(Ur);return await ni(o)?(await o.body?.cancel(),r(Cr)):o}async function ni(n){if(n.status===404||n.status===405)return!0;if(n.status!==403)return!1;try{return(await n.clone().json())?.error?.code==="sealed_required"}catch{return!1}}async function ri(n,e){if(e[0]!==gn)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:r,split:o}=t;if(r.length!==ze+4)throw new Error("The handshake reply is malformed");let s=r.slice(0,ze),i=new DataView(r.buffer,r.byteOffset).getUint32(ze,!1),[a,p]=await Promise.all([crypto.subtle.importKey("raw",o[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",o[1],"AES-GCM",!1,["decrypt"])]);return o[0].fill(0),o[1].fill(0),{requestKey:a,responseKey:p,nextRequestId:1,renewAt:Date.now()+i*1e3-Xs,header(l){let d=new Uint8Array(Fs);return d[0]=gn,d.set(s,1),new DataView(d.buffer).setBigUint64(1+ze,BigInt(l),!1),d}}}async function oi(n,e,t){let r=n.nextRequestId;n.nextRequestId+=1;let o=n.header(r),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:Mr(r,0),additionalData:o},n.requestKey,si(e,t));return{requestId:r,header:o,envelope:f(o,new Uint8Array(s))}}function Mr(n,e){let t=new Uint8Array(12),r=new DataView(t.buffer);return r.setBigUint64(0,BigInt(n),!1),r.setUint32(8,e,!1),t}function si(n,e){let t=Nr.encode(JSON.stringify(n)),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,t.length,!1),f(r,t,e)}async function ii(n,e,t,r){if(!n.body)throw new Error("The sealed response has no body");let o=ai(n.body.getReader()),s=0,i=async()=>{let d=await o.next();if(!d)return null;let u;try{u=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Mr(r,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:u[0],data:u.slice(1)}},a=await i();if(!a||a.kind!==zs)throw new Error("The sealed response is malformed");let p=JSON.parse(new TextDecoder().decode(a.data));if(ei.includes(p.status))return await o.cancel(),new Response(null,{status:p.status,headers:p.headers});let l=new ReadableStream({async pull(d){try{let u=await i();u?u.kind===Qs?d.enqueue(u.data):u.kind===Js?(d.close(),await o.cancel()):d.error(new Error("The sealed response is malformed")):d.error(new Error("The sealed response was cut short"))}catch(u){d.error(u)}},cancel(){return o.cancel()}});return new Response(l,{status:p.status,headers:p.headers})}function ai(n){let e=new Uint8Array,t=async r=>{for(;e.length<r;){let{done:o,value:s}=await n.read();if(o)return!1;e=f(e,s)}return!0};return{async next(){if(!await t(4))return null;let r=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(r>Ys)throw await n.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await t(4+r))return null;let o=e.slice(4,4+r);return e=e.slice(4+r),o},cancel:()=>n.cancel()}}async function pi(n,e){if(!n.body)return new Uint8Array;let t=n.body.getReader(),r=new Uint8Array;for(;;){let{done:o,value:s}=await t.read();if(o)return r;if(r=f(r,s),r.length>e)throw await t.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function qr(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 Je;let r=Number(n.headers.get("retry-after")),o=Number.isFinite(r)&&r>0?Math.min(r,5)*1e3:void 0;return new ee(n.status,e,t,o)}var Dr=[{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"]}],Ir=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var ci="1.2.840.10045.2.1",li={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},ui={"P-256":32,"P-384":48},di={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function Kr(n,e,t){if(e+2>t)throw new Error("it is truncated");let r=n[e];if((r&31)===31)throw new Error("it uses a tag this parser does not read");let o=n[e+1],s=e+2;if(o&128){let a=o&127;if(a===0||a>4||s+a>t)throw new Error("it has a length this parser does not read");o=0;for(let p=0;p<a;p+=1)o=o*256+n[s+p];s+=a}let i=s+o;if(i>t)throw new Error("it is truncated");return{tag:r,bytes:n,offset:e,start:s,end:i}}function Te(n){let e=Kr(n,0,n.length);if(e.end!==n.length)throw new Error("it has trailing bytes");return e}function N(n){let e=[];for(let t=n.start;t<n.end;){let r=Kr(n.bytes,t,n.end);e.push(r),t=r.end}return e}function _(n,e,t){if(!n||n.tag!==e)throw new Error(`${t} is not where it should be`);return n}function te(n){return n.bytes.slice(n.start,n.end)}function At(n){return n.bytes.slice(n.offset,n.end)}function xe(n){let e=te(_(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=[],r=0;for(let i of e)r=r*128+(i&127),i&128||(t.push(r),r=0);let o=t.shift();return[...o<80?[Math.floor(o/40),o%40]:[2,o-80],...t].join(".")}function yi(n){let e=new TextDecoder().decode(te(n)),t=n.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,r=n.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,o=t??r;if(!o)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let s=Number(o[1]);t&&(s+=s<50?2e3:1900);let[i,a,p,l,d]=o.slice(2).map(Number);return Date.UTC(s,i-1,a,p,l,d)}function bn(n){try{let[e,t,r,...o]=N(_(Te(n),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let s=N(_(e,48,"The signed part")),i=s[0]?.tag===160?1:0,[a,p,l,d,u,y,...h]=s.slice(i);_(a,2,"The serial number");let g=xe(N(_(t,48,"The signature algorithm"))[0]);if(xe(N(_(p,48,"The signature algorithm"))[0])!==g)throw new Error("it names two different signature algorithms");let B=di[g];if(!B)throw new Error(`it is signed with ${g}, not ECDSA with SHA-256 or SHA-384`);let[v,O]=N(_(d,48,"The validity")).map(yi);if(O===void 0)throw new Error("its validity is incomplete");let[M,Y]=N(_(y,48,"The public key"));_(Y,3,"The public key");let[Re,q]=N(_(M,48,"The key algorithm"));if(xe(Re)!==ci)throw new Error("its key is not an elliptic-curve key");let F=li[xe(q)];if(!F)throw new Error("its key is on a curve other than P-256 or P-384");let ue=new Map,W=h.find(de=>de.tag===163);if(W){let[de]=N(W);for(let mt of N(_(de,48,"The extensions"))){let L=N(_(mt,48,"An extension"));if(L.length===3)_(L[1],1,"An extension's critical flag");else if(L.length!==2)throw new Error("it has a malformed extension");let Ge=xe(L[0]);if(ue.has(Ge))throw new Error(`it has extension ${Ge} twice`);ue.set(Ge,te(_(L[L.length-1],4,"An extension value")))}}let $=te(_(r,3,"The signature"));if($[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:n,tbs:At(e),signatureHash:B,signature:$.slice(1),issuer:At(_(l,48,"The issuer")),subject:At(_(u,48,"The subject")),notBefore:v,notAfter:O,spki:At(y),curve:F,extensions:ue}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function $r(n){return N(_(Te(n),48,"The list")).map(xe)}function hi(n,e){let t=ui[e],r=N(_(Te(n),48,"The signature"));if(r.length!==2)throw new Error("The signature is not an ECDSA signature");let o=new Uint8Array(t*2);return r.forEach((s,i)=>{let a=te(_(s,2,"The signature"));if(a.length===0||a[0]&128)throw new Error("The signature is not an ECDSA signature");for(;a.length>1&&a[0]===0;)a=a.subarray(1);if(a.length>t)throw new Error("The signature is not an ECDSA signature");o.set(a,i*t+t-a.length)}),o}async function kt(n,e,t,r,o){let s;try{s=hi(r,e)}catch{return!1}let i=await crypto.subtle.importKey("spki",n,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:t},i,s,o)}function V(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 r=atob(t),o=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)o[s]=r.charCodeAt(s);return o}function Pn(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 V(t[0][1],e)}var fi="2.5.29.17",gi="2.5.29.37",mi="1.3.6.1.5.5.7.3.3",wi="1.3.6.1.4.1.57264.1.8",bi="1.3.6.1.4.1.57264.1.1",Pi=134,Ai=12,ki=48,_i=new TextEncoder,je=n=>new TextDecoder().decode(n);async function _t(n,e,t,r){let{base64Signature:o,cert:s,rekorBundle:i}=Ti(e),a=i.Payload;if(r!==void 0&&r.trim()!==o.trim())throw new Error("The detached signature is not the one in the bundle");let p=V(o,"The bundle signature"),l=Pn(je(V(s,"The bundle certificate")),"The bundle certificate"),d=bn(l),u=Ir.find(O=>O.logId===a.logID.toLowerCase());if(!u)throw new Error(`The bundle names Rekor log ${a.logID}, which the Sigstore trust root does not know`);let y=_i.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await kt(V(u.publicKey,"The Rekor key"),"P-256","SHA-256",V(i.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=a.integratedTime*1e3;if(!Hr(g,u.validFor))throw new Error(`Rekor log ${u.baseUrl} was not in use at ${Ye(g)}, when the entry says it was logged`);let k=ji(a.body),B=m(new Uint8Array(await crypto.subtle.digest("SHA-256",n)));if(k.hash!==B)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!An(V(k.signature,"The logged signature"),p))throw new Error("The bundle's signature is not the one Rekor logged");let v=Pn(je(V(k.publicKey,"The logged certificate")),"The logged certificate");if(!An(v,l))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await kt(d.spki,"P-256","SHA-256",p,n))throw new Error("The signature over the file does not verify with the bundle's certificate");return await Ei(d,g),xi(d,t),{integratedTime:a.integratedTime}}async function Ei(n,e){if(!Vr(n,e))throw new Error(`The signing certificate was valid ${Ye(n.notBefore)} to ${Ye(n.notAfter)}, not at ${Ye(e)} when Rekor logged it`);let t=[];for(let r of Dr){let o=r.certChain.map(i=>bn(V(i,"A Fulcio certificate")));if(!await Lr(n,o[0]))continue;let s=await Ri(o,r.validFor,e);if(!s)return;t.push(`${r.uri} (valid from ${r.validFor.start}): ${s}`)}throw new Error(t.length>0?`The signing certificate's CA is not trusted at ${Ye(e)}: ${t.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function Ri(n,e,t){if(!Hr(t,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of n.entries()){if(!Vr(o,t))return`its certificate ${r} was not valid then`;let s=n[r+1]??o;if(!await Lr(o,s))return`its certificate ${r} is not signed by the next`}}async function Lr(n,e){return An(n.issuer,e.subject)?kt(e.spki,e.curve,n.signatureHash,n.signature,n.tbs):!1}function xi(n,e){let t=n.extensions.get(fi);if(!t)throw new Error("The signing certificate names no identity");let r=N(_(Te(t),ki,"The subject alternative name")),o=r.filter(l=>l.tag===Pi).map(l=>je(te(l)));if(o.length!==1||r.length!==1||o[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(o.length===1?o[0]:o)}, not by ${e.identity}`);let s=n.extensions.get(wi),i=n.extensions.get(bi),a=s?je(te(_(Te(s),Ai,"The OIDC issuer"))):i?je(i):void 0;if(a!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${a===void 0?"missing":JSON.stringify(a)}, not ${e.issuer}`);let p=n.extensions.get(gi);if(!p||!$r(p).includes(mi))throw new Error("The signing certificate is not for code signing")}function Ti(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,r=t?.rekorBundle?.Payload;if(!(typeof t?.base64Signature=="string"&&typeof t.cert=="string"&&typeof t.rekorBundle?.SignedEntryTimestamp=="string"&&typeof r?.body=="string"&&typeof r.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(r.logID)&&Number.isSafeInteger(r.integratedTime)&&r.integratedTime>=0&&Number.isSafeInteger(r.logIndex)&&r.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return t}function ji(n){let e;try{e=JSON.parse(je(V(n,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let t=e?.spec?.data?.hash,r=e?.spec?.signature;if(e?.kind!=="hashedrekord"||t?.algorithm!=="sha256"||typeof t.value!="string"||typeof r?.content!="string"||typeof r.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:t.value.toLowerCase(),signature:r.content,publicKey:r.publicKey.content}}function Vr(n,e){return n.notBefore<=e&&e<=n.notAfter}function Hr(n,e){return Date.parse(e.start)<=n&&(e.end===void 0||n<=Date.parse(e.end))}function Ye(n){return new Date(n).toISOString()}function An(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var vi=/^[0-9a-f]{96}$/,Oi=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function fe(n){let e=ve(n.allowedMrtd??[],"allowedMrtd"),t=(n.allowedMeasurements??[]).map((a,p)=>{let l=`allowedMeasurements[${p}]`;return Oi.map(d=>ve([a?.[d]??""],`${l}.${d}`)[0]).join()}),r=[ve(n.allowedRtmr0??[],"allowedRtmr0"),ve(n.allowedRtmr1??[],"allowedRtmr1"),ve(n.allowedRtmr2??[],"allowedRtmr2"),ve(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(r.slice(1).some(a=>a.length===0))throw new Error("allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too")}let o=n.allowedTcbStatuses??["UpToDate"],s=n.now??Date.now;return Object.assign(async({quoteB64:a,nonce:p,reportDataSuffix:l,collateral:d})=>{let u=Ui(a),y=d??await n.fetchCollateral?.(u);if(!y)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let h;try{h=n.dcapVerify(u,y,Math.floor(s()/1e3))}catch(v){throw new Error(`The quote did not verify: ${v?.message??String(v)}`)}if(h.status==="Revoked"||!o.includes(h.status))throw new Error(`The platform's TCB status is ${h.status}, which is not accepted`);let g=Si(h.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 k=[g.mrTd,g.rtMr0,g.rtMr1,g.rtMr2,g.rtMr3].map(v=>m(v));if(t.length>0&&!t.includes(k.join()))throw new Error(`The measurements (MRTD ${k[0]}, RTMR0-3 ${k.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(k[0]))throw new Error(`MRTD ${k[0]} is not an image this verifier trusts`);if([g.rtMr0,g.rtMr1,g.rtMr2,g.rtMr3].forEach((v,O)=>{let M=r[O];if(M.length>0&&!M.includes(m(v)))throw new Error(`RTMR${O} ${m(v)} is not one this verifier trusts`)}),m(g.reportData)!==`${p}${l}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function ve(n,e){return n.map(t=>{let r=t.trim().toLowerCase();if(!vi.test(r))throw new Error(`${e} holds ${JSON.stringify(t)}, which is not a 48-byte hex measurement`);return r})}function Si(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 Ui(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}var Ci=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],he="locked-read-only";function kn(n,{profile:e,allowDebugProfile:t=!1}){if(n.length===0)throw new Error("No release given, so no image would be trusted");let r,o=n.map((s,i)=>{let a=s?.tag??`releases[${i}]`;if(s?.role!==void 0&&s.role!=="node")throw new Error(`${a} lists the measurements of a ${s.role}, not of a node image`);let p=s?.profiles?.[e];if(!p){let d=Object.keys(s?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${d})`)}if(e!==he&&!t)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(he)}, or pass allowDebugProfile to test`);let l=(p.allowed_tcb_statuses??["uptodate"]).map(d=>Bi(d,a));return r=r===void 0?l:r.filter(d=>l.includes(d)),{mrtd:p.mrtd,rtmr0:p.rtmr0,rtmr1:p.rtmr1,rtmr2:p.rtmr2,rtmr3:p.rtmr3}});if(!r||r.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:o,allowedTcbStatuses:r}}function Bi(n,e){let t=Ci.find(r=>r.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 _n=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"}),Ni=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],Et="https://cloud.calimero.network",En=`${Et}/api/tee/pcs`;async function Fr(n,e,t={}){let r=typeof n=="string"?new TextEncoder().encode(n):n;await _t(r,e,{identity:t.identity??_n.identity,issuer:t.issuer??_n.issuer},t.signature);let o;try{o=JSON.parse(new TextDecoder().decode(r))}catch{throw new Error("The signed release is not JSON")}if(o?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(o?.role)} release, not a node one`);let s=Object.values(o.profiles??{}),i=a=>Ni.every(p=>/^[0-9a-f]{96}$/i.test(String(a?.[p])));if(typeof o.tag!="string"||s.length===0||!s.every(i))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(t.expectedVersion!==void 0&&o.tag!==t.expectedVersion)throw new Error(`The signed release is ${o.tag}, not ${t.expectedVersion}`);return o}async function Rn(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 r;try{r=(await t.json())?.data}catch{throw new Error(`${n} did not answer with JSON`)}if(typeof r?.version!="string"||typeof r.publishedMrtds!="string"||typeof r.bundle!="string")throw new Error(`${n} did not answer with a signed node release`);return{version:r.version,publishedMrtds:r.publishedMrtds,bundle:r.bundle}}var zr="https://github.com/calimero-network/mero-tee/releases/download";async function xn(n,e={}){let t=`mero-tee-v${ne(n,"version")}`,r=`${(e.base??zr).replace(/\/+$/,"")}/${t}/published-mrtds.json`,o=async a=>{let p=await(e.fetch??fetch)(a);if(!p.ok)throw new Error(`Fetching ${a} failed: HTTP ${p.status}`);return p.text()},[s,i]=await Promise.all([o(r),o(`${r}.bundle.json`)]);return{version:n,publishedMrtds:s,bundle:i}}function Tn(n,e){return`${n.replace(/\/+$/,"")}/api/tee/node-releases/${ne(e,"version")}`}async function Rt(n){let e=ne(n.minReleaseVersion,"minReleaseVersion"),t=ne(n.release?.version,"The release version"),r=await Fr(n.release.publishedMrtds,n.release.bundle,{expectedVersion:t,identity:n.identity,issuer:n.issuer});if(We(t,e)<0)throw new Error(`Release ${t} is older than the minimum trusted, ${e}`);return kn([r],{profile:n.profile,allowDebugProfile:n.allowDebugProfile})}function Mi(n){return ne(n.minReleaseVersion,"minReleaseVersion"),Object.assign(async t=>{let r=await Rt({release:await n.release(),profile:n.profile,allowDebugProfile:n.allowDebugProfile,minReleaseVersion:n.minReleaseVersion,identity:n.identity,issuer:n.issuer});return fe({dcapVerify:n.dcapVerify,fetchCollateral:n.fetchCollateral,now:n.now,...r})(t)},{includeCollateral:!0})}var Qr=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ne(n,e){let t=typeof n=="string"?Qr.exec(n):null,r=t?.[4];if(!t||r!==void 0&&r.split(".").some(o=>o===""))throw new Error(`${e} is ${JSON.stringify(n)}, not a release version like 2.3.87`);return n}function We(n,e){let[t,r]=Gr(n),[o,s]=Gr(e);for(let p=0;p<3;p+=1)if(t[p]!==o[p])return t[p]<o[p]?-1:1;if(r===void 0||s===void 0)return r===s?0:r===void 0?1:-1;let i=r.split("."),a=s.split(".");for(let p=0;p<Math.max(i.length,a.length);p+=1){let[l,d]=[i[p],a[p]];if(l===void 0||d===void 0)return l===void 0?-1:1;let[u,y]=[/^\d+$/.test(l),/^\d+$/.test(d)],h=u&&y?Math.sign(Number(l)-Number(d)):u!==y?u?-1:1:l<d?-1:l>d?1:0;if(h!==0)return h}return 0}function Gr(n){let e=Qr.exec(n);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var Yr="MOCK_TDX_QUOTE_V1";function qi(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function jn(n,e){if(n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r++)t|=n[r]^e[r];return t===0}var Jr;async function vn(n){Jr??(Jr=import("@phala/dcap-qvl"));let e=await Jr,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 Wr(n,e){let t=ne(e,"minReleaseVersion"),r=String(n.release?.version??"").trim().replace(/^mero-tee-v/,"").replace(/^v/,""),o=ne(r,"The release the node names");if(We(o,t)<0)throw new Error(`mero-tee release ${o} is older than the minimum ${t}`);return o}var ge=class extends Error{constructor(t,r,o){super(r?`${t} answered HTTP ${r}`:`${t} could not be reached: ${o?.message}`);this.host=t;this.status=r;this.cause=o}};function Xe(n,e){return e instanceof TypeError?new ge(n,void 0,e):e}var Xr=n=>n===429||n>=500;function Di(n,e){return async(t,r)=>{let o=await n(t,r).catch(i=>{throw Xe(e,i)});if(Xr(o.status))throw new ge(e,o.status);let s=await o.arrayBuffer().catch(i=>{throw Xe(e,i)});return new Response(s,o)}}async function Ii(n,e,t){let r=e.releaseSource;if(typeof r=="function")return r(n);let o=Di(t,"the release mirror");return r==="github"?xn(n,{fetch:o}):Rn(Tn(r??Et,n),{fetch:o})}function Ki(n){let e=n.collateralSource??En;return e==="intel"?async t=>(await vn("getCollateralFromPcs"))(t).catch(o=>{throw Xe("Intel PCS",o)}):(new URL(e),async t=>(await vn("getCollateral"))(e,t).catch(o=>{throw Xe(e,o)}))}function Zr(n,e){let t=e.maxCollateralAgeDays;return t===void 0?n:async r=>{let o=await n(r),s;try{s=Date.parse(JSON.parse(o.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 i=((e.now??Date.now)()-s)/864e5;if(i>t)throw new Error(`The quote's collateral was issued ${Math.floor(i)} days ago, more than the ${t} this client accepts`);return o}}async function $i(n,e,t,r){let o=Wr(n,t.minReleaseVersion),s=t.profile??he,i=await Ii(o,t,r);if(i.version!==o)throw new Error(`The node names mero-tee release ${o}, but the release served is ${i.version}`);let a=await Rt({release:i,profile:s,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer}),p=Zr(t.fetchCollateral??Ki(t),t);return await fe({dcapVerify:t.dcapVerify??await vn("verify"),fetchCollateral:p,now:t.now,...a})(e)?{release:o,profile:s}:void 0}async function xt(n,e,t,r,o,s=(i,a)=>fetch(i,a)){let i=qi(n.quote),a=new TextEncoder().encode(Yr);if(jn(i.slice(0,a.length),a)){if(!r.allowMock)throw new Error("mock quote refused: this client only trusts real TEEs");let d=i.slice(a.length,a.length+64);if(!jn(d.slice(0,32),e)||!jn(d.slice(32),t))throw new Error(`the quote does not bind this ${o} and nonce`);return{mock:!0}}let p={quoteB64:n.quote,nonce:m(e),reportDataSuffix:m(t)},l;if(r.verifyQuote)l=await r.verifyQuote(p)?{}:void 0;else if(r.release)l=await $i(n,p,r.release,s);else throw new Error("real quote refused: this client trusts no TD image (set policy.release)");if(!l)throw new Error(`The attestation did not verify, so its ${o} is not trusted`);return{mock:!1,...l}}async function Li(n,e,t=(r,o)=>fetch(r,o)){return(await me(n,e,t)).key}function Vi(n,e){let t=x(n.appHash,"appHash",32);if(t.every(r=>r===0))throw new Error("The node bound no app: its app hash is all zero");if(e.appHash&&m(t)!==e.appHash.toLowerCase())throw new Error(`The node's app hash ${m(t)} is not the pinned ${e.appHash}`);return t}async function me(n,e,t=(r,o)=>fetch(r,o)){let r=n.replace(/\/+$/,""),o=m(crypto.getRandomValues(new Uint8Array(32))),s=new URL(`${r}/attestation`);s.searchParams.set("nonce",o),e.app?s.searchParams.set("app",e.app):e.appHash&&s.searchParams.set("appHash",e.appHash);let i=await t(s.toString());if(Xr(i.status))throw new ge("the node",i.status);if(!i.ok)throw new Error(`The node refused to attest: HTTP ${i.status}`);let a=await i.json().catch(g=>{throw Xe("the node",g)}),p=x(a.transportKey,"transportKey",32),l=e.app?Vi(a,e):void 0,d=l??(e.appHash?x(e.appHash,"appHash",32):new Uint8Array(32)),u=await mn(d,p),y=await xt(a,x(o,"nonce",32),u,e,"transport key",t),h={url:r,...y,...l?{appHash:m(l)}:{},checkedAt:Date.now()};return{key:p,verification:h}}var On="https://manager.cloud.calimero.network/api/directory";var Q=class extends Error{constructor(t,r,o,s,i){super(`directory for cluster ${t}: ${o}`);this.cluster=t;this.reason=r;this.status=s;this.cause=i;this.name="DirectoryError"}};function Hi(n,e){return`${n.replace(/\/+$/,"")}/${encodeURIComponent(e)}`}async function Sn(n,e,t){let r;try{r=await t(Hi(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(r.status===404)throw new Q(e,"not-found","unknown cluster",404);if(!r.ok)throw new Q(e,"unreachable",`answered ${r.status}`,r.status);let o;try{o=await r.json()}catch(d){throw new Q(e,"bad-response","answered something other than JSON",r.status,d)}let s=o;if(!s||typeof s!="object"||!Array.isArray(s.nodes))throw new Q(e,"bad-response","answered no node list",r.status);let i=[],a=new Set;for(let d of s.nodes){let u=Gi(d);u&&!a.has(u.url)&&(a.add(u.url),i.push(u))}if(i.length===0)throw new Q(e,"empty","lists no usable node",r.status);let p=s.refreshAfterSeconds,l=typeof p=="number"&&Number.isFinite(p)&&p>=1?p:60;return{nodes:i,refreshAfterSeconds:l}}function Gi(n){if(!n||typeof n!="object")return;let{url:e,zone:t,weight:r}=n;if(typeof e!="string"||typeof r!="number"||!Number.isInteger(r)||r<1)return;let o;try{o=new URL(e)}catch{return}if(!(o.protocol!=="https:"&&o.protocol!=="http:"))return{url:e.replace(/\/+$/,""),zone:typeof t=="string"?t:void 0,weight:r}}function Un(n,e,t){let r=e===void 0?[]:n.filter(s=>s.zone===e),o=e===void 0?n:n.filter(s=>s.zone!==e);return[...eo(r,t),...eo(o,t)]}function eo(n,e){let t=[...n],r=[];for(;t.length>0;){let o=e()*t.reduce((i,a)=>i+a.weight,0),s=0;for(;s<t.length-1&&o>=t[s].weight;)o-=t[s++].weight;r.push(t.splice(s,1)[0].url)}return r}var b=class extends Error{constructor(t,r,o,s={}){super(`${t} ${r}: ${o}`);this.status=t;this.code=r;this.details=s;this.name="CalimeroError"}},re=class extends b{constructor(e,t={}){super(401,"UNAUTHENTICATED",e,t),this.name="LoginRequired"}},Tt=class extends b{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"}},we=class extends b{constructor(e,t={}){super(421,"WRONG_NODE",e,t),this.name="WrongNode"}},Oe=class extends b{constructor(e,t={}){super(404,"NOT_FOUND",e,t),this.name="NotFound"}},Se=class extends b{constructor(e,t={}){super(412,"CONFIRM_REQUIRED",e,t),this.name="ConfirmRequired"}},Ze=class extends Error{constructor(t){super("the passkey confirmation was cancelled");this.cause=t;this.name="ConfirmCancelled"}},et=class extends Error{constructor(t){super("the passkey prompt was blocked by the browser or a password manager");this.cause=t;this.name="ConfirmPromptBlocked"}},jt=class extends b{constructor(e,t={}){super(413,"ARGS_TOO_LARGE",e,t),this.name="ArgsTooLarge"}},vt=class extends b{constructor(e,t={}){super(409,"IDEMPOTENCY_MISMATCH",e,t),this.name="IdempotencyMismatch"}},Ot=class extends b{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:""}},St=class extends b{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:[]}},Ut=class extends b{constructor(e,t={}){super(409,"CONSENT_STALE",e,t),this.name="ConsentStale"}},be=class extends b{constructor(e,t={}){let r=typeof t.origin=="string"?t.origin:"",o=typeof t.package=="string"?t.package:"",s=r?`this site (${r})`:"this site";super(403,"ORIGIN_NOT_REGISTERED",`${s} is not registered for ${o||"any package"}${e?` (${e})`:""}`,t),this.name="OriginNotRegistered",this.origin=r,this.package=o,this.nodeMessage=e}},Ct=class extends b{constructor(e,t,r={}){super(400,e,t,r),this.name="BadOrigin"}},Bt=class extends b{constructor(e,t={}){super(409,"ORIGIN_TAKEN",e,t),this.name="OriginTaken"}},Nt=class extends b{constructor(e,t={}){super(400,"NOT_SERVING",e,t),this.name="NotServing"}},Mt=class extends b{constructor(e,t={}){super(409,"CLUSTER_NOT_UPGRADED",e,t),this.name="ClusterNotUpgraded"}},qt=class extends b{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:""}},Dt=class extends b{constructor(e,t={}){super(409,"RECOVERY_NOT_READY",e,t),this.name="RecoveryNotReady",this.readyAt=typeof t.readyAt=="number"?t.readyAt:void 0}},tt=class extends b{constructor(e,t={}){super(401,"UNAUTHENTICATED",e||"unknown or used recovery code",t),this.name="WrongRecoveryCode"}},It=class extends b{constructor(e,t={}){super(403,"SIGN_UP_REFUSED",e,t),this.name="SignUpRefused",this.reason=Fi(e)}};function Fi(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 Kt=class extends b{constructor(e,t={}){super(429,"QUOTA_EXCEEDED",e,t),this.name="QuotaExceeded"}},$t=class extends b{constructor(e,t={}){super(422,"APP_ERROR",e,t),this.name="AppError";let{appCode:r,fields:o}=zi(t);this.appCode=r,this.fields=o}},Lt=class extends b{constructor(e,t={}){super(422,"TRAP",e,t),this.name="TrapError",this.kind=typeof t.kind=="string"?t.kind:""}},oe=class extends b{constructor(e,t,r={},o,s){super(503,e,t,r),this.name="UnavailableError",this.reason=e.toLowerCase(),this.committed=e==="TIMEOUT"||e==="MIGRATING"?!1:"unknown",this.retryAfter=o,this.cause=s}};function Vt(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function zi(n){let e=typeof n.code=="string"?n:Vt(n.error);return{appCode:typeof e.code=="string"?e.code:"",fields:{...Vt(e.fields)}}}function Qi(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 Ue(n,e,t){let r=Vt(e),o=typeof r.error=="string"?r.error:"ERROR",s=typeof r.message=="string"?r.message:"",i=Vt(r.details);if(n===503)return new oe(o,s,i,Qi(i,t));switch(`${n} ${o}`){case"401 UNAUTHENTICATED":return new re(s,i);case"401 PASSKEY_UNKNOWN_HERE":return new Tt(s,i);case"421 WRONG_NODE":return new we(s,i);case"404 NOT_FOUND":return new Oe(s,i);case"409 IDEMPOTENCY_MISMATCH":return new vt(s,i);case"409 RELEASE_DEADLINE":return new Ot(s,i);case"409 RUNTIME_TOO_OLD":return new St(s,i);case"409 CONSENT_STALE":return new Ut(s,i);case"403 ORIGIN_NOT_REGISTERED":return new be(s,i);case"400 BAD_ORIGIN":case"400 BAD_RP_ID":return new Ct(o,s,i);case"409 ORIGIN_TAKEN":return new Bt(s,i);case"400 NOT_SERVING":return new Nt(s,i);case"409 CLUSTER_NOT_UPGRADED":return new Mt(s,i);case"409 FEATURE_NOT_ACTIVE":return new qt(s,i);case"429 QUOTA_EXCEEDED":return new Kt(s,i);case"409 RECOVERY_NOT_READY":return new Dt(s,i);case"403 SIGN_UP_REFUSED":return new It(s,i);case"412 CONFIRM_REQUIRED":return new Se(s,i);case"413 ARGS_TOO_LARGE":return new jt(s,i);case"422 APP_ERROR":return new $t(s,i);case"422 TRAP":return new Lt(s,i);default:return new b(n,o,s,i)}}function R(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function C(n){let e=n.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((n.length+3)%4),t=atob(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}var nt=n=>n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);function Cn(n){let e=new Error(n);return e.name="NotAllowedError",e}async function to(n,e,t,r){let o=navigator.credentials,i=globalThis.CredentialsContainer?.prototype?.[n]??o[n];try{return await i.call(o,t?{...e,signal:t}:e)}catch(a){throw t?.aborted||a?.name==="AbortError"?Object.assign(Cn(`${r} was cancelled`),{cause:a}):a}}function Ji(n){let e=n.filter(t=>t.alg===-7);return e.length?e:n}function Yi(){return{async create(n,e){let t=n,r=await to("create",{publicKey:{challenge:nt(C(t.challenge)),rp:t.rp,user:{...t.user,id:nt(C(t.user.id))},pubKeyCredParams:Ji(t.pubKeyCredParams),excludeCredentials:(t.excludeCredentials??[]).map(s=>({type:s.type,id:nt(C(s.id))})),authenticatorSelection:t.authenticatorSelection,attestation:"none",timeout:t.timeout}},e?.signal,"passkey creation");if(!r)throw Cn("passkey creation was cancelled");let o=r.response;return{attestationObject:R(new Uint8Array(o.attestationObject)),clientDataJson:R(new Uint8Array(o.clientDataJSON))}},async get(n,e,t,r){let o=await to("get",{publicKey:{challenge:nt(n),rpId:e,userVerification:r?.userVerification??"preferred",allowCredentials:(t??[]).map(i=>({type:"public-key",id:nt(C(i))}))}},r?.signal,"passkey sign-in");if(!o)throw Cn("passkey sign-in was cancelled");let s=o.response;return{credentialId:R(new Uint8Array(o.rawId)),authenticatorData:R(new Uint8Array(s.authenticatorData)),clientDataJson:R(new Uint8Array(s.clientDataJSON)),signature:R(new Uint8Array(s.signature))}}}}function Wi(n,e){return n==="required"||n==="preferred"||n==="discouraged"?n:e}function Xi(n){let e=n,t=e?.name,r=typeof e?.message=="string"?e.message:"";return t==="InvalidStateError"||/not focused|already pending/i.test(r)?new et(n):t==="NotAllowedError"||t==="AbortError"?new Ze(n):n}function rt(n,e={}){return async t=>{try{return await n.get(C(t.challenge),t.rpId,t.allowCredentials,{userVerification:Wi(t.userVerification,e.userVerification??"required"),...e.signal?{signal:e.signal}:{}})}catch(r){throw Xi(r)}}}var Nn={retries:6,baseDelayMs:200,maxDelayMs:2e3};function st(n,e){return Math.min(e.baseDelayMs*2**n,e.maxDelayMs)}function Zi(n){return n instanceof ee&&n.status===413?Ue(413,{error:"TOO_LARGE",message:n.message.replace(/^Sealed request refused: /,"")}):n}async function se(n){let e=await n.text().catch(()=>""),t={};try{t=e?JSON.parse(e):{}}catch{t={message:e}}return Ue(n.status,t,n.headers.get("retry-after"))}async function*ro(n){let e=n.getReader(),t=new TextDecoder,r="";for(;;){let{value:o,done:s}=await e.read();if(s)return;r+=t.decode(o,{stream:!0});let i;for(;(i=r.indexOf(`
1
+ var qs=Object.defineProperty;var Ds=(n,e,t)=>e in n?qs(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var E=(n,e,t)=>Ds(n,typeof e!="symbol"?e+"":e,t);function m(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function x(n,e,t){let r=n.trim();if(!/^[0-9a-fA-F]*$/.test(r)||r.length!==t*2)throw new Error(`${e} must be ${t*2} hex characters, got ${r.length}`);let o=new Uint8Array(t);for(let s=0;s<t;s+=1)o[s]=Number.parseInt(r.slice(s*2,s*2+2),16);return o}function Rr(n,e){let t=n.trim();if(!/^[0-9a-fA-F]*$/.test(t)||t.length%2!==0)throw new Error(`${e} must be an even number of hex characters`);let r=new Uint8Array(t.length/2);for(let o=0;o<r.length;o+=1)r[o]=Number.parseInt(t.slice(o*2,o*2+2),16);return r}function f(...n){let e=new Uint8Array(n.reduce((r,o)=>r+o.length,0)),t=0;for(let r of n)e.set(r,t),t+=r.length;return e}var Is="Noise_NK_25519_AESGCM_SHA256",yn=32,Ks=16,$s=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),fn=class n{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(Is),t=new Uint8Array(32);return t.set(e),new n(t)}async mixHash(e){this.h=await Vs(f(this.h,e))}async mixKey(e){let[t,r]=await Tr(this.ck,e);this.ck=t,this.k=await crypto.subtle.importKey("raw",r,"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:xr(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:xr(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),t}split(){return Tr(this.ck,new Uint8Array)}};async function jr(n,e,t){let r=await fn.initialize();await r.mixHash(e),await r.mixHash(n);let o=await I(t);return await r.mixHash(o.publicKey),await r.mixKey(await z(o.privateKey,n)),{message1:f(o.publicKey,await r.encryptAndHash(new Uint8Array)),async finish(i){if(i.length<yn+Ks)throw new Error("Noise: message 2 is too short");let a=i.slice(0,yn);return await r.mixHash(a),await r.mixKey(await z(o.privateKey,a)),{payload:await r.decryptAndHash(i.slice(yn)),split:await r.split()}}}}async function I(n){if(!n){let r;try{r=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 o=new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey));return{privateKey:r.privateKey,publicKey:o}}let e=await crypto.subtle.importKey("pkcs8",f($s,n),{name:"X25519"},!0,["deriveBits"]),t=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Ls(t.x)}}async function z(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 xr(n){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(n),!1),e}async function Vs(n){return new Uint8Array(await crypto.subtle.digest("SHA-256",n))}async function hn(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 Tr(n,e){let t=await hn(n,e),r=await hn(t,new Uint8Array([1])),o=await hn(t,f(r,new Uint8Array([2])));return[r,o]}function Ls(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(t,r=>r.charCodeAt(0))}var Ur="/sealed/handshake",Cr="/sealed",Qe="application/vnd.calimero.sealed",gn=2,Hs=new TextEncoder().encode("calimero/sealed-http/v2"),ze=16,Gs=1+ze+8,Fs=0,zs=1,Qs=2,Js=1+64*1024+16,Ys=1024,Ws=6e4,Xs="calimero.tee-attest.transport-key.v1",Zs=[101,204,205,304],Br=new TextEncoder,Je=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},ee=class extends Error{constructor(t,r,o,s){super(o);this.status=t;this.code=r;this.retryAfterMs=s;this.name="SealedTransportError"}};async function mn(n,e){let t=await crypto.subtle.digest("SHA-256",f(Br.encode(Xs),n,e));return new Uint8Array(t)}function wn(n){let e=new URL(n.baseUrl),t=e.pathname.replace(/\/+$/,""),r=`${e.origin}${t}`,o=n.fetch??((u,y)=>fetch(u,y)),s=typeof n.transportPublicKey=="function"?n.transportPublicKey:void 0,i=s?Promise.resolve().then(s):Promise.resolve(n.transportPublicKey);i.catch(()=>{});let a,p=async()=>{try{return await Or(o,r,await vr(i))}catch(u){if(!(u instanceof Je)||!s)throw u;return i=Promise.resolve().then(s),Or(o,r,await vr(i))}},l=async()=>{let u=a??d(void 0),y=await u;if(Date.now()<y.renewAt)return[y,u];let h=d(u);return[await h,h]},d=u=>{if(a===u){let y=p();a=y,y.catch(()=>{a===y&&(a=void 0)})}return a};return async(u,y)=>{let h=new Request(u,y),g=new URL(h.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 A=[];h.headers.forEach((q,F)=>A.push([F,q]));let B={method:h.method,path:g.pathname.slice(t.length)+g.search,headers:A},v=new Uint8Array(await h.arrayBuffer()),O=y?.signal??(u instanceof Request?u.signal:void 0),M=async q=>{let{requestId:F,header:ue,envelope:W}=await ti(q,B,v),$=await o(`${r}${Cr}`,{method:"POST",headers:{"content-type":Qe},body:W,signal:O});if($.headers.get("content-type")!==Qe)throw await Mr($);return ri($,q.responseKey,ue,F)},[Y,Re]=await l();try{return await M(Y)}catch(q){if(!(q instanceof ee)||q.code!=="unknown_session")throw q;return M(await d(Re))}}}async function vr(n){let e=await n;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function Or(n,e,t){try{return await Sr(n,e,t)}catch(r){if(!(r instanceof ee)||r.code!=="busy")throw r;return await new Promise(o=>setTimeout(o,r.retryAfterMs??1e3)),Sr(n,e,t)}}async function Sr(n,e,t){let r=await jr(t,Hs),o=await n(`${e}${Ur}`,{method:"POST",headers:{"content-type":Qe},body:f(new Uint8Array([gn]),t,r.message1)});if(o.headers.get("content-type")!==Qe)throw await Mr(o);let s=await si(o,Ys);return ei(r,s)}async function ei(n,e){if(e[0]!==gn)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:r,split:o}=t;if(r.length!==ze+4)throw new Error("The handshake reply is malformed");let s=r.slice(0,ze),i=new DataView(r.buffer,r.byteOffset).getUint32(ze,!1),[a,p]=await Promise.all([crypto.subtle.importKey("raw",o[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",o[1],"AES-GCM",!1,["decrypt"])]);return o[0].fill(0),o[1].fill(0),{requestKey:a,responseKey:p,nextRequestId:1,renewAt:Date.now()+i*1e3-Ws,header(l){let d=new Uint8Array(Gs);return d[0]=gn,d.set(s,1),new DataView(d.buffer).setBigUint64(1+ze,BigInt(l),!1),d}}}async function ti(n,e,t){let r=n.nextRequestId;n.nextRequestId+=1;let o=n.header(r),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:Nr(r,0),additionalData:o},n.requestKey,ni(e,t));return{requestId:r,header:o,envelope:f(o,new Uint8Array(s))}}function Nr(n,e){let t=new Uint8Array(12),r=new DataView(t.buffer);return r.setBigUint64(0,BigInt(n),!1),r.setUint32(8,e,!1),t}function ni(n,e){let t=Br.encode(JSON.stringify(n)),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,t.length,!1),f(r,t,e)}async function ri(n,e,t,r){if(!n.body)throw new Error("The sealed response has no body");let o=oi(n.body.getReader()),s=0,i=async()=>{let d=await o.next();if(!d)return null;let u;try{u=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Nr(r,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:u[0],data:u.slice(1)}},a=await i();if(!a||a.kind!==Fs)throw new Error("The sealed response is malformed");let p=JSON.parse(new TextDecoder().decode(a.data));if(Zs.includes(p.status))return await o.cancel(),new Response(null,{status:p.status,headers:p.headers});let l=new ReadableStream({async pull(d){try{let u=await i();u?u.kind===zs?d.enqueue(u.data):u.kind===Qs?(d.close(),await o.cancel()):d.error(new Error("The sealed response is malformed")):d.error(new Error("The sealed response was cut short"))}catch(u){d.error(u)}},cancel(){return o.cancel()}});return new Response(l,{status:p.status,headers:p.headers})}function oi(n){let e=new Uint8Array,t=async r=>{for(;e.length<r;){let{done:o,value:s}=await n.read();if(o)return!1;e=f(e,s)}return!0};return{async next(){if(!await t(4))return null;let r=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(r>Js)throw await n.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await t(4+r))return null;let o=e.slice(4,4+r);return e=e.slice(4+r),o},cancel:()=>n.cancel()}}async function si(n,e){if(!n.body)return new Uint8Array;let t=n.body.getReader(),r=new Uint8Array;for(;;){let{done:o,value:s}=await t.read();if(o)return r;if(r=f(r,s),r.length>e)throw await t.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function Mr(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 Je;let r=Number(n.headers.get("retry-after")),o=Number.isFinite(r)&&r>0?Math.min(r,5)*1e3:void 0;return new ee(n.status,e,t,o)}var qr=[{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"]}],Dr=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var ii="1.2.840.10045.2.1",ai={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},pi={"P-256":32,"P-384":48},ci={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function Ir(n,e,t){if(e+2>t)throw new Error("it is truncated");let r=n[e];if((r&31)===31)throw new Error("it uses a tag this parser does not read");let o=n[e+1],s=e+2;if(o&128){let a=o&127;if(a===0||a>4||s+a>t)throw new Error("it has a length this parser does not read");o=0;for(let p=0;p<a;p+=1)o=o*256+n[s+p];s+=a}let i=s+o;if(i>t)throw new Error("it is truncated");return{tag:r,bytes:n,offset:e,start:s,end:i}}function Te(n){let e=Ir(n,0,n.length);if(e.end!==n.length)throw new Error("it has trailing bytes");return e}function N(n){let e=[];for(let t=n.start;t<n.end;){let r=Ir(n.bytes,t,n.end);e.push(r),t=r.end}return e}function _(n,e,t){if(!n||n.tag!==e)throw new Error(`${t} is not where it should be`);return n}function te(n){return n.bytes.slice(n.start,n.end)}function kt(n){return n.bytes.slice(n.offset,n.end)}function xe(n){let e=te(_(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=[],r=0;for(let i of e)r=r*128+(i&127),i&128||(t.push(r),r=0);let o=t.shift();return[...o<80?[Math.floor(o/40),o%40]:[2,o-80],...t].join(".")}function li(n){let e=new TextDecoder().decode(te(n)),t=n.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,r=n.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,o=t??r;if(!o)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let s=Number(o[1]);t&&(s+=s<50?2e3:1900);let[i,a,p,l,d]=o.slice(2).map(Number);return Date.UTC(s,i-1,a,p,l,d)}function bn(n){try{let[e,t,r,...o]=N(_(Te(n),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let s=N(_(e,48,"The signed part")),i=s[0]?.tag===160?1:0,[a,p,l,d,u,y,...h]=s.slice(i);_(a,2,"The serial number");let g=xe(N(_(t,48,"The signature algorithm"))[0]);if(xe(N(_(p,48,"The signature algorithm"))[0])!==g)throw new Error("it names two different signature algorithms");let B=ci[g];if(!B)throw new Error(`it is signed with ${g}, not ECDSA with SHA-256 or SHA-384`);let[v,O]=N(_(d,48,"The validity")).map(li);if(O===void 0)throw new Error("its validity is incomplete");let[M,Y]=N(_(y,48,"The public key"));_(Y,3,"The public key");let[Re,q]=N(_(M,48,"The key algorithm"));if(xe(Re)!==ii)throw new Error("its key is not an elliptic-curve key");let F=ai[xe(q)];if(!F)throw new Error("its key is on a curve other than P-256 or P-384");let ue=new Map,W=h.find(de=>de.tag===163);if(W){let[de]=N(W);for(let mt of N(_(de,48,"The extensions"))){let V=N(_(mt,48,"An extension"));if(V.length===3)_(V[1],1,"An extension's critical flag");else if(V.length!==2)throw new Error("it has a malformed extension");let Ge=xe(V[0]);if(ue.has(Ge))throw new Error(`it has extension ${Ge} twice`);ue.set(Ge,te(_(V[V.length-1],4,"An extension value")))}}let $=te(_(r,3,"The signature"));if($[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:n,tbs:kt(e),signatureHash:B,signature:$.slice(1),issuer:kt(_(l,48,"The issuer")),subject:kt(_(u,48,"The subject")),notBefore:v,notAfter:O,spki:kt(y),curve:F,extensions:ue}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function Kr(n){return N(_(Te(n),48,"The list")).map(xe)}function ui(n,e){let t=pi[e],r=N(_(Te(n),48,"The signature"));if(r.length!==2)throw new Error("The signature is not an ECDSA signature");let o=new Uint8Array(t*2);return r.forEach((s,i)=>{let a=te(_(s,2,"The signature"));if(a.length===0||a[0]&128)throw new Error("The signature is not an ECDSA signature");for(;a.length>1&&a[0]===0;)a=a.subarray(1);if(a.length>t)throw new Error("The signature is not an ECDSA signature");o.set(a,i*t+t-a.length)}),o}async function At(n,e,t,r,o){let s;try{s=ui(r,e)}catch{return!1}let i=await crypto.subtle.importKey("spki",n,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:t},i,s,o)}function L(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 r=atob(t),o=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)o[s]=r.charCodeAt(s);return o}function Pn(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 L(t[0][1],e)}var di="2.5.29.17",yi="2.5.29.37",hi="1.3.6.1.5.5.7.3.3",fi="1.3.6.1.4.1.57264.1.8",gi="1.3.6.1.4.1.57264.1.1",mi=134,wi=12,bi=48,Pi=new TextEncoder,je=n=>new TextDecoder().decode(n);async function _t(n,e,t,r){let{base64Signature:o,cert:s,rekorBundle:i}=Ei(e),a=i.Payload;if(r!==void 0&&r.trim()!==o.trim())throw new Error("The detached signature is not the one in the bundle");let p=L(o,"The bundle signature"),l=Pn(je(L(s,"The bundle certificate")),"The bundle certificate"),d=bn(l),u=Dr.find(O=>O.logId===a.logID.toLowerCase());if(!u)throw new Error(`The bundle names Rekor log ${a.logID}, which the Sigstore trust root does not know`);let y=Pi.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await At(L(u.publicKey,"The Rekor key"),"P-256","SHA-256",L(i.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=a.integratedTime*1e3;if(!Lr(g,u.validFor))throw new Error(`Rekor log ${u.baseUrl} was not in use at ${Ye(g)}, when the entry says it was logged`);let A=Ri(a.body),B=m(new Uint8Array(await crypto.subtle.digest("SHA-256",n)));if(A.hash!==B)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!kn(L(A.signature,"The logged signature"),p))throw new Error("The bundle's signature is not the one Rekor logged");let v=Pn(je(L(A.publicKey,"The logged certificate")),"The logged certificate");if(!kn(v,l))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await At(d.spki,"P-256","SHA-256",p,n))throw new Error("The signature over the file does not verify with the bundle's certificate");return await ki(d,g),_i(d,t),{integratedTime:a.integratedTime}}async function ki(n,e){if(!Vr(n,e))throw new Error(`The signing certificate was valid ${Ye(n.notBefore)} to ${Ye(n.notAfter)}, not at ${Ye(e)} when Rekor logged it`);let t=[];for(let r of qr){let o=r.certChain.map(i=>bn(L(i,"A Fulcio certificate")));if(!await $r(n,o[0]))continue;let s=await Ai(o,r.validFor,e);if(!s)return;t.push(`${r.uri} (valid from ${r.validFor.start}): ${s}`)}throw new Error(t.length>0?`The signing certificate's CA is not trusted at ${Ye(e)}: ${t.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function Ai(n,e,t){if(!Lr(t,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of n.entries()){if(!Vr(o,t))return`its certificate ${r} was not valid then`;let s=n[r+1]??o;if(!await $r(o,s))return`its certificate ${r} is not signed by the next`}}async function $r(n,e){return kn(n.issuer,e.subject)?At(e.spki,e.curve,n.signatureHash,n.signature,n.tbs):!1}function _i(n,e){let t=n.extensions.get(di);if(!t)throw new Error("The signing certificate names no identity");let r=N(_(Te(t),bi,"The subject alternative name")),o=r.filter(l=>l.tag===mi).map(l=>je(te(l)));if(o.length!==1||r.length!==1||o[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(o.length===1?o[0]:o)}, not by ${e.identity}`);let s=n.extensions.get(fi),i=n.extensions.get(gi),a=s?je(te(_(Te(s),wi,"The OIDC issuer"))):i?je(i):void 0;if(a!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${a===void 0?"missing":JSON.stringify(a)}, not ${e.issuer}`);let p=n.extensions.get(yi);if(!p||!Kr(p).includes(hi))throw new Error("The signing certificate is not for code signing")}function Ei(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,r=t?.rekorBundle?.Payload;if(!(typeof t?.base64Signature=="string"&&typeof t.cert=="string"&&typeof t.rekorBundle?.SignedEntryTimestamp=="string"&&typeof r?.body=="string"&&typeof r.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(r.logID)&&Number.isSafeInteger(r.integratedTime)&&r.integratedTime>=0&&Number.isSafeInteger(r.logIndex)&&r.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return t}function Ri(n){let e;try{e=JSON.parse(je(L(n,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let t=e?.spec?.data?.hash,r=e?.spec?.signature;if(e?.kind!=="hashedrekord"||t?.algorithm!=="sha256"||typeof t.value!="string"||typeof r?.content!="string"||typeof r.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:t.value.toLowerCase(),signature:r.content,publicKey:r.publicKey.content}}function Vr(n,e){return n.notBefore<=e&&e<=n.notAfter}function Lr(n,e){return Date.parse(e.start)<=n&&(e.end===void 0||n<=Date.parse(e.end))}function Ye(n){return new Date(n).toISOString()}function kn(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var xi=/^[0-9a-f]{96}$/,Ti=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function fe(n){let e=ve(n.allowedMrtd??[],"allowedMrtd"),t=(n.allowedMeasurements??[]).map((a,p)=>{let l=`allowedMeasurements[${p}]`;return Ti.map(d=>ve([a?.[d]??""],`${l}.${d}`)[0]).join()}),r=[ve(n.allowedRtmr0??[],"allowedRtmr0"),ve(n.allowedRtmr1??[],"allowedRtmr1"),ve(n.allowedRtmr2??[],"allowedRtmr2"),ve(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(r.slice(1).some(a=>a.length===0))throw new Error("allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too")}let o=n.allowedTcbStatuses??["UpToDate"],s=n.now??Date.now;return Object.assign(async({quoteB64:a,nonce:p,reportDataSuffix:l,collateral:d})=>{let u=vi(a),y=d??await n.fetchCollateral?.(u);if(!y)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let h;try{h=n.dcapVerify(u,y,Math.floor(s()/1e3))}catch(v){throw new Error(`The quote did not verify: ${v?.message??String(v)}`)}if(h.status==="Revoked"||!o.includes(h.status))throw new Error(`The platform's TCB status is ${h.status}, which is not accepted`);let g=ji(h.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 A=[g.mrTd,g.rtMr0,g.rtMr1,g.rtMr2,g.rtMr3].map(v=>m(v));if(t.length>0&&!t.includes(A.join()))throw new Error(`The measurements (MRTD ${A[0]}, RTMR0-3 ${A.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(A[0]))throw new Error(`MRTD ${A[0]} is not an image this verifier trusts`);if([g.rtMr0,g.rtMr1,g.rtMr2,g.rtMr3].forEach((v,O)=>{let M=r[O];if(M.length>0&&!M.includes(m(v)))throw new Error(`RTMR${O} ${m(v)} is not one this verifier trusts`)}),m(g.reportData)!==`${p}${l}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function ve(n,e){return n.map(t=>{let r=t.trim().toLowerCase();if(!xi.test(r))throw new Error(`${e} holds ${JSON.stringify(t)}, which is not a 48-byte hex measurement`);return r})}function ji(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 vi(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}var Oi=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],he="locked-read-only";function An(n,{profile:e,allowDebugProfile:t=!1}){if(n.length===0)throw new Error("No release given, so no image would be trusted");let r,o=n.map((s,i)=>{let a=s?.tag??`releases[${i}]`;if(s?.role!==void 0&&s.role!=="node")throw new Error(`${a} lists the measurements of a ${s.role}, not of a node image`);let p=s?.profiles?.[e];if(!p){let d=Object.keys(s?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${d})`)}if(e!==he&&!t)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(he)}, or pass allowDebugProfile to test`);let l=(p.allowed_tcb_statuses??["uptodate"]).map(d=>Si(d,a));return r=r===void 0?l:r.filter(d=>l.includes(d)),{mrtd:p.mrtd,rtmr0:p.rtmr0,rtmr1:p.rtmr1,rtmr2:p.rtmr2,rtmr3:p.rtmr3}});if(!r||r.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:o,allowedTcbStatuses:r}}function Si(n,e){let t=Oi.find(r=>r.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 _n=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"}),Ui=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],Et="https://cloud.calimero.network",En=`${Et}/api/tee/pcs`;async function Gr(n,e,t={}){let r=typeof n=="string"?new TextEncoder().encode(n):n;await _t(r,e,{identity:t.identity??_n.identity,issuer:t.issuer??_n.issuer},t.signature);let o;try{o=JSON.parse(new TextDecoder().decode(r))}catch{throw new Error("The signed release is not JSON")}if(o?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(o?.role)} release, not a node one`);let s=Object.values(o.profiles??{}),i=a=>Ui.every(p=>/^[0-9a-f]{96}$/i.test(String(a?.[p])));if(typeof o.tag!="string"||s.length===0||!s.every(i))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(t.expectedVersion!==void 0&&o.tag!==t.expectedVersion)throw new Error(`The signed release is ${o.tag}, not ${t.expectedVersion}`);return o}async function Rn(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 r;try{r=(await t.json())?.data}catch{throw new Error(`${n} did not answer with JSON`)}if(typeof r?.version!="string"||typeof r.publishedMrtds!="string"||typeof r.bundle!="string")throw new Error(`${n} did not answer with a signed node release`);return{version:r.version,publishedMrtds:r.publishedMrtds,bundle:r.bundle}}var Fr="https://github.com/calimero-network/mero-tee/releases/download";async function xn(n,e={}){let t=`mero-tee-v${ne(n,"version")}`,r=`${(e.base??Fr).replace(/\/+$/,"")}/${t}/published-mrtds.json`,o=async a=>{let p=await(e.fetch??fetch)(a);if(!p.ok)throw new Error(`Fetching ${a} failed: HTTP ${p.status}`);return p.text()},[s,i]=await Promise.all([o(r),o(`${r}.bundle.json`)]);return{version:n,publishedMrtds:s,bundle:i}}function Tn(n,e){return`${n.replace(/\/+$/,"")}/api/tee/node-releases/${ne(e,"version")}`}async function Rt(n){let e=ne(n.minReleaseVersion,"minReleaseVersion"),t=ne(n.release?.version,"The release version"),r=await Gr(n.release.publishedMrtds,n.release.bundle,{expectedVersion:t,identity:n.identity,issuer:n.issuer});if(We(t,e)<0)throw new Error(`Release ${t} is older than the minimum trusted, ${e}`);return An([r],{profile:n.profile,allowDebugProfile:n.allowDebugProfile})}function Ci(n){return ne(n.minReleaseVersion,"minReleaseVersion"),Object.assign(async t=>{let r=await Rt({release:await n.release(),profile:n.profile,allowDebugProfile:n.allowDebugProfile,minReleaseVersion:n.minReleaseVersion,identity:n.identity,issuer:n.issuer});return fe({dcapVerify:n.dcapVerify,fetchCollateral:n.fetchCollateral,now:n.now,...r})(t)},{includeCollateral:!0})}var zr=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ne(n,e){let t=typeof n=="string"?zr.exec(n):null,r=t?.[4];if(!t||r!==void 0&&r.split(".").some(o=>o===""))throw new Error(`${e} is ${JSON.stringify(n)}, not a release version like 2.3.87`);return n}function We(n,e){let[t,r]=Hr(n),[o,s]=Hr(e);for(let p=0;p<3;p+=1)if(t[p]!==o[p])return t[p]<o[p]?-1:1;if(r===void 0||s===void 0)return r===s?0:r===void 0?1:-1;let i=r.split("."),a=s.split(".");for(let p=0;p<Math.max(i.length,a.length);p+=1){let[l,d]=[i[p],a[p]];if(l===void 0||d===void 0)return l===void 0?-1:1;let[u,y]=[/^\d+$/.test(l),/^\d+$/.test(d)],h=u&&y?Math.sign(Number(l)-Number(d)):u!==y?u?-1:1:l<d?-1:l>d?1:0;if(h!==0)return h}return 0}function Hr(n){let e=zr.exec(n);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var Jr="MOCK_TDX_QUOTE_V1";function Bi(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function jn(n,e){if(n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r++)t|=n[r]^e[r];return t===0}var Qr;async function vn(n){Qr??(Qr=import("@phala/dcap-qvl"));let e=await Qr,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 Yr(n,e){let t=ne(e,"minReleaseVersion"),r=String(n.release?.version??"").trim().replace(/^mero-tee-v/,"").replace(/^v/,""),o=ne(r,"The release the node names");if(We(o,t)<0)throw new Error(`mero-tee release ${o} is older than the minimum ${t}`);return o}var ge=class extends Error{constructor(t,r,o){super(r?`${t} answered HTTP ${r}`:`${t} could not be reached: ${o?.message}`);this.host=t;this.status=r;this.cause=o}};function Xe(n,e){return e instanceof TypeError?new ge(n,void 0,e):e}var Wr=n=>n===429||n>=500;function Ni(n,e){return async(t,r)=>{let o=await n(t,r).catch(i=>{throw Xe(e,i)});if(Wr(o.status))throw new ge(e,o.status);let s=await o.arrayBuffer().catch(i=>{throw Xe(e,i)});return new Response(s,o)}}async function Mi(n,e,t){let r=e.releaseSource;if(typeof r=="function")return r(n);let o=Ni(t,"the release mirror");return r==="github"?xn(n,{fetch:o}):Rn(Tn(r??Et,n),{fetch:o})}function qi(n){let e=n.collateralSource??En;return e==="intel"?async t=>(await vn("getCollateralFromPcs"))(t).catch(o=>{throw Xe("Intel PCS",o)}):(new URL(e),async t=>(await vn("getCollateral"))(e,t).catch(o=>{throw Xe(e,o)}))}function Xr(n,e){let t=e.maxCollateralAgeDays;return t===void 0?n:async r=>{let o=await n(r),s;try{s=Date.parse(JSON.parse(o.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 i=((e.now??Date.now)()-s)/864e5;if(i>t)throw new Error(`The quote's collateral was issued ${Math.floor(i)} days ago, more than the ${t} this client accepts`);return o}}async function Di(n,e,t,r){let o=Yr(n,t.minReleaseVersion),s=t.profile??he,i=await Mi(o,t,r);if(i.version!==o)throw new Error(`The node names mero-tee release ${o}, but the release served is ${i.version}`);let a=await Rt({release:i,profile:s,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer}),p=Xr(t.fetchCollateral??qi(t),t);return await fe({dcapVerify:t.dcapVerify??await vn("verify"),fetchCollateral:p,now:t.now,...a})(e)?{release:o,profile:s}:void 0}async function xt(n,e,t,r,o,s=(i,a)=>fetch(i,a)){let i=Bi(n.quote),a=new TextEncoder().encode(Jr);if(jn(i.slice(0,a.length),a)){if(!r.allowMock)throw new Error("mock quote refused: this client only trusts real TEEs");let d=i.slice(a.length,a.length+64);if(!jn(d.slice(0,32),e)||!jn(d.slice(32),t))throw new Error(`the quote does not bind this ${o} and nonce`);return{mock:!0}}let p={quoteB64:n.quote,nonce:m(e),reportDataSuffix:m(t)},l;if(r.verifyQuote)l=await r.verifyQuote(p)?{}:void 0;else if(r.release)l=await Di(n,p,r.release,s);else throw new Error("real quote refused: this client trusts no TD image (set policy.release)");if(!l)throw new Error(`The attestation did not verify, so its ${o} is not trusted`);return{mock:!1,...l}}async function Ii(n,e,t=(r,o)=>fetch(r,o)){return(await me(n,e,t)).key}function Ki(n,e){let t=x(n.appHash,"appHash",32);if(t.every(r=>r===0))throw new Error("The node bound no app: its app hash is all zero");if(e.appHash&&m(t)!==e.appHash.toLowerCase())throw new Error(`The node's app hash ${m(t)} is not the pinned ${e.appHash}`);return t}async function me(n,e,t=(r,o)=>fetch(r,o)){let r=n.replace(/\/+$/,""),o=m(crypto.getRandomValues(new Uint8Array(32))),s=new URL(`${r}/attestation`);s.searchParams.set("nonce",o),e.app?s.searchParams.set("app",e.app):e.appHash&&s.searchParams.set("appHash",e.appHash);let i=await t(s.toString());if(Wr(i.status))throw new ge("the node",i.status);if(!i.ok)throw new Error(`The node refused to attest: HTTP ${i.status}`);let a=await i.json().catch(g=>{throw Xe("the node",g)}),p=x(a.transportKey,"transportKey",32),l=e.app?Ki(a,e):void 0,d=l??(e.appHash?x(e.appHash,"appHash",32):new Uint8Array(32)),u=await mn(d,p),y=await xt(a,x(o,"nonce",32),u,e,"transport key",t),h={url:r,...y,...l?{appHash:m(l)}:{},checkedAt:Date.now()};return{key:p,verification:h}}var On="https://manager.cloud.calimero.network/api/directory";var Q=class extends Error{constructor(t,r,o,s,i){super(`directory for cluster ${t}: ${o}`);this.cluster=t;this.reason=r;this.status=s;this.cause=i;this.name="DirectoryError"}};function $i(n,e){return`${n.replace(/\/+$/,"")}/${encodeURIComponent(e)}`}async function Sn(n,e,t){let r;try{r=await t($i(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(r.status===404)throw new Q(e,"not-found","unknown cluster",404);if(!r.ok)throw new Q(e,"unreachable",`answered ${r.status}`,r.status);let o;try{o=await r.json()}catch(d){throw new Q(e,"bad-response","answered something other than JSON",r.status,d)}let s=o;if(!s||typeof s!="object"||!Array.isArray(s.nodes))throw new Q(e,"bad-response","answered no node list",r.status);let i=[],a=new Set;for(let d of s.nodes){let u=Vi(d);u&&!a.has(u.url)&&(a.add(u.url),i.push(u))}if(i.length===0)throw new Q(e,"empty","lists no usable node",r.status);let p=s.refreshAfterSeconds,l=typeof p=="number"&&Number.isFinite(p)&&p>=1?p:60;return{nodes:i,refreshAfterSeconds:l}}function Vi(n){if(!n||typeof n!="object")return;let{url:e,zone:t,weight:r}=n;if(typeof e!="string"||typeof r!="number"||!Number.isInteger(r)||r<1)return;let o;try{o=new URL(e)}catch{return}if(!(o.protocol!=="https:"&&o.protocol!=="http:"))return{url:e.replace(/\/+$/,""),zone:typeof t=="string"?t:void 0,weight:r}}function Un(n,e,t){let r=e===void 0?[]:n.filter(s=>s.zone===e),o=e===void 0?n:n.filter(s=>s.zone!==e);return[...Zr(r,t),...Zr(o,t)]}function Zr(n,e){let t=[...n],r=[];for(;t.length>0;){let o=e()*t.reduce((i,a)=>i+a.weight,0),s=0;for(;s<t.length-1&&o>=t[s].weight;)o-=t[s++].weight;r.push(t.splice(s,1)[0].url)}return r}var b=class extends Error{constructor(t,r,o,s={}){super(`${t} ${r}: ${o}`);this.status=t;this.code=r;this.details=s;this.name="CalimeroError"}},re=class extends b{constructor(e,t={}){super(401,"UNAUTHENTICATED",e,t),this.name="LoginRequired"}},Tt=class extends b{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"}},we=class extends b{constructor(e,t={}){super(421,"WRONG_NODE",e,t),this.name="WrongNode"}},Oe=class extends b{constructor(e,t={}){super(404,"NOT_FOUND",e,t),this.name="NotFound"}},Se=class extends b{constructor(e,t={}){super(412,"CONFIRM_REQUIRED",e,t),this.name="ConfirmRequired"}},Ze=class extends Error{constructor(t){super("the passkey confirmation was cancelled");this.cause=t;this.name="ConfirmCancelled"}},et=class extends Error{constructor(t){super("the passkey prompt was blocked by the browser or a password manager");this.cause=t;this.name="ConfirmPromptBlocked"}},jt=class extends b{constructor(e,t={}){super(413,"ARGS_TOO_LARGE",e,t),this.name="ArgsTooLarge"}},vt=class extends b{constructor(e,t={}){super(409,"IDEMPOTENCY_MISMATCH",e,t),this.name="IdempotencyMismatch"}},Ot=class extends b{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:""}},St=class extends b{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:[]}},Ut=class extends b{constructor(e,t={}){super(409,"CONSENT_STALE",e,t),this.name="ConsentStale"}},be=class extends b{constructor(e,t={}){let r=typeof t.origin=="string"?t.origin:"",o=typeof t.package=="string"?t.package:"",s=r?`this site (${r})`:"this site";super(403,"ORIGIN_NOT_REGISTERED",`${s} is not registered for ${o||"any package"}${e?` (${e})`:""}`,t),this.name="OriginNotRegistered",this.origin=r,this.package=o,this.nodeMessage=e}},Ct=class extends b{constructor(e,t,r={}){super(400,e,t,r),this.name="BadOrigin"}},Bt=class extends b{constructor(e,t={}){super(409,"ORIGIN_TAKEN",e,t),this.name="OriginTaken"}},Nt=class extends b{constructor(e,t={}){super(400,"NOT_SERVING",e,t),this.name="NotServing"}},Mt=class extends b{constructor(e,t={}){super(409,"CLUSTER_NOT_UPGRADED",e,t),this.name="ClusterNotUpgraded"}},qt=class extends b{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:""}},Dt=class extends b{constructor(e,t={}){super(409,"RECOVERY_NOT_READY",e,t),this.name="RecoveryNotReady",this.readyAt=typeof t.readyAt=="number"?t.readyAt:void 0}},tt=class extends b{constructor(e,t={}){super(401,"UNAUTHENTICATED",e||"unknown or used recovery code",t),this.name="WrongRecoveryCode"}},It=class extends b{constructor(e,t={}){super(403,"SIGN_UP_REFUSED",e,t),this.name="SignUpRefused",this.reason=Li(e)}};function Li(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 Kt=class extends b{constructor(e,t={}){super(429,"QUOTA_EXCEEDED",e,t),this.name="QuotaExceeded"}},$t=class extends b{constructor(e,t={}){super(422,"APP_ERROR",e,t),this.name="AppError";let{appCode:r,fields:o}=Hi(t);this.appCode=r,this.fields=o}},Vt=class extends b{constructor(e,t={}){super(422,"TRAP",e,t),this.name="TrapError",this.kind=typeof t.kind=="string"?t.kind:""}},oe=class extends b{constructor(e,t,r={},o,s){super(503,e,t,r),this.name="UnavailableError",this.reason=e.toLowerCase(),this.committed=e==="TIMEOUT"||e==="MIGRATING"?!1:"unknown",this.retryAfter=o,this.cause=s}};function Lt(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function Hi(n){let e=typeof n.code=="string"?n:Lt(n.error);return{appCode:typeof e.code=="string"?e.code:"",fields:{...Lt(e.fields)}}}function Gi(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 Ue(n,e,t){let r=Lt(e),o=typeof r.error=="string"?r.error:"ERROR",s=typeof r.message=="string"?r.message:"",i=Lt(r.details);if(n===503)return new oe(o,s,i,Gi(i,t));switch(`${n} ${o}`){case"401 UNAUTHENTICATED":return new re(s,i);case"401 PASSKEY_UNKNOWN_HERE":return new Tt(s,i);case"421 WRONG_NODE":return new we(s,i);case"404 NOT_FOUND":return new Oe(s,i);case"409 IDEMPOTENCY_MISMATCH":return new vt(s,i);case"409 RELEASE_DEADLINE":return new Ot(s,i);case"409 RUNTIME_TOO_OLD":return new St(s,i);case"409 CONSENT_STALE":return new Ut(s,i);case"403 ORIGIN_NOT_REGISTERED":return new be(s,i);case"400 BAD_ORIGIN":case"400 BAD_RP_ID":return new Ct(o,s,i);case"409 ORIGIN_TAKEN":return new Bt(s,i);case"400 NOT_SERVING":return new Nt(s,i);case"409 CLUSTER_NOT_UPGRADED":return new Mt(s,i);case"409 FEATURE_NOT_ACTIVE":return new qt(s,i);case"429 QUOTA_EXCEEDED":return new Kt(s,i);case"409 RECOVERY_NOT_READY":return new Dt(s,i);case"403 SIGN_UP_REFUSED":return new It(s,i);case"412 CONFIRM_REQUIRED":return new Se(s,i);case"413 ARGS_TOO_LARGE":return new jt(s,i);case"422 APP_ERROR":return new $t(s,i);case"422 TRAP":return new Vt(s,i);default:return new b(n,o,s,i)}}function R(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function C(n){let e=n.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((n.length+3)%4),t=atob(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}var nt=n=>n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);function Cn(n){let e=new Error(n);return e.name="NotAllowedError",e}async function eo(n,e,t,r){let o=navigator.credentials,i=globalThis.CredentialsContainer?.prototype?.[n]??o[n];try{return await i.call(o,t?{...e,signal:t}:e)}catch(a){throw t?.aborted||a?.name==="AbortError"?Object.assign(Cn(`${r} was cancelled`),{cause:a}):a}}function Fi(n){let e=n.filter(t=>t.alg===-7);return e.length?e:n}function zi(){return{async create(n,e){let t=n,r=await eo("create",{publicKey:{challenge:nt(C(t.challenge)),rp:t.rp,user:{...t.user,id:nt(C(t.user.id))},pubKeyCredParams:Fi(t.pubKeyCredParams),excludeCredentials:(t.excludeCredentials??[]).map(s=>({type:s.type,id:nt(C(s.id))})),authenticatorSelection:t.authenticatorSelection,attestation:"none",timeout:t.timeout}},e?.signal,"passkey creation");if(!r)throw Cn("passkey creation was cancelled");let o=r.response;return{attestationObject:R(new Uint8Array(o.attestationObject)),clientDataJson:R(new Uint8Array(o.clientDataJSON))}},async get(n,e,t,r){let o=await eo("get",{publicKey:{challenge:nt(n),rpId:e,userVerification:r?.userVerification??"preferred",allowCredentials:(t??[]).map(i=>({type:"public-key",id:nt(C(i))}))}},r?.signal,"passkey sign-in");if(!o)throw Cn("passkey sign-in was cancelled");let s=o.response;return{credentialId:R(new Uint8Array(o.rawId)),authenticatorData:R(new Uint8Array(s.authenticatorData)),clientDataJson:R(new Uint8Array(s.clientDataJSON)),signature:R(new Uint8Array(s.signature))}}}}function Qi(n,e){return n==="required"||n==="preferred"||n==="discouraged"?n:e}function Ji(n){let e=n,t=e?.name,r=typeof e?.message=="string"?e.message:"";return t==="InvalidStateError"||/not focused|already pending/i.test(r)?new et(n):t==="NotAllowedError"||t==="AbortError"?new Ze(n):n}function rt(n,e={}){return async t=>{try{return await n.get(C(t.challenge),t.rpId,t.allowCredentials,{userVerification:Qi(t.userVerification,e.userVerification??"required"),...e.signal?{signal:e.signal}:{}})}catch(r){throw Ji(r)}}}var Nn={retries:6,baseDelayMs:200,maxDelayMs:2e3};function st(n,e){return Math.min(e.baseDelayMs*2**n,e.maxDelayMs)}function Yi(n){return n instanceof ee&&n.status===413?Ue(413,{error:"TOO_LARGE",message:n.message.replace(/^Sealed request refused: /,"")}):n}async function se(n){let e=await n.text().catch(()=>""),t={};try{t=e?JSON.parse(e):{}}catch{t={message:e}}return Ue(n.status,t,n.headers.get("retry-after"))}async function*no(n){let e=n.getReader(),t=new TextDecoder,r="";for(;;){let{value:o,done:s}=await e.read();if(s)return;r+=t.decode(o,{stream:!0});let i;for(;(i=r.indexOf(`
2
2
 
3
3
  `))>=0;){let a=r.slice(0,i);r=r.slice(i+2);let p="",l="",d="";for(let y of a.split(`
4
- `))y.startsWith("id:")?p=y.slice(3).trim():y.startsWith("event:")?l=y.slice(6).trim():y.startsWith("data:")&&(d+=y.slice(5).trim());if(!l&&!d)continue;let u=d;try{u=JSON.parse(d)}catch{}yield{id:p,kind:l,data:u}}}}function Mn(){return`node:c-${R(crypto.getRandomValues(new Uint8Array(16)))}`}function Ae(n,e={}){return n.replace(/\{([^}]+)\}/g,(t,r)=>{let o=e[r];if(o===void 0)throw new Error(`no value for path parameter ${r} of ${n}`);return encodeURIComponent(String(o))})}function Bn(n){if(!n)return"";let e=new URLSearchParams;for(let[r,o]of Object.entries(n))for(let s of Array.isArray(o)?o:[o])s!=null&&e.append(r,String(s));let t=e.toString();return t?`?${t}`:""}function no(n){return n==="auth/refresh"||n.startsWith("auth/passkey/")||ea.has(n)}var ea=new Set(["auth/recovery/begin","auth/recovery/start","auth/recovery/finish"]);function ot(n){return n.replace(/^\/+/,"")}var Pe=class{constructor(e){this.at=0;this.channels=new Map;this.checks=new Map;this.attempts=new Map;this.keys=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={...Nn,...e.retry};let r=e.fetch??((s,i)=>fetch(s,i)),o=async(s,i)=>{try{return await r(s,i)}catch(a){throw a instanceof TypeError&&this.networkFailures.add(a),a}};this.raw=o}isNetworkFailure(e){return e instanceof TypeError&&this.networkFailures.has(e)||e instanceof ge}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}get nodePolicy(){return this.policy}channel(e){let t=this.channels.get(e);if(!t){let r=()=>this.channels.get(e)===s,o,s=wn({baseUrl:e,transportPublicKey:()=>{let i=o??this.attest(e,r);return o=void 0,i},fetch:this.raw});this.channels.set(e,s),o=this.attest(e,r),t=s}return t}attest(e,t){if(!t())return me(e,this.policy,this.raw).then(({key:o})=>o);this.checks.set(e,{status:"checking",url:e});let r=me(e,this.policy,this.raw).then(({key:o,verification:s})=>(t()&&(this.checks.set(e,{status:"verified",...s}),this.keys.set(e,o)),o),o=>{let s=o instanceof Error?o.message:String(o),i=this.isNetworkFailure(o);throw t()&&(this.checks.set(e,{status:i?"unreachable":"refused",url:e,reason:s,checkedAt:Date.now()}),i&&this.channels.delete(e)),o});return r.catch(()=>{}),this.attempts.set(e,r),r}verification(e=this.nodeUrl){return this.checks.get(e)}async attestApp(e,t=this.nodeUrl){let r=this.policy.app===e?this.policy.appHash:void 0,o={...this.policy,app:e,appHash:r};await this.settled(t);let s=await me(t,o,this.raw);if(!this.sameKey(t,s.key)&&(this.channels.delete(t),await this.settled(t),s=await me(t,o,this.raw),!this.sameKey(t,s.key)))throw new Error("The node attested the app under another transport key than its channel");return s.verification}async settled(e){let t=await this.verify(e);if(t.status==="refused"||t.status==="unreachable")throw new Error(t.reason)}sameKey(e,t){let r=this.keys.get(e);return r!==void 0&&m(r)===m(t)}async verify(e=this.nodeUrl){for(this.channel(e);;){let t=this.attempts.get(e);if(await t?.catch(()=>{}),this.attempts.get(e)===t)return this.checks.get(e)}}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 r=this.nodeUrls.length;for(let o=1;o<r;o++){let s=(this.at+o)%r;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=Sn(e.directory,e.cluster,this.raw).then(t=>{let r=this.nodeUrl,o=Un(t.nodes,e.zone,e.random);this.nodeUrls=[r,...o.filter(s=>s!==r)],this.at=0,e.due=Date.now()+t.refreshAfterSeconds*1e3}).catch(()=>{}).finally(()=>{e.reading=void 0}))}async once(e,t,r){let o={};this.auth&&(o.authorization=`Bearer ${this.auth}`);let s;r.bytes?(o["content-type"]=r.contentType??"application/wasm",s=r.bytes):r.body!==void 0&&(o["content-type"]="application/json",s=JSON.stringify(r.body)),this.source&&Date.now()>=this.source.due&&this.reread();let i=this.nodeUrl;try{return await this.channel(i)(`${i}/${t}${Bn(r.query)}`,{method:e,headers:o,body:s,signal:r.signal})}catch(a){throw Zi(a)}}async send(e,t,r){let o=await this.answer(e,t,r);if(!o.ok)throw await se(o);return o}async answer(e,t,r){let o=!1,s=!1;for(;;){let[i,a]=[this.auth,this.nodeUrl],p=await this.once(e,t,r);if(p.ok||p.status!==401&&p.status!==421)return p;let l=await se(p.clone());if(l instanceof we&&!s){if(s=!0,this.moveOn(a)&&!no(t))continue}else if(l instanceof re&&!o&&this.mayRefresh(i,t)){o=!0,await this.renew(i);continue}return p}}mayRefresh(e,t){return e!==void 0&&this.current!==void 0&&!no(t)}async renew(e){this.auth===e&&await this.refresh()}async read(e,t,r){let s=await(await this.send(e,t,r)).text();return s?JSON.parse(s):{}}async retried(e,t,r,o){let s=await this.answerRetried(e,t,r,o);if(!s.ok)throw await se(s);let i=await s.text();return i?JSON.parse(i):{}}async answerRetried(e,t,r,o){let s=o?0:this.retry.retries,i=new Set;for(;;){let a,p,l=this.nodeUrl;for(let d=0;;d++){l=this.nodeUrl,i.add(l);try{let y=await this.answer(e,t,r);if(y.status!==503)return y;p=y,a=await se(y.clone())}catch(y){if(y instanceof TypeError&&this.networkFailures.has(y))p=void 0,a=new oe("NETWORK",`the node could not be reached: ${y.message}`,{},void 0,y);else throw y}if(d>=s)break;let u=st(d,this.retry);await new Promise(y=>setTimeout(y,Math.max(u,(a.retryAfter??0)*1e3)))}if(o||!this.failOver(l,i)){if(p)return p;throw a}}}exchange(e,t,r={}){let o=ot(t);return r.retry?this.answerRetried(e,o,r,r.retry==="once"):this.answer(e,o,r)}attempt(e,t,r){if(!r.retry)return this.read(e,t,r);let o=r.body?.confirm!==void 0;return this.retried(e,t,r,r.retry==="once"||o)}async confirmed(e,t,r){let{passkey:o}=r;try{return await this.attempt(e,t,r)}catch(s){if(!(s instanceof Se)||!o)throw s;let i=s.details,a=await rt(o,{userVerification:r.userVerification,signal:r.promptSignal??r.signal})(i,{request:new Request(`${this.nodeUrl}/${t}`,{method:e})}),p={...r.body,confirm:{challengeId:i.challengeId,assertion:a}};return this.attempt(e,t,{...r,body:p})}}request(e,t,r={}){return this.send(e,ot(t),r)}json(e,t,r={}){return this.confirmed(e,ot(t),r)}async*events(e,t={}){let r=await this.send("GET",ot(e),t);if(!r.body)throw new b(r.status,"EVENTS","the event stream has no body");yield*ro(r.body)}async unsealed(e,t={}){let r=await this.inTheClear(e,t);if(!r.ok)throw await se(r);return r}inTheClear(e,t={}){return this.raw(`${this.nodeUrl}/${ot(e)}${Bn(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 r=1;t===void 0;r++)try{t=await this.json("POST","auth/refresh",{body:{refreshToken:e.refreshToken}})}catch(o){if(!(o instanceof we)||r>=this.nodeUrls.length)throw o}return this.current===e&&this.useSession(t),t}};async function qn(n){let e=n.random??Math.random,t=n.fetch??((a,p)=>fetch(a,p)),r=await Sn(n.directory,n.cluster,t),[o,...s]=Un(r.nodes,n.zone,e),i=new Pe({baseUrl:o,nodes:s,policy:n.policy,fetch:n.fetch,retry:n.retry});return i.useDirectory({directory:n.directory,cluster:n.cluster,zone:n.zone,random:e,due:Date.now()+r.refreshAfterSeconds*1e3}),i}var ta=/\{[^{}]+\}/g,na=()=>typeof process=="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici;function ra(){return Math.random().toString(36).slice(2,11)}function ao(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:r=globalThis.fetch,querySerializer:o,bodySerializer:s,pathSerializer:i,headers:a,requestInitExt:p=void 0,...l}={...n};p=na()?p:void 0,e=io(e);let d=[];async function u(y,h){let{baseUrl:g,fetch:k=r,Request:B=t,headers:v,params:O={},parseAs:M="json",querySerializer:Y,bodySerializer:Re=s??sa,pathSerializer:q,body:F,middleware:ue=[],...W}=h||{},$=e;g&&($=io(g)??e);let de=typeof o=="function"?o:oo(o);Y&&(de=typeof Y=="function"?Y:oo({...typeof o=="object"?o:{},...Y}));let mt=q||i||oa,L=F===void 0?void 0:Re(F,so(a,v,O.header)),Ge=so(L===void 0||L instanceof FormData?{}:{"Content-Type":"application/json"},a,v,O.header),X=[...d,...ue],qs={redirect:"follow",...l,...W,body:L,headers:Ge},wt,bt,Z=new B(ia(y,{baseUrl:$,params:O,querySerializer:de,pathSerializer:mt}),qs),T;for(let U in W)U in Z||(Z[U]=W[U]);if(X.length){wt=ra(),bt=Object.freeze({baseUrl:$,fetch:k,parseAs:M,querySerializer:de,bodySerializer:Re,pathSerializer:mt});for(let U of X)if(U&&typeof U=="object"&&typeof U.onRequest=="function"){let j=await U.onRequest({request:Z,schemaPath:y,params:O,options:bt,id:wt});if(j)if(j instanceof B)Z=j;else if(j instanceof Response){T=j;break}else throw new Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!T){try{T=await k(Z,p)}catch(U){let j=U;if(X.length)for(let ye=X.length-1;ye>=0;ye--){let Pt=X[ye];if(Pt&&typeof Pt=="object"&&typeof Pt.onError=="function"){let Fe=await Pt.onError({request:Z,error:j,schemaPath:y,params:O,options:bt,id:wt});if(Fe){if(Fe instanceof Response){j=void 0,T=Fe;break}if(Fe instanceof Error){j=Fe;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(j)throw j}if(X.length)for(let U=X.length-1;U>=0;U--){let j=X[U];if(j&&typeof j=="object"&&typeof j.onResponse=="function"){let ye=await j.onResponse({request:Z,response:T,schemaPath:y,params:O,options:bt,id:wt});if(ye){if(!(ye instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");T=ye}}}}let Er=T.headers.get("Content-Length");if(T.status===204||Z.method==="HEAD"||Er==="0"&&!T.headers.get("Transfer-Encoding")?.includes("chunked"))return T.ok?{data:void 0,response:T}:{error:void 0,response:T};if(T.ok)return{data:await(async()=>{if(M==="stream")return T.body;if(M==="json"&&!Er){let j=await T.text();return j?JSON.parse(j):void 0}return await T[M]()})(),response:T};let dn=await T.text();try{dn=JSON.parse(dn)}catch{}return{error:dn,response:T}}return{request(y,h,g){return u(h,{...g,method:y.toUpperCase()})},GET(y,h){return u(y,{...h,method:"GET"})},PUT(y,h){return u(y,{...h,method:"PUT"})},POST(y,h){return u(y,{...h,method:"POST"})},DELETE(y,h){return u(y,{...h,method:"DELETE"})},OPTIONS(y,h){return u(y,{...h,method:"OPTIONS"})},HEAD(y,h){return u(y,{...h,method:"HEAD"})},PATCH(y,h){return u(y,{...h,method:"PATCH"})},TRACE(y,h){return u(y,{...h,method:"TRACE"})},use(...y){for(let h of y)if(h){if(typeof h!="object"||!("onRequest"in h||"onResponse"in h||"onError"in h))throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");d.push(h)}},eject(...y){for(let h of y){let g=d.indexOf(h);g!==-1&&d.splice(g,1)}}}}function Ht(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 po(n,e,t){if(!e||typeof e!="object")return"";let r=[],o={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(let a in e)r.push(a,t.allowReserved===!0?e[a]:encodeURIComponent(e[a]));let i=r.join(",");switch(t.style){case"form":return`${n}=${i}`;case"label":return`.${i}`;case"matrix":return`;${n}=${i}`;default:return i}}for(let i in e){let a=t.style==="deepObject"?`${n}[${i}]`:i;r.push(Ht(a,e[i],t))}let s=r.join(o);return t.style==="label"||t.style==="matrix"?`${o}${s}`:s}function co(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){let s={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",i=(t.allowReserved===!0?e:e.map(a=>encodeURIComponent(a))).join(s);switch(t.style){case"simple":return i;case"label":return`.${i}`;case"matrix":return`;${n}=${i}`;default:return`${n}=${i}`}}let r={simple:",",label:".",matrix:";"}[t.style]||"&",o=[];for(let s of e)t.style==="simple"||t.style==="label"?o.push(t.allowReserved===!0?s:encodeURIComponent(s)):o.push(Ht(n,s,t));return t.style==="label"||t.style==="matrix"?`${r}${o.join(r)}`:o.join(r)}function oo(n){return function(t){let r=[];if(t&&typeof t=="object")for(let o in t){let s=t[o];if(s!=null){if(Array.isArray(s)){if(s.length===0)continue;r.push(co(o,s,{style:"form",explode:!0,...n?.array,allowReserved:n?.allowReserved||!1}));continue}if(typeof s=="object"){r.push(po(o,s,{style:"deepObject",explode:!0,...n?.object,allowReserved:n?.allowReserved||!1}));continue}r.push(Ht(o,s,n))}}return r.join("&")}}function oa(n,e){let t=n;for(let r of n.match(ta)??[]){let o=r.substring(1,r.length-1),s=!1,i="simple";if(o.endsWith("*")&&(s=!0,o=o.substring(0,o.length-1)),o.startsWith(".")?(i="label",o=o.substring(1)):o.startsWith(";")&&(i="matrix",o=o.substring(1)),!e||e[o]===void 0||e[o]===null)continue;let a=e[o];if(Array.isArray(a)){t=t.replace(r,co(o,a,{style:i,explode:s}));continue}if(typeof a=="object"){t=t.replace(r,po(o,a,{style:i,explode:s}));continue}if(i==="matrix"){t=t.replace(r,`;${Ht(o,a)}`);continue}t=t.replace(r,i==="label"?`.${encodeURIComponent(a)}`:encodeURIComponent(a))}return t}function sa(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 ia(n,e){let t=`${e.baseUrl}${n}`;e.params?.path&&(t=e.pathSerializer(t,e.params.path));let r=e.querySerializer(e.params.query??{});return r.startsWith("?")&&(r=r.substring(1)),r&&(t+=`?${r}`),t}function so(...n){let e=new Headers;for(let t of n){if(!t||typeof t!="object")continue;let r=t instanceof Headers?t.entries():Object.entries(t);for(let[o,s]of r)if(s===null)e.delete(o);else if(Array.isArray(s))for(let i of s)e.append(o,i);else s!==void 0&&e.set(o,s)}return e}function io(n){return n.endsWith("/")?n.substring(0,n.length-1):n}function lo(n,e,t){let r=new Map;return{onRequest({request:o,id:s}){let i=o.headers.get("content-type");(i===null||i.startsWith("application/json"))&&o.method!=="GET"&&o.method!=="HEAD"&&r.set(s,o.clone())},async onResponse({response:o,id:s,options:i}){let a=r.get(s);if(r.delete(s),o.status!==n||!a)return;let p=await o.clone().json().catch(()=>{});if(p?.error!==e)return;let l=await t(p.details??{},a),d=await a.text(),u=d?JSON.parse(d):{},y=new Headers(a.headers);y.set("content-type","application/json");let h=new Request(a.url,{method:a.method,headers:y,body:JSON.stringify({...u,...l}),signal:a.signal});return i.fetch(h)},onError({id:o}){r.delete(o)}}}function Gt(n){return lo(412,"CONFIRM_REQUIRED",async(e,t)=>({confirm:{challengeId:e.challengeId,assertion:await n(e,{request:t})}}))}function Ft(n){return lo(428,"OPERATOR_SIGNATURE_REQUIRED",async(e,t)=>({operatorProof:await n(e,{request:t})}))}async function c(n,e,t,r={}){let o=t??{},s={},i={},a={};for(let[u,y]of Object.entries(o))e.pathParams.includes(u)?s[u]=y:e.queryWhole&&u==="query"?Object.assign(i,y):!e.queryWhole&&e.query.includes(u)?i[u]=y:a[u]=y;for(let u of e.pathParams)if(s[u]===void 0)throw new TypeError(`${e.method} ${e.path}: no value for ${u}`);let p={params:{path:s,query:i}};e.body==="fields"?Object.values(a).every(y=>y===void 0)&&e.optionalBody||(p.body=a):e.body==="whole"?(a.body!==void 0||!e.optionalBody)&&(p.body=a.body):e.body==="raw"&&(p.body=a.body,p.bodySerializer=u=>u,p.headers={"Content-Type":a.contentType??e.media??"application/octet-stream"}),e.reply==="bytes"?p.parseAs="blob":e.reply==="text"&&(p.parseAs="text");let l=[];if(r.confirm){let u=r.confirm,y=e.userVerification?(h,g)=>u({userVerification:e.userVerification,...h},g):u;l.push(Gt(y))}r.operatorProof&&l.push(Ft(r.operatorProof)),l.length&&(p.middleware=l),r.signal&&(p.signal=r.signal);let d=n.request;return uo(d(e.method.toLowerCase(),e.path,p))}function Dn(n){return{apps:{abi:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/abi",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),access:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/access",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),attestation:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/attestation",pathParams:["app"],query:["nonce"],body:"none",optionalBody:!1,reply:"json"},e,t),blobDelete:(e,t)=>c(n,{method:"DELETE",path:"/apps/{app}/blobs/{id}",pathParams:["app","id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),blobDownload:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/blobs/{id}",pathParams:["app","id"],query:["grant"],body:"none",optionalBody:!1,reply:"bytes"},e,t),blobInfo:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/blobs/{id}/info",pathParams:["app","id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),blobList:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/blobs",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),blobRevoke:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/blobs/{id}/revoke",pathParams:["app","id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),blobUpload:(e,t)=>c(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)=>c(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)=>c(n,{method:"POST",path:"/apps",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),delete:(e,t)=>c(n,{method:"DELETE",path:"/apps/{app}",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),exportsExport:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/files/{id}/export",pathParams:["app","id"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),exportsSegment:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/files/{id}/segments/{k}",pathParams:["app","id","k"],query:[],body:"none",optionalBody:!1,reply:"bytes"},e,t),fileInfo:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/files/{id}",pathParams:["app","id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),filesList:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/files",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),filesUpload:(e,t)=>c(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)=>c(n,{method:"GET",path:"/apps/{app}",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),list:(e={},t)=>c(n,{method:"GET",path:"/apps",pathParams:[],query:["package","bundle"],body:"none",optionalBody:!1,reply:"json"},e,t),metadata:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/metadata",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),method:(e,t)=>c(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)=>c(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)=>c(n,{method:"GET",path:"/apps/{app}/openapi.json",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),pipelineReceiptReceipt:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/pipeline-runs/{run}/receipt",pathParams:["app","run"],query:["version"],body:"none",optionalBody:!1,reply:"json"},e,t),pipelinesCancel:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/pipeline-runs/{run}/cancel",pathParams:["app","run"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),pipelinesEstimateRun:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/pipelines/{name}/estimate",pathParams:["app","name"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),pipelinesGet:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/pipeline-runs/{run}",pathParams:["app","run"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),pipelinesList:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/pipeline-runs",pathParams:["app"],query:["limit"],body:"none",optionalBody:!1,reply:"json"},e,t),pipelinesRetry:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/pipeline-runs/{run}/retry",pathParams:["app","run"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),pipelinesStart:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/pipelines/{name}/runs",pathParams:["app","name"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),pipelinesValidate:(e,t)=>c(n,{method:"POST",path:"/pipelines/validate",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),presenceGet:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/presence",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),presencePublish:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/presence",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),run:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/runs/{run}",pathParams:["app","run"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),runLogs:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/runs/{run}/logs",pathParams:["app","run"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),runs:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/runs",pathParams:["app"],query:["limit","before"],body:"none",optionalBody:!1,reply:"json"},e,t),storage:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/storage",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),transfer:(e,t)=>c(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)=>c(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)=>c(n,{method:"DELETE",path:"/apps/{app}/files/uploads/{upload}",pathParams:["app","upload"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),uploadBegin:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/files/uploads",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),uploadComplete:(e,t)=>c(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)=>c(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)=>c(n,{method:"GET",path:"/apps/{app}/files/uploads/{upload}",pathParams:["app","upload"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),usage:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/usage",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),view:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/views",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),xcalls:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/xcalls",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},auth:{accountApps:(e={},t)=>c(n,{method:"GET",path:"/auth/apps",pathParams:[],query:["after","limit"],body:"none",optionalBody:!1,reply:"json"},e,t),accountBackupKey:(e={},t)=>c(n,{method:"GET",path:"/auth/backup-key",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),accountProofProve:(e,t)=>c(n,{method:"POST",path:"/auth/account-proof",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),accountRecoveryBegin:(e,t)=>c(n,{method:"POST",path:"/auth/recovery/begin",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),accountRecoveryCancel:(e={},t)=>c(n,{method:"POST",path:"/auth/recovery/cancel",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),accountRecoveryFinish:(e={},t)=>c(n,{method:"POST",path:"/auth/recovery/finish",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),accountRecoveryStart:(e,t)=>c(n,{method:"POST",path:"/auth/recovery/start",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),accountSetBackupKey:(e,t)=>c(n,{method:"POST",path:"/auth/backup-key",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),activityList:(e={},t)=>c(n,{method:"GET",path:"/auth/activity",pathParams:[],query:["after"],body:"none",optionalBody:!1,reply:"json"},e,t),aliasDelete:(e,t)=>c(n,{method:"DELETE",path:"/auth/aliases/{alias}",pathParams:["alias"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),aliasGet:(e,t)=>c(n,{method:"GET",path:"/auth/aliases/{alias}",pathParams:["alias"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),aliasList:(e={},t)=>c(n,{method:"GET",path:"/auth/aliases",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),aliasSet:(e,t)=>c(n,{method:"PUT",path:"/auth/aliases/{alias}",pathParams:["alias"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),apikeyCreate:(e={},t)=>c(n,{method:"POST",path:"/auth/apikeys",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),apikeyList:(e={},t)=>c(n,{method:"GET",path:"/auth/apikeys",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),apikeyRevoke:(e,t)=>c(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)=>c(n,{method:"POST",path:"/auth/passkey/login/begin",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json"},e,t),loginFinish:(e,t)=>c(n,{method:"POST",path:"/auth/passkey/login/finish",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),logout:(e={},t)=>c(n,{method:"POST",path:"/auth/logout",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),logoutAll:(e={},t)=>c(n,{method:"POST",path:"/auth/logout-all",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),me:(e={},t)=>c(n,{method:"GET",path:"/auth/me",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),passkeyAddBegin:(e={},t)=>c(n,{method:"POST",path:"/auth/passkeys/add/begin",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),passkeyAddFinish:(e,t)=>c(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)=>c(n,{method:"POST",path:"/auth/passkeys/{cred}",pathParams:["cred"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),passkeyRemove:(e,t)=>c(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)=>c(n,{method:"POST",path:"/auth/recovery",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),recoveryRemove:(e={},t)=>c(n,{method:"DELETE",path:"/auth/recovery",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),refresh:(e,t)=>c(n,{method:"POST",path:"/auth/refresh",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),registerBegin:(e={},t)=>c(n,{method:"POST",path:"/auth/passkey/register/begin",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),registerFinish:(e,t)=>c(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)=>c(n,{method:"DELETE",path:"/auth/sessions/{session}",pathParams:["session"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),sessionsList:(e={},t)=>c(n,{method:"GET",path:"/auth/sessions",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),usage:(e={},t)=>c(n,{method:"GET",path:"/auth/usage",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},consent:{pageCreate:(e,t)=>c(n,{method:"POST",path:"/consent/requests",pathParams:[],query:[],body:"whole",optionalBody:!1,reply:"json"},e,t),pageResult:(e,t)=>c(n,{method:"GET",path:"/consent/{request}/result",pathParams:["request"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},deployments:{create:(e,t)=>c(n,{method:"POST",path:"/deployments",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),delete:(e,t)=>c(n,{method:"DELETE",path:"/deployments/{id}",pathParams:["id"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),deployerGrant:(e,t)=>c(n,{method:"POST",path:"/deployers",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),deployerList:(e={},t)=>c(n,{method:"GET",path:"/deployers",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),deployerRevoke:(e,t)=>c(n,{method:"DELETE",path:"/deployers/{key}",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),get:(e,t)=>c(n,{method:"GET",path:"/deployments/{id}",pathParams:["id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),list:(e={},t)=>c(n,{method:"GET",path:"/deployments",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),offer:(e,t)=>c(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)=>c(n,{method:"GET",path:"/deployments/{id}/orgs",pathParams:["id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),signUpInviteCreate:(e={},t)=>c(n,{method:"POST",path:"/sign-up/invites",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),signUpInviteList:(e={},t)=>c(n,{method:"GET",path:"/sign-up/invites",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),signUpInviteRevoke:(e,t)=>c(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)=>c(n,{method:"GET",path:"/sign-up",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),signUpSet:(e,t)=>c(n,{method:"POST",path:"/sign-up",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),withdraw:(e,t)=>c(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)=>c(n,{method:"GET",path:"/ops/apps",pathParams:[],query:["after","limit"],body:"none",optionalBody:!1,reply:"json"},e,t),backup:(e={},t)=>c(n,{method:"POST",path:"/ops/backup",pathParams:[],query:["all"],body:"none",optionalBody:!1,reply:"json"},e,t),backupKey:(e={},t)=>c(n,{method:"GET",path:"/ops/backup-key",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),cluster:(e={},t)=>c(n,{method:"GET",path:"/ops/cluster",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),clusterOwner:(e,t)=>c(n,{method:"POST",path:"/ops/cluster-owner",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),deployerGrant:(e,t)=>c(n,{method:"POST",path:"/ops/deployers",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),deployerRevokeDelete:(e,t)=>c(n,{method:"DELETE",path:"/ops/deployers/{key}",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),deployerRevokePost:(e,t)=>c(n,{method:"POST",path:"/ops/deployers/{key}/revoke",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),deploymentsGranted:(e={},t)=>c(n,{method:"POST",path:"/ops/deployments/granted",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),jobNodeAttestation:(e,t)=>c(n,{method:"GET",path:"/ops/job-nodes/{id}/attestation",pathParams:["id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),metrics:(e={},t)=>c(n,{method:"GET",path:"/ops/metrics",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"text"},e,t),orgs:(e={},t)=>c(n,{method:"GET",path:"/ops/orgs",pathParams:[],query:["after","limit"],body:"none",optionalBody:!1,reply:"json"},e,t),orgUpgrade:(e,t)=>c(n,{method:"POST",path:"/ops/orgs/{org}/upgrade",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),outbound:(e,t)=>c(n,{method:"POST",path:"/ops/outbound",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),packageInstall:(e,t)=>c(n,{method:"POST",path:"/ops/packages/install",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),packageList:(e={},t)=>c(n,{method:"GET",path:"/ops/packages",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),packageUninstall:(e,t)=>c(n,{method:"DELETE",path:"/ops/packages/{package}",pathParams:["package"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),packageUpload:(e,t)=>c(n,{method:"POST",path:"/ops/packages",pathParams:[],query:[],body:"raw",optionalBody:!1,media:"application/octet-stream",reply:"json"},e,t),packageVersionUninstall:(e,t)=>c(n,{method:"DELETE",path:"/ops/packages/{package}/{version}",pathParams:["package","version"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),placement:(e={},t)=>c(n,{method:"GET",path:"/ops/placement",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),poolsGet:(e={},t)=>c(n,{method:"GET",path:"/ops/pools",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),poolsSet:(e,t)=>c(n,{method:"POST",path:"/ops/pools",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),pricesGet:(e={},t)=>c(n,{method:"GET",path:"/ops/prices",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),pricesSet:(e,t)=>c(n,{method:"POST",path:"/ops/prices",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),quotasGet:(e={},t)=>c(n,{method:"GET",path:"/ops/quotas",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),quotasSet:(e={},t)=>c(n,{method:"POST",path:"/ops/quotas",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),receiptKey:(e,t)=>c(n,{method:"GET",path:"/ops/nodes/{id}/receipt-key",pathParams:["id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),recover:(e,t)=>c(n,{method:"POST",path:"/ops/recover",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),recoveryFiles:(e={},t)=>c(n,{method:"GET",path:"/ops/recovery-files",pathParams:[],query:["holder"],body:"none",optionalBody:!1,reply:"json"},e,t),registerNode:(e,t)=>c(n,{method:"POST",path:"/ops/nodes",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),release:(e,t)=>c(n,{method:"POST",path:"/ops/releases",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),releaseDeadline:(e,t)=>c(n,{method:"POST",path:"/ops/releases/{version}/deadline",pathParams:["version"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),releaseDeadlineLift:(e,t)=>c(n,{method:"DELETE",path:"/ops/releases/{version}/deadline",pathParams:["version"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),removeNode:(e,t)=>c(n,{method:"DELETE",path:"/ops/nodes/{id}",pathParams:["id"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),restore:(e,t)=>c(n,{method:"POST",path:"/ops/apps/{app}/restore",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),served:(e={},t)=>c(n,{method:"GET",path:"/ops/served-origins",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),setBackupKey:(e,t)=>c(n,{method:"POST",path:"/ops/backup-key",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),setReplicas:(e,t)=>c(n,{method:"POST",path:"/ops/apps/{app}/replicas",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),signUpInviteCreate:(e,t)=>c(n,{method:"POST",path:"/ops/sign-up/invites",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),signUpInviteList:(e={},t)=>c(n,{method:"GET",path:"/ops/sign-up/invites",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),signUpInviteRevokeDelete:(e,t)=>c(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)=>c(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)=>c(n,{method:"POST",path:"/ops/sign-up",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),status:(e={},t)=>c(n,{method:"GET",path:"/ops/status",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),upgrade:(e,t)=>c(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)=>c(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)=>c(n,{method:"GET",path:"/orgs/{org}/apps",pathParams:["org"],query:["after","limit"],body:"none",optionalBody:!1,reply:"json"},e,t),appTeamList:(e,t)=>c(n,{method:"GET",path:"/orgs/{org}/app-teams",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),appTeamsScope:(e,t)=>c(n,{method:"POST",path:"/orgs/{org}/app-teams",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),backupKey:(e,t)=>c(n,{method:"GET",path:"/orgs/{org}/backup-key",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),capabilities:(e,t)=>c(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)=>c(n,{method:"POST",path:"/orgs",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),delete:(e,t)=>c(n,{method:"DELETE",path:"/orgs/{org}",pathParams:["org"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),get:(e,t)=>c(n,{method:"GET",path:"/orgs/{org}",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),inviteCreate:(e,t)=>c(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)=>c(n,{method:"GET",path:"/orgs/{org}/invites",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),inviteRedeem:(e,t)=>c(n,{method:"POST",path:"/invites/{token}/redeem",pathParams:["token"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),inviteRevoke:(e,t)=>c(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)=>c(n,{method:"POST",path:"/orgs/{org}/members/{account}/metadata",pathParams:["org","account"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),memberRemoveTeams:(e,t)=>c(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)=>c(n,{method:"GET",path:"/orgs/{org}/members",pathParams:["org"],query:["detail"],body:"none",optionalBody:!1,reply:"json"},e,t),memberSetTeams:(e,t)=>c(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)=>c(n,{method:"POST",path:"/orgs/{org}/metadata",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),outboundApproval:(e,t)=>c(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)=>c(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)=>c(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)=>c(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)=>c(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)=>c(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)=>c(n,{method:"POST",path:"/orgs/{org}/recovery/start",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),releaseApproval:(e,t)=>c(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)=>c(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)=>c(n,{method:"POST",path:"/orgs/{org}/name",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),setBackupKey:(e,t)=>c(n,{method:"POST",path:"/orgs/{org}/backup-key",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),setMember:(e,t)=>c(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)=>c(n,{method:"POST",path:"/orgs/{org}/teams",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),teamDelete:(e,t)=>c(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)=>c(n,{method:"GET",path:"/orgs/{org}/teams/{team}",pathParams:["org","team"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),teamRemoveMember:(e,t)=>c(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)=>c(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)=>c(n,{method:"POST",path:"/orgs/{org}/teams/{team}",pathParams:["org","team"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),upgrade:(e,t)=>c(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)=>c(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)=>c(n,{method:"GET",path:"/orgs/{org}/upgrades/{run}",pathParams:["org","run"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),usage:(e,t)=>c(n,{method:"GET",path:"/orgs/{org}/usage",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},packages:{bundlePut:(e,t)=>c(n,{method:"POST",path:"/bundles",pathParams:[],query:[],body:"raw",optionalBody:!1,media:"application/wasm",reply:"json"},e,t),capabilities:(e,t)=>c(n,{method:"GET",path:"/packages/{package}/{version}/capabilities",pathParams:["package","version"],query:["service"],body:"none",optionalBody:!1,reply:"json"},e,t),get:(e,t)=>c(n,{method:"GET",path:"/packages/{package}",pathParams:["package"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),install:(e,t)=>c(n,{method:"POST",path:"/packages/install",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),list:(e={},t)=>c(n,{method:"GET",path:"/packages",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),originsAdd:(e,t)=>c(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)=>c(n,{method:"GET",path:"/package-origins/{package}",pathParams:["package"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),originsRemove:(e,t)=>c(n,{method:"DELETE",path:"/package-origins/{package}",pathParams:["package"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),pipelines:(e,t)=>c(n,{method:"GET",path:"/packages/{package}/{version}/pipelines",pathParams:["package","version"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),uninstall:(e,t)=>c(n,{method:"DELETE",path:"/packages/{package}",pathParams:["package"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),upload:(e,t)=>c(n,{method:"POST",path:"/packages",pathParams:[],query:[],body:"raw",optionalBody:!1,media:"application/octet-stream",reply:"json"},e,t),versionUninstall:(e,t)=>c(n,{method:"DELETE",path:"/packages/{package}/{version}",pathParams:["package","version"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},public:{attestation:(e,t)=>c(n,{method:"GET",path:"/attestation",pathParams:[],query:["nonce","app","appHash","purpose"],body:"none",optionalBody:!1,reply:"json"},e,t),health:(e={},t)=>c(n,{method:"GET",path:"/health",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),publisherBinding:(e,t)=>c(n,{method:"GET",path:"/publishers/{signer}",pathParams:["signer"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),releasesPublic:(e={},t)=>c(n,{method:"GET",path:"/releases",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),restoreRecoverHolder:(e,t)=>c(n,{method:"POST",path:"/recover/holder",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t)}}}var In=[{method:"POST",path:"/apps/{app}/intents",requires:"idempotencyKey"},{method:"POST",path:"/apps/{app}/methods/{method}",requires:"idempotencyKey"},{method:"POST",path:"/apps/{app}/views"}];var yo="https://calimero-node.invalid",aa=new Set(["attestation","health"]),pa=In.map(n=>({method:n.method,pattern:new RegExp(`^${n.path.replace(/^\//,"").replace(/\{[^}]+\}/g,"[^/]+")}$`)})),ca=new Set(In.filter(n=>n.requires==="idempotencyKey").map(n=>`${n.method} ${n.path}`));function la(n){return async e=>{if(!e.url.startsWith(`${yo}/`))throw new Error(`not a route of the generated client: ${e.url}`);let t=new URL(e.url),r=t.pathname.replace(/^\/+/,""),o={};for(let[d,u]of t.searchParams)(o[d]??(o[d]=[])).push(u);let s=e.method;if(s==="GET"&&aa.has(r)&&n.inTheClear)return n.inTheClear(r,{query:o,signal:e.signal});let i=e.headers.get("content-type")??void 0,a=s==="GET"?void 0:new Uint8Array(await e.arrayBuffer()),p=a&&a.length>0?a:void 0,l=!1;return pa.some(d=>d.method===s&&d.pattern.test(r))&&(l=(p?JSON.parse(new TextDecoder().decode(p)):{}).confirm===void 0?!0:"once"),n.exchange(s,r,{query:o,...p?{bytes:p,contentType:i??"application/octet-stream"}:{},retry:l,signal:e.signal})}}var ua={async onRequest({request:n,schemaPath:e}){if(!ca.has(`${n.method} ${e}`))return;let t=await n.clone().text(),r=t?JSON.parse(t):{};if(r.idempotencyKey===void 0)return new Request(n,{body:JSON.stringify({...r,idempotencyKey:Mn()})})}};function Kn(n,e={}){let t=ao({baseUrl:yo,fetch:la(n)});return t.use(ua),e.confirm&&t.use(Gt(e.confirm)),e.operatorProof&&t.use(Ft(e.operatorProof)),t}async function uo(n){let{data:e,error:t,response:r}=await n;if(!r.ok)throw da(r,t);return e??{}}function da(n,e){let t=typeof e=="string"?e?{message:e}:{}:e;return Ue(n.status,t,n.headers.get("retry-after"))}var ya=n=>n/2**32|0,ha=n=>n>>>0;function ho(n,e,t,r){let o=ya(t),s=ha(t);n.setUint32(e,r?s:o,r),n.setUint32(e+4,r?o:s,r)}function fo(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}var $n=n=>n?`"${n}" `:"";function fa(n,e=""){if(typeof n!="number")throw new TypeError($n(e)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError($n(e)+"expected integer >= 0, got "+n);return n}function Ln(n,e,t=""){if(fo(n)&&(e===void 0||n.length===e))return n;e!==void 0&&fa(e,"length");let r=fo(n),o=e!==void 0?` of length ${e}`:"",s=r?`length=${n.length}`:`type=${typeof n}`,i=$n(t)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}var ga=(n,e)=>{if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof n)},go=(n,e)=>{ga(n,e);let t=Object.getPrototypeOf(n);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(n,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function Vn(n,e=!0){if(n.destroyed)throw new Error("hash was destroyed");if(e&&n.finished)throw new Error("digest() was already called")}function mo(n,e){Ln(n,void 0,"output");let t=e.outputLen;if(!(n.length>=t))throw new RangeError('"output" expected length >= '+t)}function Hn(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function zt(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function K(n,e){return n<<32-e|n>>>e}function ma(n,e,t="opts"){return go(n,"defaults"),e!==void 0&&go(e,t),Object.assign(Object.create(null),n,e)}function wo(n,e={}){if(typeof n!="function")throw new TypeError('"hashCons" expected function, got type='+typeof n);e=ma({},e,"info");let t=(o,s)=>n(s).update(o).digest(),r=n(void 0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.canXOF=r.canXOF,t.create=o=>n(o),Object.assign(t,e),Object.freeze(t)}var bo=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function Po(n,e,t){return n&e^~n&t}function Ao(n,e,t){return n&e^n&t^e&t}var Qt=class{constructor(e,t,r,o){E(this,"blockLen");E(this,"outputLen");E(this,"canXOF",!1);E(this,"padOffset");E(this,"isLE");E(this,"buffer");E(this,"view");E(this,"finished",!1);E(this,"length",0);E(this,"pos",0);E(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=zt(this.buffer)}update(e){Vn(this),Ln(e);let{view:t,buffer:r,blockLen:o}=this,s=e.length,i=!1;for(let a=0;a<s;){let p=Math.min(o-this.pos,s-a);if(p===o){let l=zt(e);for(;o<=s-a;a+=o)this.process(l,a);i=!0;continue}r.set(a===0&&p===s?e:e.subarray(a,a+p),this.pos),this.pos+=p,a+=p,this.pos===o&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){Vn(this),mo(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>o-i&&(this.process(r,0),t.fill(0)),ho(r,o-8,this.length*8,s),this.process(r,0),this.roundClean();let a=e===t?r:zt(e),p=this.outputLen,l=p/4,d=this.get();if(p%4||l>d.length)throw new Error("invalid outputLen");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=r,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},ko=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var wa=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ie=new Uint32Array(64),Gn=class extends Qt{constructor(t,r){super(64,t,8,!1);E(this,"A",0);E(this,"B",0);E(this,"C",0);E(this,"D",0);E(this,"E",0);E(this,"F",0);E(this,"G",0);E(this,"H",0);this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:t,B:r,C:o,D:s,E:i,F:a,G:p,H:l}=this;return[t,r,o,s,i,a,p,l]}set(t,r,o,s,i,a,p,l){this.A=t|0,this.B=r|0,this.C=o|0,this.D=s|0,this.E=i|0,this.F=a|0,this.G=p|0,this.H=l|0}_cloneInto(t){return(t||(t=new this.constructor)).set(...this.get()),this._cloneIntoMeta(t)}process(t,r){for(let y=0;y<16;y++,r+=4)ie[y]=t.getUint32(r,!1);for(let y=16;y<64;y++){let h=ie[y-15],g=ie[y-2],k=K(h,7)^K(h,18)^h>>>3,B=K(g,17)^K(g,19)^g>>>10;ie[y]=B+ie[y-7]+k+ie[y-16]|0}let{A:o,B:s,C:i,D:a,E:p,F:l,G:d,H:u}=this;for(let y=0;y<64;y++){let h=K(p,6)^K(p,11)^K(p,25),g=u+h+Po(p,l,d)+wa[y]+ie[y]|0,B=(K(o,2)^K(o,13)^K(o,22))+Ao(o,s,i)|0;u=d,d=l,l=p,p=a+g|0,a=i,i=s,s=o,o=g+B|0}o=o+this.A|0,s=s+this.B|0,i=i+this.C|0,a=a+this.D|0,p=p+this.E|0,l=l+this.F|0,d=d+this.G|0,u=u+this.H|0,this.set(o,s,i,a,p,l,d,u)}roundClean(){Hn(ie)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Hn(this.buffer)}},Fn=class extends Gn{constructor(){super(32,ko)}};var Ce=wo(()=>new Fn,bo(1));var ba=64*1024,Eo=16,Jt=ba+Eo,Xt=256*Jt,Yt=12,it=new TextEncoder,Pa=it.encode("calimero.file.v1"),Aa=it.encode("calimero.file.segments.v1\0"),ka=it.encode("calimero.export-wrap.v1"),_a=it.encode("calimero.sealed.derive.v1\0"),A=class extends Error{constructor(t,r){super(r);this.code=t;this.name="ExportError"}},Ro=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",n));function xo(n){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n.length,!1),Ro(f(Aa,e,...n))}function _o(n){let e=it.encode(n),t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e.length,!1),f(t,e)}async function To(n,e,t,r){if(r.length<Yt)throw new A("TAMPERED","the wrapped key is truncated");let o=await z(n.privateKey,e);if(o.every(d=>d===0))throw new A("BAD_ANSWER","the ephemeral key is of low order");let s=f(e,n.publicKey,_o(t.appId),_o(t.fileId)),i=await crypto.subtle.importKey("raw",o,"HKDF",!1,["deriveBits"]),a=await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:ka,info:f(_a,s)},i,256),p=await crypto.subtle.importKey("raw",a,"AES-GCM",!1,["decrypt"]),l;try{l=await crypto.subtle.decrypt({name:"AES-GCM",iv:r.subarray(0,Yt)},p,r.subarray(Yt))}catch{throw new A("TAMPERED","the wrapped key does not open")}if(l.byteLength!==32)throw new A("TAMPERED","the wrapped key has the wrong length");return new Uint8Array(l)}var Wt=class n{constructor(e,t){this.key=e;this.segments=t;this.pending=new Uint8Array;this.index=0;this.next=0;this.size=0;this.hash=Ce.create()}static async create(e,t){let r=await crypto.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]);return new n(r,t.map(m))}async push(e,t){let r=this.segments[this.next];if(r===void 0)throw new A("TAMPERED",`the file has no segment ${this.next}`);if(this.next+1<this.segments.length&&e.length!==Xt)throw new A("TAMPERED",`segment ${this.next} is not a whole segment`);if(m(await Ro(e))!==r)throw new A("TAMPERED",`segment ${this.next} is not the one the file lists`);this.next+=1;let o=f(this.pending,e),s=0;for(;o.length-s>Jt;)await t(await this.open(o.subarray(s,s+Jt),!1)),s+=Jt;this.pending=o.slice(s)}async finishExpecting(e,t){if(this.next!==this.segments.length)throw new A("TAMPERED","the file is missing segments");if(this.pending.length<Eo)throw new A("TAMPERED","the file is truncated");let r=await this.open(this.pending,!0);if(this.size!==e||m(this.hash.digest())!==t)throw new A("TAMPERED","the file is not the one that was sealed");return r}async open(e,t){let r=new Uint8Array(Yt);new DataView(r.buffer).setBigUint64(4,BigInt(this.index),!1);let o;try{o=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:r,additionalData:f(Pa,new Uint8Array([t?1:0]))},this.key,e))}catch{throw new A("TAMPERED",`chunk ${this.index} does not open: the file is altered, truncated or under another key`)}return this.hash.update(o),this.size+=o.length,this.index+=1,o}};function at(n,e,t){if(typeof n!="string")throw new A("BAD_ANSWER",`the node answered a bad ${e}`);try{return t===void 0?Rr(n,e):x(n,e,t)}catch{throw new A("BAD_ANSWER",`the node answered a bad ${e}`)}}function Ea(n){let e=n;if(typeof e!="object"||e===null)throw new A("BAD_ANSWER","the node answered a bad export");if(typeof e.app!="string")throw new A("BAD_ANSWER","the node answered a bad app");if(typeof e.size!="number"||!Number.isSafeInteger(e.size)||e.size<0)throw new A("BAD_ANSWER","the node answered a bad size");if(!Array.isArray(e.segments))throw new A("BAD_ANSWER","the node answered a bad segment list");return{app:e.app,size:e.size,named:at(e.id,"file id",32),segments:e.segments.map(t=>at(t,"segment hash",32)),sha256:m(at(e.sha256,"sha256",32)),ephemeral:at(e.ephemeral,"ephemeral key",32),wrapped:at(e.wrapped,"wrapped key")}}var zn=()=>new A("ABORTED","the export was aborted");async function Ra(n,e){let t=Number(n.headers.get("content-length"));if(Number.isFinite(t)&&t>Xt)throw await n.body?.cancel(),new A("TOO_LARGE","a segment is longer than a whole segment");if(!n.body)return new Uint8Array;let r=n.body.getReader(),o=()=>{r.cancel()};e?.addEventListener("abort",o);let s=[],i=0;try{for(;;){let{done:a,value:p}=await r.read();if(a)break;if(i+=p.length,i>Xt)throw await r.cancel(),new A("TOO_LARGE","a segment is longer than a whole segment");s.push(p)}}finally{e?.removeEventListener("abort",o)}if(e?.aborted)throw zn();return f(...s)}async function Qn(n,e,t,r,o,s){try{return await xa(n,e,t,r,o,s)}catch(i){throw o?.aborted&&!(i instanceof A)?zn():i}}async function xa(n,e,t,r,o,s){let i=await I(s),a=Ea(await n.exportsExport({app:e,id:t,recipient:m(i.publicKey)},{signal:o})),{segments:p,named:l}=a;if(p.length===0||m(await xo(p))!==m(l)||m(l)!==t)throw new A("NOT_THE_FILE",`the node answered segments that are not the file ${t}`);let d=await To(i,a.ephemeral,{appId:a.app,fileId:t},a.wrapped),u=await Wt.create(d,p);for(let h=0;h<p.length;h+=1){if(o?.aborted)throw zn();let g=await n.request("GET",Ae("apps/{app}/files/{id}/segments/{k}",{app:e,id:t,k:h}),{signal:o});await u.push(await Ra(g,o),k=>r.write(k))}let y=await u.finishExpecting(a.size,a.sha256);return y.length>0&&await r.write(y),{size:a.size,sha256:a.sha256}}async function jo(n,e,t,r){let o=[];return await Qn(n,e,t,{write:s=>{o.push(s)}},r),f(...o)}var vo="calimero.org-recovery.v1\0",Yn=64,Jn=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function Ta(){return crypto.getRandomValues(new Uint8Array(32))}function ja(n){So(n);let e=Array.from(n,r=>r.toString(16).padStart(2,"0")).join(""),t=[];for(let r=0;r<e.length;r+=8)t.push(e.slice(r,r+8));return t.join("-")}function va(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,r)=>parseInt(e.slice(2*r,2*r+2),16))}function Oo(n,e,t){return new TextEncoder().encode(`${vo}${n}\0${e}\0${t}`)}async function Zt(n){let e=await Be(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 Wn(n,e,t,r){let o=new TextEncoder().encode(r).length;if(o===0||o>Yn)throw new Error(`a recovery nonce is 1 to ${Yn} bytes`);let s=await Be(n,!1),i=await crypto.subtle.sign("Ed25519",s,S(Oo(e,t,r)));return R(new Uint8Array(i))}function So(n){if(n.length!==32)throw new Error("a recovery seed is 32 bytes")}function Be(n,e){So(n);let t=new Uint8Array(Jn.length+32);return t.set(Jn),t.set(n,Jn.length),crypto.subtle.importKey("pkcs8",S(t),{name:"Ed25519"},e,["sign"])}var S=n=>n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);var Uo=1,Oa=new TextEncoder().encode("calimero.recovery-backup.v1\0"),Sa=new TextEncoder().encode("calimero.recovery-backup.v1"),Ua=new TextEncoder().encode("calimero.recovery-backup.key.v1"),Bo=32,Ca=1,Ba=2,Na=0,D=n=>new TextEncoder().encode(n),ct=n=>new Uint8Array([n>>8&255,n&255]),Co=f(D("KEM"),ct(Bo)),pt=f(D("HPKE"),ct(Bo),ct(Ca),ct(Ba));function Ne(n){return n.kind==="operator"?"operator":`${n.kind}:${n.id}`}async function ou(){let n=crypto.getRandomValues(new Uint8Array(32));return{secret:n,publicKey:await Ma(n)}}async function Ma(n){return m((await I(n)).publicKey)}async function qa(n){let e=D(n.header),t=JSON.parse(n.header);if(typeof t.format!="number"||t.format>Uo)throw new Error(`recovery file format ${t.format} is not one this release reads (${Uo})`);let r=await crypto.subtle.importKey("raw",x(t.signingKey,"signing key",32),{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify("Ed25519",r,x(n.signature,"signature",64),f(Oa,e)))throw new Error("the node's signature over the header does not hold");return t}async function No(n,e){let t=n.length===0?new Uint8Array(32):n,r=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",r,e))}async function Da(n,e,t){let r=new Uint8Array(t),o=new Uint8Array(0);for(let s=1,i=0;i<t;s+=1)o=await No(n,f(o,e,new Uint8Array([s]))),r.set(o.subarray(0,Math.min(o.length,t-i)),i),i+=o.length;return r}var en=(n,e,t,r)=>No(e,f(D("HPKE-v1"),n,D(t),r)),Xn=(n,e,t,r,o)=>Da(e,f(ct(o),D("HPKE-v1"),n,D(t),r),o);async function Ia(n,e){let t=await I(e);if(m(t.publicKey)!==n.recipient)throw new Error("this key is not the one the file was sealed to");let r=x(n.enc,"encapsulated key",32),o=await z(t.privateKey,r),s=new Uint8Array(0),i=await en(Co,s,"eae_prk",o),a=await Xn(Co,i,"shared_secret",f(r,t.publicKey),32),p=await en(pt,s,"psk_id_hash",s),l=await en(pt,s,"info_hash",Sa),d=f(new Uint8Array([Na]),p,l),u=await en(pt,a,"secret",s),y=await Xn(pt,u,"key",d,32),h=await Xn(pt,u,"base_nonce",d,12),g=await crypto.subtle.importKey("raw",y,"AES-GCM",!1,["decrypt"]),k;try{k=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:h,additionalData:Ua},g,x(n.wrappedKey,"wrapped key",48)))}catch{throw new Error("this key does not open the file")}if(k.length!==32)throw new Error("the data key is not 32 bytes");return k}async function su(n,e,t,r={}){let o=[];for(let p of[...e].sort((l,d)=>l.name.localeCompare(d.name))){let l=await qa(p);if(r.verifyQuote&&await $a(l,r.verifyQuote),Ne(l.holder)!==Ne(n))throw new Error(`${p.name} is ${Ne(l.holder)}'s, not ${Ne(n)}'s`);o.push({name:p.name,header:l})}let s=async p=>({file:p.name,key:m(await Ia(p.header,t))}),i=o.filter(p=>p.header.kind==="holder").pop();if(!i)throw new Error(`no holder file of ${Ne(n)}`);let a=new Map;for(let p of o)p.header.kind==="app"&&p.header.app&&(!r.apps||r.apps.includes(p.header.app))&&a.set(p.header.app,p);return{holder:Ne(n),slice:await s(i),apps:await Promise.all([...a.values()].map(s)),code:await Promise.all(o.filter(p=>p.header.kind==="code").map(s))}}async function Zn(n){return new Uint8Array(await crypto.subtle.digest("SHA-256",n))}async function Ka(n,e){let t=D(n),r=new Uint8Array(4);new DataView(r.buffer).setUint32(0,t.length,!1);let o=new Uint8Array(8);return new DataView(o.buffer).setBigUint64(0,BigInt(e),!1),m(await Zn(f(D("calimero.recovery-backup.attest.v1\0"),r,t,o)))}var Me=(n,e,t,r)=>{if(n===void 0&&r)return r;if(!e.includes(n))throw new Error(`the governance's ${t} is not one of ${e.join(", ")}`);return n};function er(n){let e={releases:Me(n.releases,["owner","operator"],"releases"),appUpgrades:Me(n.appUpgrades,["owner","operator"],"appUpgrades"),outbound:Me(n.outbound,["owner","operator"],"outbound")},t=Me(n.deployments,["open","granted"],"deployments","open");t!=="open"&&(e.deployments=t);let r=Me(n.deployers,["operator","owner"],"deployers","operator");r!=="operator"&&(e.deployers=r);let o=Me(n.signUp,["open","invite","closed"],"signUp","open");return o!=="open"&&(e.signUp=o),D(JSON.stringify(e))}async function tr(n,e,t,r){let o=await Zn(er(e)),s=D(t),i=new Uint8Array(4);new DataView(i.buffer).setUint32(0,s.length,!1);let a=new Uint8Array(8);return new DataView(a.buffer).setBigUint64(0,BigInt(r),!1),m(await Zn(f(D("calimero.tee-attest.receipt-key.v3"),n,o,i,s,a)))}async function $a(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 r=await Ka(n.cluster,n.node);if(t.nonce!==r)throw new Error("the attestation is not over the recovery nonce");if(!t.governance)throw new Error("the attestation names no governance");let o=await tr(x(n.signingKey,"signing key",32),t.governance,n.cluster,n.node);if(!await e({quoteB64:t.quote,nonce:r,reportDataSuffix:o}))throw new Error("the quote was not accepted")}var nr=1024*1024,rr=16,or=64*1024,sr=512*1024*1024,ir=(64*1024*1024-1024*1024)/4*3,La="did:key:z6MknF3p5L5FDHJQ7FREUapuX4Wmp4MtF6WrHYaXS2B3eZQd",Va=new TextEncoder().encode("calimero.bundle.manifest.v1\0"),Ha="0.1.0",Ga=[237,1],Fa="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",za=[0,97,115,109,13,0,1,0],Qa=/^pipelines\/[A-Za-z0-9._-]+\.yaml$/,Ja=/^[A-Za-z0-9_-]{43}$/,Ya=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,qe=n=>new TextEncoder().encode(n),tn=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),nn=(...n)=>{let e=new Uint8Array(n.reduce((r,o)=>r+o.length,0)),t=0;for(let r of n)e.set(r,t),t+=r.length;return e};async function lt(){let n=new Error("this runtime cannot sign Ed25519 packages (WebCrypto Ed25519 is missing)");if(!globalThis.crypto?.subtle)throw n;try{await Be(new Uint8Array(32),!1)}catch{throw n}}async function Io(n){if(await lt(),n.length!==32)throw new Error("a publisher seed is 32 bytes");let e=C(await Zt(n));return{seed:Uint8Array.from(n),publicKey:e}}async function Wa(){return await lt(),Io(crypto.getRandomValues(new Uint8Array(32)))}async function Xa(n){return await lt(),{privateKey:await Be(Uint8Array.from(n.seed),!1),publicKey:Uint8Array.from(n.publicKey)}}function Za(n){let e=0n;for(let r of n)e=e<<8n|BigInt(r);let t="";for(;e>0n;e/=58n)t=Fa[Number(e%58n)]+t;return"1".repeat(n.findIndex(r=>r!==0)===-1?n.length:n.findIndex(r=>r!==0))+t}function De(n){return`did:key:z${Za(nn(Uint8Array.from(Ga),n.publicKey))}`}function ep(n){return De(n)===La}function tp(n){return qe(JSON.stringify({private_key:R(n.seed),public_key:R(n.publicKey),signer_id:De(n)},null,2))}async function np(n){let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new Error("a publisher key backup is a JSON document")}let t=e?.private_key;if(typeof t!="string"||!Ja.test(t)||R(C(t))!==t)throw new Error("the backup private_key is not an unpadded base64url 32-byte seed");let r=await Io(C(t));if(e.public_key!==void 0&&e.public_key!==R(r.publicKey))throw new Error("the backup public_key is not the seed's");if(e.signer_id!==void 0&&e.signer_id!==De(r))throw new Error("the backup signer_id is not the seed's");return r}function Ko(n){let e=Object.fromEntries(Object.entries(n).filter(([t])=>t!=="signature"&&!t.startsWith("_")));return qe(ke(e))}function ke(n,e=!1){if(typeof n=="string"){if(/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(n))throw new Error("a lone surrogate cannot be canonicalized");return JSON.stringify(n)}if(typeof n=="number"){if(e?!Number.isFinite(n):!Number.isSafeInteger(n))throw new Error(e?"a non-finite number cannot be canonicalized":"only safe integers can be canonicalized");return String(n)}if(n===null||typeof n=="boolean")return String(n);if(typeof n!="object")throw new Error(`a ${typeof n} cannot be canonicalized`);return Array.isArray(n)?`[${n.map(t=>ke(t,e)).join(",")}]`:`{${Object.keys(n).sort().map(t=>`${ke(t,e)}:${ke(n[t],e)}`).join(",")}}`}async function ar(n){return Ce(nn(Va,Ko(n)))}async function rp(n){await lt();let e=n.signature;if(!e)throw new Error("manifest is missing required 'signature' field");if(e.algorithm!=="ed25519")throw new Error(`unsupported signature algorithm: '${e.algorithm}'`);let t=C(e.publicKey??""),r=C(e.signature??"");if(t.length!==32||r.length!==64)throw new Error("malformed signature field");let o=await crypto.subtle.importKey("raw",S(t),{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify("Ed25519",o,S(r),S(await ar(n))))throw new Error("Ed25519 signature verification failed");let i=De({publicKey:t});if(n.signerId!==i)throw new Error(`signerId mismatch: manifest declares '${n.signerId}' but signature public key derives to '${i}'`);return i}function Mo(n,e){if(!n)throw new Error(`${e} is empty`);if(n.includes(".."))throw new Error(`${e} contains path traversal sequence '..'`);if(n.includes("/")||n.includes("\\"))throw new Error(`${e} contains directory separator`);if(n.includes("\0"))throw new Error(`${e} contains null byte`);if(n.length>=2&&n[1]===":")throw new Error(`${e} appears to be an absolute path`)}function op(n,e){if(!n)throw new Error(`${e} is empty`);if(n.includes("\0"))throw new Error(`${e} contains null byte`);if(n.includes("\\"))throw new Error(`${e} contains backslash (use forward slashes)`);if(n.startsWith("/"))throw new Error(`${e} is an absolute path`);if(n[1]===":")throw new Error(`${e} appears to be an absolute Windows path`);if(n.split("/").includes(".."))throw new Error(`${e} contains path traversal component '..'`);if(!Qa.test(n)||qe(n).length>100)throw new Error(`${e} must be pipelines/<name>.yaml (A-Z a-z 0-9 . _ -), at most 100 bytes`)}var qo=["name","description","author","icon","license","category","guide"];function sp(n){let e=s=>new Error(`metadata ${s}`);if(typeof n!="object"||n===null||Array.isArray(n))throw e("must be an object");let t=new Set([...qo,"tags"]),r=Object.keys(n).find(s=>!t.has(s));if(r!==void 0)throw e(`has an unknown field '${r}'`);let o={};for(let s of qo){let i=n[s];if(i!==void 0){if(typeof i!="string")throw e(`${s} must be a string`);o[s]=i}}if(typeof o.name!="string")throw e("name is required");if(n.tags!==void 0){if(!Array.isArray(n.tags)||n.tags.some(s=>typeof s!="string"))throw e("tags must be an array of strings");o.tags=[...n.tags]}return o}var Do=(n,e)=>({path:n,hash:tn(Ce(e)),size:e.length}),$o=n=>512+Math.ceil(n/512)*512;function ip(n,e){let t=new Uint8Array(512),r=(o,s)=>t.set(qe(s),o);return r(0,n),r(100,"0000644\0"),r(108,"0000000\0"),r(116,"0000000\0"),r(124,`${e.length.toString(8).padStart(11,"0")}\0`),r(136,"00000000000\0"),r(148," "),r(156,"0"),r(257,"ustar\0"),r(263,"00"),r(148,`${t.reduce((o,s)=>o+s,0).toString(8).padStart(6,"0")}\0 `),nn(t,e,new Uint8Array((512-e.length%512)%512))}function ap(n){let e=new Map,t=(r,o)=>new TextDecoder().decode(n.subarray(r,o)).replace(/\0.*$/s,"");for(let r=0;r+512<=n.length&&n[r]!==0;){let o=t(r,r+100),s=parseInt(t(r+124,r+136).trim(),8);if(e.has(o))throw new Error(`the archive has more than one entry at '${o}'`);e.set(o,n.subarray(r+512,r+512+s)),r+=$o(s)}return e}async function pp(n,e){let t=ap(n),r=t.get("manifest.json");if(!r)throw new Error("manifest.json not found in bundle");let o=JSON.parse(new TextDecoder().decode(r));if(await rp(o),o.signature.publicKey!==R(e))throw new Error("the manifest is not signed by the publisher key");let s=[o.compute,...o.pipelines??[]],i=["manifest.json",...s.map(a=>a.path)];if(i.length!==t.size||i.some(a=>!t.has(a)))throw new Error("the archive does not hold exactly the files its manifest declares");for(let a of s){let p=t.get(a.path);if(!p||p.length!==a.size||tn(Ce(p))!==a.hash)throw new Error(`bundle artifact '${a.path}' failed its integrity check`)}}async function cp(n){if(typeof CompressionStream>"u")throw new Error("this runtime cannot gzip packages (no CompressionStream)");let e=new Blob([S(n)]).stream().pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(e).arrayBuffer())}async function lp(n,e,t){if(e){let o=C(await Zt(e));if(tn(o)!==tn(t))throw new Error("the publisher key's publicKey is not its seed's");return{signing:await Be(e,!1),publicKey:o}}let r=n.privateKey;if(r?.algorithm?.name!=="Ed25519"||r.type!=="private"||!r.usages.includes("sign"))throw new Error("the publisher key is not an Ed25519 signing key");return{signing:r,publicKey:t}}async function up(n,e){let t="seed"in e&&e.seed?Uint8Array.from(e.seed):void 0,r=Uint8Array.from(e.publicKey),o=dp(n);await lt();let{signing:s,publicKey:i}=await lp(e,t,r),a={...o.manifest,signerId:De({publicKey:i})},p=await crypto.subtle.sign("Ed25519",s,S(await ar(a)));a.signature={algorithm:"ed25519",publicKey:R(i),signature:R(new Uint8Array(p))};let l=qe(ke(a));if(l.length>nr)throw new Error(`bundle manifest.json exceeds the ${nr} byte cap`);let d=[["manifest.json",l],["compute.wasm",o.compute],...o.files];Lo(d.map(([,h])=>h.length));let u=nn(...d.map(([h,g])=>ip(h,g)),new Uint8Array(1024));await pp(u,i);let y=await cp(u);if(y.length>ir)throw new Error(`a package is limited to ${ir>>20} MiB`);return y}function Lo(n){if(n.reduce((e,t)=>e+$o(t),1024)>sr)throw new Error(`bundle archive exceeds the ${sr} byte decompressed cap`)}function dp(n){if(Mo(n.package,"package"),Mo(n.version,"appVersion"),!Ya.test(n.version))throw new Error(`appVersion '${n.version}' is not a semantic version`);if(!n.compute?.length)throw new Error("the package ships no WASM");if(n.pipelines.length>rr)throw new Error(`bundle declares ${n.pipelines.length} pipelines, at most ${rr} are allowed`);Lo([n.compute.length]);let e=Uint8Array.from(n.compute);if(za.some((a,p)=>e[p]!==a))throw new Error("compute: not a WASM component (an SDK 0.12 core module is refused by the node)");let t=n.pipelines.map((a,p)=>(op(a.path,`pipelines[${p}].path`),[a.path,qe(a.source)])),r=t.find(([,a])=>a.length>or);if(r)throw new Error(`pipeline '${r[0]}' exceeds the ${or} byte cap`);let o=t.map(([a])=>a.toLowerCase());if(new Set(o).size!==t.length)throw new Error("two pipelines have the same path");let s=n.metadata===void 0?void 0:sp(n.metadata);return{manifest:{version:"1.0",package:n.package,appVersion:n.version,minRuntimeVersion:Ha,...s?{metadata:s}:{},compute:Do("compute.wasm",e),...t.length?{pipelines:t.map(([a,p])=>Do(a,p))}:{}},compute:e,files:t}}var Qo="calimero.pipeline.receipt.v1\0",pe=n=>new TextEncoder().encode(n),H=(n,e)=>{throw new Error(`the receipt's ${n} ${e}`)},ae=(n,e)=>Object.prototype.hasOwnProperty.call(n,e),J=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),w=(n,e)=>typeof n=="string"||H(e,"is not a string"),Jo=(n,e)=>typeof n=="boolean"||H(e,"is not a boolean"),yp=()=>{},Vo=(n,e)=>J(n)||H(e,"is not an object"),hp=n=>(e,t)=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=n||H(t,"is not an unsigned integer in range"),rn=hp(4294967295),$e=(n,e)=>typeof n=="number"&&Number.isInteger(n)&&n>=0&&n<2**64||H(e,"is not an unsigned integer in range"),Le=n=>(e,t)=>{Array.isArray(e)||H(t,"is not an array"),e.forEach((r,o)=>n(r,`${t}[${o}]`))},ut=n=>(e,t)=>{J(e)||H(t,"is not an object");for(let[r,o]of Object.entries(e))n(o,`${t}.${r}`)},G=(n,e={},t={},r=!1)=>(o,s)=>{if(!J(o))return H(s,"is not an object");for(let i of Object.keys(o))!r&&!ae(n,i)&&!ae(e,i)&&!ae(t,i)&&H(`${s}.${i}`,"is not a known field");for(let[i,a]of Object.entries(n))ae(o,i)||H(`${s}.${i}`,"is missing"),a(o[i],`${s}.${i}`);for(let[i,a]of Object.entries(e))ae(o,i)&&o[i]!==null&&a(o[i],`${s}.${i}`);for(let[i,a]of Object.entries(t))ae(o,i)&&a(o[i],`${s}.${i}`)},Yo=G({id:w,size:$e,sha256:w}),fp=G({id:w,size:$e,sha256:w,segments:Le(w)}),gp=G({resultSha256:w,segments:Le(Le(w))},{log:fp},{message:w}),mp=G({quote:w,transportKey:w,appHash:w,nonce:w,release:G({version:w,profile:w},{},{},!0),cluster:w,node:$e,mock:Jo},{receiptKey:w,governance:Vo,kms:Vo,jobKey:w,clusterIdentity:w},{},!0),wp=G({run:w,step:w,index:rn,outcome:w,attempt:rn,outputs:Le(Yo),usage:G({cpuMicros:w,gibMicros:w,fuel:w})},{node:$e,jobKey:w,assignmentDigest:w,reportSha256:w,signature:w,job:gp}),bp=G({index:rn,cached:Jo,cacheKey:w}),Pp=(n,e)=>{try{bp(n,e)}catch{wp(n,e)}},Ap=G({version:rn,cluster:w,app:w,run:w,pipeline:w,release:w,pipelineHash:w,modules:ut(w),inputs:ut(Le(Yo)),params:ut(yp),state:w,startTsMs:$e,endTsMs:$e,steps:ut(G({status:w,runs:Le(Pp)},{reason:w}))},{costSoFar:w},{jobAttestations:ut(mp)});function on(n,e,t){if(typeof n!="string"||n.length!==t*2||!/^[0-9a-fA-F]*$/.test(n))throw new Error(`${e} is not ${t} bytes of hex`);return x(n,e,t)}function pr(n,e){if(typeof n!="number"||!Number.isSafeInteger(n)||n<0)throw new Error(`${e} is not a node id`);return n}async function Wo(n,e,t,r,o){if(typeof n.quote!="string")throw new Error("the attestation carries no quote");if(!n.receiptKey)throw new Error("the attestation names no receipt key");if(!J(n.governance))throw new Error("the attestation names no governance");let s=on(n.receiptKey,"the receipt key",32),i=x(await tr(s,n.governance,t,r),"binding",32);return await xt(n,e,i,o,"receipt key"),{key:s,governance:JSON.parse(new TextDecoder().decode(er(n.governance)))}}async function an(n,e,t){let r=crypto.getRandomValues(new Uint8Array(32)),o=await n.apps.attestation({app:e,nonce:m(r)});if(!J(o)||typeof o.cluster!="string"||!Array.isArray(o.replicas))throw new Error("the node answered a malformed attestation");let s=o.cluster,i=new Map,a;for(let p of o.replicas){if(!J(p))throw new Error("a replica entry is not an object");let l=pr(p.node,"a replica");if(ae(p,"error"))throw new Error(`replica ${l} gave no attestation: ${String(p.error)}`);let d=p.attestation;if(!J(d))throw new Error(`replica ${l} gave neither an attestation nor an error`);if(pr(d.node,`replica ${l}'s document`)!==l)throw new Error(`replica ${l} answered as node ${String(d.node)}`);let u;try{u=await Wo(d,r,s,l,t)}catch(y){throw new Error(`replica ${l}: ${y instanceof Error?y.message:String(y)}`)}if(a&&JSON.stringify(a)!==JSON.stringify(u.governance))throw new Error(`replica ${l} attests other governance`);a=u.governance,i.set(l,u.key)}if(!a)throw new Error(`no replica of ${e} attested`);return{keys:i,governance:a,cluster:s}}var Xo=n=>ke(n,!0),kp=n=>f(pe(Qo),pe(Xo(n)));async function _p(n,e){if(!J(n))throw new Error("the receipt answer is not an object");let t=Object.keys(n).find(a=>!["receipt","node","signature"].includes(a));if(t!==void 0)throw new Error(`the receipt answer's ${t} is not a known field`);let r=on(n.signature,"the signature",64),o=Xo(n.receipt),s=await crypto.subtle.importKey("raw",S(e),{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify("Ed25519",s,S(r),S(f(pe(Qo),pe(o)))))throw new Error("the receipt is not signed by that key");let i=JSON.parse(o);return Ap(i,"receipt"),i}var Ep="calimero.compute.report.v1\0",Rp="calimero.compute.report.log.v1\0",xp="calimero.tee-attest.job-key.v1",Ho=2,Tp=["fuel","memory","trap","app-error","integrity","cancelled"],jp=["lost","refused","timeout","quota","not-granted","too-large"],Zo=2n**64n-1n,es=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",S(n))),sn=n=>{let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n,!1),e},cr=n=>{let e=BigInt(n);if(e<0n||e>Zo)throw new Error("a number is past 2^64-1");let t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,e,!1),t},Ke=n=>{let e=pe(n);return f(sn(e.length),e)};function _e(n){if(typeof n!="string"||!/^[0-9a-f]{64}$/.test(n))throw new Error("a hash is 64 lowercase hex digits");return x(n,"hash",32)}function vp(n){if(!/^[0-9]+$/.test(n))throw new Error(`${JSON.stringify(n)} is not a decimal integer`);let e=BigInt(n);if(e>Zo)throw new Error(`${JSON.stringify(n)} is not a decimal integer`);return e}function Go(n){return f(_e(n.id),cr(n.size),_e(n.sha256),sn(n.segments.length),...n.segments.map(_e))}function ts(n){return f(pe(Ep),_e(n.assignment),Ke(n.app),Ke(n.run),sn(n.attempt),new Uint8Array([n.reason===null?0:1]),Ke(n.reason??""),Ke(n.message),_e(n.resultSha256),sn(n.outputs.length),...n.outputs.map(Go),...n.usage.map(e=>cr(vp(e))),...n.log?[pe(Rp),Go(n.log)]:[])}async function ns(n,e,t,r,o,s){return m(await es(f(pe(xp),n,e,Ke(t),Ke(r),cr(o),s??new Uint8Array(0))))}function Op(n,e){if(n==="done")return{reason:null};if(n==="cancelled")return e?{reason:"cancelled"}:null;let t=()=>new Error(`the outcome ${JSON.stringify(n)} is not one a run ends with`);if(!n.startsWith("failed:"))throw t();let r=n.slice(7);if(Tp.includes(r))return{reason:r};if(!jp.includes(r))throw t();return null}var Sp=2n**252n+27742317777372353535851937790883648493n,P=2n**255n-19n,Fo=(P-121665n)%P*Ie(121666n,P-2n)%P;function Ie(n,e){let t=1n;for(n%=P;e>0n;e>>=1n,n=n*n%P)e&1n&&(t=t*n%P);return t}function zo(n){let e=0n;for(let a=31;a>=0;a--)e=e<<8n|BigInt(n[a]&(a===31?127:255));e%=P;let t=n[31]>>7&1,r=e*e%P,o=(r-1n+P)%P*Ie((Fo*r+1n)%P,P-2n)%P,s=Ie(o,(P+3n)/8n);if(s*s%P!==o&&(s=s*Ie(2n,(P-1n)/4n)%P),s*s%P!==o)return!1;Number(s&1n)!==t&&(s=(P-s)%P);let i=[s,e];for(let a=0;a<3;a++){let[p,l]=i,d=Fo*p*p*l*l%P;i=[2n*p*l*Ie((1n+d)%P,P-2n)%P,(l*l+p*p)*Ie((1n-d+P)%P,P-2n)%P]}return i[0]===0n&&i[1]===1n}async function Up(n,e,t){let r=0n;for(let s=63;s>=32;s--)r=r<<8n|BigInt(t[s]);if(r>=Sp||zo(n)||zo(t.slice(0,32)))return!1;let o=await crypto.subtle.importKey("raw",S(n),{name:"Ed25519"},!1,["verify"]);return crypto.subtle.verify("Ed25519",o,S(t),S(e))}async function Cp(n,e,t){let r=`${n.run}.${e}.${t.index}`;if(t.run!==r||t.step!==e)throw new Error(`the proof of ${t.run} is listed as ${r}`);let o=t.signature!=null,s=Op(t.outcome,o);if(!s){let u=[t.usage.cpuMicros,t.usage.gibMicros,t.usage.fuel].every(y=>y==="0");if(o||t.reportSha256!=null||t.job!=null||t.outputs.length>0||!u)throw new Error(`${t.run} ended ${t.outcome} by the leader, yet names a report, outputs or usage`);return null}let i=u=>new Error(`${t.run} ended ${t.outcome} but its proof has no ${u}`);if(t.node==null)throw i("job node");if(t.jobKey==null)throw i("job key");if(t.assignmentDigest==null)throw i("assignment digest");if(t.reportSha256==null)throw i("report hash");if(t.signature==null)throw i("report signature");if(t.job==null)throw i("job evidence (it ended before receipts carried it)");let a=t.job;if(a.segments.length!==t.outputs.length)throw new Error(`${t.run}: the job evidence lists segments for ${a.segments.length} outputs, the proof ${t.outputs.length}`);let p=t.outputs.map((u,y)=>({id:u.id,size:u.size,sha256:u.sha256,segments:a.segments[y]})),l;try{l=ts({assignment:t.assignmentDigest,app:n.app,run:t.run,attempt:t.attempt,reason:s.reason,message:a.message??"",resultSha256:a.resultSha256,outputs:p,usage:[t.usage.cpuMicros,t.usage.gibMicros,t.usage.fuel],log:a.log})}catch(u){throw new Error(`${t.run}: ${u instanceof Error?u.message:String(u)}`)}if(m(await es(l))!==t.reportSha256)throw new Error(`${t.run}: the report hash is not that of what the proof says`);let d=_e(t.jobKey);if(!/^[0-9a-fA-F]{128}$/.test(t.signature))throw new Error(`${t.run}: the report signature is not 64 bytes of hex`);if(!await Up(d,l,x(t.signature,"signature",64)))throw new Error(`${t.run}: the job key did not sign what the proof says`);return{key:t.jobKey,node:t.node}}async function rs(n){if(n.version!==Ho)throw new Error(`the receipt is version ${n.version}; only version ${Ho} carries what each job signed`);let e=new Map;for(let[t,r]of Object.entries(n.steps))for(let[o,s]of r.runs.entries()){if(s.index!==o)throw new Error(`step ${t} lists run ${s.index} where run ${o} belongs`);if("cached"in s){if(!s.cached)throw new Error(`step ${t} run ${o} is listed as not cached`);continue}let i=await Cp(n,t,s);if(i&&(e.get(i.key)??i.node)!==i.node)throw new Error(`job key ${i.key} is named on two nodes`);i&&e.set(i.key,i.node)}return e}async function Bp(n,e,t,r,o){let s=n.jobAttestations&&ae(n.jobAttestations,t)?n.jobAttestations[t]:void 0;if(!s)throw new Error("the receipt carries no attestation for it");if(s.jobKey!==t)throw new Error("its attestation is another key's");if(s.node!==r||s.cluster!==e)throw new Error(`it is attested as node ${s.node} of cluster ${s.cluster}, not node ${r} of ${e}`);if(s.clusterIdentity!==n.cluster)throw new Error("its job node takes work from another cluster identity");let i;try{i=_e(s.nonce)}catch{throw new Error("its attestation's nonce is not 32 bytes of hex")}let a=await ns(on(s.transportKey,"the transport key",32),x(t,"the job key",32),s.release.version,s.cluster,s.node,on(s.clusterIdentity,"the cluster identity",32));await xt(s,i,x(a,"binding",32),o,"job key")}async function lr(n,e,t,r,o){let{keys:s,cluster:i}=await an(n,e,o);if(!J(r))throw new Error("the receipt answer is not an object");let a=pr(r.node,"the receipt answer"),p=s.get(a);if(!p)throw new Error(`node ${a} is not an attested replica of ${e}`);let l=await _p(r,p);if(l.app!==e)throw new Error(`the receipt is for app ${l.app}, not ${e}`);if(l.run!==t)throw new Error(`the receipt is for run ${l.run}, not ${t}`);for(let[d,u]of await rs(l))try{await Bp(l,i,d,u,o)}catch(y){throw new Error(`job key ${d}: ${y instanceof Error?y.message:String(y)}`)}return l}var ur=100;function dr(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>ur)throw new RangeError(`limit is 1 to ${ur}`);e.set("limit",String(n.limit))}let t=e.toString();return t?`?${t}`:""}function dt(n,e){try{return We(n,e)}catch{return n<e?-1:n>e?1:0}}function os(n,e,t=Date.now()/1e3){if(n===null||n.length===0)return null;let r=n.reduce((s,i)=>dt(s,i)>=0?s:i),o=null;for(let s of e)s.afterSecs<=t&&dt(r,s.version)<0&&(o===null||dt(s.version,o.version)>0)&&(o=s);return o}function ss(n,e,t,r){return`calimero-publisher-binding/v1
4
+ `))y.startsWith("id:")?p=y.slice(3).trim():y.startsWith("event:")?l=y.slice(6).trim():y.startsWith("data:")&&(d+=y.slice(5).trim());if(!l&&!d)continue;let u=d;try{u=JSON.parse(d)}catch{}yield{id:p,kind:l,data:u}}}}function Mn(){return`node:c-${R(crypto.getRandomValues(new Uint8Array(16)))}`}function ke(n,e={}){return n.replace(/\{([^}]+)\}/g,(t,r)=>{let o=e[r];if(o===void 0)throw new Error(`no value for path parameter ${r} of ${n}`);return encodeURIComponent(String(o))})}function Bn(n){if(!n)return"";let e=new URLSearchParams;for(let[r,o]of Object.entries(n))for(let s of Array.isArray(o)?o:[o])s!=null&&e.append(r,String(s));let t=e.toString();return t?`?${t}`:""}function to(n){return n==="auth/refresh"||n.startsWith("auth/passkey/")||Wi.has(n)}var Wi=new Set(["auth/recovery/begin","auth/recovery/start","auth/recovery/finish"]);function ot(n){return n.replace(/^\/+/,"")}var Pe=class{constructor(e){this.at=0;this.channels=new Map;this.checks=new Map;this.attempts=new Map;this.keys=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={...Nn,...e.retry};let r=e.fetch??((s,i)=>fetch(s,i)),o=async(s,i)=>{try{return await r(s,i)}catch(a){throw a instanceof TypeError&&this.networkFailures.add(a),a}};this.raw=o}isNetworkFailure(e){return e instanceof TypeError&&this.networkFailures.has(e)||e instanceof ge}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}get nodePolicy(){return this.policy}channel(e){let t=this.channels.get(e);if(!t){let r=()=>this.channels.get(e)===s,o,s=wn({baseUrl:e,transportPublicKey:()=>{let i=o??this.attest(e,r);return o=void 0,i},fetch:this.raw});this.channels.set(e,s),o=this.attest(e,r),t=s}return t}attest(e,t){if(!t())return me(e,this.policy,this.raw).then(({key:o})=>o);this.checks.set(e,{status:"checking",url:e});let r=me(e,this.policy,this.raw).then(({key:o,verification:s})=>(t()&&(this.checks.set(e,{status:"verified",...s}),this.keys.set(e,o)),o),o=>{let s=o instanceof Error?o.message:String(o),i=this.isNetworkFailure(o);throw t()&&(this.checks.set(e,{status:i?"unreachable":"refused",url:e,reason:s,checkedAt:Date.now()}),i&&this.channels.delete(e)),o});return r.catch(()=>{}),this.attempts.set(e,r),r}verification(e=this.nodeUrl){return this.checks.get(e)}async attestApp(e,t=this.nodeUrl){let r=this.policy.app===e?this.policy.appHash:void 0,o={...this.policy,app:e,appHash:r};await this.settled(t);let s=await me(t,o,this.raw);if(!this.sameKey(t,s.key)&&(this.channels.delete(t),await this.settled(t),s=await me(t,o,this.raw),!this.sameKey(t,s.key)))throw new Error("The node attested the app under another transport key than its channel");return s.verification}async settled(e){let t=await this.verify(e);if(t.status==="refused"||t.status==="unreachable")throw new Error(t.reason)}sameKey(e,t){let r=this.keys.get(e);return r!==void 0&&m(r)===m(t)}async verify(e=this.nodeUrl){for(this.channel(e);;){let t=this.attempts.get(e);if(await t?.catch(()=>{}),this.attempts.get(e)===t)return this.checks.get(e)}}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 r=this.nodeUrls.length;for(let o=1;o<r;o++){let s=(this.at+o)%r;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=Sn(e.directory,e.cluster,this.raw).then(t=>{let r=this.nodeUrl,o=Un(t.nodes,e.zone,e.random);this.nodeUrls=[r,...o.filter(s=>s!==r)],this.at=0,e.due=Date.now()+t.refreshAfterSeconds*1e3}).catch(()=>{}).finally(()=>{e.reading=void 0}))}async once(e,t,r){let o={};this.auth&&(o.authorization=`Bearer ${this.auth}`);let s;r.bytes?(o["content-type"]=r.contentType??"application/wasm",s=r.bytes):r.body!==void 0&&(o["content-type"]="application/json",s=JSON.stringify(r.body)),this.source&&Date.now()>=this.source.due&&this.reread();let i=this.nodeUrl;try{return await this.channel(i)(`${i}/${t}${Bn(r.query)}`,{method:e,headers:o,body:s,signal:r.signal})}catch(a){throw Yi(a)}}async send(e,t,r){let o=await this.answer(e,t,r);if(!o.ok)throw await se(o);return o}async answer(e,t,r){let o=!1,s=!1;for(;;){let[i,a]=[this.auth,this.nodeUrl],p=await this.once(e,t,r);if(p.ok||p.status!==401&&p.status!==421)return p;let l=await se(p.clone());if(l instanceof we&&!s){if(s=!0,this.moveOn(a)&&!to(t))continue}else if(l instanceof re&&!o&&this.mayRefresh(i,t)){o=!0,await this.renew(i);continue}return p}}mayRefresh(e,t){return e!==void 0&&this.current!==void 0&&!to(t)}async renew(e){this.auth===e&&await this.refresh()}async read(e,t,r){let s=await(await this.send(e,t,r)).text();return s?JSON.parse(s):{}}async retried(e,t,r,o){let s=await this.answerRetried(e,t,r,o);if(!s.ok)throw await se(s);let i=await s.text();return i?JSON.parse(i):{}}async answerRetried(e,t,r,o){let s=o?0:this.retry.retries,i=new Set;for(;;){let a,p,l=this.nodeUrl;for(let d=0;;d++){l=this.nodeUrl,i.add(l);try{let y=await this.answer(e,t,r);if(y.status!==503)return y;p=y,a=await se(y.clone())}catch(y){if(y instanceof TypeError&&this.networkFailures.has(y))p=void 0,a=new oe("NETWORK",`the node could not be reached: ${y.message}`,{},void 0,y);else throw y}if(d>=s)break;let u=st(d,this.retry);await new Promise(y=>setTimeout(y,Math.max(u,(a.retryAfter??0)*1e3)))}if(o||!this.failOver(l,i)){if(p)return p;throw a}}}exchange(e,t,r={}){let o=ot(t);return r.retry?this.answerRetried(e,o,r,r.retry==="once"):this.answer(e,o,r)}attempt(e,t,r){if(!r.retry)return this.read(e,t,r);let o=r.body?.confirm!==void 0;return this.retried(e,t,r,r.retry==="once"||o)}async confirmed(e,t,r){let{passkey:o}=r;try{return await this.attempt(e,t,r)}catch(s){if(!(s instanceof Se)||!o)throw s;let i=s.details,a=await rt(o,{userVerification:r.userVerification,signal:r.promptSignal??r.signal})(i,{request:new Request(`${this.nodeUrl}/${t}`,{method:e})}),p={...r.body,confirm:{challengeId:i.challengeId,assertion:a}};return this.attempt(e,t,{...r,body:p})}}request(e,t,r={}){return this.send(e,ot(t),r)}json(e,t,r={}){return this.confirmed(e,ot(t),r)}async*events(e,t={}){let r=await this.send("GET",ot(e),t);if(!r.body)throw new b(r.status,"EVENTS","the event stream has no body");yield*no(r.body)}async unsealed(e,t={}){let r=await this.inTheClear(e,t);if(!r.ok)throw await se(r);return r}inTheClear(e,t={}){return this.raw(`${this.nodeUrl}/${ot(e)}${Bn(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 r=1;t===void 0;r++)try{t=await this.json("POST","auth/refresh",{body:{refreshToken:e.refreshToken}})}catch(o){if(!(o instanceof we)||r>=this.nodeUrls.length)throw o}return this.current===e&&this.useSession(t),t}};async function qn(n){let e=n.random??Math.random,t=n.fetch??((a,p)=>fetch(a,p)),r=await Sn(n.directory,n.cluster,t),[o,...s]=Un(r.nodes,n.zone,e),i=new Pe({baseUrl:o,nodes:s,policy:n.policy,fetch:n.fetch,retry:n.retry});return i.useDirectory({directory:n.directory,cluster:n.cluster,zone:n.zone,random:e,due:Date.now()+r.refreshAfterSeconds*1e3}),i}var Xi=/\{[^{}]+\}/g,Zi=()=>typeof process=="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici;function ea(){return Math.random().toString(36).slice(2,11)}function io(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:r=globalThis.fetch,querySerializer:o,bodySerializer:s,pathSerializer:i,headers:a,requestInitExt:p=void 0,...l}={...n};p=Zi()?p:void 0,e=so(e);let d=[];async function u(y,h){let{baseUrl:g,fetch:A=r,Request:B=t,headers:v,params:O={},parseAs:M="json",querySerializer:Y,bodySerializer:Re=s??na,pathSerializer:q,body:F,middleware:ue=[],...W}=h||{},$=e;g&&($=so(g)??e);let de=typeof o=="function"?o:ro(o);Y&&(de=typeof Y=="function"?Y:ro({...typeof o=="object"?o:{},...Y}));let mt=q||i||ta,V=F===void 0?void 0:Re(F,oo(a,v,O.header)),Ge=oo(V===void 0||V instanceof FormData?{}:{"Content-Type":"application/json"},a,v,O.header),X=[...d,...ue],Ms={redirect:"follow",...l,...W,body:V,headers:Ge},wt,bt,Z=new B(ra(y,{baseUrl:$,params:O,querySerializer:de,pathSerializer:mt}),Ms),T;for(let U in W)U in Z||(Z[U]=W[U]);if(X.length){wt=ea(),bt=Object.freeze({baseUrl:$,fetch:A,parseAs:M,querySerializer:de,bodySerializer:Re,pathSerializer:mt});for(let U of X)if(U&&typeof U=="object"&&typeof U.onRequest=="function"){let j=await U.onRequest({request:Z,schemaPath:y,params:O,options:bt,id:wt});if(j)if(j instanceof B)Z=j;else if(j instanceof Response){T=j;break}else throw new Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!T){try{T=await A(Z,p)}catch(U){let j=U;if(X.length)for(let ye=X.length-1;ye>=0;ye--){let Pt=X[ye];if(Pt&&typeof Pt=="object"&&typeof Pt.onError=="function"){let Fe=await Pt.onError({request:Z,error:j,schemaPath:y,params:O,options:bt,id:wt});if(Fe){if(Fe instanceof Response){j=void 0,T=Fe;break}if(Fe instanceof Error){j=Fe;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(j)throw j}if(X.length)for(let U=X.length-1;U>=0;U--){let j=X[U];if(j&&typeof j=="object"&&typeof j.onResponse=="function"){let ye=await j.onResponse({request:Z,response:T,schemaPath:y,params:O,options:bt,id:wt});if(ye){if(!(ye instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");T=ye}}}}let Er=T.headers.get("Content-Length");if(T.status===204||Z.method==="HEAD"||Er==="0"&&!T.headers.get("Transfer-Encoding")?.includes("chunked"))return T.ok?{data:void 0,response:T}:{error:void 0,response:T};if(T.ok)return{data:await(async()=>{if(M==="stream")return T.body;if(M==="json"&&!Er){let j=await T.text();return j?JSON.parse(j):void 0}return await T[M]()})(),response:T};let dn=await T.text();try{dn=JSON.parse(dn)}catch{}return{error:dn,response:T}}return{request(y,h,g){return u(h,{...g,method:y.toUpperCase()})},GET(y,h){return u(y,{...h,method:"GET"})},PUT(y,h){return u(y,{...h,method:"PUT"})},POST(y,h){return u(y,{...h,method:"POST"})},DELETE(y,h){return u(y,{...h,method:"DELETE"})},OPTIONS(y,h){return u(y,{...h,method:"OPTIONS"})},HEAD(y,h){return u(y,{...h,method:"HEAD"})},PATCH(y,h){return u(y,{...h,method:"PATCH"})},TRACE(y,h){return u(y,{...h,method:"TRACE"})},use(...y){for(let h of y)if(h){if(typeof h!="object"||!("onRequest"in h||"onResponse"in h||"onError"in h))throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");d.push(h)}},eject(...y){for(let h of y){let g=d.indexOf(h);g!==-1&&d.splice(g,1)}}}}function Ht(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 ao(n,e,t){if(!e||typeof e!="object")return"";let r=[],o={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(let a in e)r.push(a,t.allowReserved===!0?e[a]:encodeURIComponent(e[a]));let i=r.join(",");switch(t.style){case"form":return`${n}=${i}`;case"label":return`.${i}`;case"matrix":return`;${n}=${i}`;default:return i}}for(let i in e){let a=t.style==="deepObject"?`${n}[${i}]`:i;r.push(Ht(a,e[i],t))}let s=r.join(o);return t.style==="label"||t.style==="matrix"?`${o}${s}`:s}function po(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){let s={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",i=(t.allowReserved===!0?e:e.map(a=>encodeURIComponent(a))).join(s);switch(t.style){case"simple":return i;case"label":return`.${i}`;case"matrix":return`;${n}=${i}`;default:return`${n}=${i}`}}let r={simple:",",label:".",matrix:";"}[t.style]||"&",o=[];for(let s of e)t.style==="simple"||t.style==="label"?o.push(t.allowReserved===!0?s:encodeURIComponent(s)):o.push(Ht(n,s,t));return t.style==="label"||t.style==="matrix"?`${r}${o.join(r)}`:o.join(r)}function ro(n){return function(t){let r=[];if(t&&typeof t=="object")for(let o in t){let s=t[o];if(s!=null){if(Array.isArray(s)){if(s.length===0)continue;r.push(po(o,s,{style:"form",explode:!0,...n?.array,allowReserved:n?.allowReserved||!1}));continue}if(typeof s=="object"){r.push(ao(o,s,{style:"deepObject",explode:!0,...n?.object,allowReserved:n?.allowReserved||!1}));continue}r.push(Ht(o,s,n))}}return r.join("&")}}function ta(n,e){let t=n;for(let r of n.match(Xi)??[]){let o=r.substring(1,r.length-1),s=!1,i="simple";if(o.endsWith("*")&&(s=!0,o=o.substring(0,o.length-1)),o.startsWith(".")?(i="label",o=o.substring(1)):o.startsWith(";")&&(i="matrix",o=o.substring(1)),!e||e[o]===void 0||e[o]===null)continue;let a=e[o];if(Array.isArray(a)){t=t.replace(r,po(o,a,{style:i,explode:s}));continue}if(typeof a=="object"){t=t.replace(r,ao(o,a,{style:i,explode:s}));continue}if(i==="matrix"){t=t.replace(r,`;${Ht(o,a)}`);continue}t=t.replace(r,i==="label"?`.${encodeURIComponent(a)}`:encodeURIComponent(a))}return t}function na(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 ra(n,e){let t=`${e.baseUrl}${n}`;e.params?.path&&(t=e.pathSerializer(t,e.params.path));let r=e.querySerializer(e.params.query??{});return r.startsWith("?")&&(r=r.substring(1)),r&&(t+=`?${r}`),t}function oo(...n){let e=new Headers;for(let t of n){if(!t||typeof t!="object")continue;let r=t instanceof Headers?t.entries():Object.entries(t);for(let[o,s]of r)if(s===null)e.delete(o);else if(Array.isArray(s))for(let i of s)e.append(o,i);else s!==void 0&&e.set(o,s)}return e}function so(n){return n.endsWith("/")?n.substring(0,n.length-1):n}function co(n,e,t){let r=new Map;return{onRequest({request:o,id:s}){let i=o.headers.get("content-type");(i===null||i.startsWith("application/json"))&&o.method!=="GET"&&o.method!=="HEAD"&&r.set(s,o.clone())},async onResponse({response:o,id:s,options:i}){let a=r.get(s);if(r.delete(s),o.status!==n||!a)return;let p=await o.clone().json().catch(()=>{});if(p?.error!==e)return;let l=await t(p.details??{},a),d=await a.text(),u=d?JSON.parse(d):{},y=new Headers(a.headers);y.set("content-type","application/json");let h=new Request(a.url,{method:a.method,headers:y,body:JSON.stringify({...u,...l}),signal:a.signal});return i.fetch(h)},onError({id:o}){r.delete(o)}}}function Gt(n){return co(412,"CONFIRM_REQUIRED",async(e,t)=>({confirm:{challengeId:e.challengeId,assertion:await n(e,{request:t})}}))}function Ft(n){return co(428,"OPERATOR_SIGNATURE_REQUIRED",async(e,t)=>({operatorProof:await n(e,{request:t})}))}async function c(n,e,t,r={}){let o=t??{},s={},i={},a={};for(let[u,y]of Object.entries(o))e.pathParams.includes(u)?s[u]=y:e.queryWhole&&u==="query"?Object.assign(i,y):!e.queryWhole&&e.query.includes(u)?i[u]=y:a[u]=y;for(let u of e.pathParams)if(s[u]===void 0)throw new TypeError(`${e.method} ${e.path}: no value for ${u}`);let p={params:{path:s,query:i}};e.body==="fields"?Object.values(a).every(y=>y===void 0)&&e.optionalBody||(p.body=a):e.body==="whole"?(a.body!==void 0||!e.optionalBody)&&(p.body=a.body):e.body==="raw"&&(p.body=a.body,p.bodySerializer=u=>u,p.headers={"Content-Type":a.contentType??e.media??"application/octet-stream"}),e.reply==="bytes"?p.parseAs="blob":e.reply==="text"&&(p.parseAs="text");let l=[];if(r.confirm){let u=r.confirm,y=e.userVerification?(h,g)=>u({userVerification:e.userVerification,...h},g):u;l.push(Gt(y))}r.operatorProof&&l.push(Ft(r.operatorProof)),l.length&&(p.middleware=l),r.signal&&(p.signal=r.signal);let d=n.request;return lo(d(e.method.toLowerCase(),e.path,p))}function Dn(n){return{apps:{abi:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/abi",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),access:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/access",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),attestation:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/attestation",pathParams:["app"],query:["nonce"],body:"none",optionalBody:!1,reply:"json"},e,t),blobDelete:(e,t)=>c(n,{method:"DELETE",path:"/apps/{app}/blobs/{id}",pathParams:["app","id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),blobDownload:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/blobs/{id}",pathParams:["app","id"],query:["grant"],body:"none",optionalBody:!1,reply:"bytes"},e,t),blobInfo:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/blobs/{id}/info",pathParams:["app","id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),blobList:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/blobs",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),blobRevoke:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/blobs/{id}/revoke",pathParams:["app","id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),blobUpload:(e,t)=>c(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)=>c(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)=>c(n,{method:"POST",path:"/apps",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),delete:(e,t)=>c(n,{method:"DELETE",path:"/apps/{app}",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),exportsExport:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/files/{id}/export",pathParams:["app","id"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),exportsSegment:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/files/{id}/segments/{k}",pathParams:["app","id","k"],query:[],body:"none",optionalBody:!1,reply:"bytes"},e,t),fileInfo:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/files/{id}",pathParams:["app","id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),filesList:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/files",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),filesUpload:(e,t)=>c(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)=>c(n,{method:"GET",path:"/apps/{app}",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),list:(e={},t)=>c(n,{method:"GET",path:"/apps",pathParams:[],query:["package","bundle"],body:"none",optionalBody:!1,reply:"json"},e,t),metadata:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/metadata",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),method:(e,t)=>c(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)=>c(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)=>c(n,{method:"GET",path:"/apps/{app}/openapi.json",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),pipelineReceiptReceipt:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/pipeline-runs/{run}/receipt",pathParams:["app","run"],query:["version"],body:"none",optionalBody:!1,reply:"json"},e,t),pipelinesCancel:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/pipeline-runs/{run}/cancel",pathParams:["app","run"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),pipelinesEstimateRun:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/pipelines/{name}/estimate",pathParams:["app","name"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),pipelinesGet:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/pipeline-runs/{run}",pathParams:["app","run"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),pipelinesList:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/pipeline-runs",pathParams:["app"],query:["limit"],body:"none",optionalBody:!1,reply:"json"},e,t),pipelinesRetry:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/pipeline-runs/{run}/retry",pathParams:["app","run"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),pipelinesStart:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/pipelines/{name}/runs",pathParams:["app","name"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),pipelinesValidate:(e,t)=>c(n,{method:"POST",path:"/pipelines/validate",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),presenceGet:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/presence",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),presencePublish:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/presence",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),run:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/runs/{run}",pathParams:["app","run"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),runLogs:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/runs/{run}/logs",pathParams:["app","run"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),runs:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/runs",pathParams:["app"],query:["limit","before"],body:"none",optionalBody:!1,reply:"json"},e,t),storage:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/storage",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),transfer:(e,t)=>c(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)=>c(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)=>c(n,{method:"DELETE",path:"/apps/{app}/files/uploads/{upload}",pathParams:["app","upload"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),uploadBegin:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/files/uploads",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),uploadComplete:(e,t)=>c(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)=>c(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)=>c(n,{method:"GET",path:"/apps/{app}/files/uploads/{upload}",pathParams:["app","upload"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),usage:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/usage",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),view:(e,t)=>c(n,{method:"POST",path:"/apps/{app}/views",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),xcalls:(e,t)=>c(n,{method:"GET",path:"/apps/{app}/xcalls",pathParams:["app"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},auth:{accountApps:(e={},t)=>c(n,{method:"GET",path:"/auth/apps",pathParams:[],query:["after","limit"],body:"none",optionalBody:!1,reply:"json"},e,t),accountBackupKey:(e={},t)=>c(n,{method:"GET",path:"/auth/backup-key",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),accountProofProve:(e,t)=>c(n,{method:"POST",path:"/auth/account-proof",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),accountRecoveryBegin:(e,t)=>c(n,{method:"POST",path:"/auth/recovery/begin",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),accountRecoveryCancel:(e={},t)=>c(n,{method:"POST",path:"/auth/recovery/cancel",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),accountRecoveryFinish:(e={},t)=>c(n,{method:"POST",path:"/auth/recovery/finish",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),accountRecoveryStart:(e,t)=>c(n,{method:"POST",path:"/auth/recovery/start",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),accountSetBackupKey:(e,t)=>c(n,{method:"POST",path:"/auth/backup-key",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),activityList:(e={},t)=>c(n,{method:"GET",path:"/auth/activity",pathParams:[],query:["after"],body:"none",optionalBody:!1,reply:"json"},e,t),aliasDelete:(e,t)=>c(n,{method:"DELETE",path:"/auth/aliases/{alias}",pathParams:["alias"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),aliasGet:(e,t)=>c(n,{method:"GET",path:"/auth/aliases/{alias}",pathParams:["alias"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),aliasList:(e={},t)=>c(n,{method:"GET",path:"/auth/aliases",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),aliasSet:(e,t)=>c(n,{method:"PUT",path:"/auth/aliases/{alias}",pathParams:["alias"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),apikeyCreate:(e={},t)=>c(n,{method:"POST",path:"/auth/apikeys",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),apikeyList:(e={},t)=>c(n,{method:"GET",path:"/auth/apikeys",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),apikeyRevoke:(e,t)=>c(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)=>c(n,{method:"POST",path:"/auth/passkey/login/begin",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json"},e,t),loginFinish:(e,t)=>c(n,{method:"POST",path:"/auth/passkey/login/finish",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),logout:(e={},t)=>c(n,{method:"POST",path:"/auth/logout",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),logoutAll:(e={},t)=>c(n,{method:"POST",path:"/auth/logout-all",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),me:(e={},t)=>c(n,{method:"GET",path:"/auth/me",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),passkeyAddBegin:(e={},t)=>c(n,{method:"POST",path:"/auth/passkeys/add/begin",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),passkeyAddFinish:(e,t)=>c(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)=>c(n,{method:"POST",path:"/auth/passkeys/{cred}",pathParams:["cred"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),passkeyRemove:(e,t)=>c(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)=>c(n,{method:"POST",path:"/auth/recovery",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),recoveryRemove:(e={},t)=>c(n,{method:"DELETE",path:"/auth/recovery",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),refresh:(e,t)=>c(n,{method:"POST",path:"/auth/refresh",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),registerBegin:(e={},t)=>c(n,{method:"POST",path:"/auth/passkey/register/begin",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),registerFinish:(e,t)=>c(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)=>c(n,{method:"DELETE",path:"/auth/sessions/{session}",pathParams:["session"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),sessionsList:(e={},t)=>c(n,{method:"GET",path:"/auth/sessions",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),usage:(e={},t)=>c(n,{method:"GET",path:"/auth/usage",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},consent:{pageCreate:(e,t)=>c(n,{method:"POST",path:"/consent/requests",pathParams:[],query:[],body:"whole",optionalBody:!1,reply:"json"},e,t),pageResult:(e,t)=>c(n,{method:"GET",path:"/consent/{request}/result",pathParams:["request"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},deployments:{create:(e,t)=>c(n,{method:"POST",path:"/deployments",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),delete:(e,t)=>c(n,{method:"DELETE",path:"/deployments/{id}",pathParams:["id"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),deployerGrant:(e,t)=>c(n,{method:"POST",path:"/deployers",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),deployerList:(e={},t)=>c(n,{method:"GET",path:"/deployers",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),deployerRevoke:(e,t)=>c(n,{method:"DELETE",path:"/deployers/{key}",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),get:(e,t)=>c(n,{method:"GET",path:"/deployments/{id}",pathParams:["id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),list:(e={},t)=>c(n,{method:"GET",path:"/deployments",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),offer:(e,t)=>c(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)=>c(n,{method:"GET",path:"/deployments/{id}/orgs",pathParams:["id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),signUpInviteCreate:(e={},t)=>c(n,{method:"POST",path:"/sign-up/invites",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),signUpInviteList:(e={},t)=>c(n,{method:"GET",path:"/sign-up/invites",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),signUpInviteRevoke:(e,t)=>c(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)=>c(n,{method:"GET",path:"/sign-up",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),signUpSet:(e,t)=>c(n,{method:"POST",path:"/sign-up",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),withdraw:(e,t)=>c(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)=>c(n,{method:"GET",path:"/ops/apps",pathParams:[],query:["after","limit"],body:"none",optionalBody:!1,reply:"json"},e,t),backup:(e={},t)=>c(n,{method:"POST",path:"/ops/backup",pathParams:[],query:["all"],body:"none",optionalBody:!1,reply:"json"},e,t),backupKey:(e={},t)=>c(n,{method:"GET",path:"/ops/backup-key",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),cluster:(e={},t)=>c(n,{method:"GET",path:"/ops/cluster",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),clusterOwner:(e,t)=>c(n,{method:"POST",path:"/ops/cluster-owner",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),deployerGrant:(e,t)=>c(n,{method:"POST",path:"/ops/deployers",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),deployerRevokeDelete:(e,t)=>c(n,{method:"DELETE",path:"/ops/deployers/{key}",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),deployerRevokePost:(e,t)=>c(n,{method:"POST",path:"/ops/deployers/{key}/revoke",pathParams:["key"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),deploymentsGranted:(e={},t)=>c(n,{method:"POST",path:"/ops/deployments/granted",pathParams:[],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),jobNodeAttestation:(e,t)=>c(n,{method:"GET",path:"/ops/job-nodes/{id}/attestation",pathParams:["id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),metrics:(e={},t)=>c(n,{method:"GET",path:"/ops/metrics",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"text"},e,t),orgs:(e={},t)=>c(n,{method:"GET",path:"/ops/orgs",pathParams:[],query:["after","limit"],body:"none",optionalBody:!1,reply:"json"},e,t),orgUpgrade:(e,t)=>c(n,{method:"POST",path:"/ops/orgs/{org}/upgrade",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),outbound:(e,t)=>c(n,{method:"POST",path:"/ops/outbound",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),packageInstall:(e,t)=>c(n,{method:"POST",path:"/ops/packages/install",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),packageList:(e={},t)=>c(n,{method:"GET",path:"/ops/packages",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),packageUninstall:(e,t)=>c(n,{method:"DELETE",path:"/ops/packages/{package}",pathParams:["package"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),packageUpload:(e,t)=>c(n,{method:"POST",path:"/ops/packages",pathParams:[],query:[],body:"raw",optionalBody:!1,media:"application/octet-stream",reply:"json"},e,t),packageVersionUninstall:(e,t)=>c(n,{method:"DELETE",path:"/ops/packages/{package}/{version}",pathParams:["package","version"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),placement:(e={},t)=>c(n,{method:"GET",path:"/ops/placement",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),poolsGet:(e={},t)=>c(n,{method:"GET",path:"/ops/pools",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),poolsSet:(e,t)=>c(n,{method:"POST",path:"/ops/pools",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),pricesGet:(e={},t)=>c(n,{method:"GET",path:"/ops/prices",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),pricesSet:(e,t)=>c(n,{method:"POST",path:"/ops/prices",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),quotasGet:(e={},t)=>c(n,{method:"GET",path:"/ops/quotas",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),quotasSet:(e={},t)=>c(n,{method:"POST",path:"/ops/quotas",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),receiptKey:(e,t)=>c(n,{method:"GET",path:"/ops/nodes/{id}/receipt-key",pathParams:["id"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),recover:(e,t)=>c(n,{method:"POST",path:"/ops/recover",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),recoveryFiles:(e={},t)=>c(n,{method:"GET",path:"/ops/recovery-files",pathParams:[],query:["holder"],body:"none",optionalBody:!1,reply:"json"},e,t),registerNode:(e,t)=>c(n,{method:"POST",path:"/ops/nodes",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),release:(e,t)=>c(n,{method:"POST",path:"/ops/releases",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),releaseDeadline:(e,t)=>c(n,{method:"POST",path:"/ops/releases/{version}/deadline",pathParams:["version"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),releaseDeadlineLift:(e,t)=>c(n,{method:"DELETE",path:"/ops/releases/{version}/deadline",pathParams:["version"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),removeNode:(e,t)=>c(n,{method:"DELETE",path:"/ops/nodes/{id}",pathParams:["id"],query:[],body:"fields",optionalBody:!0,reply:"json",operator:!0},e,t),restore:(e,t)=>c(n,{method:"POST",path:"/ops/apps/{app}/restore",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),served:(e={},t)=>c(n,{method:"GET",path:"/ops/served-origins",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),setBackupKey:(e,t)=>c(n,{method:"POST",path:"/ops/backup-key",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),setReplicas:(e,t)=>c(n,{method:"POST",path:"/ops/apps/{app}/replicas",pathParams:["app"],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),signUpInviteCreate:(e,t)=>c(n,{method:"POST",path:"/ops/sign-up/invites",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),signUpInviteList:(e={},t)=>c(n,{method:"GET",path:"/ops/sign-up/invites",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),signUpInviteRevokeDelete:(e,t)=>c(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)=>c(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)=>c(n,{method:"POST",path:"/ops/sign-up",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t),status:(e={},t)=>c(n,{method:"GET",path:"/ops/status",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),upgrade:(e,t)=>c(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)=>c(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)=>c(n,{method:"GET",path:"/orgs/{org}/apps",pathParams:["org"],query:["after","limit"],body:"none",optionalBody:!1,reply:"json"},e,t),appTeamList:(e,t)=>c(n,{method:"GET",path:"/orgs/{org}/app-teams",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),appTeamsScope:(e,t)=>c(n,{method:"POST",path:"/orgs/{org}/app-teams",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),backupKey:(e,t)=>c(n,{method:"GET",path:"/orgs/{org}/backup-key",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),capabilities:(e,t)=>c(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)=>c(n,{method:"POST",path:"/orgs",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),delete:(e,t)=>c(n,{method:"DELETE",path:"/orgs/{org}",pathParams:["org"],query:[],body:"fields",optionalBody:!0,reply:"json",stepUp:!0,userVerification:"required"},e,t),get:(e,t)=>c(n,{method:"GET",path:"/orgs/{org}",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),inviteCreate:(e,t)=>c(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)=>c(n,{method:"GET",path:"/orgs/{org}/invites",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),inviteRedeem:(e,t)=>c(n,{method:"POST",path:"/invites/{token}/redeem",pathParams:["token"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),inviteRevoke:(e,t)=>c(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)=>c(n,{method:"POST",path:"/orgs/{org}/members/{account}/metadata",pathParams:["org","account"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),memberRemoveTeams:(e,t)=>c(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)=>c(n,{method:"GET",path:"/orgs/{org}/members",pathParams:["org"],query:["detail"],body:"none",optionalBody:!1,reply:"json"},e,t),memberSetTeams:(e,t)=>c(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)=>c(n,{method:"POST",path:"/orgs/{org}/metadata",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),outboundApproval:(e,t)=>c(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)=>c(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)=>c(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)=>c(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)=>c(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)=>c(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)=>c(n,{method:"POST",path:"/orgs/{org}/recovery/start",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),releaseApproval:(e,t)=>c(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)=>c(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)=>c(n,{method:"POST",path:"/orgs/{org}/name",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),setBackupKey:(e,t)=>c(n,{method:"POST",path:"/orgs/{org}/backup-key",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),setMember:(e,t)=>c(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)=>c(n,{method:"POST",path:"/orgs/{org}/teams",pathParams:["org"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),teamDelete:(e,t)=>c(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)=>c(n,{method:"GET",path:"/orgs/{org}/teams/{team}",pathParams:["org","team"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),teamRemoveMember:(e,t)=>c(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)=>c(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)=>c(n,{method:"POST",path:"/orgs/{org}/teams/{team}",pathParams:["org","team"],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),upgrade:(e,t)=>c(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)=>c(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)=>c(n,{method:"GET",path:"/orgs/{org}/upgrades/{run}",pathParams:["org","run"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),usage:(e,t)=>c(n,{method:"GET",path:"/orgs/{org}/usage",pathParams:["org"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},packages:{bundlePut:(e,t)=>c(n,{method:"POST",path:"/bundles",pathParams:[],query:[],body:"raw",optionalBody:!1,media:"application/wasm",reply:"json"},e,t),capabilities:(e,t)=>c(n,{method:"GET",path:"/packages/{package}/{version}/capabilities",pathParams:["package","version"],query:["service"],body:"none",optionalBody:!1,reply:"json"},e,t),get:(e,t)=>c(n,{method:"GET",path:"/packages/{package}",pathParams:["package"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),install:(e,t)=>c(n,{method:"POST",path:"/packages/install",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json"},e,t),list:(e={},t)=>c(n,{method:"GET",path:"/packages",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),originsAdd:(e,t)=>c(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)=>c(n,{method:"GET",path:"/package-origins/{package}",pathParams:["package"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),originsRemove:(e,t)=>c(n,{method:"DELETE",path:"/package-origins/{package}",pathParams:["package"],query:[],body:"fields",optionalBody:!1,reply:"json",stepUp:!0,userVerification:"required"},e,t),pipelines:(e,t)=>c(n,{method:"GET",path:"/packages/{package}/{version}/pipelines",pathParams:["package","version"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),uninstall:(e,t)=>c(n,{method:"DELETE",path:"/packages/{package}",pathParams:["package"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),upload:(e,t)=>c(n,{method:"POST",path:"/packages",pathParams:[],query:[],body:"raw",optionalBody:!1,media:"application/octet-stream",reply:"json"},e,t),versionUninstall:(e,t)=>c(n,{method:"DELETE",path:"/packages/{package}/{version}",pathParams:["package","version"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t)},public:{attestation:(e,t)=>c(n,{method:"GET",path:"/attestation",pathParams:[],query:["nonce","app","appHash","purpose"],body:"none",optionalBody:!1,reply:"json"},e,t),health:(e={},t)=>c(n,{method:"GET",path:"/health",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),publisherBinding:(e,t)=>c(n,{method:"GET",path:"/publishers/{signer}",pathParams:["signer"],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),releasesPublic:(e={},t)=>c(n,{method:"GET",path:"/releases",pathParams:[],query:[],body:"none",optionalBody:!1,reply:"json"},e,t),restoreRecoverHolder:(e,t)=>c(n,{method:"POST",path:"/recover/holder",pathParams:[],query:[],body:"fields",optionalBody:!1,reply:"json",operator:!0},e,t)}}}var In=[{method:"POST",path:"/apps/{app}/intents",requires:"idempotencyKey"},{method:"POST",path:"/apps/{app}/methods/{method}",requires:"idempotencyKey"},{method:"POST",path:"/apps/{app}/views"}];var uo="https://calimero-node.invalid",oa=new Set(["attestation","health"]),sa=In.map(n=>({method:n.method,pattern:new RegExp(`^${n.path.replace(/^\//,"").replace(/\{[^}]+\}/g,"[^/]+")}$`)})),ia=new Set(In.filter(n=>n.requires==="idempotencyKey").map(n=>`${n.method} ${n.path}`));function aa(n){return async e=>{if(!e.url.startsWith(`${uo}/`))throw new Error(`not a route of the generated client: ${e.url}`);let t=new URL(e.url),r=t.pathname.replace(/^\/+/,""),o={};for(let[d,u]of t.searchParams)(o[d]??(o[d]=[])).push(u);let s=e.method;if(s==="GET"&&oa.has(r)&&n.inTheClear)return n.inTheClear(r,{query:o,signal:e.signal});let i=e.headers.get("content-type")??void 0,a=s==="GET"?void 0:new Uint8Array(await e.arrayBuffer()),p=a&&a.length>0?a:void 0,l=!1;return sa.some(d=>d.method===s&&d.pattern.test(r))&&(l=(p?JSON.parse(new TextDecoder().decode(p)):{}).confirm===void 0?!0:"once"),n.exchange(s,r,{query:o,...p?{bytes:p,contentType:i??"application/octet-stream"}:{},retry:l,signal:e.signal})}}var pa={async onRequest({request:n,schemaPath:e}){if(!ia.has(`${n.method} ${e}`))return;let t=await n.clone().text(),r=t?JSON.parse(t):{};if(r.idempotencyKey===void 0)return new Request(n,{body:JSON.stringify({...r,idempotencyKey:Mn()})})}};function Kn(n,e={}){let t=io({baseUrl:uo,fetch:aa(n)});return t.use(pa),e.confirm&&t.use(Gt(e.confirm)),e.operatorProof&&t.use(Ft(e.operatorProof)),t}async function lo(n){let{data:e,error:t,response:r}=await n;if(!r.ok)throw ca(r,t);return e??{}}function ca(n,e){let t=typeof e=="string"?e?{message:e}:{}:e;return Ue(n.status,t,n.headers.get("retry-after"))}var la=n=>n/2**32|0,ua=n=>n>>>0;function yo(n,e,t,r){let o=la(t),s=ua(t);n.setUint32(e,r?s:o,r),n.setUint32(e+4,r?o:s,r)}function ho(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}var $n=n=>n?`"${n}" `:"";function da(n,e=""){if(typeof n!="number")throw new TypeError($n(e)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError($n(e)+"expected integer >= 0, got "+n);return n}function Vn(n,e,t=""){if(ho(n)&&(e===void 0||n.length===e))return n;e!==void 0&&da(e,"length");let r=ho(n),o=e!==void 0?` of length ${e}`:"",s=r?`length=${n.length}`:`type=${typeof n}`,i=$n(t)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}var ya=(n,e)=>{if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof n)},fo=(n,e)=>{ya(n,e);let t=Object.getPrototypeOf(n);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(n,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function Ln(n,e=!0){if(n.destroyed)throw new Error("hash was destroyed");if(e&&n.finished)throw new Error("digest() was already called")}function go(n,e){Vn(n,void 0,"output");let t=e.outputLen;if(!(n.length>=t))throw new RangeError('"output" expected length >= '+t)}function Hn(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function zt(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function K(n,e){return n<<32-e|n>>>e}function ha(n,e,t="opts"){return fo(n,"defaults"),e!==void 0&&fo(e,t),Object.assign(Object.create(null),n,e)}function mo(n,e={}){if(typeof n!="function")throw new TypeError('"hashCons" expected function, got type='+typeof n);e=ha({},e,"info");let t=(o,s)=>n(s).update(o).digest(),r=n(void 0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.canXOF=r.canXOF,t.create=o=>n(o),Object.assign(t,e),Object.freeze(t)}var wo=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function bo(n,e,t){return n&e^~n&t}function Po(n,e,t){return n&e^n&t^e&t}var Qt=class{constructor(e,t,r,o){E(this,"blockLen");E(this,"outputLen");E(this,"canXOF",!1);E(this,"padOffset");E(this,"isLE");E(this,"buffer");E(this,"view");E(this,"finished",!1);E(this,"length",0);E(this,"pos",0);E(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=zt(this.buffer)}update(e){Ln(this),Vn(e);let{view:t,buffer:r,blockLen:o}=this,s=e.length,i=!1;for(let a=0;a<s;){let p=Math.min(o-this.pos,s-a);if(p===o){let l=zt(e);for(;o<=s-a;a+=o)this.process(l,a);i=!0;continue}r.set(a===0&&p===s?e:e.subarray(a,a+p),this.pos),this.pos+=p,a+=p,this.pos===o&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){Ln(this),go(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>o-i&&(this.process(r,0),t.fill(0)),yo(r,o-8,this.length*8,s),this.process(r,0),this.roundClean();let a=e===t?r:zt(e),p=this.outputLen,l=p/4,d=this.get();if(p%4||l>d.length)throw new Error("invalid outputLen");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=r,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},ko=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var fa=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ie=new Uint32Array(64),Gn=class extends Qt{constructor(t,r){super(64,t,8,!1);E(this,"A",0);E(this,"B",0);E(this,"C",0);E(this,"D",0);E(this,"E",0);E(this,"F",0);E(this,"G",0);E(this,"H",0);this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:t,B:r,C:o,D:s,E:i,F:a,G:p,H:l}=this;return[t,r,o,s,i,a,p,l]}set(t,r,o,s,i,a,p,l){this.A=t|0,this.B=r|0,this.C=o|0,this.D=s|0,this.E=i|0,this.F=a|0,this.G=p|0,this.H=l|0}_cloneInto(t){return(t||(t=new this.constructor)).set(...this.get()),this._cloneIntoMeta(t)}process(t,r){for(let y=0;y<16;y++,r+=4)ie[y]=t.getUint32(r,!1);for(let y=16;y<64;y++){let h=ie[y-15],g=ie[y-2],A=K(h,7)^K(h,18)^h>>>3,B=K(g,17)^K(g,19)^g>>>10;ie[y]=B+ie[y-7]+A+ie[y-16]|0}let{A:o,B:s,C:i,D:a,E:p,F:l,G:d,H:u}=this;for(let y=0;y<64;y++){let h=K(p,6)^K(p,11)^K(p,25),g=u+h+bo(p,l,d)+fa[y]+ie[y]|0,B=(K(o,2)^K(o,13)^K(o,22))+Po(o,s,i)|0;u=d,d=l,l=p,p=a+g|0,a=i,i=s,s=o,o=g+B|0}o=o+this.A|0,s=s+this.B|0,i=i+this.C|0,a=a+this.D|0,p=p+this.E|0,l=l+this.F|0,d=d+this.G|0,u=u+this.H|0,this.set(o,s,i,a,p,l,d,u)}roundClean(){Hn(ie)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Hn(this.buffer)}},Fn=class extends Gn{constructor(){super(32,ko)}};var Ce=mo(()=>new Fn,wo(1));var ga=64*1024,_o=16,Jt=ga+_o,Xt=256*Jt,Yt=12,it=new TextEncoder,ma=it.encode("calimero.file.v1"),wa=it.encode("calimero.file.segments.v1\0"),ba=it.encode("calimero.export-wrap.v1"),Pa=it.encode("calimero.sealed.derive.v1\0"),k=class extends Error{constructor(t,r){super(r);this.code=t;this.name="ExportError"}},Eo=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",n));function Ro(n){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n.length,!1),Eo(f(wa,e,...n))}function Ao(n){let e=it.encode(n),t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e.length,!1),f(t,e)}async function xo(n,e,t,r){if(r.length<Yt)throw new k("TAMPERED","the wrapped key is truncated");let o=await z(n.privateKey,e);if(o.every(d=>d===0))throw new k("BAD_ANSWER","the ephemeral key is of low order");let s=f(e,n.publicKey,Ao(t.appId),Ao(t.fileId)),i=await crypto.subtle.importKey("raw",o,"HKDF",!1,["deriveBits"]),a=await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:ba,info:f(Pa,s)},i,256),p=await crypto.subtle.importKey("raw",a,"AES-GCM",!1,["decrypt"]),l;try{l=await crypto.subtle.decrypt({name:"AES-GCM",iv:r.subarray(0,Yt)},p,r.subarray(Yt))}catch{throw new k("TAMPERED","the wrapped key does not open")}if(l.byteLength!==32)throw new k("TAMPERED","the wrapped key has the wrong length");return new Uint8Array(l)}var Wt=class n{constructor(e,t){this.key=e;this.segments=t;this.pending=new Uint8Array;this.index=0;this.next=0;this.size=0;this.hash=Ce.create()}static async create(e,t){let r=await crypto.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]);return new n(r,t.map(m))}async push(e,t){let r=this.segments[this.next];if(r===void 0)throw new k("TAMPERED",`the file has no segment ${this.next}`);if(this.next+1<this.segments.length&&e.length!==Xt)throw new k("TAMPERED",`segment ${this.next} is not a whole segment`);if(m(await Eo(e))!==r)throw new k("TAMPERED",`segment ${this.next} is not the one the file lists`);this.next+=1;let o=f(this.pending,e),s=0;for(;o.length-s>Jt;)await t(await this.open(o.subarray(s,s+Jt),!1)),s+=Jt;this.pending=o.slice(s)}async finishExpecting(e,t){if(this.next!==this.segments.length)throw new k("TAMPERED","the file is missing segments");if(this.pending.length<_o)throw new k("TAMPERED","the file is truncated");let r=await this.open(this.pending,!0);if(this.size!==e||m(this.hash.digest())!==t)throw new k("TAMPERED","the file is not the one that was sealed");return r}async open(e,t){let r=new Uint8Array(Yt);new DataView(r.buffer).setBigUint64(4,BigInt(this.index),!1);let o;try{o=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:r,additionalData:f(ma,new Uint8Array([t?1:0]))},this.key,e))}catch{throw new k("TAMPERED",`chunk ${this.index} does not open: the file is altered, truncated or under another key`)}return this.hash.update(o),this.size+=o.length,this.index+=1,o}};function at(n,e,t){if(typeof n!="string")throw new k("BAD_ANSWER",`the node answered a bad ${e}`);try{return t===void 0?Rr(n,e):x(n,e,t)}catch{throw new k("BAD_ANSWER",`the node answered a bad ${e}`)}}function ka(n){let e=n;if(typeof e!="object"||e===null)throw new k("BAD_ANSWER","the node answered a bad export");if(typeof e.app!="string")throw new k("BAD_ANSWER","the node answered a bad app");if(typeof e.size!="number"||!Number.isSafeInteger(e.size)||e.size<0)throw new k("BAD_ANSWER","the node answered a bad size");if(!Array.isArray(e.segments))throw new k("BAD_ANSWER","the node answered a bad segment list");return{app:e.app,size:e.size,named:at(e.id,"file id",32),segments:e.segments.map(t=>at(t,"segment hash",32)),sha256:m(at(e.sha256,"sha256",32)),ephemeral:at(e.ephemeral,"ephemeral key",32),wrapped:at(e.wrapped,"wrapped key")}}var zn=()=>new k("ABORTED","the export was aborted");async function Aa(n,e){let t=Number(n.headers.get("content-length"));if(Number.isFinite(t)&&t>Xt)throw await n.body?.cancel(),new k("TOO_LARGE","a segment is longer than a whole segment");if(!n.body)return new Uint8Array;let r=n.body.getReader(),o=()=>{r.cancel()};e?.addEventListener("abort",o);let s=[],i=0;try{for(;;){let{done:a,value:p}=await r.read();if(a)break;if(i+=p.length,i>Xt)throw await r.cancel(),new k("TOO_LARGE","a segment is longer than a whole segment");s.push(p)}}finally{e?.removeEventListener("abort",o)}if(e?.aborted)throw zn();return f(...s)}async function Qn(n,e,t,r,o,s){try{return await _a(n,e,t,r,o,s)}catch(i){throw o?.aborted&&!(i instanceof k)?zn():i}}async function _a(n,e,t,r,o,s){let i=await I(s),a=ka(await n.exportsExport({app:e,id:t,recipient:m(i.publicKey)},{signal:o})),{segments:p,named:l}=a;if(p.length===0||m(await Ro(p))!==m(l)||m(l)!==t)throw new k("NOT_THE_FILE",`the node answered segments that are not the file ${t}`);let d=await xo(i,a.ephemeral,{appId:a.app,fileId:t},a.wrapped),u=await Wt.create(d,p);for(let h=0;h<p.length;h+=1){if(o?.aborted)throw zn();let g=await n.request("GET",ke("apps/{app}/files/{id}/segments/{k}",{app:e,id:t,k:h}),{signal:o});await u.push(await Aa(g,o),A=>r.write(A))}let y=await u.finishExpecting(a.size,a.sha256);return y.length>0&&await r.write(y),{size:a.size,sha256:a.sha256}}async function To(n,e,t,r){let o=[];return await Qn(n,e,t,{write:s=>{o.push(s)}},r),f(...o)}var jo="calimero.org-recovery.v1\0",Yn=64,Jn=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function Ea(){return crypto.getRandomValues(new Uint8Array(32))}function Ra(n){Oo(n);let e=Array.from(n,r=>r.toString(16).padStart(2,"0")).join(""),t=[];for(let r=0;r<e.length;r+=8)t.push(e.slice(r,r+8));return t.join("-")}function xa(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,r)=>parseInt(e.slice(2*r,2*r+2),16))}function vo(n,e,t){return new TextEncoder().encode(`${jo}${n}\0${e}\0${t}`)}async function Zt(n){let e=await Be(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 Wn(n,e,t,r){let o=new TextEncoder().encode(r).length;if(o===0||o>Yn)throw new Error(`a recovery nonce is 1 to ${Yn} bytes`);let s=await Be(n,!1),i=await crypto.subtle.sign("Ed25519",s,S(vo(e,t,r)));return R(new Uint8Array(i))}function Oo(n){if(n.length!==32)throw new Error("a recovery seed is 32 bytes")}function Be(n,e){Oo(n);let t=new Uint8Array(Jn.length+32);return t.set(Jn),t.set(n,Jn.length),crypto.subtle.importKey("pkcs8",S(t),{name:"Ed25519"},e,["sign"])}var S=n=>n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);var So=1,Ta=new TextEncoder().encode("calimero.recovery-backup.v1\0"),ja=new TextEncoder().encode("calimero.recovery-backup.v1"),va=new TextEncoder().encode("calimero.recovery-backup.key.v1"),Co=32,Oa=1,Sa=2,Ua=0,D=n=>new TextEncoder().encode(n),ct=n=>new Uint8Array([n>>8&255,n&255]),Uo=f(D("KEM"),ct(Co)),pt=f(D("HPKE"),ct(Co),ct(Oa),ct(Sa));function Ne(n){return n.kind==="operator"?"operator":`${n.kind}:${n.id}`}async function tu(){let n=crypto.getRandomValues(new Uint8Array(32));return{secret:n,publicKey:await Ca(n)}}async function Ca(n){return m((await I(n)).publicKey)}async function Ba(n){let e=D(n.header),t=JSON.parse(n.header);if(typeof t.format!="number"||t.format>So)throw new Error(`recovery file format ${t.format} is not one this release reads (${So})`);let r=await crypto.subtle.importKey("raw",x(t.signingKey,"signing key",32),{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify("Ed25519",r,x(n.signature,"signature",64),f(Ta,e)))throw new Error("the node's signature over the header does not hold");return t}async function Bo(n,e){let t=n.length===0?new Uint8Array(32):n,r=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",r,e))}async function Na(n,e,t){let r=new Uint8Array(t),o=new Uint8Array(0);for(let s=1,i=0;i<t;s+=1)o=await Bo(n,f(o,e,new Uint8Array([s]))),r.set(o.subarray(0,Math.min(o.length,t-i)),i),i+=o.length;return r}var en=(n,e,t,r)=>Bo(e,f(D("HPKE-v1"),n,D(t),r)),Xn=(n,e,t,r,o)=>Na(e,f(ct(o),D("HPKE-v1"),n,D(t),r),o);async function Ma(n,e){let t=await I(e);if(m(t.publicKey)!==n.recipient)throw new Error("this key is not the one the file was sealed to");let r=x(n.enc,"encapsulated key",32),o=await z(t.privateKey,r),s=new Uint8Array(0),i=await en(Uo,s,"eae_prk",o),a=await Xn(Uo,i,"shared_secret",f(r,t.publicKey),32),p=await en(pt,s,"psk_id_hash",s),l=await en(pt,s,"info_hash",ja),d=f(new Uint8Array([Ua]),p,l),u=await en(pt,a,"secret",s),y=await Xn(pt,u,"key",d,32),h=await Xn(pt,u,"base_nonce",d,12),g=await crypto.subtle.importKey("raw",y,"AES-GCM",!1,["decrypt"]),A;try{A=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:h,additionalData:va},g,x(n.wrappedKey,"wrapped key",48)))}catch{throw new Error("this key does not open the file")}if(A.length!==32)throw new Error("the data key is not 32 bytes");return A}async function nu(n,e,t,r={}){let o=[];for(let p of[...e].sort((l,d)=>l.name.localeCompare(d.name))){let l=await Ba(p);if(r.verifyQuote&&await Da(l,r.verifyQuote),Ne(l.holder)!==Ne(n))throw new Error(`${p.name} is ${Ne(l.holder)}'s, not ${Ne(n)}'s`);o.push({name:p.name,header:l})}let s=async p=>({file:p.name,key:m(await Ma(p.header,t))}),i=o.filter(p=>p.header.kind==="holder").pop();if(!i)throw new Error(`no holder file of ${Ne(n)}`);let a=new Map;for(let p of o)p.header.kind==="app"&&p.header.app&&(!r.apps||r.apps.includes(p.header.app))&&a.set(p.header.app,p);return{holder:Ne(n),slice:await s(i),apps:await Promise.all([...a.values()].map(s)),code:await Promise.all(o.filter(p=>p.header.kind==="code").map(s))}}async function Zn(n){return new Uint8Array(await crypto.subtle.digest("SHA-256",n))}async function qa(n,e){let t=D(n),r=new Uint8Array(4);new DataView(r.buffer).setUint32(0,t.length,!1);let o=new Uint8Array(8);return new DataView(o.buffer).setBigUint64(0,BigInt(e),!1),m(await Zn(f(D("calimero.recovery-backup.attest.v1\0"),r,t,o)))}var Me=(n,e,t,r)=>{if(n===void 0&&r)return r;if(!e.includes(n))throw new Error(`the governance's ${t} is not one of ${e.join(", ")}`);return n};function er(n){let e={releases:Me(n.releases,["owner","operator"],"releases"),appUpgrades:Me(n.appUpgrades,["owner","operator"],"appUpgrades"),outbound:Me(n.outbound,["owner","operator"],"outbound")},t=Me(n.deployments,["open","granted"],"deployments","open");t!=="open"&&(e.deployments=t);let r=Me(n.deployers,["operator","owner"],"deployers","operator");r!=="operator"&&(e.deployers=r);let o=Me(n.signUp,["open","invite","closed"],"signUp","open");return o!=="open"&&(e.signUp=o),D(JSON.stringify(e))}async function tr(n,e,t,r){let o=await Zn(er(e)),s=D(t),i=new Uint8Array(4);new DataView(i.buffer).setUint32(0,s.length,!1);let a=new Uint8Array(8);return new DataView(a.buffer).setBigUint64(0,BigInt(r),!1),m(await Zn(f(D("calimero.tee-attest.receipt-key.v3"),n,o,i,s,a)))}async function Da(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 r=await qa(n.cluster,n.node);if(t.nonce!==r)throw new Error("the attestation is not over the recovery nonce");if(!t.governance)throw new Error("the attestation names no governance");let o=await tr(x(n.signingKey,"signing key",32),t.governance,n.cluster,n.node);if(!await e({quoteB64:t.quote,nonce:r,reportDataSuffix:o}))throw new Error("the quote was not accepted")}var nr=1024*1024,rr=16,or=64*1024,sr=512*1024*1024,ir=(64*1024*1024-1024*1024)/4*3,Ia="did:key:z6MknF3p5L5FDHJQ7FREUapuX4Wmp4MtF6WrHYaXS2B3eZQd",Ka=new TextEncoder().encode("calimero.bundle.manifest.v1\0"),$a="0.1.0",Va=[237,1],La="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Ha=[0,97,115,109,13,0,1,0],Ga=/^pipelines\/[A-Za-z0-9._-]+\.yaml$/,Fa=/^[A-Za-z0-9_-]{43}$/,za=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,qe=n=>new TextEncoder().encode(n),tn=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),nn=(...n)=>{let e=new Uint8Array(n.reduce((r,o)=>r+o.length,0)),t=0;for(let r of n)e.set(r,t),t+=r.length;return e};async function lt(){let n=new Error("this runtime cannot sign Ed25519 packages (WebCrypto Ed25519 is missing)");if(!globalThis.crypto?.subtle)throw n;try{await Be(new Uint8Array(32),!1)}catch{throw n}}async function Do(n){if(await lt(),n.length!==32)throw new Error("a publisher seed is 32 bytes");let e=C(await Zt(n));return{seed:Uint8Array.from(n),publicKey:e}}async function Qa(){return await lt(),Do(crypto.getRandomValues(new Uint8Array(32)))}async function Ja(n){return await lt(),{privateKey:await Be(Uint8Array.from(n.seed),!1),publicKey:Uint8Array.from(n.publicKey)}}function Ya(n){let e=0n;for(let r of n)e=e<<8n|BigInt(r);let t="";for(;e>0n;e/=58n)t=La[Number(e%58n)]+t;return"1".repeat(n.findIndex(r=>r!==0)===-1?n.length:n.findIndex(r=>r!==0))+t}function De(n){return`did:key:z${Ya(nn(Uint8Array.from(Va),n.publicKey))}`}function Wa(n){return De(n)===Ia}function Xa(n){return qe(JSON.stringify({private_key:R(n.seed),public_key:R(n.publicKey),signer_id:De(n)},null,2))}async function Za(n){let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new Error("a publisher key backup is a JSON document")}let t=e?.private_key;if(typeof t!="string"||!Fa.test(t)||R(C(t))!==t)throw new Error("the backup private_key is not an unpadded base64url 32-byte seed");let r=await Do(C(t));if(e.public_key!==void 0&&e.public_key!==R(r.publicKey))throw new Error("the backup public_key is not the seed's");if(e.signer_id!==void 0&&e.signer_id!==De(r))throw new Error("the backup signer_id is not the seed's");return r}function Io(n){let e=Object.fromEntries(Object.entries(n).filter(([t])=>t!=="signature"&&!t.startsWith("_")));return qe(Ae(e))}function Ae(n,e=!1){if(typeof n=="string"){if(/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(n))throw new Error("a lone surrogate cannot be canonicalized");return JSON.stringify(n)}if(typeof n=="number"){if(e?!Number.isFinite(n):!Number.isSafeInteger(n))throw new Error(e?"a non-finite number cannot be canonicalized":"only safe integers can be canonicalized");return String(n)}if(n===null||typeof n=="boolean")return String(n);if(typeof n!="object")throw new Error(`a ${typeof n} cannot be canonicalized`);return Array.isArray(n)?`[${n.map(t=>Ae(t,e)).join(",")}]`:`{${Object.keys(n).sort().map(t=>`${Ae(t,e)}:${Ae(n[t],e)}`).join(",")}}`}async function ar(n){return Ce(nn(Ka,Io(n)))}async function ep(n){await lt();let e=n.signature;if(!e)throw new Error("manifest is missing required 'signature' field");if(e.algorithm!=="ed25519")throw new Error(`unsupported signature algorithm: '${e.algorithm}'`);let t=C(e.publicKey??""),r=C(e.signature??"");if(t.length!==32||r.length!==64)throw new Error("malformed signature field");let o=await crypto.subtle.importKey("raw",S(t),{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify("Ed25519",o,S(r),S(await ar(n))))throw new Error("Ed25519 signature verification failed");let i=De({publicKey:t});if(n.signerId!==i)throw new Error(`signerId mismatch: manifest declares '${n.signerId}' but signature public key derives to '${i}'`);return i}function No(n,e){if(!n)throw new Error(`${e} is empty`);if(n.includes(".."))throw new Error(`${e} contains path traversal sequence '..'`);if(n.includes("/")||n.includes("\\"))throw new Error(`${e} contains directory separator`);if(n.includes("\0"))throw new Error(`${e} contains null byte`);if(n.length>=2&&n[1]===":")throw new Error(`${e} appears to be an absolute path`)}function tp(n,e){if(!n)throw new Error(`${e} is empty`);if(n.includes("\0"))throw new Error(`${e} contains null byte`);if(n.includes("\\"))throw new Error(`${e} contains backslash (use forward slashes)`);if(n.startsWith("/"))throw new Error(`${e} is an absolute path`);if(n[1]===":")throw new Error(`${e} appears to be an absolute Windows path`);if(n.split("/").includes(".."))throw new Error(`${e} contains path traversal component '..'`);if(!Ga.test(n)||qe(n).length>100)throw new Error(`${e} must be pipelines/<name>.yaml (A-Z a-z 0-9 . _ -), at most 100 bytes`)}var Mo=["name","description","author","icon","license","category","guide"];function np(n){let e=s=>new Error(`metadata ${s}`);if(typeof n!="object"||n===null||Array.isArray(n))throw e("must be an object");let t=new Set([...Mo,"tags"]),r=Object.keys(n).find(s=>!t.has(s));if(r!==void 0)throw e(`has an unknown field '${r}'`);let o={};for(let s of Mo){let i=n[s];if(i!==void 0){if(typeof i!="string")throw e(`${s} must be a string`);o[s]=i}}if(typeof o.name!="string")throw e("name is required");if(n.tags!==void 0){if(!Array.isArray(n.tags)||n.tags.some(s=>typeof s!="string"))throw e("tags must be an array of strings");o.tags=[...n.tags]}return o}var qo=(n,e)=>({path:n,hash:tn(Ce(e)),size:e.length}),Ko=n=>512+Math.ceil(n/512)*512;function rp(n,e){let t=new Uint8Array(512),r=(o,s)=>t.set(qe(s),o);return r(0,n),r(100,"0000644\0"),r(108,"0000000\0"),r(116,"0000000\0"),r(124,`${e.length.toString(8).padStart(11,"0")}\0`),r(136,"00000000000\0"),r(148," "),r(156,"0"),r(257,"ustar\0"),r(263,"00"),r(148,`${t.reduce((o,s)=>o+s,0).toString(8).padStart(6,"0")}\0 `),nn(t,e,new Uint8Array((512-e.length%512)%512))}function op(n){let e=new Map,t=(r,o)=>new TextDecoder().decode(n.subarray(r,o)).replace(/\0.*$/s,"");for(let r=0;r+512<=n.length&&n[r]!==0;){let o=t(r,r+100),s=parseInt(t(r+124,r+136).trim(),8);if(e.has(o))throw new Error(`the archive has more than one entry at '${o}'`);e.set(o,n.subarray(r+512,r+512+s)),r+=Ko(s)}return e}async function sp(n,e){let t=op(n),r=t.get("manifest.json");if(!r)throw new Error("manifest.json not found in bundle");let o=JSON.parse(new TextDecoder().decode(r));if(await ep(o),o.signature.publicKey!==R(e))throw new Error("the manifest is not signed by the publisher key");let s=[o.compute,...o.pipelines??[]],i=["manifest.json",...s.map(a=>a.path)];if(i.length!==t.size||i.some(a=>!t.has(a)))throw new Error("the archive does not hold exactly the files its manifest declares");for(let a of s){let p=t.get(a.path);if(!p||p.length!==a.size||tn(Ce(p))!==a.hash)throw new Error(`bundle artifact '${a.path}' failed its integrity check`)}}async function ip(n){if(typeof CompressionStream>"u")throw new Error("this runtime cannot gzip packages (no CompressionStream)");let e=new Blob([S(n)]).stream().pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(e).arrayBuffer())}async function ap(n,e,t){if(e){let o=C(await Zt(e));if(tn(o)!==tn(t))throw new Error("the publisher key's publicKey is not its seed's");return{signing:await Be(e,!1),publicKey:o}}let r=n.privateKey;if(r?.algorithm?.name!=="Ed25519"||r.type!=="private"||!r.usages.includes("sign"))throw new Error("the publisher key is not an Ed25519 signing key");return{signing:r,publicKey:t}}async function pp(n,e){let t="seed"in e&&e.seed?Uint8Array.from(e.seed):void 0,r=Uint8Array.from(e.publicKey),o=cp(n);await lt();let{signing:s,publicKey:i}=await ap(e,t,r),a={...o.manifest,signerId:De({publicKey:i})},p=await crypto.subtle.sign("Ed25519",s,S(await ar(a)));a.signature={algorithm:"ed25519",publicKey:R(i),signature:R(new Uint8Array(p))};let l=qe(Ae(a));if(l.length>nr)throw new Error(`bundle manifest.json exceeds the ${nr} byte cap`);let d=[["manifest.json",l],["compute.wasm",o.compute],...o.files];$o(d.map(([,h])=>h.length));let u=nn(...d.map(([h,g])=>rp(h,g)),new Uint8Array(1024));await sp(u,i);let y=await ip(u);if(y.length>ir)throw new Error(`a package is limited to ${ir>>20} MiB`);return y}function $o(n){if(n.reduce((e,t)=>e+Ko(t),1024)>sr)throw new Error(`bundle archive exceeds the ${sr} byte decompressed cap`)}function cp(n){if(No(n.package,"package"),No(n.version,"appVersion"),!za.test(n.version))throw new Error(`appVersion '${n.version}' is not a semantic version`);if(!n.compute?.length)throw new Error("the package ships no WASM");if(n.pipelines.length>rr)throw new Error(`bundle declares ${n.pipelines.length} pipelines, at most ${rr} are allowed`);$o([n.compute.length]);let e=Uint8Array.from(n.compute);if(Ha.some((a,p)=>e[p]!==a))throw new Error("compute: not a WASM component (an SDK 0.12 core module is refused by the node)");let t=n.pipelines.map((a,p)=>(tp(a.path,`pipelines[${p}].path`),[a.path,qe(a.source)])),r=t.find(([,a])=>a.length>or);if(r)throw new Error(`pipeline '${r[0]}' exceeds the ${or} byte cap`);let o=t.map(([a])=>a.toLowerCase());if(new Set(o).size!==t.length)throw new Error("two pipelines have the same path");let s=n.metadata===void 0?void 0:np(n.metadata);return{manifest:{version:"1.0",package:n.package,appVersion:n.version,minRuntimeVersion:$a,...s?{metadata:s}:{},compute:qo("compute.wasm",e),...t.length?{pipelines:t.map(([a,p])=>qo(a,p))}:{}},compute:e,files:t}}var zo="calimero.pipeline.receipt.v1\0",pe=n=>new TextEncoder().encode(n),H=(n,e)=>{throw new Error(`the receipt's ${n} ${e}`)},ae=(n,e)=>Object.prototype.hasOwnProperty.call(n,e),J=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),w=(n,e)=>typeof n=="string"||H(e,"is not a string"),Qo=(n,e)=>typeof n=="boolean"||H(e,"is not a boolean"),lp=()=>{},Vo=(n,e)=>J(n)||H(e,"is not an object"),up=n=>(e,t)=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=n||H(t,"is not an unsigned integer in range"),rn=up(4294967295),$e=(n,e)=>typeof n=="number"&&Number.isInteger(n)&&n>=0&&n<2**64||H(e,"is not an unsigned integer in range"),Ve=n=>(e,t)=>{Array.isArray(e)||H(t,"is not an array"),e.forEach((r,o)=>n(r,`${t}[${o}]`))},ut=n=>(e,t)=>{J(e)||H(t,"is not an object");for(let[r,o]of Object.entries(e))n(o,`${t}.${r}`)},G=(n,e={},t={},r=!1)=>(o,s)=>{if(!J(o))return H(s,"is not an object");for(let i of Object.keys(o))!r&&!ae(n,i)&&!ae(e,i)&&!ae(t,i)&&H(`${s}.${i}`,"is not a known field");for(let[i,a]of Object.entries(n))ae(o,i)||H(`${s}.${i}`,"is missing"),a(o[i],`${s}.${i}`);for(let[i,a]of Object.entries(e))ae(o,i)&&o[i]!==null&&a(o[i],`${s}.${i}`);for(let[i,a]of Object.entries(t))ae(o,i)&&a(o[i],`${s}.${i}`)},Jo=G({id:w,size:$e,sha256:w}),dp=G({id:w,size:$e,sha256:w,segments:Ve(w)}),yp=G({resultSha256:w,segments:Ve(Ve(w))},{log:dp},{message:w}),hp=G({quote:w,transportKey:w,appHash:w,nonce:w,release:G({version:w,profile:w},{},{},!0),cluster:w,node:$e,mock:Qo},{receiptKey:w,governance:Vo,kms:Vo,jobKey:w,clusterIdentity:w},{},!0),fp=G({run:w,step:w,index:rn,outcome:w,attempt:rn,outputs:Ve(Jo),usage:G({cpuMicros:w,gibMicros:w,fuel:w})},{node:$e,jobKey:w,assignmentDigest:w,reportSha256:w,signature:w,job:yp}),gp=G({index:rn,cached:Qo,cacheKey:w}),mp=(n,e)=>{try{gp(n,e)}catch{fp(n,e)}},wp=G({version:rn,cluster:w,app:w,run:w,pipeline:w,release:w,pipelineHash:w,modules:ut(w),inputs:ut(Ve(Jo)),params:ut(lp),state:w,startTsMs:$e,endTsMs:$e,steps:ut(G({status:w,runs:Ve(mp)},{reason:w}))},{costSoFar:w},{jobAttestations:ut(hp)});function on(n,e,t){if(typeof n!="string"||n.length!==t*2||!/^[0-9a-fA-F]*$/.test(n))throw new Error(`${e} is not ${t} bytes of hex`);return x(n,e,t)}function pr(n,e){if(typeof n!="number"||!Number.isSafeInteger(n)||n<0)throw new Error(`${e} is not a node id`);return n}async function Yo(n,e,t,r,o){if(typeof n.quote!="string")throw new Error("the attestation carries no quote");if(!n.receiptKey)throw new Error("the attestation names no receipt key");if(!J(n.governance))throw new Error("the attestation names no governance");let s=on(n.receiptKey,"the receipt key",32),i=x(await tr(s,n.governance,t,r),"binding",32);return await xt(n,e,i,o,"receipt key"),{key:s,governance:JSON.parse(new TextDecoder().decode(er(n.governance)))}}async function an(n,e,t){let r=crypto.getRandomValues(new Uint8Array(32)),o=await n.apps.attestation({app:e,nonce:m(r)});if(!J(o)||typeof o.cluster!="string"||!Array.isArray(o.replicas))throw new Error("the node answered a malformed attestation");let s=o.cluster,i=new Map,a;for(let p of o.replicas){if(!J(p))throw new Error("a replica entry is not an object");let l=pr(p.node,"a replica");if(ae(p,"error"))throw new Error(`replica ${l} gave no attestation: ${String(p.error)}`);let d=p.attestation;if(!J(d))throw new Error(`replica ${l} gave neither an attestation nor an error`);if(pr(d.node,`replica ${l}'s document`)!==l)throw new Error(`replica ${l} answered as node ${String(d.node)}`);let u;try{u=await Yo(d,r,s,l,t)}catch(y){throw new Error(`replica ${l}: ${y instanceof Error?y.message:String(y)}`)}if(a&&JSON.stringify(a)!==JSON.stringify(u.governance))throw new Error(`replica ${l} attests other governance`);a=u.governance,i.set(l,u.key)}if(!a)throw new Error(`no replica of ${e} attested`);return{keys:i,governance:a,cluster:s}}var Wo=n=>Ae(n,!0),bp=n=>f(pe(zo),pe(Wo(n)));async function Pp(n,e){if(!J(n))throw new Error("the receipt answer is not an object");let t=Object.keys(n).find(a=>!["receipt","node","signature"].includes(a));if(t!==void 0)throw new Error(`the receipt answer's ${t} is not a known field`);let r=on(n.signature,"the signature",64),o=Wo(n.receipt),s=await crypto.subtle.importKey("raw",S(e),{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify("Ed25519",s,S(r),S(f(pe(zo),pe(o)))))throw new Error("the receipt is not signed by that key");let i=JSON.parse(o);return wp(i,"receipt"),i}var kp="calimero.compute.report.v1\0",Ap="calimero.compute.report.log.v1\0",_p="calimero.tee-attest.job-key.v1",Lo=2,Ep=["fuel","memory","trap","app-error","integrity","cancelled"],Rp=["lost","refused","timeout","quota","not-granted","too-large"],Xo=2n**64n-1n,Zo=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",S(n))),sn=n=>{let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n,!1),e},cr=n=>{let e=BigInt(n);if(e<0n||e>Xo)throw new Error("a number is past 2^64-1");let t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,e,!1),t},Ke=n=>{let e=pe(n);return f(sn(e.length),e)};function _e(n){if(typeof n!="string"||!/^[0-9a-f]{64}$/.test(n))throw new Error("a hash is 64 lowercase hex digits");return x(n,"hash",32)}function xp(n){if(!/^[0-9]+$/.test(n))throw new Error(`${JSON.stringify(n)} is not a decimal integer`);let e=BigInt(n);if(e>Xo)throw new Error(`${JSON.stringify(n)} is not a decimal integer`);return e}function Ho(n){return f(_e(n.id),cr(n.size),_e(n.sha256),sn(n.segments.length),...n.segments.map(_e))}function es(n){return f(pe(kp),_e(n.assignment),Ke(n.app),Ke(n.run),sn(n.attempt),new Uint8Array([n.reason===null?0:1]),Ke(n.reason??""),Ke(n.message),_e(n.resultSha256),sn(n.outputs.length),...n.outputs.map(Ho),...n.usage.map(e=>cr(xp(e))),...n.log?[pe(Ap),Ho(n.log)]:[])}async function ts(n,e,t,r,o,s){return m(await Zo(f(pe(_p),n,e,Ke(t),Ke(r),cr(o),s??new Uint8Array(0))))}function Tp(n,e){if(n==="done")return{reason:null};if(n==="cancelled")return e?{reason:"cancelled"}:null;let t=()=>new Error(`the outcome ${JSON.stringify(n)} is not one a run ends with`);if(!n.startsWith("failed:"))throw t();let r=n.slice(7);if(Ep.includes(r))return{reason:r};if(!Rp.includes(r))throw t();return null}var jp=2n**252n+27742317777372353535851937790883648493n,P=2n**255n-19n,Go=(P-121665n)%P*Ie(121666n,P-2n)%P;function Ie(n,e){let t=1n;for(n%=P;e>0n;e>>=1n,n=n*n%P)e&1n&&(t=t*n%P);return t}function Fo(n){let e=0n;for(let a=31;a>=0;a--)e=e<<8n|BigInt(n[a]&(a===31?127:255));e%=P;let t=n[31]>>7&1,r=e*e%P,o=(r-1n+P)%P*Ie((Go*r+1n)%P,P-2n)%P,s=Ie(o,(P+3n)/8n);if(s*s%P!==o&&(s=s*Ie(2n,(P-1n)/4n)%P),s*s%P!==o)return!1;Number(s&1n)!==t&&(s=(P-s)%P);let i=[s,e];for(let a=0;a<3;a++){let[p,l]=i,d=Go*p*p*l*l%P;i=[2n*p*l*Ie((1n+d)%P,P-2n)%P,(l*l+p*p)*Ie((1n-d+P)%P,P-2n)%P]}return i[0]===0n&&i[1]===1n}async function vp(n,e,t){let r=0n;for(let s=63;s>=32;s--)r=r<<8n|BigInt(t[s]);if(r>=jp||Fo(n)||Fo(t.slice(0,32)))return!1;let o=await crypto.subtle.importKey("raw",S(n),{name:"Ed25519"},!1,["verify"]);return crypto.subtle.verify("Ed25519",o,S(t),S(e))}async function Op(n,e,t){let r=`${n.run}.${e}.${t.index}`;if(t.run!==r||t.step!==e)throw new Error(`the proof of ${t.run} is listed as ${r}`);let o=t.signature!=null,s=Tp(t.outcome,o);if(!s){let u=[t.usage.cpuMicros,t.usage.gibMicros,t.usage.fuel].every(y=>y==="0");if(o||t.reportSha256!=null||t.job!=null||t.outputs.length>0||!u)throw new Error(`${t.run} ended ${t.outcome} by the leader, yet names a report, outputs or usage`);return null}let i=u=>new Error(`${t.run} ended ${t.outcome} but its proof has no ${u}`);if(t.node==null)throw i("job node");if(t.jobKey==null)throw i("job key");if(t.assignmentDigest==null)throw i("assignment digest");if(t.reportSha256==null)throw i("report hash");if(t.signature==null)throw i("report signature");if(t.job==null)throw i("job evidence (it ended before receipts carried it)");let a=t.job;if(a.segments.length!==t.outputs.length)throw new Error(`${t.run}: the job evidence lists segments for ${a.segments.length} outputs, the proof ${t.outputs.length}`);let p=t.outputs.map((u,y)=>({id:u.id,size:u.size,sha256:u.sha256,segments:a.segments[y]})),l;try{l=es({assignment:t.assignmentDigest,app:n.app,run:t.run,attempt:t.attempt,reason:s.reason,message:a.message??"",resultSha256:a.resultSha256,outputs:p,usage:[t.usage.cpuMicros,t.usage.gibMicros,t.usage.fuel],log:a.log})}catch(u){throw new Error(`${t.run}: ${u instanceof Error?u.message:String(u)}`)}if(m(await Zo(l))!==t.reportSha256)throw new Error(`${t.run}: the report hash is not that of what the proof says`);let d=_e(t.jobKey);if(!/^[0-9a-fA-F]{128}$/.test(t.signature))throw new Error(`${t.run}: the report signature is not 64 bytes of hex`);if(!await vp(d,l,x(t.signature,"signature",64)))throw new Error(`${t.run}: the job key did not sign what the proof says`);return{key:t.jobKey,node:t.node}}async function ns(n){if(n.version!==Lo)throw new Error(`the receipt is version ${n.version}; only version ${Lo} carries what each job signed`);let e=new Map;for(let[t,r]of Object.entries(n.steps))for(let[o,s]of r.runs.entries()){if(s.index!==o)throw new Error(`step ${t} lists run ${s.index} where run ${o} belongs`);if("cached"in s){if(!s.cached)throw new Error(`step ${t} run ${o} is listed as not cached`);continue}let i=await Op(n,t,s);if(i&&(e.get(i.key)??i.node)!==i.node)throw new Error(`job key ${i.key} is named on two nodes`);i&&e.set(i.key,i.node)}return e}async function Sp(n,e,t,r,o){let s=n.jobAttestations&&ae(n.jobAttestations,t)?n.jobAttestations[t]:void 0;if(!s)throw new Error("the receipt carries no attestation for it");if(s.jobKey!==t)throw new Error("its attestation is another key's");if(s.node!==r||s.cluster!==e)throw new Error(`it is attested as node ${s.node} of cluster ${s.cluster}, not node ${r} of ${e}`);if(s.clusterIdentity!==n.cluster)throw new Error("its job node takes work from another cluster identity");let i;try{i=_e(s.nonce)}catch{throw new Error("its attestation's nonce is not 32 bytes of hex")}let a=await ts(on(s.transportKey,"the transport key",32),x(t,"the job key",32),s.release.version,s.cluster,s.node,on(s.clusterIdentity,"the cluster identity",32));await xt(s,i,x(a,"binding",32),o,"job key")}async function lr(n,e,t,r,o){let{keys:s,cluster:i}=await an(n,e,o);if(!J(r))throw new Error("the receipt answer is not an object");let a=pr(r.node,"the receipt answer"),p=s.get(a);if(!p)throw new Error(`node ${a} is not an attested replica of ${e}`);let l=await Pp(r,p);if(l.app!==e)throw new Error(`the receipt is for app ${l.app}, not ${e}`);if(l.run!==t)throw new Error(`the receipt is for run ${l.run}, not ${t}`);for(let[d,u]of await ns(l))try{await Sp(l,i,d,u,o)}catch(y){throw new Error(`job key ${d}: ${y instanceof Error?y.message:String(y)}`)}return l}var ur=100;function dr(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>ur)throw new RangeError(`limit is 1 to ${ur}`);e.set("limit",String(n.limit))}let t=e.toString();return t?`?${t}`:""}function dt(n,e){try{return We(n,e)}catch{return n<e?-1:n>e?1:0}}function rs(n,e,t=Date.now()/1e3){if(n===null||n.length===0)return null;let r=n.reduce((s,i)=>dt(s,i)>=0?s:i),o=null;for(let s of e)s.afterSecs<=t&&dt(r,s.version)<0&&(o===null||dt(s.version,o.version)>0)&&(o=s);return o}function os(n,e,t,r){return`calimero-publisher-binding/v1
5
5
  ${n}
6
6
  ${e}
7
7
  ${t}
8
- ${r}`}function Np(n,e,t,r){return new TextEncoder().encode(ss(n,e,t,r))}var Mp="0123456789ABCDEFGHJKMNPQRSTVWXYZ";async function yr(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,r="";for(let o=0;o<6;o++)o===3&&(r+="-"),r+=Mp[t>>>27-5*o&31];return r}function qp(n){let e=typeof n=="string"?new URL(n):n,t=e.searchParams.get("request_id"),r=e.searchParams.get("result");return!t||r!=="approved"&&r!=="declined"?null:{requestId:t,result:r}}function hr(n){let e=new URL(String(n));return e.searchParams.delete("request_id"),e.searchParams.delete("result"),e.toString()}var Ve="calimero.consent",is="https://mero-tee.vercel.app";function as(n){return`https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(n)}`}function ps(n){return`${is}/mero-tee?${new URLSearchParams(n)}`}function cs(n){return ps({release_tag:`mero-tee-v${n}`})}function Dp(n,e){return ps({node_url:n.replace(/\/+$/,""),release_tag:`mero-tee-v${e}`})}function fr(n,e,t=Date.now()/1e3){let r=p=>e.deadlines.find(l=>l.version===p)??null,o=n.governance.releases==="owner",s=n.governance.appUpgrades==="owner",i=n.clusterReleases.filter(p=>!p.approved).sort((p,l)=>dt(l.release,p.release)).map(p=>({version:p.release,nodes:p.nodes,actionable:o,releaseNotesUrl:as(p.release),verifyUrl:cs(p.release),deadline:r(p.release)})),a=[];for(let p of n.apps){let l=p.availableVersions??[];if(p.package===null||l.length===0)continue;let d=l[l.length-1],u=p.latestReachable===void 0?d:p.latestReachable;a.push({app:p.app,name:p.name??null,package:p.package.package,from:p.package.version,to:u??d,reachable:u!==null,blocked:p.latestBlocked??null,available:l,actionable:s})}return{scope:n.scope,governance:n.governance,approvedReleases:n.approvedReleases,releases:i,upgrades:a,stalledBy:os(n.approvedReleases,e.deadlines,t),actionable:i.some(p=>p.actionable)||a.some(p=>p.actionable)}}function ls(n,e,t,r={}){return{kind:"release",scope:n.kind==="org"?{org:n.org}:"account",subject:r.withdraw?{version:e,withdraw:!0}:{version:e},returnTo:t}}function Ip(n,e,t){return ls(n,e,t,{withdraw:!0})}function Kp(n,e,t){return{kind:"upgrade",subject:{app:n,toVersion:e},returnTo:t}}function $p(n,e,t){return{kind:"createOrg",subject:t===void 0?{name:n}:{name:n,capabilities:t},returnTo:e}}function Lp(n,e){return{kind:"createInvite",subject:n,returnTo:e}}function Vp(n,e){return{kind:"acceptInvite",subject:{token:n},returnTo:e}}function Hp(n,e){return{kind:"leaveOrg",subject:{org:n},returnTo:e}}function Gp(n,e,t){return{kind:"removeMember",subject:{org:n,account:e},returnTo:t}}function Fp(n,e,t,r){return{kind:"setMemberRole",subject:{org:n,account:e,role:t},returnTo:r}}function zp(n,e,t,r){return{kind:"setMemberTeams",subject:{org:n,account:e,teams:t},returnTo:r}}function Qp(n,e,t,r){return{kind:"removeMemberTeams",subject:{org:n,account:e,teams:t},returnTo:r}}function Jp(n,e,t){return{kind:"revokeInvite",subject:{org:n,inviteKey:e},returnTo:t}}function Yp(n,e,t){return{kind:"renameOrg",subject:{org:n,name:e},returnTo:t}}function Wp(n,e){return{kind:"deleteOrg",subject:{org:n},returnTo:e}}function Xp(n,e){return{kind:"setCapabilities",subject:n,returnTo:e}}function Zp(n,e,t,r){return{kind:"setAllApps",subject:{org:n,account:e,allApps:t},returnTo:r}}var hs=16*1024*1024,ec=1,tc=8,nc=16,rc=8;function oc(n){return"account"in n?`account:${n.account}`:`org:${n.org}`}async function sc(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 r=await e(new URL("/.well-known/calimero.json",t).toString());if(!r.ok)throw await se(r);let o=await r.json();return{...o,deployments:o.deployments??[]}}function ic(n){let e=n??globalThis.location?.href;if(!e)return null;try{return new URL(e).searchParams.get("deployment")||null}catch{return null}}function us(n){return dr(n),{after:n.after,limit:n.limit}}function ac(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function pc(n){return n===null?null:ac(n)}async function ds(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 gr(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 mr=class n{static async connect(e,t={}){let r=await qn({...e,directory:e.directory??On});return new n(r,t)}constructor(e,t={}){this.transport=e instanceof Pe?e:new Pe(e);let r=Dn(Kn(this.transport,t));this.apps=r.apps,this.auth=r.auth,this.consent=r.consent,this.ops=r.ops,this.orgs=r.orgs,this.public=r.public,this.packages=r.packages,this.deployments=r.deployments}as(e){return e}confirmWith(e,t={}){return e?{confirm:rt(e,t)}:void 0}get nodeUrl(){return this.transport.nodeUrl}get nodes(){return this.transport.nodes}verification(e){return this.transport.verification(e)}verify(e){return this.transport.verify(e)}useApiKey(e){this.transport.useApiKey(e)}useSession(e){this.transport.useSession(e)}get session(){return this.transport.session}json(e,t,r){return this.transport.json(e,t,{body:r})}attestApp(e,t){return this.transport.attestApp(e,t)}packageCapabilities(e,t,r={}){return this.transport.json("GET",Ae("packages/{package}/{version}/capabilities",{package:e,version:t}),{query:{service:r.service}})}async signUp(e,t,r={}){let o=this.pageOrigin(r),s=r.invite?{invite:r.invite}:{},i=await this.begin(this.auth.registerBegin({...o===void 0?{name:t,...s}:{name:t,origin:o,...s}}),o),a=r.signal,p=await(a?e.create(i.options,{signal:a}):e.create(i.options)),l=await this.auth.registerFinish({challengeId:i.challengeId,registration:p,...s},this.confirmWith(e,{signal:a}));return this.useSession(l),l}async signIn(e,t={}){let r=this.pageOrigin(t),o=await this.begin(this.auth.loginBegin({...r===void 0?{}:{origin:r}}),r),s=o.options.rpId??o.options.rp?.id??"",i=C(o.options.challenge),a=await(t.signal?e.get(i,s,void 0,{signal:t.signal}):e.get(i,s)),p=await this.auth.loginFinish({challengeId:o.challengeId,assertion:a});return this.useSession(p),p}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(o=>{try{return new URL(o).origin}catch{return o}})).has(t)?void 0:t}async begin(e,t){try{return await this.as(e)}catch(r){throw r instanceof be&&!r.origin&&t!==void 0?new be(r.nodeMessage,{...r.details,origin:t}):r}}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 r=await this.as(this.auth.passkeyAddBegin()),o=await e.create(r.options),{credentialId:s}=await this.auth.passkeyAddFinish({challengeId:r.challengeId,registration:o},this.confirmWith(t));return s}async startAccountRecovery(e,t){try{let r=await this.as(this.auth.accountRecoveryBegin({code:e})),o=await t.create(r.options);return await this.auth.accountRecoveryStart({challengeId:r.challengeId,code:e,registration:o})}catch(r){throw r instanceof re?new tt(r.message.replace(/^401 UNAUTHENTICATED: /,""),r.details):r}}async finishAccountRecovery(e,t){let r=await this.auth.accountRecoveryFinish({...t?{accountId:t}:{}},this.confirmWith(e));return this.useSession(r),r}async downloadBlob(e,t){return new Uint8Array(await(await this.apps.blobDownload({app:e,id:t})).arrayBuffer())}get exportClient(){return{exportsExport:this.apps.exportsExport,request:this.transport.request.bind(this.transport)}}exportFileTo(e,t,r,o){return Qn(this.exportClient,e,t,r,o)}exportFile(e,t,r){return jo(this.exportClient,e,t,r)}get attestationPolicy(){let e=this.transport.nodePolicy;if(!e)throw new Error("this client has no attestation policy, so it cannot verify an attestation");return e}async verifyAppCluster(e){return an(this,e,this.attestationPolicy)}async pipelineReceipt(e,t){return await this.apps.pipelineReceiptReceipt({app:e,run:t,version:2})}async verifyPipelineReceipt(e,t,r){return lr(this,e,t,r,this.attestationPolicy)}async downloadBlobGranted(e,t,r){return new Uint8Array(await(await this.apps.blobDownload({app:e,id:t,grant:r})).arrayBuffer())}async uploadFile(e,t){let r=t instanceof Blob?t.size:t.byteLength;if(r<=hs)return this.apps.filesUpload({app:e,body:await ds(t,0,r)});try{return await this.uploadSession(e,t,r)}catch(o){if(!(o instanceof b)||o.code!=="UPLOAD_UNKNOWN")throw o;return this.uploadSession(e,t,r)}}async uploadSession(e,t,r){let o=await this.untilAvailable(()=>this.apps.uploadBegin({app:e,size:r})),{uploadId:s,partBytes:i,parts:a}=o;if(!s||!i||i<=0||a!==Math.ceil(r/i))throw new Error(`the node began an upload it cannot take: ${JSON.stringify(o)}`);try{return await this.sendParts(e,s,t,r,i,a),await this.untilAvailable(()=>this.apps.uploadComplete({app:e,upload:s}))}catch(p){throw p instanceof b&&p.code==="UPLOAD_UNKNOWN"||await this.apps.uploadAbort({app:e,upload:s}).catch(()=>{}),p}}async sendParts(e,t,r,o,s,i){let[a,p,l]=[0,0,0];for(;a<i;)try{let d=await ds(r,a*s,Math.min((a+1)*s,o));a=gr(await this.apps.uploadPart({app:e,upload:t,k:String(a),body:d}),i),p=0;continue}catch(d){if(d instanceof b&&d.code==="PART_OUT_OF_ORDER"){if(l+=1,l>nc)throw d;a=gr(d.details,i);continue}if(!this.isTransient(d)||++p>tc)throw d;if(await new Promise(u=>setTimeout(u,st(p-1,this.transport.retry))),p>ec)try{let u=gr(await this.apps.uploadStatus({app:e,upload:t}),i);u>a&&(p=0),a=u}catch(u){if(!this.isTransient(u))throw u}}}async untilAvailable(e){for(let t=0;;t++)try{return await e()}catch(r){if(!this.isTransient(r)||t>=rc)throw r;await new Promise(o=>setTimeout(o,st(t,this.transport.retry)))}}isTransient(e){return e instanceof oe||this.transport.isNetworkFailure(e)}events(e,t=0,r){return this.transport.events(Ae("apps/{app}/events",{app:e}),{query:{from:t},signal:r})}presenceStream(e,t){return this.transport.events(Ae("apps/{app}/presence/stream",{app:e}),{signal:t})}async startRecovery(e,t){let r=(await this.auth.me()).accountId,o=R(crypto.getRandomValues(new Uint8Array(16))),s=await Wn(t,e,r,o);return this.orgs.recoveryStart({org:e,nonce:o,signature:s})}async appsReportAll(e){let t=(i={})=>e===null?this.auth.accountApps(us(i)):this.orgs.apps({org:e,...us(i)}),r=await t(),o=[...r.apps],s=r.next;for(;s!==null;){let i=await t({after:s});o.push(...i.apps),s=i.next}return{...r,apps:o,next:null}}async pendingApprovals(e=null){let[t,r]=await Promise.all([this.appsReportAll(e),this.public.releasesPublic()]);return fr(t,r)}async openConsentPage(e,t={}){let r=typeof t=="function"?{navigate:t}:t,o=r.navigate??(i=>{let a=globalThis.window;if(!a)throw new Error("no window to open the consent page in; pass `navigate`");a.location.assign(i)}),s=await this.consent.pageCreate({body:e});if(s.code!==void 0){let i=await yr(s.requestId);if(s.code!==i)throw new b(200,"CONSENT_CODE_MISMATCH","the consent page code does not match the request",{requestId:s.requestId,code:s.code,expected:i})}if(r.confirm&&!await r.confirm(s))return s;try{wr()?.setItem(Ve,s.requestId)}catch{}return o(s.url),s}async resumeConsent(e={}){let t=globalThis,r=e.href??t.location?.href;if(r===void 0)throw new Error("no page to read the consent return from; pass `href`");let o=new URL(r),s=o.searchParams.get("request_id");if(!s)return null;e.href===void 0&&t.history&&t.history.replaceState(t.history.state,"",hr(o));let i=e.requestId;if(i===void 0)try{i=wr()?.getItem(Ve)??void 0}catch{i=void 0}if(!i)throw new b(200,"CONSENT_NOT_STARTED","this page started no consent request",{returned:s});if(s!==i)throw new b(200,"CONSENT_REQUEST_MISMATCH","the consent page returned another request than this page started",{requestId:i,returned:s});let a;try{a=await this.consent.pageResult({request:i})}catch(p){throw p instanceof Oe?(ys(i),new b(404,"CONSENT_REPLACED","this page's consent request was replaced by a newer one",{requestId:i})):p}if(a.requestId!==i)throw new b(200,"CONSENT_REQUEST_MISMATCH","the node answered another request",{requestId:i,returned:a.requestId});if(a.status==="pending")throw new b(200,"CONSENT_NOT_DECIDED","the consent page returned, but this request is still pending",{requestId:i});return ys(i),a}async waitForConsent(e,t={}){let r=t.intervalMs??2e3;for(;;){let o=await this.consent.pageResult({request:e});if(o.status!=="pending"||t.signal?.aborted||t.expiresAt!==void 0&&Date.now()/1e3>=t.expiresAt)return o;await new Promise(s=>setTimeout(s,r))}}};function wr(){try{return globalThis.sessionStorage}catch{return}}function ys(n){try{let e=wr();e?.getItem(Ve)===n&&e.removeItem(Ve)}catch{}}var br={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,CREATE_CHILD_TEAM:2048},cc=br.JOIN_OPEN_TEAMS;function lc(...n){return n.reduce((e,t)=>e|br[t],0)}function pn(n,e){return(n<<e|n>>>32-e)>>>0}function ce(n,e,t,r,o){n[e]=n[e]+n[t]>>>0,n[o]=pn(n[o]^n[e],16),n[r]=n[r]+n[o]>>>0,n[t]=pn(n[t]^n[r],12),n[e]=n[e]+n[t]>>>0,n[o]=pn(n[o]^n[e],8),n[r]=n[r]+n[o]>>>0,n[t]=pn(n[t]^n[r],7)}function fs(n,e){return(n[e]|n[e+1]<<8|n[e+2]<<16|n[e+3]<<24)>>>0}function ws(n,e,t){let r=new Uint32Array(16);r[0]=1634760805,r[1]=857760878,r[2]=2036477234,r[3]=1797285236;for(let i=0;i<8;i+=1)r[4+i]=fs(n,i*4);r[12]=e>>>0;for(let i=0;i<3;i+=1)r[13+i]=fs(t,i*4);let o=r.slice();for(let i=0;i<10;i+=1)ce(o,0,4,8,12),ce(o,1,5,9,13),ce(o,2,6,10,14),ce(o,3,7,11,15),ce(o,0,5,10,15),ce(o,1,6,11,12),ce(o,2,7,8,13),ce(o,3,4,9,14);let s=new Uint8Array(64);for(let i=0;i<16;i+=1){let a=o[i]+r[i]>>>0;s[i*4]=a&255,s[i*4+1]=a>>>8&255,s[i*4+2]=a>>>16&255,s[i*4+3]=a>>>24&255}return s}function uc(n,e,t,r){let o=new Uint8Array(r.length);for(let s=0,i=e;s<r.length;s+=64,i+=1){let a=ws(n,i,t),p=Math.min(s+64,r.length);for(let l=s;l<p;l+=1)o[l]=r[l]^a[l-s]}return o}function Pr(n){let e=0n;for(let t=n.length-1;t>=0;t-=1)e=e<<8n|BigInt(n[t]);return e}var dc=(1n<<130n)-5n;function yc(n,e){let t=Pr(n.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,r=Pr(n.subarray(16,32)),o=0n;for(let a=0;a<e.length;a+=16){let p=e.subarray(a,Math.min(a+16,e.length)),l=Pr(p)+(1n<<BigInt(8*p.length));o=(o+l)*t%dc}let s=o+r&(1n<<128n)-1n,i=new Uint8Array(16);for(let a=0;a<16;a+=1)i[a]=Number(s&0xffn),s>>=8n;return i}function gs(n){return new Uint8Array((16-n%16)%16)}function ms(n){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(n),!0),e}function hc(n,e){let t=[n,gs(n.length),e,gs(e.length),ms(n.length),ms(e.length)],r=new Uint8Array(t.reduce((s,i)=>s+i.length,0)),o=0;for(let s of t)r.set(s,o),o+=s.length;return r}function fc(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 bs(n,e,t,r=new Uint8Array(0)){fc(n,e);let o=ws(n,0,e).subarray(0,32),s=uc(n,1,e,t),i=yc(o,hc(r,s)),a=new Uint8Array(s.length+16);return a.set(s),a.set(i,s.length),a}var As=32,gc=1,mc=3,wc=2,bc=32,Pc=32,Ac=12,He=n=>new TextEncoder().encode(n),ht=n=>new Uint8Array([n>>8&255,n&255]),Ps=f(He("KEM"),ht(As)),yt=f(He("HPKE"),ht(As),ht(gc),ht(mc));async function ks(n,e){let t=n.length===0?new Uint8Array(32):n,r=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",r,e))}async function kc(n,e,t){let r=new Uint8Array(t),o=new Uint8Array(0);for(let s=1,i=0;i<t;s+=1)o=await ks(n,f(o,e,new Uint8Array([s]))),r.set(o.subarray(0,Math.min(o.length,t-i)),i),i+=o.length;return r}function cn(n,e,t,r){return ks(e,f(He("HPKE-v1"),n,He(t),r))}function Ar(n,e,t,r,o){return kc(e,f(ht(o),He("HPKE-v1"),n,He(t),r),o)}async function _c(n,e){let t=await cn(Ps,new Uint8Array(0),"eae_prk",n);return Ar(Ps,t,"shared_secret",e,bc)}async function Ec(n,e){let t=new Uint8Array(0),r=await cn(yt,t,"psk_id_hash",t),o=await cn(yt,t,"info_hash",e),s=f(new Uint8Array([wc]),r,o),i=await cn(yt,n,"secret",t);return{key:await Ar(yt,i,"key",s,Pc),nonce:await Ar(yt,i,"base_nonce",s,Ac)}}async function _s(n,e,t,r,o=new Uint8Array(0),s){if(n.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let i=await I(s),a=await I(e),p=f(await z(i.privateKey,n),await z(a.privateKey,n)),l=await _c(p,f(i.publicKey,n,a.publicKey)),{key:d,nonce:u}=await Ec(l,t);return{enc:i.publicKey,ciphertext:bs(d,u,r,o)}}var xs="mero-agent-gate/attest/v3",Ts="mero-agent-gate/provision/v2",Rc=/^[a-z0-9][a-z0-9-]{0,62}$/,xc=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,Es=64,Rs=64*1024,le=class extends Error{constructor(t,r,o){super(t);this.status=r;this.code=o;this.name="AgentGateError"}};function js(n){if(!Rc.test(n))throw new Error(`Agent id ${JSON.stringify(n)} must match [a-z0-9][a-z0-9-]{0,62}`)}function ft(n){return new TextEncoder().encode(n)}function vs(n){let e=ft(n);return f(new Uint8Array([e.length]),e)}function Ee(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}function ln(n,e,t){let r;try{r=Uint8Array.from(atob(n.trim()),o=>o.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(t!==void 0&&r.length!==t)throw new Error(`${e} is not ${t} bytes`);return r}async function Os(n,e,t,r){let o=new Uint8Array(32),s=f(ft(xs),n,vs(e),t??o,r??o);return new Uint8Array(await crypto.subtle.digest("SHA-256",s))}function Ss(n,e){return f(ft(Ts),n,vs(e))}async function Tc(){let n=crypto.getRandomValues(new Uint8Array(32));return{secret:n,publicKey:await un(n)}}async function un(n){if(n.length!==32)throw new Error("An owner key is 32 bytes");return Ee((await I(n)).publicKey)}function Us(n,e){return`${n.replace(/\/+$/,"")}${e}`}async function Cs(n,e,t){let r=await n(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),o=await r.text(),s;try{s=o?JSON.parse(o):void 0}catch{}if(!r.ok){let i=s;throw new le(`The gate answered ${r.status}${i?.error?` ${i.error}`:""}: ${i?.details??o.slice(0,200)}`,r.status,i?.error)}return s}async function kr(n){let e=n.agentId??"";e&&js(e);let t=crypto.getRandomValues(new Uint8Array(32)),r=await Cs(n.fetch??fetch,Us(n.gateUrl,"/attest"),{nonceB64:Ee(t),...e?{agentId:e}:{}});if((r?.agentId??"")!==e)throw new Error(`Asked about agent ${JSON.stringify(e)}, the gate answered for ${JSON.stringify(r?.agentId)}`);let o=ln(r.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),s=r.signingPublicKeyB64?ln(r.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,i=r.ownerPublicKeyB64?ln(r.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!s!=!i)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let a=await Os(o,e,s,i);return await n.verifier({quoteB64:r.quoteB64,nonce:m(t),reportDataSuffix:m(a)}),{agentId:e,provisioningPublicKey:Ee(o),...s?{signingPublicKey:Ee(s)}:{},...i?{ownerPublicKey:Ee(i)}:{}}}async function Bs(n,e){let t=await un(e);if(n.ownerPublicKey&&n.ownerPublicKey!==t)throw new le(`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 jc(n){let e=Object.keys(n);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>Es)throw new Error(`At most ${Es} secrets at once`);for(let t of e){if(!xc.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(ft(n[t]).length>Rs)throw new Error(`Secret ${t} is over ${Rs} bytes`)}}async function Ns(n,e,t,r,o,s){if(!r.agentId)throw new Error("This quote names no agent; attest with the agent id");let i=await Bs(r,o),a=ln(r.provisioningPublicKey,"provisioningPublicKey",32),p=await _s(a,o,Ss(a,r.agentId),ft(JSON.stringify(s)));return Cs(n,Us(e,t),{agentId:r.agentId,provisioningPublicKeyB64:r.provisioningPublicKey,senderPublicKeyB64:i,encappedKeyB64:Ee(p.enc),ciphertextB64:Ee(p.ciphertext)})}async function vc(n){jc(n.secrets);let e=n.fetch??fetch,t=await Ns(e,n.gateUrl,"/provision",n.agent,n.ownerSecret,{secrets:n.secrets}),r=await kr({gateUrl:n.gateUrl,agentId:n.agent.agentId,verifier:n.verifier,fetch:e}),o=await un(n.ownerSecret);if(r.ownerPublicKey!==o||!r.signingPublicKey)throw new le("The gate accepted the secrets, but its quote does not name your key as owner");if(n.agent.signingPublicKey&&n.agent.signingPublicKey!==r.signingPublicKey)throw new le("The agent's signing key changed while provisioning");return{agentId:r.agentId,provisioningPublicKey:r.provisioningPublicKey,signingPublicKey:r.signingPublicKey,ownerPublicKey:o,written:t?.written??[],claimed:t?.claimed===!0}}async function Oc(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 Ns(e,n.gateUrl,"/release",n.agent,n.ownerSecret,{release:!0}),(await kr({gateUrl:n.gateUrl,agentId:n.agent.agentId,verifier:n.verifier,fetch:e})).ownerPublicKey)throw new le("The gate says it released the agent, but its quote still names an owner")}var _r=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),Sc=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function Uc(n,e,t={}){let r=typeof n=="string"?new TextEncoder().encode(n):n;await _t(r,e,{identity:t.identity??_r.identity,issuer:t.issuer??_r.issuer});let o;try{o=JSON.parse(new TextDecoder().decode(r))}catch{throw new Error("The signed agent policy is not JSON")}let s=t.role??"agent";if(o?.role!==s)throw new Error(`The signed file is a ${JSON.stringify(o?.role)} policy, not an ${s} one`);let i=t.profile??he;if(o.profile!==i)throw new Error(`The signed agent policy is for the ${JSON.stringify(o.profile)} profile, not ${i}`);if(t.expectedVersion!==void 0&&o.version!==t.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(o.version)}, not ${t.expectedVersion}`);return Ms(o),o}function Ms(n){for(let e of Sc)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 Cc=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function Bc(n){let e=Cc.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 gt=n=>n.trim().replace(/^0x/i,"");function Nc(n,e){return Ms(n),fe({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:n.allowed_tcb_statuses.map(Bc),allowedMrtd:n.allowed_mrtd.map(gt),allowedRtmr0:n.allowed_rtmr0.map(gt),allowedRtmr1:n.allowed_rtmr1.map(gt),allowedRtmr2:n.allowed_rtmr2.map(gt),allowedRtmr3:n.allowed_rtmr3.map(gt)})}export{xs as AGENT_ATTEST_DOMAIN,Ts as AGENT_PROVISION_INFO_DOMAIN,le as AgentGateError,$t as AppError,jt as ArgsTooLarge,Ct as BadOrigin,Ve as CONSENT_STORAGE_KEY,mr as CalimeroClient,b as CalimeroError,Mt as ClusterNotUpgraded,Ze as ConfirmCancelled,et as ConfirmPromptBlocked,Se as ConfirmRequired,Ut as ConsentStale,En as DEFAULT_COLLATERAL_MIRROR,On as DEFAULT_DIRECTORY,cc as DEFAULT_ORG_CAPABILITIES,Et as DEFAULT_RELEASE_MIRROR,Nn as DEFAULT_RETRY,Q as DirectoryError,A as ExportError,hs as FILE_PART_BYTES,qt as FeatureNotActive,zr as GITHUB_RELEASES,Ur as HANDSHAKE_PATH,Ua as HPKE_AAD,Sa as HPKE_INFO,vt as IdempotencyMismatch,_r as KMS_RELEASE_SIGNER,Cr as LEGACY_HANDSHAKE_PATH,re as LoginRequired,sr as MAX_ARCHIVE_BYTES,nr as MAX_MANIFEST_BYTES,ir as MAX_MPK_BYTES,rr as MAX_PIPELINES_PER_PACKAGE,or as MAX_PIPELINE_BYTES,Yn as MAX_RECOVERY_NONCE_BYTES,ur as MAX_REPORT_PAGE,Yr as MOCK_QUOTE_HEADER,_n as NODE_RELEASE_SIGNER,Pe as NodeTransport,Oe as NotFound,Nt as NotServing,br as ORG_CAPABILITIES,be as OriginNotRegistered,Bt as OriginTaken,he as PRODUCTION_PROFILE,Tt as PasskeyUnknownHere,Kt as QuotaExceeded,vo as RECOVERY_DOMAIN,Uo as RECOVERY_FORMAT,is as RELEASE_VERIFIER,Dt as RecoveryNotReady,Ot as ReleaseDeadlineError,St as RuntimeTooOld,Qe as SEALED_CONTENT_TYPE,Br as SEALED_PATH,Oa as SIGNING_LABEL,ee as SealedTransportError,It as SignUpRefused,Je as StaleTransportKeyError,Lt as TrapError,oe as UnavailableError,we as WrongNode,tt as WrongRecoveryCode,Vp as acceptInviteConsent,Os as agentKeyBinding,Nc as agentQuoteVerifier,kr as attestAgent,R as b64url,Ma as backupPublicKey,Yi as browserPasskey,Ko as canonicalizeManifest,Bs as checkOwner,Wr as claimedRelease,Tn as cloudNodeReleaseUrl,dt as compareVersions,yr as confirmationCode,qp as consentReturn,Lp as createInviteConsent,$p as createOrgConsent,fe as createQuoteVerifier,Kn as createRouteClient,Dn as createRoutes,wn as createSealedFetch,Mi as createSignedReleaseVerifier,Wp as deleteOrgConsent,oc as deployerKey,qn as directoryTransport,Ue as errorFrom,tp as exportPublisherKey,Li as fetchAttestedKey,xn as fetchGithubNodeRelease,Rn as fetchNodeRelease,Zr as freshCollateral,C as fromB64url,sc as frontendManifest,Tc as generateOwnerKey,Wa as generatePublisherKey,er as governanceCanonical,Ne as holderKey,su as holderRecoveryBody,np as importPublisherKey,ep as isDevPublisherKey,ns as jobKeyBinding,Hp as leaveOrgConsent,ou as newBackupKeyPair,Mn as newIdempotencyKey,Ta as newRecoverySeed,Ia as openDataKey,lc as orgCapabilities,un as ownerPublicKey,up as packComputePackage,ic as pageDeployment,dr as pageQuery,va as parseRecoverySeed,rt as passkeyConfirm,fr as pendingApprovalsFrom,pc as presenceState,vc as provisionAgent,Ss as provisionInfo,Np as publisherBindingBytes,ss as publisherBindingMessage,Bn as queryString,tr as receiptKeyBinding,kp as receiptMessage,Ka as recoveryAttestationNonce,Oo as recoveryMessage,Zt as recoveryPublicKey,ja as recoverySeedText,se as refusal,Oc as releaseAgent,ls as releaseConsent,as as releaseNotesUrl,Gp as removeMemberConsent,Qp as removeMemberTeamsConsent,Yp as renameOrgConsent,ts as reportMessage,st as retryDelayMs,Jp as revokeInviteConsent,Ae as routePath,Zp as setAllAppsConsent,Xp as setCapabilitiesConsent,Fp as setMemberRoleConsent,zp as setMemberTeamsConsent,Wn as signRecovery,De as signerIdOf,ar as signingPayload,ro as sseFrames,os as stalledBy,mn as transportKeyBinding,Rt as trustSignedRelease,kn as trustedMeasurementsFromReleases,Kp as upgradeConsent,js as validateAgentId,an as verifyAppCluster,rs as verifyJobReports,me as verifyNode,Dp as verifyNodeUrl,lr as verifyPipelineReceipt,Wo as verifyReceiptKey,$a as verifyRecoveryAttestation,qa as verifyRecoveryHeader,cs as verifyReleaseUrl,Uc as verifySignedAgentPolicy,Fr as verifySignedNodeRelease,Xa as webCryptoPublisherKey,Ip as withdrawConsent,hr as withoutConsentReturn};
8
+ ${r}`}function Up(n,e,t,r){return new TextEncoder().encode(os(n,e,t,r))}var Cp="0123456789ABCDEFGHJKMNPQRSTVWXYZ";async function yr(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,r="";for(let o=0;o<6;o++)o===3&&(r+="-"),r+=Cp[t>>>27-5*o&31];return r}function Bp(n){let e=typeof n=="string"?new URL(n):n,t=e.searchParams.get("request_id"),r=e.searchParams.get("result");return!t||r!=="approved"&&r!=="declined"?null:{requestId:t,result:r}}function hr(n){let e=new URL(String(n));return e.searchParams.delete("request_id"),e.searchParams.delete("result"),e.toString()}var Le="calimero.consent",ss="https://mero-tee.vercel.app";function is(n){return`https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(n)}`}function as(n){return`${ss}/mero-tee?${new URLSearchParams(n)}`}function ps(n){return as({release_tag:`mero-tee-v${n}`})}function Np(n,e){return as({node_url:n.replace(/\/+$/,""),release_tag:`mero-tee-v${e}`})}function fr(n,e,t=Date.now()/1e3){let r=p=>e.deadlines.find(l=>l.version===p)??null,o=n.governance.releases==="owner",s=n.governance.appUpgrades==="owner",i=n.clusterReleases.filter(p=>!p.approved).sort((p,l)=>dt(l.release,p.release)).map(p=>({version:p.release,nodes:p.nodes,actionable:o,releaseNotesUrl:is(p.release),verifyUrl:ps(p.release),deadline:r(p.release)})),a=[];for(let p of n.apps){let l=p.availableVersions??[];if(p.package===null||l.length===0)continue;let d=l[l.length-1],u=p.latestReachable===void 0?d:p.latestReachable;a.push({app:p.app,name:p.name??null,package:p.package.package,from:p.package.version,to:u??d,reachable:u!==null,blocked:p.latestBlocked??null,available:l,actionable:s})}return{scope:n.scope,governance:n.governance,approvedReleases:n.approvedReleases,releases:i,upgrades:a,stalledBy:rs(n.approvedReleases,e.deadlines,t),actionable:i.some(p=>p.actionable)||a.some(p=>p.actionable)}}function cs(n,e,t,r={}){return{kind:"release",scope:n.kind==="org"?{org:n.org}:"account",subject:r.withdraw?{version:e,withdraw:!0}:{version:e},returnTo:t}}function Mp(n,e,t){return cs(n,e,t,{withdraw:!0})}function qp(n,e,t){return{kind:"upgrade",subject:{app:n,toVersion:e},returnTo:t}}function Dp(n,e,t){return{kind:"createOrg",subject:t===void 0?{name:n}:{name:n,capabilities:t},returnTo:e}}function Ip(n,e){return{kind:"createInvite",subject:n,returnTo:e}}function Kp(n,e){return{kind:"acceptInvite",subject:{token:n},returnTo:e}}function $p(n,e){return{kind:"leaveOrg",subject:{org:n},returnTo:e}}function Vp(n,e,t){return{kind:"removeMember",subject:{org:n,account:e},returnTo:t}}function Lp(n,e,t,r){return{kind:"setMemberRole",subject:{org:n,account:e,role:t},returnTo:r}}function Hp(n,e,t,r){return{kind:"setMemberTeams",subject:{org:n,account:e,teams:t},returnTo:r}}function Gp(n,e,t,r){return{kind:"removeMemberTeams",subject:{org:n,account:e,teams:t},returnTo:r}}function Fp(n,e,t){return{kind:"revokeInvite",subject:{org:n,inviteKey:e},returnTo:t}}function zp(n,e,t){return{kind:"renameOrg",subject:{org:n,name:e},returnTo:t}}function Qp(n,e){return{kind:"deleteOrg",subject:{org:n},returnTo:e}}function Jp(n,e){return{kind:"setCapabilities",subject:n,returnTo:e}}function Yp(n,e,t,r){return{kind:"setAllApps",subject:{org:n,account:e,allApps:t},returnTo:r}}var ys=16*1024*1024,Wp=1,Xp=8,Zp=16,ec=8;function tc(n){return"account"in n?`account:${n.account}`:`org:${n.org}`}async function nc(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 r=await e(new URL("/.well-known/calimero.json",t).toString());if(!r.ok)throw await se(r);let o=await r.json();return{...o,deployments:o.deployments??[]}}function rc(n){let e=n??globalThis.location?.href;if(!e)return null;try{return new URL(e).searchParams.get("deployment")||null}catch{return null}}function ls(n){return dr(n),{after:n.after,limit:n.limit}}function oc(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function sc(n){return n===null?null:oc(n)}async function us(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 gr(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 mr=class n{static async connect(e,t={}){let r=await qn({...e,directory:e.directory??On});return new n(r,t)}constructor(e,t={}){this.transport=e instanceof Pe?e:new Pe(e);let r=Dn(Kn(this.transport,t));this.apps=r.apps,this.auth=r.auth,this.consent=r.consent,this.ops=r.ops,this.orgs=r.orgs,this.public=r.public,this.packages=r.packages,this.deployments=r.deployments}as(e){return e}confirmWith(e,t={}){return e?{confirm:rt(e,t)}:void 0}get nodeUrl(){return this.transport.nodeUrl}get nodes(){return this.transport.nodes}verification(e){return this.transport.verification(e)}verify(e){return this.transport.verify(e)}useApiKey(e){this.transport.useApiKey(e)}useSession(e){this.transport.useSession(e)}get session(){return this.transport.session}json(e,t,r){return this.transport.json(e,t,{body:r})}attestApp(e,t){return this.transport.attestApp(e,t)}packageCapabilities(e,t,r={}){return this.transport.json("GET",ke("packages/{package}/{version}/capabilities",{package:e,version:t}),{query:{service:r.service}})}async signUp(e,t,r={}){let o=this.pageOrigin(r),s=r.invite?{invite:r.invite}:{},i=await this.begin(this.auth.registerBegin({...o===void 0?{name:t,...s}:{name:t,origin:o,...s}}),o),a=r.signal,p=await(a?e.create(i.options,{signal:a}):e.create(i.options)),l=await this.auth.registerFinish({challengeId:i.challengeId,registration:p,...s},this.confirmWith(e,{signal:a}));return this.useSession(l),l}async signIn(e,t={}){let r=this.pageOrigin(t),o=await this.begin(this.auth.loginBegin({...r===void 0?{}:{origin:r}}),r),s=o.options.rpId??o.options.rp?.id??"",i=C(o.options.challenge),a=await(t.signal?e.get(i,s,void 0,{signal:t.signal}):e.get(i,s)),p=await this.auth.loginFinish({challengeId:o.challengeId,assertion:a});return this.useSession(p),p}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(o=>{try{return new URL(o).origin}catch{return o}})).has(t)?void 0:t}async begin(e,t){try{return await this.as(e)}catch(r){throw r instanceof be&&!r.origin&&t!==void 0?new be(r.nodeMessage,{...r.details,origin:t}):r}}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 r=await this.as(this.auth.passkeyAddBegin()),o=await e.create(r.options),{credentialId:s}=await this.auth.passkeyAddFinish({challengeId:r.challengeId,registration:o},this.confirmWith(t));return s}async startAccountRecovery(e,t){try{let r=await this.as(this.auth.accountRecoveryBegin({code:e})),o=await t.create(r.options);return await this.auth.accountRecoveryStart({challengeId:r.challengeId,code:e,registration:o})}catch(r){throw r instanceof re?new tt(r.message.replace(/^401 UNAUTHENTICATED: /,""),r.details):r}}async finishAccountRecovery(e,t){let r=await this.auth.accountRecoveryFinish({...t?{accountId:t}:{}},this.confirmWith(e));return this.useSession(r),r}async downloadBlob(e,t){return new Uint8Array(await(await this.apps.blobDownload({app:e,id:t})).arrayBuffer())}get exportClient(){return{exportsExport:this.apps.exportsExport,request:this.transport.request.bind(this.transport)}}exportFileTo(e,t,r,o){return Qn(this.exportClient,e,t,r,o)}exportFile(e,t,r){return To(this.exportClient,e,t,r)}get attestationPolicy(){let e=this.transport.nodePolicy;if(!e)throw new Error("this client has no attestation policy, so it cannot verify an attestation");return e}async verifyAppCluster(e){return an(this,e,this.attestationPolicy)}async pipelineReceipt(e,t){return await this.apps.pipelineReceiptReceipt({app:e,run:t,version:2})}async verifyPipelineReceipt(e,t,r){return lr(this,e,t,r,this.attestationPolicy)}async downloadBlobGranted(e,t,r){return new Uint8Array(await(await this.apps.blobDownload({app:e,id:t,grant:r})).arrayBuffer())}async uploadFile(e,t){let r=t instanceof Blob?t.size:t.byteLength;if(r<=ys)return this.apps.filesUpload({app:e,body:await us(t,0,r)});try{return await this.uploadSession(e,t,r)}catch(o){if(!(o instanceof b)||o.code!=="UPLOAD_UNKNOWN")throw o;return this.uploadSession(e,t,r)}}async uploadSession(e,t,r){let o=await this.untilAvailable(()=>this.apps.uploadBegin({app:e,size:r})),{uploadId:s,partBytes:i,parts:a}=o;if(!s||!i||i<=0||a!==Math.ceil(r/i))throw new Error(`the node began an upload it cannot take: ${JSON.stringify(o)}`);try{return await this.sendParts(e,s,t,r,i,a),await this.untilAvailable(()=>this.apps.uploadComplete({app:e,upload:s}))}catch(p){throw p instanceof b&&p.code==="UPLOAD_UNKNOWN"||await this.apps.uploadAbort({app:e,upload:s}).catch(()=>{}),p}}async sendParts(e,t,r,o,s,i){let[a,p,l]=[0,0,0];for(;a<i;)try{let d=await us(r,a*s,Math.min((a+1)*s,o));a=gr(await this.apps.uploadPart({app:e,upload:t,k:String(a),body:d}),i),p=0;continue}catch(d){if(d instanceof b&&d.code==="PART_OUT_OF_ORDER"){if(l+=1,l>Zp)throw d;a=gr(d.details,i);continue}if(!this.isTransient(d)||++p>Xp)throw d;if(await new Promise(u=>setTimeout(u,st(p-1,this.transport.retry))),p>Wp)try{let u=gr(await this.apps.uploadStatus({app:e,upload:t}),i);u>a&&(p=0),a=u}catch(u){if(!this.isTransient(u))throw u}}}async untilAvailable(e){for(let t=0;;t++)try{return await e()}catch(r){if(!this.isTransient(r)||t>=ec)throw r;await new Promise(o=>setTimeout(o,st(t,this.transport.retry)))}}isTransient(e){return e instanceof oe||this.transport.isNetworkFailure(e)}events(e,t=0,r){return this.transport.events(ke("apps/{app}/events",{app:e}),{query:{from:t},signal:r})}presenceStream(e,t){return this.transport.events(ke("apps/{app}/presence/stream",{app:e}),{signal:t})}async startRecovery(e,t){let r=(await this.auth.me()).accountId,o=R(crypto.getRandomValues(new Uint8Array(16))),s=await Wn(t,e,r,o);return this.orgs.recoveryStart({org:e,nonce:o,signature:s})}async appsReportAll(e){let t=(i={})=>e===null?this.auth.accountApps(ls(i)):this.orgs.apps({org:e,...ls(i)}),r=await t(),o=[...r.apps],s=r.next;for(;s!==null;){let i=await t({after:s});o.push(...i.apps),s=i.next}return{...r,apps:o,next:null}}async pendingApprovals(e=null){let[t,r]=await Promise.all([this.appsReportAll(e),this.public.releasesPublic()]);return fr(t,r)}async openConsentPage(e,t={}){let r=typeof t=="function"?{navigate:t}:t,o=r.navigate??(i=>{let a=globalThis.window;if(!a)throw new Error("no window to open the consent page in; pass `navigate`");a.location.assign(i)}),s=await this.consent.pageCreate({body:e});if(s.code!==void 0){let i=await yr(s.requestId);if(s.code!==i)throw new b(200,"CONSENT_CODE_MISMATCH","the consent page code does not match the request",{requestId:s.requestId,code:s.code,expected:i})}if(r.confirm&&!await r.confirm(s))return s;try{wr()?.setItem(Le,s.requestId)}catch{}return o(s.url),s}async resumeConsent(e={}){let t=globalThis,r=e.href??t.location?.href;if(r===void 0)throw new Error("no page to read the consent return from; pass `href`");let o=new URL(r),s=o.searchParams.get("request_id");if(!s)return null;e.href===void 0&&t.history&&t.history.replaceState(t.history.state,"",hr(o));let i=e.requestId;if(i===void 0)try{i=wr()?.getItem(Le)??void 0}catch{i=void 0}if(!i)throw new b(200,"CONSENT_NOT_STARTED","this page started no consent request",{returned:s});if(s!==i)throw new b(200,"CONSENT_REQUEST_MISMATCH","the consent page returned another request than this page started",{requestId:i,returned:s});let a;try{a=await this.consent.pageResult({request:i})}catch(p){throw p instanceof Oe?(ds(i),new b(404,"CONSENT_REPLACED","this page's consent request was replaced by a newer one",{requestId:i})):p}if(a.requestId!==i)throw new b(200,"CONSENT_REQUEST_MISMATCH","the node answered another request",{requestId:i,returned:a.requestId});if(a.status==="pending")throw new b(200,"CONSENT_NOT_DECIDED","the consent page returned, but this request is still pending",{requestId:i});return ds(i),a}async waitForConsent(e,t={}){let r=t.intervalMs??2e3;for(;;){let o=await this.consent.pageResult({request:e});if(o.status!=="pending"||t.signal?.aborted||t.expiresAt!==void 0&&Date.now()/1e3>=t.expiresAt)return o;await new Promise(s=>setTimeout(s,r))}}};function wr(){try{return globalThis.sessionStorage}catch{return}}function ds(n){try{let e=wr();e?.getItem(Le)===n&&e.removeItem(Le)}catch{}}var br={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,CREATE_CHILD_TEAM:2048},ic=br.JOIN_OPEN_TEAMS;function ac(...n){return n.reduce((e,t)=>e|br[t],0)}function pn(n,e){return(n<<e|n>>>32-e)>>>0}function ce(n,e,t,r,o){n[e]=n[e]+n[t]>>>0,n[o]=pn(n[o]^n[e],16),n[r]=n[r]+n[o]>>>0,n[t]=pn(n[t]^n[r],12),n[e]=n[e]+n[t]>>>0,n[o]=pn(n[o]^n[e],8),n[r]=n[r]+n[o]>>>0,n[t]=pn(n[t]^n[r],7)}function hs(n,e){return(n[e]|n[e+1]<<8|n[e+2]<<16|n[e+3]<<24)>>>0}function ms(n,e,t){let r=new Uint32Array(16);r[0]=1634760805,r[1]=857760878,r[2]=2036477234,r[3]=1797285236;for(let i=0;i<8;i+=1)r[4+i]=hs(n,i*4);r[12]=e>>>0;for(let i=0;i<3;i+=1)r[13+i]=hs(t,i*4);let o=r.slice();for(let i=0;i<10;i+=1)ce(o,0,4,8,12),ce(o,1,5,9,13),ce(o,2,6,10,14),ce(o,3,7,11,15),ce(o,0,5,10,15),ce(o,1,6,11,12),ce(o,2,7,8,13),ce(o,3,4,9,14);let s=new Uint8Array(64);for(let i=0;i<16;i+=1){let a=o[i]+r[i]>>>0;s[i*4]=a&255,s[i*4+1]=a>>>8&255,s[i*4+2]=a>>>16&255,s[i*4+3]=a>>>24&255}return s}function pc(n,e,t,r){let o=new Uint8Array(r.length);for(let s=0,i=e;s<r.length;s+=64,i+=1){let a=ms(n,i,t),p=Math.min(s+64,r.length);for(let l=s;l<p;l+=1)o[l]=r[l]^a[l-s]}return o}function Pr(n){let e=0n;for(let t=n.length-1;t>=0;t-=1)e=e<<8n|BigInt(n[t]);return e}var cc=(1n<<130n)-5n;function lc(n,e){let t=Pr(n.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,r=Pr(n.subarray(16,32)),o=0n;for(let a=0;a<e.length;a+=16){let p=e.subarray(a,Math.min(a+16,e.length)),l=Pr(p)+(1n<<BigInt(8*p.length));o=(o+l)*t%cc}let s=o+r&(1n<<128n)-1n,i=new Uint8Array(16);for(let a=0;a<16;a+=1)i[a]=Number(s&0xffn),s>>=8n;return i}function fs(n){return new Uint8Array((16-n%16)%16)}function gs(n){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(n),!0),e}function uc(n,e){let t=[n,fs(n.length),e,fs(e.length),gs(n.length),gs(e.length)],r=new Uint8Array(t.reduce((s,i)=>s+i.length,0)),o=0;for(let s of t)r.set(s,o),o+=s.length;return r}function dc(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 ws(n,e,t,r=new Uint8Array(0)){dc(n,e);let o=ms(n,0,e).subarray(0,32),s=pc(n,1,e,t),i=lc(o,uc(r,s)),a=new Uint8Array(s.length+16);return a.set(s),a.set(i,s.length),a}var Ps=32,yc=1,hc=3,fc=2,gc=32,mc=32,wc=12,He=n=>new TextEncoder().encode(n),ht=n=>new Uint8Array([n>>8&255,n&255]),bs=f(He("KEM"),ht(Ps)),yt=f(He("HPKE"),ht(Ps),ht(yc),ht(hc));async function ks(n,e){let t=n.length===0?new Uint8Array(32):n,r=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",r,e))}async function bc(n,e,t){let r=new Uint8Array(t),o=new Uint8Array(0);for(let s=1,i=0;i<t;s+=1)o=await ks(n,f(o,e,new Uint8Array([s]))),r.set(o.subarray(0,Math.min(o.length,t-i)),i),i+=o.length;return r}function cn(n,e,t,r){return ks(e,f(He("HPKE-v1"),n,He(t),r))}function kr(n,e,t,r,o){return bc(e,f(ht(o),He("HPKE-v1"),n,He(t),r),o)}async function Pc(n,e){let t=await cn(bs,new Uint8Array(0),"eae_prk",n);return kr(bs,t,"shared_secret",e,gc)}async function kc(n,e){let t=new Uint8Array(0),r=await cn(yt,t,"psk_id_hash",t),o=await cn(yt,t,"info_hash",e),s=f(new Uint8Array([fc]),r,o),i=await cn(yt,n,"secret",t);return{key:await kr(yt,i,"key",s,mc),nonce:await kr(yt,i,"base_nonce",s,wc)}}async function As(n,e,t,r,o=new Uint8Array(0),s){if(n.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let i=await I(s),a=await I(e),p=f(await z(i.privateKey,n),await z(a.privateKey,n)),l=await Pc(p,f(i.publicKey,n,a.publicKey)),{key:d,nonce:u}=await kc(l,t);return{enc:i.publicKey,ciphertext:ws(d,u,r,o)}}var Rs="mero-agent-gate/attest/v3",xs="mero-agent-gate/provision/v2",Ac=/^[a-z0-9][a-z0-9-]{0,62}$/,_c=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,_s=64,Es=64*1024,le=class extends Error{constructor(t,r,o){super(t);this.status=r;this.code=o;this.name="AgentGateError"}};function Ts(n){if(!Ac.test(n))throw new Error(`Agent id ${JSON.stringify(n)} must match [a-z0-9][a-z0-9-]{0,62}`)}function ft(n){return new TextEncoder().encode(n)}function js(n){let e=ft(n);return f(new Uint8Array([e.length]),e)}function Ee(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}function ln(n,e,t){let r;try{r=Uint8Array.from(atob(n.trim()),o=>o.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(t!==void 0&&r.length!==t)throw new Error(`${e} is not ${t} bytes`);return r}async function vs(n,e,t,r){let o=new Uint8Array(32),s=f(ft(Rs),n,js(e),t??o,r??o);return new Uint8Array(await crypto.subtle.digest("SHA-256",s))}function Os(n,e){return f(ft(xs),n,js(e))}async function Ec(){let n=crypto.getRandomValues(new Uint8Array(32));return{secret:n,publicKey:await un(n)}}async function un(n){if(n.length!==32)throw new Error("An owner key is 32 bytes");return Ee((await I(n)).publicKey)}function Ss(n,e){return`${n.replace(/\/+$/,"")}${e}`}async function Us(n,e,t){let r=await n(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),o=await r.text(),s;try{s=o?JSON.parse(o):void 0}catch{}if(!r.ok){let i=s;throw new le(`The gate answered ${r.status}${i?.error?` ${i.error}`:""}: ${i?.details??o.slice(0,200)}`,r.status,i?.error)}return s}async function Ar(n){let e=n.agentId??"";e&&Ts(e);let t=crypto.getRandomValues(new Uint8Array(32)),r=await Us(n.fetch??fetch,Ss(n.gateUrl,"/attest"),{nonceB64:Ee(t),...e?{agentId:e}:{}});if((r?.agentId??"")!==e)throw new Error(`Asked about agent ${JSON.stringify(e)}, the gate answered for ${JSON.stringify(r?.agentId)}`);let o=ln(r.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),s=r.signingPublicKeyB64?ln(r.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,i=r.ownerPublicKeyB64?ln(r.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!s!=!i)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let a=await vs(o,e,s,i);return await n.verifier({quoteB64:r.quoteB64,nonce:m(t),reportDataSuffix:m(a)}),{agentId:e,provisioningPublicKey:Ee(o),...s?{signingPublicKey:Ee(s)}:{},...i?{ownerPublicKey:Ee(i)}:{}}}async function Cs(n,e){let t=await un(e);if(n.ownerPublicKey&&n.ownerPublicKey!==t)throw new le(`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 Rc(n){let e=Object.keys(n);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>_s)throw new Error(`At most ${_s} secrets at once`);for(let t of e){if(!_c.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(ft(n[t]).length>Es)throw new Error(`Secret ${t} is over ${Es} bytes`)}}async function Bs(n,e,t,r,o,s){if(!r.agentId)throw new Error("This quote names no agent; attest with the agent id");let i=await Cs(r,o),a=ln(r.provisioningPublicKey,"provisioningPublicKey",32),p=await As(a,o,Os(a,r.agentId),ft(JSON.stringify(s)));return Us(n,Ss(e,t),{agentId:r.agentId,provisioningPublicKeyB64:r.provisioningPublicKey,senderPublicKeyB64:i,encappedKeyB64:Ee(p.enc),ciphertextB64:Ee(p.ciphertext)})}async function xc(n){Rc(n.secrets);let e=n.fetch??fetch,t=await Bs(e,n.gateUrl,"/provision",n.agent,n.ownerSecret,{secrets:n.secrets}),r=await Ar({gateUrl:n.gateUrl,agentId:n.agent.agentId,verifier:n.verifier,fetch:e}),o=await un(n.ownerSecret);if(r.ownerPublicKey!==o||!r.signingPublicKey)throw new le("The gate accepted the secrets, but its quote does not name your key as owner");if(n.agent.signingPublicKey&&n.agent.signingPublicKey!==r.signingPublicKey)throw new le("The agent's signing key changed while provisioning");return{agentId:r.agentId,provisioningPublicKey:r.provisioningPublicKey,signingPublicKey:r.signingPublicKey,ownerPublicKey:o,written:t?.written??[],claimed:t?.claimed===!0}}async function Tc(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 Bs(e,n.gateUrl,"/release",n.agent,n.ownerSecret,{release:!0}),(await Ar({gateUrl:n.gateUrl,agentId:n.agent.agentId,verifier:n.verifier,fetch:e})).ownerPublicKey)throw new le("The gate says it released the agent, but its quote still names an owner")}var _r=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),jc=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function vc(n,e,t={}){let r=typeof n=="string"?new TextEncoder().encode(n):n;await _t(r,e,{identity:t.identity??_r.identity,issuer:t.issuer??_r.issuer});let o;try{o=JSON.parse(new TextDecoder().decode(r))}catch{throw new Error("The signed agent policy is not JSON")}let s=t.role??"agent";if(o?.role!==s)throw new Error(`The signed file is a ${JSON.stringify(o?.role)} policy, not an ${s} one`);let i=t.profile??he;if(o.profile!==i)throw new Error(`The signed agent policy is for the ${JSON.stringify(o.profile)} profile, not ${i}`);if(t.expectedVersion!==void 0&&o.version!==t.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(o.version)}, not ${t.expectedVersion}`);return Ns(o),o}function Ns(n){for(let e of jc)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 Oc=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function Sc(n){let e=Oc.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 gt=n=>n.trim().replace(/^0x/i,"");function Uc(n,e){return Ns(n),fe({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:n.allowed_tcb_statuses.map(Sc),allowedMrtd:n.allowed_mrtd.map(gt),allowedRtmr0:n.allowed_rtmr0.map(gt),allowedRtmr1:n.allowed_rtmr1.map(gt),allowedRtmr2:n.allowed_rtmr2.map(gt),allowedRtmr3:n.allowed_rtmr3.map(gt)})}export{Rs as AGENT_ATTEST_DOMAIN,xs as AGENT_PROVISION_INFO_DOMAIN,le as AgentGateError,$t as AppError,jt as ArgsTooLarge,Ct as BadOrigin,Le as CONSENT_STORAGE_KEY,mr as CalimeroClient,b as CalimeroError,Mt as ClusterNotUpgraded,Ze as ConfirmCancelled,et as ConfirmPromptBlocked,Se as ConfirmRequired,Ut as ConsentStale,En as DEFAULT_COLLATERAL_MIRROR,On as DEFAULT_DIRECTORY,ic as DEFAULT_ORG_CAPABILITIES,Et as DEFAULT_RELEASE_MIRROR,Nn as DEFAULT_RETRY,Q as DirectoryError,k as ExportError,ys as FILE_PART_BYTES,qt as FeatureNotActive,Fr as GITHUB_RELEASES,Ur as HANDSHAKE_PATH,va as HPKE_AAD,ja as HPKE_INFO,vt as IdempotencyMismatch,_r as KMS_RELEASE_SIGNER,re as LoginRequired,sr as MAX_ARCHIVE_BYTES,nr as MAX_MANIFEST_BYTES,ir as MAX_MPK_BYTES,rr as MAX_PIPELINES_PER_PACKAGE,or as MAX_PIPELINE_BYTES,Yn as MAX_RECOVERY_NONCE_BYTES,ur as MAX_REPORT_PAGE,Jr as MOCK_QUOTE_HEADER,_n as NODE_RELEASE_SIGNER,Pe as NodeTransport,Oe as NotFound,Nt as NotServing,br as ORG_CAPABILITIES,be as OriginNotRegistered,Bt as OriginTaken,he as PRODUCTION_PROFILE,Tt as PasskeyUnknownHere,Kt as QuotaExceeded,jo as RECOVERY_DOMAIN,So as RECOVERY_FORMAT,ss as RELEASE_VERIFIER,Dt as RecoveryNotReady,Ot as ReleaseDeadlineError,St as RuntimeTooOld,Qe as SEALED_CONTENT_TYPE,Cr as SEALED_PATH,Ta as SIGNING_LABEL,ee as SealedTransportError,It as SignUpRefused,Je as StaleTransportKeyError,Vt as TrapError,oe as UnavailableError,we as WrongNode,tt as WrongRecoveryCode,Kp as acceptInviteConsent,vs as agentKeyBinding,Uc as agentQuoteVerifier,Ar as attestAgent,R as b64url,Ca as backupPublicKey,zi as browserPasskey,Io as canonicalizeManifest,Cs as checkOwner,Yr as claimedRelease,Tn as cloudNodeReleaseUrl,dt as compareVersions,yr as confirmationCode,Bp as consentReturn,Ip as createInviteConsent,Dp as createOrgConsent,fe as createQuoteVerifier,Kn as createRouteClient,Dn as createRoutes,wn as createSealedFetch,Ci as createSignedReleaseVerifier,Qp as deleteOrgConsent,tc as deployerKey,qn as directoryTransport,Ue as errorFrom,Xa as exportPublisherKey,Ii as fetchAttestedKey,xn as fetchGithubNodeRelease,Rn as fetchNodeRelease,Xr as freshCollateral,C as fromB64url,nc as frontendManifest,Ec as generateOwnerKey,Qa as generatePublisherKey,er as governanceCanonical,Ne as holderKey,nu as holderRecoveryBody,Za as importPublisherKey,Wa as isDevPublisherKey,ts as jobKeyBinding,$p as leaveOrgConsent,tu as newBackupKeyPair,Mn as newIdempotencyKey,Ea as newRecoverySeed,Ma as openDataKey,ac as orgCapabilities,un as ownerPublicKey,pp as packComputePackage,rc as pageDeployment,dr as pageQuery,xa as parseRecoverySeed,rt as passkeyConfirm,fr as pendingApprovalsFrom,sc as presenceState,xc as provisionAgent,Os as provisionInfo,Up as publisherBindingBytes,os as publisherBindingMessage,Bn as queryString,tr as receiptKeyBinding,bp as receiptMessage,qa as recoveryAttestationNonce,vo as recoveryMessage,Zt as recoveryPublicKey,Ra as recoverySeedText,se as refusal,Tc as releaseAgent,cs as releaseConsent,is as releaseNotesUrl,Vp as removeMemberConsent,Gp as removeMemberTeamsConsent,zp as renameOrgConsent,es as reportMessage,st as retryDelayMs,Fp as revokeInviteConsent,ke as routePath,Yp as setAllAppsConsent,Jp as setCapabilitiesConsent,Lp as setMemberRoleConsent,Hp as setMemberTeamsConsent,Wn as signRecovery,De as signerIdOf,ar as signingPayload,no as sseFrames,rs as stalledBy,mn as transportKeyBinding,Rt as trustSignedRelease,An as trustedMeasurementsFromReleases,qp as upgradeConsent,Ts as validateAgentId,an as verifyAppCluster,ns as verifyJobReports,me as verifyNode,Np as verifyNodeUrl,lr as verifyPipelineReceipt,Yo as verifyReceiptKey,Da as verifyRecoveryAttestation,Ba as verifyRecoveryHeader,ps as verifyReleaseUrl,vc as verifySignedAgentPolicy,Gr as verifySignedNodeRelease,Ja as webCryptoPublisherKey,Mp as withdrawConsent,hr as withoutConsentReturn};
9
9
  //# sourceMappingURL=index.browser.mjs.map