@calimero-network/mero-js 35.0.0 → 35.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -9
- package/dist/client/recovery-key.d.ts +2 -0
- package/dist/client/recovery-key.js +2 -2
- package/dist/generated/api.d.ts +83 -1
- package/dist/generated/methods.d.ts +7 -0
- package/dist/generated/methods.js +7 -0
- package/dist/index.browser.mjs +3 -3
- package/dist/index.browser.mjs.map +4 -4
- package/dist/index.cjs +311 -2
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/index.mjs +311 -2
- package/dist/index.mjs.map +4 -4
- package/dist/package/pack.d.ts +93 -0
- package/dist/package/pack.js +370 -0
- package/package.json +1 -1
package/dist/index.browser.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var jr=Object.defineProperty;var Or=(n,e,t)=>e in n?jr(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var A=(n,e,t)=>Or(n,typeof e!="symbol"?e+"":e,t);function w(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function C(n,e,t){let o=n.trim();if(!/^[0-9a-fA-F]*$/.test(o)||o.length!==t*2)throw new Error(`${e} must be ${t*2} hex characters, got ${o.length}`);let r=new Uint8Array(t);for(let s=0;s<t;s+=1)r[s]=Number.parseInt(o.slice(s*2,s*2+2),16);return r}function Nn(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 o=new Uint8Array(t.length/2);for(let r=0;r<o.length;r+=1)o[r]=Number.parseInt(t.slice(r*2,r*2+2),16);return o}function m(...n){let e=new Uint8Array(n.reduce((o,r)=>o+r.length,0)),t=0;for(let o of n)e.set(o,t),t+=o.length;return e}var vr="Noise_NK_25519_AESGCM_SHA256",Bt=32,Sr=16,Ur=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Mt=class n{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(vr),t=new Uint8Array(32);return t.set(e),new n(t)}async mixHash(e){this.h=await Cr(m(this.h,e))}async mixKey(e){let[t,o]=await In(this.ck,e);this.ck=t,this.k=await crypto.subtle.importKey("raw",o,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let t=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:Dn(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:Dn(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),t}split(){return In(this.ck,new Uint8Array)}};async function Ln(n,e,t){let o=await Mt.initialize();await o.mixHash(e),await o.mixHash(n);let r=await q(t);return await o.mixHash(r.publicKey),await o.mixKey(await K(r.privateKey,n)),{message1:m(r.publicKey,await o.encryptAndHash(new Uint8Array)),async finish(a){if(a.length<Bt+Sr)throw new Error("Noise: message 2 is too short");let i=a.slice(0,Bt);return await o.mixHash(i),await o.mixKey(await K(r.privateKey,i)),{payload:await o.decryptAndHash(a.slice(Bt)),split:await o.split()}}}}async function q(n){if(!n){let o;try{o=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"])}catch(s){throw new Error(`Sealed transport needs WebCrypto with X25519, which this runtime lacks (${s?.name??"no crypto.subtle"}). Current browsers and Node have it; in React Native, install react-native-quick-crypto as the global crypto.`)}let r=new Uint8Array(await crypto.subtle.exportKey("raw",o.publicKey));return{privateKey:o.privateKey,publicKey:r}}let e=await crypto.subtle.importKey("pkcs8",m(Ur,n),{name:"X25519"},!0,["deriveBits"]),t=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Br(t.x)}}async function K(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 Dn(n){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(n),!1),e}async function Cr(n){return new Uint8Array(await crypto.subtle.digest("SHA-256",n))}async function qt(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 In(n,e){let t=await qt(n,e),o=await qt(t,new Uint8Array([1])),r=await qt(t,m(o,new Uint8Array([2])));return[o,r]}function Br(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(t,o=>o.charCodeAt(0))}var Gn="/sealed/v2/handshake",$n="/sealed/v2",Te="application/vnd.calimero.sealed",Nt=2,qr=new TextEncoder().encode("calimero/sealed-http/v2"),xe=16,Mr=1+xe+8,Nr=0,Dr=1,Ir=2,Lr=1+64*1024+16,Kr=1024,Vr=6e4,Hr="calimero.tee-attest.transport-key.v1",Gr=[101,204,205,304],Fn=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"}},Q=class extends Error{constructor(t,o,r,s){super(r);this.status=t;this.code=o;this.retryAfterMs=s;this.name="SealedTransportError"}};async function Dt(n,e){let t=await crypto.subtle.digest("SHA-256",m(Fn.encode(Hr),n,e));return new Uint8Array(t)}function It(n){let e=new URL(n.baseUrl),t=e.pathname.replace(/\/+$/,""),o=`${e.origin}${t}`,r=n.fetch??((d,y)=>fetch(d,y)),s=typeof n.transportPublicKey=="function"?n.transportPublicKey:void 0,a=s?Promise.resolve().then(s):Promise.resolve(n.transportPublicKey);a.catch(()=>{});let i,p=async()=>{try{return await Vn(r,o,await Kn(a))}catch(d){if(!(d instanceof je)||!s)throw d;return a=Promise.resolve().then(s),Vn(r,o,await Kn(a))}},l=async()=>{let d=i??u(void 0),y=await d;if(Date.now()<y.renewAt)return[y,d];let h=u(d);return[await h,h]},u=d=>{if(i===d){let y=p();i=y,y.catch(()=>{i===y&&(i=void 0)})}return i};return async(d,y)=>{let h=new Request(d,y),f=new URL(h.url);if(f.origin!==e.origin||!f.pathname.startsWith(`${t}/`))throw new Error(`Refusing to send ${f.href} outside the sealed node at ${n.baseUrl}`);let P=[];h.headers.forEach((U,L)=>P.push([L,U]));let j={method:h.method,path:f.pathname.slice(t.length)+f.search,headers:P},E=new Uint8Array(await h.arrayBuffer()),x=y?.signal??(d instanceof Request?d.signal:void 0),S=async U=>{let{requestId:L,header:oe,envelope:G}=await Fr(U,j,E),N=await r(`${o}${$n}`,{method:"POST",headers:{"content-type":Te},body:G,signal:x});if(N.headers.get("content-type")!==Te)throw await zn(N);return zr(N,U.responseKey,oe,L)},[H,ye]=await l();try{return await S(H)}catch(U){if(!(U instanceof Q)||U.code!=="unknown_session")throw U;return S(await u(ye))}}}async function Kn(n){let e=await n;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function Vn(n,e,t){try{return await Hn(n,e,t)}catch(o){if(!(o instanceof Q)||o.code!=="busy")throw o;return await new Promise(r=>setTimeout(r,o.retryAfterMs??1e3)),Hn(n,e,t)}}async function Hn(n,e,t){let o=await Ln(t,qr),r=await n(`${e}${Gn}`,{method:"POST",headers:{"content-type":Te},body:m(new Uint8Array([Nt]),t,o.message1)});if(r.headers.get("content-type")!==Te)throw await zn(r);let s=await Jr(r,Kr);return $r(o,s)}async function $r(n,e){if(e[0]!==Nt)throw new Error("The handshake reply is malformed");let t;try{t=await n.finish(e.slice(1))}catch{throw new Error("The handshake reply did not open: it did not come from the attested node")}let{payload:o,split:r}=t;if(o.length!==xe+4)throw new Error("The handshake reply is malformed");let s=o.slice(0,xe),a=new DataView(o.buffer,o.byteOffset).getUint32(xe,!1),[i,p]=await Promise.all([crypto.subtle.importKey("raw",r[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",r[1],"AES-GCM",!1,["decrypt"])]);return r[0].fill(0),r[1].fill(0),{requestKey:i,responseKey:p,nextRequestId:1,renewAt:Date.now()+a*1e3-Vr,header(l){let u=new Uint8Array(Mr);return u[0]=Nt,u.set(s,1),new DataView(u.buffer).setBigUint64(1+xe,BigInt(l),!1),u}}}async function Fr(n,e,t){let o=n.nextRequestId;n.nextRequestId+=1;let r=n.header(o),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:Qn(o,0),additionalData:r},n.requestKey,Qr(e,t));return{requestId:o,header:r,envelope:m(r,new Uint8Array(s))}}function Qn(n,e){let t=new Uint8Array(12),o=new DataView(t.buffer);return o.setBigUint64(0,BigInt(n),!1),o.setUint32(8,e,!1),t}function Qr(n,e){let t=Fn.encode(JSON.stringify(n)),o=new Uint8Array(4);return new DataView(o.buffer).setUint32(0,t.length,!1),m(o,t,e)}async function zr(n,e,t,o){if(!n.body)throw new Error("The sealed response has no body");let r=Yr(n.body.getReader()),s=0,a=async()=>{let u=await r.next();if(!u)return null;let d;try{d=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Qn(o,s),additionalData:t},e,u))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return s+=1,{kind:d[0],data:d.slice(1)}},i=await a();if(!i||i.kind!==Nr)throw new Error("The sealed response is malformed");let p=JSON.parse(new TextDecoder().decode(i.data));if(Gr.includes(p.status))return await r.cancel(),new Response(null,{status:p.status,headers:p.headers});let l=new ReadableStream({async pull(u){try{let d=await a();d?d.kind===Dr?u.enqueue(d.data):d.kind===Ir?(u.close(),await r.cancel()):u.error(new Error("The sealed response is malformed")):u.error(new Error("The sealed response was cut short"))}catch(d){u.error(d)}},cancel(){return r.cancel()}});return new Response(l,{status:p.status,headers:p.headers})}function Yr(n){let e=new Uint8Array,t=async o=>{for(;e.length<o;){let{done:r,value:s}=await n.read();if(r)return!1;e=m(e,s)}return!0};return{async next(){if(!await t(4))return null;let o=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(o>Lr)throw await n.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await t(4+o))return null;let r=e.slice(4,4+o);return e=e.slice(4+o),r},cancel:()=>n.cancel()}}async function Jr(n,e){if(!n.body)return new Uint8Array;let t=n.body.getReader(),o=new Uint8Array;for(;;){let{done:r,value:s}=await t.read();if(r)return o;if(o=m(o,s),o.length>e)throw await t.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function zn(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 o=Number(n.headers.get("retry-after")),r=Number.isFinite(o)&&o>0?Math.min(o,5)*1e3:void 0;return new Q(n.status,e,t,r)}var Yn=[{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"]}],Jn=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var Wr="1.2.840.10045.2.1",Xr={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},Zr={"P-256":32,"P-384":48},es={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function Wn(n,e,t){if(e+2>t)throw new Error("it is truncated");let o=n[e];if((o&31)===31)throw new Error("it uses a tag this parser does not read");let r=n[e+1],s=e+2;if(r&128){let i=r&127;if(i===0||i>4||s+i>t)throw new Error("it has a length this parser does not read");r=0;for(let p=0;p<i;p+=1)r=r*256+n[s+p];s+=i}let a=s+r;if(a>t)throw new Error("it is truncated");return{tag:o,bytes:n,offset:e,start:s,end:a}}function fe(n){let e=Wn(n,0,n.length);if(e.end!==n.length)throw new Error("it has trailing bytes");return e}function O(n){let e=[];for(let t=n.start;t<n.end;){let o=Wn(n.bytes,t,n.end);e.push(o),t=o.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 z(n){return n.bytes.slice(n.start,n.end)}function We(n){return n.bytes.slice(n.offset,n.end)}function he(n){let e=z(_(n,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let t=[],o=0;for(let a of e)o=o*128+(a&127),a&128||(t.push(o),o=0);let r=t.shift();return[...r<80?[Math.floor(r/40),r%40]:[2,r-80],...t].join(".")}function ts(n){let e=new TextDecoder().decode(z(n)),t=n.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,o=n.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,r=t??o;if(!r)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let s=Number(r[1]);t&&(s+=s<50?2e3:1900);let[a,i,p,l,u]=r.slice(2).map(Number);return Date.UTC(s,a-1,i,p,l,u)}function Lt(n){try{let[e,t,o,...r]=O(_(fe(n),48,"The certificate"));if(r.length>0)throw new Error("it has fields after its signature");let s=O(_(e,48,"The signed part")),a=s[0]?.tag===160?1:0,[i,p,l,u,d,y,...h]=s.slice(a);_(i,2,"The serial number");let f=he(O(_(t,48,"The signature algorithm"))[0]);if(he(O(_(p,48,"The signature algorithm"))[0])!==f)throw new Error("it names two different signature algorithms");let j=es[f];if(!j)throw new Error(`it is signed with ${f}, not ECDSA with SHA-256 or SHA-384`);let[E,x]=O(_(u,48,"The validity")).map(ts);if(x===void 0)throw new Error("its validity is incomplete");let[S,H]=O(_(y,48,"The public key"));_(H,3,"The public key");let[ye,U]=O(_(S,48,"The key algorithm"));if(he(ye)!==Wr)throw new Error("its key is not an elliptic-curve key");let L=Xr[he(U)];if(!L)throw new Error("its key is on a curve other than P-256 or P-384");let oe=new Map,G=h.find(re=>re.tag===163);if(G){let[re]=O(G);for(let Qe of O(_(re,48,"The extensions"))){let D=O(_(Qe,48,"An extension"));if(D.length===3)_(D[1],1,"An extension's critical flag");else if(D.length!==2)throw new Error("it has a malformed extension");let Re=he(D[0]);if(oe.has(Re))throw new Error(`it has extension ${Re} twice`);oe.set(Re,z(_(D[D.length-1],4,"An extension value")))}}let N=z(_(o,3,"The signature"));if(N[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:n,tbs:We(e),signatureHash:j,signature:N.slice(1),issuer:We(_(l,48,"The issuer")),subject:We(_(d,48,"The subject")),notBefore:E,notAfter:x,spki:We(y),curve:L,extensions:oe}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function Xn(n){return O(_(fe(n),48,"The list")).map(he)}function ns(n,e){let t=Zr[e],o=O(_(fe(n),48,"The signature"));if(o.length!==2)throw new Error("The signature is not an ECDSA signature");let r=new Uint8Array(t*2);return o.forEach((s,a)=>{let i=z(_(s,2,"The signature"));if(i.length===0||i[0]&128)throw new Error("The signature is not an ECDSA signature");for(;i.length>1&&i[0]===0;)i=i.subarray(1);if(i.length>t)throw new Error("The signature is not an ECDSA signature");r.set(i,a*t+t-i.length)}),r}async function Xe(n,e,t,o,r){let s;try{s=ns(o,e)}catch{return!1}let a=await crypto.subtle.importKey("spki",n,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:t},a,s,r)}function I(n,e){let t=n.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t)||t.length%4!==0)throw new Error(`${e} is not base64`);let o=atob(t),r=new Uint8Array(o.length);for(let s=0;s<o.length;s+=1)r[s]=o.charCodeAt(s);return r}function Kt(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 I(t[0][1],e)}var os="2.5.29.17",rs="2.5.29.37",ss="1.3.6.1.5.5.7.3.3",as="1.3.6.1.4.1.57264.1.8",is="1.3.6.1.4.1.57264.1.1",ps=134,cs=12,ls=48,ds=new TextEncoder,me=n=>new TextDecoder().decode(n);async function Ze(n,e,t,o){let{base64Signature:r,cert:s,rekorBundle:a}=fs(e),i=a.Payload;if(o!==void 0&&o.trim()!==r.trim())throw new Error("The detached signature is not the one in the bundle");let p=I(r,"The bundle signature"),l=Kt(me(I(s,"The bundle certificate")),"The bundle certificate"),u=Lt(l),d=Jn.find(x=>x.logId===i.logID.toLowerCase());if(!d)throw new Error(`The bundle names Rekor log ${i.logID}, which the Sigstore trust root does not know`);let y=ds.encode(`{"body":${JSON.stringify(i.body)},"integratedTime":${i.integratedTime},"logID":${JSON.stringify(i.logID)},"logIndex":${i.logIndex}}`);if(!await Xe(I(d.publicKey,"The Rekor key"),"P-256","SHA-256",I(a.SignedEntryTimestamp,"The signed entry timestamp"),y))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let f=i.integratedTime*1e3;if(!to(f,d.validFor))throw new Error(`Rekor log ${d.baseUrl} was not in use at ${Oe(f)}, when the entry says it was logged`);let P=ms(i.body),j=w(new Uint8Array(await crypto.subtle.digest("SHA-256",n)));if(P.hash!==j)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!Vt(I(P.signature,"The logged signature"),p))throw new Error("The bundle's signature is not the one Rekor logged");let E=Kt(me(I(P.publicKey,"The logged certificate")),"The logged certificate");if(!Vt(E,l))throw new Error("The bundle's certificate is not the one Rekor logged");if(u.curve!=="P-256"||!await Xe(u.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 us(u,f),hs(u,t),{integratedTime:i.integratedTime}}async function us(n,e){if(!eo(n,e))throw new Error(`The signing certificate was valid ${Oe(n.notBefore)} to ${Oe(n.notAfter)}, not at ${Oe(e)} when Rekor logged it`);let t=[];for(let o of Yn){let r=o.certChain.map(a=>Lt(I(a,"A Fulcio certificate")));if(!await Zn(n,r[0]))continue;let s=await ys(r,o.validFor,e);if(!s)return;t.push(`${o.uri} (valid from ${o.validFor.start}): ${s}`)}throw new Error(t.length>0?`The signing certificate's CA is not trusted at ${Oe(e)}: ${t.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function ys(n,e,t){if(!to(t,e))return"the trust root says it was not issuing certificates then";for(let[o,r]of n.entries()){if(!eo(r,t))return`its certificate ${o} was not valid then`;let s=n[o+1]??r;if(!await Zn(r,s))return`its certificate ${o} is not signed by the next`}}async function Zn(n,e){return Vt(n.issuer,e.subject)?Xe(e.spki,e.curve,n.signatureHash,n.signature,n.tbs):!1}function hs(n,e){let t=n.extensions.get(os);if(!t)throw new Error("The signing certificate names no identity");let o=O(_(fe(t),ls,"The subject alternative name")),r=o.filter(l=>l.tag===ps).map(l=>me(z(l)));if(r.length!==1||o.length!==1||r[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(r.length===1?r[0]:r)}, not by ${e.identity}`);let s=n.extensions.get(as),a=n.extensions.get(is),i=s?me(z(_(fe(s),cs,"The OIDC issuer"))):a?me(a):void 0;if(i!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${i===void 0?"missing":JSON.stringify(i)}, not ${e.issuer}`);let p=n.extensions.get(rs);if(!p||!Xn(p).includes(ss))throw new Error("The signing certificate is not for code signing")}function fs(n){let e=n;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let t=e,o=t?.rekorBundle?.Payload;if(!(typeof t?.base64Signature=="string"&&typeof t.cert=="string"&&typeof t.rekorBundle?.SignedEntryTimestamp=="string"&&typeof o?.body=="string"&&typeof o.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(o.logID)&&Number.isSafeInteger(o.integratedTime)&&o.integratedTime>=0&&Number.isSafeInteger(o.logIndex)&&o.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return t}function ms(n){let e;try{e=JSON.parse(me(I(n,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let t=e?.spec?.data?.hash,o=e?.spec?.signature;if(e?.kind!=="hashedrekord"||t?.algorithm!=="sha256"||typeof t.value!="string"||typeof o?.content!="string"||typeof o.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:t.value.toLowerCase(),signature:o.content,publicKey:o.publicKey.content}}function eo(n,e){return n.notBefore<=e&&e<=n.notAfter}function to(n,e){return Date.parse(e.start)<=n&&(e.end===void 0||n<=Date.parse(e.end))}function Oe(n){return new Date(n).toISOString()}function Vt(n,e){return n.length===e.length&&n.every((t,o)=>t===e[o])}var gs=/^[0-9a-f]{96}$/,ws=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function ie(n){let e=ge(n.allowedMrtd??[],"allowedMrtd"),t=(n.allowedMeasurements??[]).map((i,p)=>{let l=`allowedMeasurements[${p}]`;return ws.map(u=>ge([i?.[u]??""],`${l}.${u}`)[0]).join()}),o=[ge(n.allowedRtmr0??[],"allowedRtmr0"),ge(n.allowedRtmr1??[],"allowedRtmr1"),ge(n.allowedRtmr2??[],"allowedRtmr2"),ge(n.allowedRtmr3??[],"allowedRtmr3")];if(n.allowedMeasurements!==void 0&&t.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(t.length===0){if(e.length===0)throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");if(o.slice(1).some(i=>i.length===0))throw new Error("allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too")}let r=n.allowedTcbStatuses??["UpToDate"],s=n.now??Date.now;return Object.assign(async({quoteB64:i,nonce:p,reportDataSuffix:l,collateral:u})=>{let d=Ps(i),y=u??await n.fetchCollateral?.(d);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(d,y,Math.floor(s()/1e3))}catch(E){throw new Error(`The quote did not verify: ${E?.message??String(E)}`)}if(h.status==="Revoked"||!r.includes(h.status))throw new Error(`The platform's TCB status is ${h.status}, which is not accepted`);let f=bs(h.report);if(f.tdAttributes?.length!==8||(f.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let P=[f.mrTd,f.rtMr0,f.rtMr1,f.rtMr2,f.rtMr3].map(E=>w(E));if(t.length>0&&!t.includes(P.join()))throw new Error(`The measurements (MRTD ${P[0]}, RTMR0-3 ${P.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(P[0]))throw new Error(`MRTD ${P[0]} is not an image this verifier trusts`);if([f.rtMr0,f.rtMr1,f.rtMr2,f.rtMr3].forEach((E,x)=>{let S=o[x];if(S.length>0&&!S.includes(w(E)))throw new Error(`RTMR${x} ${w(E)} is not one this verifier trusts`)}),w(f.reportData)!==`${p}${l}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function ge(n,e){return n.map(t=>{let o=t.trim().toLowerCase();if(!gs.test(o))throw new Error(`${e} holds ${JSON.stringify(t)}, which is not a 48-byte hex measurement`);return o})}function bs(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 Ps(n){let e=atob(n),t=new Uint8Array(e.length);for(let o=0;o<e.length;o+=1)t[o]=e.charCodeAt(o);return t}var _s=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],ae="locked-read-only";function Ht(n,{profile:e,allowDebugProfile:t=!1}){if(n.length===0)throw new Error("No release given, so no image would be trusted");let o,r=n.map((s,a)=>{let i=s?.tag??`releases[${a}]`;if(s?.role!==void 0&&s.role!=="node")throw new Error(`${i} lists the measurements of a ${s.role}, not of a node image`);let p=s?.profiles?.[e];if(!p){let u=Object.keys(s?.profiles??{}).join(", ")||"none";throw new Error(`${i} has no profile ${JSON.stringify(e)} (it has: ${u})`)}if(e!==ae&&!t)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(ae)}, or pass allowDebugProfile to test`);let l=(p.allowed_tcb_statuses??["uptodate"]).map(u=>As(u,i));return o=o===void 0?l:o.filter(u=>l.includes(u)),{mrtd:p.mrtd,rtmr0:p.rtmr0,rtmr1:p.rtmr1,rtmr2:p.rtmr2,rtmr3:p.rtmr3}});if(!o||o.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:r,allowedTcbStatuses:o}}function As(n,e){let t=_s.find(o=>o.toLowerCase()===String(n).toLowerCase());if(!t)throw new Error(`${e} accepts TCB status ${JSON.stringify(n)}, which this verifier does not know`);return t}var Gt=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"}),ks=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],et="https://cloud.calimero.network",$t=`${et}/api/tee/pcs`;async function oo(n,e,t={}){let o=typeof n=="string"?new TextEncoder().encode(n):n;await Ze(o,e,{identity:t.identity??Gt.identity,issuer:t.issuer??Gt.issuer},t.signature);let r;try{r=JSON.parse(new TextDecoder().decode(o))}catch{throw new Error("The signed release is not JSON")}if(r?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(r?.role)} release, not a node one`);let s=Object.values(r.profiles??{}),a=i=>ks.every(p=>/^[0-9a-f]{96}$/i.test(String(i?.[p])));if(typeof r.tag!="string"||s.length===0||!s.every(a))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(t.expectedVersion!==void 0&&r.tag!==t.expectedVersion)throw new Error(`The signed release is ${r.tag}, not ${t.expectedVersion}`);return r}async function Ft(n,e={}){let t=await(e.fetch??fetch)(n,{headers:{accept:"application/json"}});if(!t.ok)throw new Error(`Fetching the node release from ${n} failed: HTTP ${t.status}`);let o;try{o=(await t.json())?.data}catch{throw new Error(`${n} did not answer with JSON`)}if(typeof o?.version!="string"||typeof o.publishedMrtds!="string"||typeof o.bundle!="string")throw new Error(`${n} did not answer with a signed node release`);return{version:o.version,publishedMrtds:o.publishedMrtds,bundle:o.bundle}}var ro="https://github.com/calimero-network/mero-tee/releases/download";async function Qt(n,e={}){let t=`mero-tee-v${Y(n,"version")}`,o=`${(e.base??ro).replace(/\/+$/,"")}/${t}/published-mrtds.json`,r=async i=>{let p=await(e.fetch??fetch)(i);if(!p.ok)throw new Error(`Fetching ${i} failed: HTTP ${p.status}`);return p.text()},[s,a]=await Promise.all([r(o),r(`${o}.bundle.json`)]);return{version:n,publishedMrtds:s,bundle:a}}function zt(n,e){return`${n.replace(/\/+$/,"")}/api/tee/node-releases/${Y(e,"version")}`}async function tt(n){let e=Y(n.minReleaseVersion,"minReleaseVersion"),t=Y(n.release?.version,"The release version"),o=await oo(n.release.publishedMrtds,n.release.bundle,{expectedVersion:t,identity:n.identity,issuer:n.issuer});if(ve(t,e)<0)throw new Error(`Release ${t} is older than the minimum trusted, ${e}`);return Ht([o],{profile:n.profile,allowDebugProfile:n.allowDebugProfile})}function Rs(n){return Y(n.minReleaseVersion,"minReleaseVersion"),Object.assign(async t=>{let o=await tt({release:await n.release(),profile:n.profile,allowDebugProfile:n.allowDebugProfile,minReleaseVersion:n.minReleaseVersion,identity:n.identity,issuer:n.issuer});return ie({dcapVerify:n.dcapVerify,fetchCollateral:n.fetchCollateral,now:n.now,...o})(t)},{includeCollateral:!0})}var so=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Y(n,e){let t=typeof n=="string"?so.exec(n):null,o=t?.[4];if(!t||o!==void 0&&o.split(".").some(r=>r===""))throw new Error(`${e} is ${JSON.stringify(n)}, not a release version like 2.3.87`);return n}function ve(n,e){let[t,o]=no(n),[r,s]=no(e);for(let p=0;p<3;p+=1)if(t[p]!==r[p])return t[p]<r[p]?-1:1;if(o===void 0||s===void 0)return o===s?0:o===void 0?1:-1;let a=o.split("."),i=s.split(".");for(let p=0;p<Math.max(a.length,i.length);p+=1){let[l,u]=[a[p],i[p]];if(l===void 0||u===void 0)return l===void 0?-1:1;let[d,y]=[/^\d+$/.test(l),/^\d+$/.test(u)],h=d&&y?Math.sign(Number(l)-Number(u)):d!==y?d?-1:1:l<u?-1:l>u?1:0;if(h!==0)return h}return 0}function no(n){let e=so.exec(n);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var io="MOCK_TDX_QUOTE_V1";function Es(n){let e=atob(n),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);return t}function Yt(n,e){if(n.length!==e.length)return!1;let t=0;for(let o=0;o<n.length;o++)t|=n[o]^e[o];return t===0}var ao;async function Jt(n){ao??(ao=import("@phala/dcap-qvl"));let e=await ao,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 po(n,e){let t=Y(e,"minReleaseVersion"),o=String(n.release?.version??"").trim().replace(/^mero-tee-v/,"").replace(/^v/,""),r=Y(o,"The release the node names");if(ve(r,t)<0)throw new Error(`mero-tee release ${r} is older than the minimum ${t}`);return r}async function xs(n,e,t){let o=e.releaseSource;return typeof o=="function"?o(n):o==="github"?Qt(n,{fetch:t}):Ft(zt(o??et,n),{fetch:t})}function Ts(n){let e=n.collateralSource??$t;return e==="intel"?async t=>(await Jt("getCollateralFromPcs"))(t):async t=>(await Jt("getCollateral"))(e,t)}function co(n,e){let t=e.maxCollateralAgeDays;return t===void 0?n:async o=>{let r=await n(o),s;try{s=Date.parse(JSON.parse(r.tcb_info).issueDate??"")}catch{s=Number.NaN}if(!Number.isFinite(s))throw new Error("The quote's collateral names no TCB info issue date");let a=((e.now??Date.now)()-s)/864e5;if(a>t)throw new Error(`The quote's collateral was issued ${Math.floor(a)} days ago, more than the ${t} this client accepts`);return r}}async function js(n,e,t,o){let r=po(n,t.minReleaseVersion),s=await tt({release:await xs(r,t,o),profile:t.profile??ae,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer}),a=co(t.fetchCollateral??Ts(t),t);return ie({dcapVerify:t.dcapVerify??await Jt("verify"),fetchCollateral:a,now:t.now,...s})(e)}async function Wt(n,e,t=(o,r)=>fetch(o,r)){let o=w(crypto.getRandomValues(new Uint8Array(32))),r=new URL(`${n.replace(/\/+$/,"")}/attestation`);r.searchParams.set("nonce",o),e.appHash&&r.searchParams.set("appHash",e.appHash);let s=await t(r.toString());if(!s.ok)throw new Error(`The node refused to attest: HTTP ${s.status}`);let a=await s.json(),i=C(a.transportKey,"transportKey",32),p=e.appHash?C(e.appHash,"appHash",32):new Uint8Array(32),l=await Dt(p,i),u=Es(a.quote),d=new TextEncoder().encode(io);if(Yt(u.slice(0,d.length),d)){if(!e.allowMock)throw new Error("mock quote refused: this client only trusts real TEEs");let f=u.slice(d.length,d.length+64);if(!Yt(f.slice(0,32),C(o,"nonce",32))||!Yt(f.slice(32),l))throw new Error("the quote does not bind this transport key, app and nonce");return i}let y={quoteB64:a.quote,nonce:o,reportDataSuffix:w(l)},h;if(e.verifyQuote)h=await e.verifyQuote(y);else if(e.release)h=await js(a,y,e.release,t);else throw new Error("real quote refused: this client trusts no TD image (set policy.release)");if(!h)throw new Error("The attestation did not verify, so its transport key is not trusted");return i}var Xt="https://manager.cloud.calimero.network/api/v2/directory";var V=class extends Error{constructor(t,o,r,s,a){super(`directory for cluster ${t}: ${r}`);this.cluster=t;this.reason=o;this.status=s;this.cause=a;this.name="DirectoryError"}};function Os(n,e){return`${n.replace(/\/+$/,"")}/${encodeURIComponent(e)}`}async function Zt(n,e,t){let o;try{o=await t(Os(n,e),{method:"GET",headers:{accept:"application/json"}})}catch(u){throw new V(e,"unreachable",`could not be reached: ${String(u)}`,void 0,u)}if(o.status===404)throw new V(e,"not-found","unknown cluster",404);if(!o.ok)throw new V(e,"unreachable",`answered ${o.status}`,o.status);let r;try{r=await o.json()}catch(u){throw new V(e,"bad-response","answered something other than JSON",o.status,u)}let s=r;if(!s||typeof s!="object"||!Array.isArray(s.nodes))throw new V(e,"bad-response","answered no node list",o.status);let a=[],i=new Set;for(let u of s.nodes){let d=vs(u);d&&!i.has(d.url)&&(i.add(d.url),a.push(d))}if(a.length===0)throw new V(e,"empty","lists no usable node",o.status);let p=s.refreshAfterSeconds,l=typeof p=="number"&&Number.isFinite(p)&&p>=1?p:60;return{nodes:a,refreshAfterSeconds:l}}function vs(n){if(!n||typeof n!="object")return;let{url:e,zone:t,weight:o}=n;if(typeof e!="string"||typeof o!="number"||!Number.isInteger(o)||o<1)return;let r;try{r=new URL(e)}catch{return}if(!(r.protocol!=="https:"&&r.protocol!=="http:"))return{url:e.replace(/\/+$/,""),zone:typeof t=="string"?t:void 0,weight:o}}function en(n,e,t){let o=e===void 0?[]:n.filter(s=>s.zone===e),r=e===void 0?n:n.filter(s=>s.zone!==e);return[...lo(o,t),...lo(r,t)]}function lo(n,e){let t=[...n],o=[];for(;t.length>0;){let r=e()*t.reduce((a,i)=>a+i.weight,0),s=0;for(;s<t.length-1&&r>=t[s].weight;)r-=t[s++].weight;o.push(t.splice(s,1)[0].url)}return o}var g=class extends Error{constructor(t,o,r,s={}){super(`${t} ${o}: ${r}`);this.status=t;this.code=o;this.details=s;this.name="CalimeroError"}},J=class extends g{constructor(e,t={}){super(401,"UNAUTHENTICATED",e,t),this.name="LoginRequired"}},nt=class extends g{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"}},pe=class extends g{constructor(e,t={}){super(421,"WRONG_NODE",e,t),this.name="WrongNode"}},we=class extends g{constructor(e,t={}){super(404,"NOT_FOUND",e,t),this.name="NotFound"}},be=class extends g{constructor(e,t={}){super(412,"CONFIRM_REQUIRED",e,t),this.name="ConfirmRequired"}},Se=class extends Error{constructor(t){super("the passkey confirmation was cancelled");this.cause=t;this.name="ConfirmCancelled"}},Ue=class extends Error{constructor(t){super("the passkey prompt was blocked by the browser or a password manager");this.cause=t;this.name="ConfirmPromptBlocked"}},ot=class extends g{constructor(e,t={}){super(413,"ARGS_TOO_LARGE",e,t),this.name="ArgsTooLarge"}},rt=class extends g{constructor(e,t={}){super(409,"IDEMPOTENCY_MISMATCH",e,t),this.name="IdempotencyMismatch"}},st=class extends g{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:""}},at=class extends g{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:[]}},it=class extends g{constructor(e,t={}){super(409,"CONSENT_STALE",e,t),this.name="ConsentStale"}},ce=class extends g{constructor(e,t={}){let o=typeof t.origin=="string"?t.origin:"",r=typeof t.package=="string"?t.package:"",s=o?`this site (${o})`:"this site";super(403,"ORIGIN_NOT_REGISTERED",`${s} is not registered for ${r||"any package"}${e?` (${e})`:""}`,t),this.name="OriginNotRegistered",this.origin=o,this.package=r,this.nodeMessage=e}},pt=class extends g{constructor(e,t,o={}){super(400,e,t,o),this.name="BadOrigin"}},ct=class extends g{constructor(e,t={}){super(409,"ORIGIN_TAKEN",e,t),this.name="OriginTaken"}},lt=class extends g{constructor(e,t={}){super(400,"NOT_SERVING",e,t),this.name="NotServing"}},dt=class extends g{constructor(e,t={}){super(409,"CLUSTER_NOT_UPGRADED",e,t),this.name="ClusterNotUpgraded"}},ut=class extends g{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:""}},yt=class extends g{constructor(e,t={}){super(409,"RECOVERY_NOT_READY",e,t),this.name="RecoveryNotReady",this.readyAt=typeof t.readyAt=="number"?t.readyAt:void 0}},Ce=class extends g{constructor(e,t={}){super(401,"UNAUTHENTICATED",e||"unknown or used recovery code",t),this.name="WrongRecoveryCode"}},ht=class extends g{constructor(e,t={}){super(403,"SIGN_UP_REFUSED",e,t),this.name="SignUpRefused",this.reason=Ss(e)}};function Ss(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 ft=class extends g{constructor(e,t={}){super(429,"QUOTA_EXCEEDED",e,t),this.name="QuotaExceeded"}},mt=class extends g{constructor(e,t={}){super(422,"APP_ERROR",e,t),this.name="AppError";let{appCode:o,fields:r}=Us(t);this.appCode=o,this.fields=r}},gt=class extends g{constructor(e,t={}){super(422,"TRAP",e,t),this.name="TrapError",this.kind=typeof t.kind=="string"?t.kind:""}},W=class extends g{constructor(e,t,o={},r,s){super(503,e,t,o),this.name="UnavailableError",this.reason=e.toLowerCase(),this.committed=e==="TIMEOUT"||e==="MIGRATING"?!1:"unknown",this.retryAfter=r,this.cause=s}};function wt(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function Us(n){let e=typeof n.code=="string"?n:wt(n.error);return{appCode:typeof e.code=="string"?e.code:"",fields:{...wt(e.fields)}}}function Cs(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 Pe(n,e,t){let o=wt(e),r=typeof o.error=="string"?o.error:"ERROR",s=typeof o.message=="string"?o.message:"",a=wt(o.details);if(n===503)return new W(r,s,a,Cs(a,t));switch(`${n} ${r}`){case"401 UNAUTHENTICATED":return new J(s,a);case"401 PASSKEY_UNKNOWN_HERE":return new nt(s,a);case"421 WRONG_NODE":return new pe(s,a);case"404 NOT_FOUND":return new we(s,a);case"409 IDEMPOTENCY_MISMATCH":return new rt(s,a);case"409 RELEASE_DEADLINE":return new st(s,a);case"409 RUNTIME_TOO_OLD":return new at(s,a);case"409 CONSENT_STALE":return new it(s,a);case"403 ORIGIN_NOT_REGISTERED":return new ce(s,a);case"400 BAD_ORIGIN":case"400 BAD_RP_ID":return new pt(r,s,a);case"409 ORIGIN_TAKEN":return new ct(s,a);case"400 NOT_SERVING":return new lt(s,a);case"409 CLUSTER_NOT_UPGRADED":return new dt(s,a);case"409 FEATURE_NOT_ACTIVE":return new ut(s,a);case"429 QUOTA_EXCEEDED":return new ft(s,a);case"409 RECOVERY_NOT_READY":return new yt(s,a);case"403 SIGN_UP_REFUSED":return new ht(s,a);case"412 CONFIRM_REQUIRED":return new be(s,a);case"413 ARGS_TOO_LARGE":return new ot(s,a);case"422 APP_ERROR":return new mt(s,a);case"422 TRAP":return new gt(s,a);default:return new g(n,r,s,a)}}function v(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function X(n){let e=n.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((n.length+3)%4),t=atob(e),o=new Uint8Array(t.length);for(let r=0;r<t.length;r++)o[r]=t.charCodeAt(r);return o}var Be=n=>n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);function tn(n){let e=new Error(n);return e.name="NotAllowedError",e}async function uo(n,e,t,o){let r=navigator.credentials,a=globalThis.CredentialsContainer?.prototype?.[n]??r[n];try{return await a.call(r,t?{...e,signal:t}:e)}catch(i){throw t?.aborted||i?.name==="AbortError"?Object.assign(tn(`${o} was cancelled`),{cause:i}):i}}function Bs(n){let e=n.filter(t=>t.alg===-7);return e.length?e:n}function qs(){return{async create(n,e){let t=n,o=await uo("create",{publicKey:{challenge:Be(X(t.challenge)),rp:t.rp,user:{...t.user,id:Be(X(t.user.id))},pubKeyCredParams:Bs(t.pubKeyCredParams),excludeCredentials:(t.excludeCredentials??[]).map(s=>({type:s.type,id:Be(X(s.id))})),authenticatorSelection:t.authenticatorSelection,attestation:"none",timeout:t.timeout}},e?.signal,"passkey creation");if(!o)throw tn("passkey creation was cancelled");let r=o.response;return{attestationObject:v(new Uint8Array(r.attestationObject)),clientDataJson:v(new Uint8Array(r.clientDataJSON))}},async get(n,e,t,o){let r=await uo("get",{publicKey:{challenge:Be(n),rpId:e,userVerification:o?.userVerification??"preferred",allowCredentials:(t??[]).map(a=>({type:"public-key",id:Be(X(a))}))}},o?.signal,"passkey sign-in");if(!r)throw tn("passkey sign-in was cancelled");let s=r.response;return{credentialId:v(new Uint8Array(r.rawId)),authenticatorData:v(new Uint8Array(s.authenticatorData)),clientDataJson:v(new Uint8Array(s.clientDataJSON)),signature:v(new Uint8Array(s.signature))}}}}function Ms(n,e){return n==="required"||n==="preferred"||n==="discouraged"?n:e}function Ns(n){let e=n,t=e?.name,o=typeof e?.message=="string"?e.message:"";return t==="InvalidStateError"||/not focused|already pending/i.test(o)?new Ue(n):t==="NotAllowedError"||t==="AbortError"?new Se(n):n}function qe(n,e={}){return async t=>{try{return await n.get(X(t.challenge),t.rpId,t.allowCredentials,{userVerification:Ms(t.userVerification,e.userVerification??"required"),...e.signal?{signal:e.signal}:{}})}catch(o){throw Ns(o)}}}var on={retries:6,baseDelayMs:200,maxDelayMs:2e3};function Ne(n,e){return Math.min(e.baseDelayMs*2**n,e.maxDelayMs)}function Ds(n){return n instanceof Q&&n.status===413?Pe(413,{error:"TOO_LARGE",message:n.message.replace(/^Sealed request refused: /,"")}):n}async function Z(n){let e=await n.text().catch(()=>""),t={};try{t=e?JSON.parse(e):{}}catch{t={message:e}}return Pe(n.status,t,n.headers.get("retry-after"))}async function*ho(n){let e=n.getReader(),t=new TextDecoder,o="";for(;;){let{value:r,done:s}=await e.read();if(s)return;o+=t.decode(r,{stream:!0});let a;for(;(a=o.indexOf(`
|
|
1
|
+
var zr=Object.defineProperty;var Jr=(n,e,t)=>e in n?zr(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var A=(n,e,t)=>Jr(n,typeof e!="symbol"?e+"":e,t);function w(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function B(n,e,t){let o=n.trim();if(!/^[0-9a-fA-F]*$/.test(o)||o.length!==t*2)throw new Error(`${e} must be ${t*2} hex characters, got ${o.length}`);let r=new Uint8Array(t);for(let s=0;s<t;s+=1)r[s]=Number.parseInt(o.slice(s*2,s*2+2),16);return r}function Zn(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 o=new Uint8Array(t.length/2);for(let r=0;r<o.length;r+=1)o[r]=Number.parseInt(t.slice(r*2,r*2+2),16);return o}function m(...n){let e=new Uint8Array(n.reduce((o,r)=>o+r.length,0)),t=0;for(let o of n)e.set(o,t),t+=o.length;return e}var Yr="Noise_NK_25519_AESGCM_SHA256",Gt=32,Wr=16,Xr=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Ft=class n{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(Yr),t=new Uint8Array(32);return t.set(e),new n(t)}async mixHash(e){this.h=await Zr(m(this.h,e))}async mixKey(e){let[t,o]=await to(this.ck,e);this.ck=t,this.k=await crypto.subtle.importKey("raw",o,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let t=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:eo(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:eo(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),t}split(){return to(this.ck,new Uint8Array)}};async function no(n,e,t){let o=await Ft.initialize();await o.mixHash(e),await o.mixHash(n);let r=await q(t);return await o.mixHash(r.publicKey),await o.mixKey(await V(r.privateKey,n)),{message1:m(r.publicKey,await o.encryptAndHash(new Uint8Array)),async finish(a){if(a.length<Gt+Wr)throw new Error("Noise: message 2 is too short");let i=a.slice(0,Gt);return await o.mixHash(i),await o.mixKey(await V(r.privateKey,i)),{payload:await o.decryptAndHash(a.slice(Gt)),split:await o.split()}}}}async function q(n){if(!n){let o;try{o=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"])}catch(s){throw new Error(`Sealed transport needs WebCrypto with X25519, which this runtime lacks (${s?.name??"no crypto.subtle"}). Current browsers and Node have it; in React Native, install react-native-quick-crypto as the global crypto.`)}let r=new Uint8Array(await crypto.subtle.exportKey("raw",o.publicKey));return{privateKey:o.privateKey,publicKey:r}}let e=await crypto.subtle.importKey("pkcs8",m(Xr,n),{name:"X25519"},!0,["deriveBits"]),t=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:es(t.x)}}async function V(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 eo(n){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(n),!1),e}async function Zr(n){return new Uint8Array(await crypto.subtle.digest("SHA-256",n))}async function Ht(n,e){let t=await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",t,e))}async function to(n,e){let t=await Ht(n,e),o=await Ht(t,new Uint8Array([1])),r=await Ht(t,m(o,new Uint8Array([2])));return[o,r]}function es(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(t,o=>o.charCodeAt(0))}var ao="/sealed/v2/handshake",io="/sealed/v2",Ue="application/vnd.calimero.sealed",Qt=2,ts=new TextEncoder().encode("calimero/sealed-http/v2"),Se=16,ns=1+Se+8,os=0,rs=1,ss=2,as=1+64*1024+16,is=1024,ps=6e4,cs="calimero.tee-attest.transport-key.v1",ls=[101,204,205,304],po=new TextEncoder,Ce=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},z=class extends Error{constructor(t,o,r,s){super(r);this.status=t;this.code=o;this.retryAfterMs=s;this.name="SealedTransportError"}};async function zt(n,e){let t=await crypto.subtle.digest("SHA-256",m(po.encode(cs),n,e));return new Uint8Array(t)}function Jt(n){let e=new URL(n.baseUrl),t=e.pathname.replace(/\/+$/,""),o=`${e.origin}${t}`,r=n.fetch??((d,y)=>fetch(d,y)),s=typeof n.transportPublicKey=="function"?n.transportPublicKey:void 0,a=s?Promise.resolve().then(s):Promise.resolve(n.transportPublicKey);a.catch(()=>{});let i,p=async()=>{try{return await ro(r,o,await oo(a))}catch(d){if(!(d instanceof Ce)||!s)throw d;return a=Promise.resolve().then(s),ro(r,o,await oo(a))}},l=async()=>{let d=i??u(void 0),y=await d;if(Date.now()<y.renewAt)return[y,d];let h=u(d);return[await h,h]},u=d=>{if(i===d){let y=p();i=y,y.catch(()=>{i===y&&(i=void 0)})}return i};return async(d,y)=>{let h=new Request(d,y),f=new URL(h.url);if(f.origin!==e.origin||!f.pathname.startsWith(`${t}/`))throw new Error(`Refusing to send ${f.href} outside the sealed node at ${n.baseUrl}`);let P=[];h.headers.forEach((C,L)=>P.push([L,C]));let v={method:h.method,path:f.pathname.slice(t.length)+f.search,headers:P},x=new Uint8Array(await h.arrayBuffer()),T=y?.signal??(d instanceof Request?d.signal:void 0),U=async C=>{let{requestId:L,header:re,envelope:H}=await us(C,v,x),D=await r(`${o}${io}`,{method:"POST",headers:{"content-type":Ue},body:H,signal:T});if(D.headers.get("content-type")!==Ue)throw await lo(D);return hs(D,C.responseKey,re,L)},[G,he]=await l();try{return await U(G)}catch(C){if(!(C instanceof z)||C.code!=="unknown_session")throw C;return U(await u(he))}}}async function oo(n){let e=await n;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function ro(n,e,t){try{return await so(n,e,t)}catch(o){if(!(o instanceof z)||o.code!=="busy")throw o;return await new Promise(r=>setTimeout(r,o.retryAfterMs??1e3)),so(n,e,t)}}async function so(n,e,t){let o=await no(t,ts),r=await n(`${e}${ao}`,{method:"POST",headers:{"content-type":Ue},body:m(new Uint8Array([Qt]),t,o.message1)});if(r.headers.get("content-type")!==Ue)throw await lo(r);let s=await ms(r,is);return ds(o,s)}async function ds(n,e){if(e[0]!==Qt)throw new Error("The handshake reply is malformed");let t;try{t=await n.finish(e.slice(1))}catch{throw new Error("The handshake reply did not open: it did not come from the attested node")}let{payload:o,split:r}=t;if(o.length!==Se+4)throw new Error("The handshake reply is malformed");let s=o.slice(0,Se),a=new DataView(o.buffer,o.byteOffset).getUint32(Se,!1),[i,p]=await Promise.all([crypto.subtle.importKey("raw",r[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",r[1],"AES-GCM",!1,["decrypt"])]);return r[0].fill(0),r[1].fill(0),{requestKey:i,responseKey:p,nextRequestId:1,renewAt:Date.now()+a*1e3-ps,header(l){let u=new Uint8Array(ns);return u[0]=Qt,u.set(s,1),new DataView(u.buffer).setBigUint64(1+Se,BigInt(l),!1),u}}}async function us(n,e,t){let o=n.nextRequestId;n.nextRequestId+=1;let r=n.header(o),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:co(o,0),additionalData:r},n.requestKey,ys(e,t));return{requestId:o,header:r,envelope:m(r,new Uint8Array(s))}}function co(n,e){let t=new Uint8Array(12),o=new DataView(t.buffer);return o.setBigUint64(0,BigInt(n),!1),o.setUint32(8,e,!1),t}function ys(n,e){let t=po.encode(JSON.stringify(n)),o=new Uint8Array(4);return new DataView(o.buffer).setUint32(0,t.length,!1),m(o,t,e)}async function hs(n,e,t,o){if(!n.body)throw new Error("The sealed response has no body");let r=fs(n.body.getReader()),s=0,a=async()=>{let u=await r.next();if(!u)return null;let d;try{d=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:co(o,s),additionalData:t},e,u))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return s+=1,{kind:d[0],data:d.slice(1)}},i=await a();if(!i||i.kind!==os)throw new Error("The sealed response is malformed");let p=JSON.parse(new TextDecoder().decode(i.data));if(ls.includes(p.status))return await r.cancel(),new Response(null,{status:p.status,headers:p.headers});let l=new ReadableStream({async pull(u){try{let d=await a();d?d.kind===rs?u.enqueue(d.data):d.kind===ss?(u.close(),await r.cancel()):u.error(new Error("The sealed response is malformed")):u.error(new Error("The sealed response was cut short"))}catch(d){u.error(d)}},cancel(){return r.cancel()}});return new Response(l,{status:p.status,headers:p.headers})}function fs(n){let e=new Uint8Array,t=async o=>{for(;e.length<o;){let{done:r,value:s}=await n.read();if(r)return!1;e=m(e,s)}return!0};return{async next(){if(!await t(4))return null;let o=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(o>as)throw await n.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await t(4+o))return null;let r=e.slice(4,4+o);return e=e.slice(4+o),r},cancel:()=>n.cancel()}}async function ms(n,e){if(!n.body)return new Uint8Array;let t=n.body.getReader(),o=new Uint8Array;for(;;){let{done:r,value:s}=await t.read();if(r)return o;if(o=m(o,s),o.length>e)throw await t.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function lo(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 Ce;let o=Number(n.headers.get("retry-after")),r=Number.isFinite(o)&&o>0?Math.min(o,5)*1e3:void 0;return new z(n.status,e,t,r)}var uo=[{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"]}],yo=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var gs="1.2.840.10045.2.1",ws={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},bs={"P-256":32,"P-384":48},Ps={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function ho(n,e,t){if(e+2>t)throw new Error("it is truncated");let o=n[e];if((o&31)===31)throw new Error("it uses a tag this parser does not read");let r=n[e+1],s=e+2;if(r&128){let i=r&127;if(i===0||i>4||s+i>t)throw new Error("it has a length this parser does not read");r=0;for(let p=0;p<i;p+=1)r=r*256+n[s+p];s+=i}let a=s+r;if(a>t)throw new Error("it is truncated");return{tag:o,bytes:n,offset:e,start:s,end:a}}function me(n){let e=ho(n,0,n.length);if(e.end!==n.length)throw new Error("it has trailing bytes");return e}function S(n){let e=[];for(let t=n.start;t<n.end;){let o=ho(n.bytes,t,n.end);e.push(o),t=o.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 J(n){return n.bytes.slice(n.start,n.end)}function rt(n){return n.bytes.slice(n.offset,n.end)}function fe(n){let e=J(_(n,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let t=[],o=0;for(let a of e)o=o*128+(a&127),a&128||(t.push(o),o=0);let r=t.shift();return[...r<80?[Math.floor(r/40),r%40]:[2,r-80],...t].join(".")}function _s(n){let e=new TextDecoder().decode(J(n)),t=n.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,o=n.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,r=t??o;if(!r)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let s=Number(r[1]);t&&(s+=s<50?2e3:1900);let[a,i,p,l,u]=r.slice(2).map(Number);return Date.UTC(s,a-1,i,p,l,u)}function Yt(n){try{let[e,t,o,...r]=S(_(me(n),48,"The certificate"));if(r.length>0)throw new Error("it has fields after its signature");let s=S(_(e,48,"The signed part")),a=s[0]?.tag===160?1:0,[i,p,l,u,d,y,...h]=s.slice(a);_(i,2,"The serial number");let f=fe(S(_(t,48,"The signature algorithm"))[0]);if(fe(S(_(p,48,"The signature algorithm"))[0])!==f)throw new Error("it names two different signature algorithms");let v=Ps[f];if(!v)throw new Error(`it is signed with ${f}, not ECDSA with SHA-256 or SHA-384`);let[x,T]=S(_(u,48,"The validity")).map(_s);if(T===void 0)throw new Error("its validity is incomplete");let[U,G]=S(_(y,48,"The public key"));_(G,3,"The public key");let[he,C]=S(_(U,48,"The key algorithm"));if(fe(he)!==gs)throw new Error("its key is not an elliptic-curve key");let L=ws[fe(C)];if(!L)throw new Error("its key is on a curve other than P-256 or P-384");let re=new Map,H=h.find(se=>se.tag===163);if(H){let[se]=S(H);for(let et of S(_(se,48,"The extensions"))){let I=S(_(et,48,"An extension"));if(I.length===3)_(I[1],1,"An extension's critical flag");else if(I.length!==2)throw new Error("it has a malformed extension");let Oe=fe(I[0]);if(re.has(Oe))throw new Error(`it has extension ${Oe} twice`);re.set(Oe,J(_(I[I.length-1],4,"An extension value")))}}let D=J(_(o,3,"The signature"));if(D[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:n,tbs:rt(e),signatureHash:v,signature:D.slice(1),issuer:rt(_(l,48,"The issuer")),subject:rt(_(d,48,"The subject")),notBefore:x,notAfter:T,spki:rt(y),curve:L,extensions:re}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function fo(n){return S(_(me(n),48,"The list")).map(fe)}function As(n,e){let t=bs[e],o=S(_(me(n),48,"The signature"));if(o.length!==2)throw new Error("The signature is not an ECDSA signature");let r=new Uint8Array(t*2);return o.forEach((s,a)=>{let i=J(_(s,2,"The signature"));if(i.length===0||i[0]&128)throw new Error("The signature is not an ECDSA signature");for(;i.length>1&&i[0]===0;)i=i.subarray(1);if(i.length>t)throw new Error("The signature is not an ECDSA signature");r.set(i,a*t+t-i.length)}),r}async function st(n,e,t,o,r){let s;try{s=As(o,e)}catch{return!1}let a=await crypto.subtle.importKey("spki",n,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:t},a,s,r)}function K(n,e){let t=n.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t)||t.length%4!==0)throw new Error(`${e} is not base64`);let o=atob(t),r=new Uint8Array(o.length);for(let s=0;s<o.length;s+=1)r[s]=o.charCodeAt(s);return r}function Wt(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 K(t[0][1],e)}var ks="2.5.29.17",Es="2.5.29.37",Rs="1.3.6.1.5.5.7.3.3",xs="1.3.6.1.4.1.57264.1.8",Ts="1.3.6.1.4.1.57264.1.1",js=134,Os=12,vs=48,Ss=new TextEncoder,ge=n=>new TextDecoder().decode(n);async function at(n,e,t,o){let{base64Signature:r,cert:s,rekorBundle:a}=Ms(e),i=a.Payload;if(o!==void 0&&o.trim()!==r.trim())throw new Error("The detached signature is not the one in the bundle");let p=K(r,"The bundle signature"),l=Wt(ge(K(s,"The bundle certificate")),"The bundle certificate"),u=Yt(l),d=yo.find(T=>T.logId===i.logID.toLowerCase());if(!d)throw new Error(`The bundle names Rekor log ${i.logID}, which the Sigstore trust root does not know`);let y=Ss.encode(`{"body":${JSON.stringify(i.body)},"integratedTime":${i.integratedTime},"logID":${JSON.stringify(i.logID)},"logIndex":${i.logIndex}}`);if(!await st(K(d.publicKey,"The Rekor key"),"P-256","SHA-256",K(a.SignedEntryTimestamp,"The signed entry timestamp"),y))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let f=i.integratedTime*1e3;if(!wo(f,d.validFor))throw new Error(`Rekor log ${d.baseUrl} was not in use at ${Be(f)}, when the entry says it was logged`);let P=qs(i.body),v=w(new Uint8Array(await crypto.subtle.digest("SHA-256",n)));if(P.hash!==v)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!Xt(K(P.signature,"The logged signature"),p))throw new Error("The bundle's signature is not the one Rekor logged");let x=Wt(ge(K(P.publicKey,"The logged certificate")),"The logged certificate");if(!Xt(x,l))throw new Error("The bundle's certificate is not the one Rekor logged");if(u.curve!=="P-256"||!await st(u.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 Us(u,f),Bs(u,t),{integratedTime:i.integratedTime}}async function Us(n,e){if(!go(n,e))throw new Error(`The signing certificate was valid ${Be(n.notBefore)} to ${Be(n.notAfter)}, not at ${Be(e)} when Rekor logged it`);let t=[];for(let o of uo){let r=o.certChain.map(a=>Yt(K(a,"A Fulcio certificate")));if(!await mo(n,r[0]))continue;let s=await Cs(r,o.validFor,e);if(!s)return;t.push(`${o.uri} (valid from ${o.validFor.start}): ${s}`)}throw new Error(t.length>0?`The signing certificate's CA is not trusted at ${Be(e)}: ${t.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function Cs(n,e,t){if(!wo(t,e))return"the trust root says it was not issuing certificates then";for(let[o,r]of n.entries()){if(!go(r,t))return`its certificate ${o} was not valid then`;let s=n[o+1]??r;if(!await mo(r,s))return`its certificate ${o} is not signed by the next`}}async function mo(n,e){return Xt(n.issuer,e.subject)?st(e.spki,e.curve,n.signatureHash,n.signature,n.tbs):!1}function Bs(n,e){let t=n.extensions.get(ks);if(!t)throw new Error("The signing certificate names no identity");let o=S(_(me(t),vs,"The subject alternative name")),r=o.filter(l=>l.tag===js).map(l=>ge(J(l)));if(r.length!==1||o.length!==1||r[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(r.length===1?r[0]:r)}, not by ${e.identity}`);let s=n.extensions.get(xs),a=n.extensions.get(Ts),i=s?ge(J(_(me(s),Os,"The OIDC issuer"))):a?ge(a):void 0;if(i!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${i===void 0?"missing":JSON.stringify(i)}, not ${e.issuer}`);let p=n.extensions.get(Es);if(!p||!fo(p).includes(Rs))throw new Error("The signing certificate is not for code signing")}function Ms(n){let e=n;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let t=e,o=t?.rekorBundle?.Payload;if(!(typeof t?.base64Signature=="string"&&typeof t.cert=="string"&&typeof t.rekorBundle?.SignedEntryTimestamp=="string"&&typeof o?.body=="string"&&typeof o.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(o.logID)&&Number.isSafeInteger(o.integratedTime)&&o.integratedTime>=0&&Number.isSafeInteger(o.logIndex)&&o.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return t}function qs(n){let e;try{e=JSON.parse(ge(K(n,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let t=e?.spec?.data?.hash,o=e?.spec?.signature;if(e?.kind!=="hashedrekord"||t?.algorithm!=="sha256"||typeof t.value!="string"||typeof o?.content!="string"||typeof o.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:t.value.toLowerCase(),signature:o.content,publicKey:o.publicKey.content}}function go(n,e){return n.notBefore<=e&&e<=n.notAfter}function wo(n,e){return Date.parse(e.start)<=n&&(e.end===void 0||n<=Date.parse(e.end))}function Be(n){return new Date(n).toISOString()}function Xt(n,e){return n.length===e.length&&n.every((t,o)=>t===e[o])}var Ns=/^[0-9a-f]{96}$/,Ds=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function pe(n){let e=we(n.allowedMrtd??[],"allowedMrtd"),t=(n.allowedMeasurements??[]).map((i,p)=>{let l=`allowedMeasurements[${p}]`;return Ds.map(u=>we([i?.[u]??""],`${l}.${u}`)[0]).join()}),o=[we(n.allowedRtmr0??[],"allowedRtmr0"),we(n.allowedRtmr1??[],"allowedRtmr1"),we(n.allowedRtmr2??[],"allowedRtmr2"),we(n.allowedRtmr3??[],"allowedRtmr3")];if(n.allowedMeasurements!==void 0&&t.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(t.length===0){if(e.length===0)throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");if(o.slice(1).some(i=>i.length===0))throw new Error("allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too")}let r=n.allowedTcbStatuses??["UpToDate"],s=n.now??Date.now;return Object.assign(async({quoteB64:i,nonce:p,reportDataSuffix:l,collateral:u})=>{let d=Ks(i),y=u??await n.fetchCollateral?.(d);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(d,y,Math.floor(s()/1e3))}catch(x){throw new Error(`The quote did not verify: ${x?.message??String(x)}`)}if(h.status==="Revoked"||!r.includes(h.status))throw new Error(`The platform's TCB status is ${h.status}, which is not accepted`);let f=Is(h.report);if(f.tdAttributes?.length!==8||(f.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let P=[f.mrTd,f.rtMr0,f.rtMr1,f.rtMr2,f.rtMr3].map(x=>w(x));if(t.length>0&&!t.includes(P.join()))throw new Error(`The measurements (MRTD ${P[0]}, RTMR0-3 ${P.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(P[0]))throw new Error(`MRTD ${P[0]} is not an image this verifier trusts`);if([f.rtMr0,f.rtMr1,f.rtMr2,f.rtMr3].forEach((x,T)=>{let U=o[T];if(U.length>0&&!U.includes(w(x)))throw new Error(`RTMR${T} ${w(x)} is not one this verifier trusts`)}),w(f.reportData)!==`${p}${l}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function we(n,e){return n.map(t=>{let o=t.trim().toLowerCase();if(!Ns.test(o))throw new Error(`${e} holds ${JSON.stringify(t)}, which is not a 48-byte hex measurement`);return o})}function Is(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 Ks(n){let e=atob(n),t=new Uint8Array(e.length);for(let o=0;o<e.length;o+=1)t[o]=e.charCodeAt(o);return t}var Ls=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],ie="locked-read-only";function Zt(n,{profile:e,allowDebugProfile:t=!1}){if(n.length===0)throw new Error("No release given, so no image would be trusted");let o,r=n.map((s,a)=>{let i=s?.tag??`releases[${a}]`;if(s?.role!==void 0&&s.role!=="node")throw new Error(`${i} lists the measurements of a ${s.role}, not of a node image`);let p=s?.profiles?.[e];if(!p){let u=Object.keys(s?.profiles??{}).join(", ")||"none";throw new Error(`${i} has no profile ${JSON.stringify(e)} (it has: ${u})`)}if(e!==ie&&!t)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(ie)}, or pass allowDebugProfile to test`);let l=(p.allowed_tcb_statuses??["uptodate"]).map(u=>Vs(u,i));return o=o===void 0?l:o.filter(u=>l.includes(u)),{mrtd:p.mrtd,rtmr0:p.rtmr0,rtmr1:p.rtmr1,rtmr2:p.rtmr2,rtmr3:p.rtmr3}});if(!o||o.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:r,allowedTcbStatuses:o}}function Vs(n,e){let t=Ls.find(o=>o.toLowerCase()===String(n).toLowerCase());if(!t)throw new Error(`${e} accepts TCB status ${JSON.stringify(n)}, which this verifier does not know`);return t}var en=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"}),$s=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],it="https://cloud.calimero.network",tn=`${it}/api/tee/pcs`;async function Po(n,e,t={}){let o=typeof n=="string"?new TextEncoder().encode(n):n;await at(o,e,{identity:t.identity??en.identity,issuer:t.issuer??en.issuer},t.signature);let r;try{r=JSON.parse(new TextDecoder().decode(o))}catch{throw new Error("The signed release is not JSON")}if(r?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(r?.role)} release, not a node one`);let s=Object.values(r.profiles??{}),a=i=>$s.every(p=>/^[0-9a-f]{96}$/i.test(String(i?.[p])));if(typeof r.tag!="string"||s.length===0||!s.every(a))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(t.expectedVersion!==void 0&&r.tag!==t.expectedVersion)throw new Error(`The signed release is ${r.tag}, not ${t.expectedVersion}`);return r}async function nn(n,e={}){let t=await(e.fetch??fetch)(n,{headers:{accept:"application/json"}});if(!t.ok)throw new Error(`Fetching the node release from ${n} failed: HTTP ${t.status}`);let o;try{o=(await t.json())?.data}catch{throw new Error(`${n} did not answer with JSON`)}if(typeof o?.version!="string"||typeof o.publishedMrtds!="string"||typeof o.bundle!="string")throw new Error(`${n} did not answer with a signed node release`);return{version:o.version,publishedMrtds:o.publishedMrtds,bundle:o.bundle}}var _o="https://github.com/calimero-network/mero-tee/releases/download";async function on(n,e={}){let t=`mero-tee-v${Y(n,"version")}`,o=`${(e.base??_o).replace(/\/+$/,"")}/${t}/published-mrtds.json`,r=async i=>{let p=await(e.fetch??fetch)(i);if(!p.ok)throw new Error(`Fetching ${i} failed: HTTP ${p.status}`);return p.text()},[s,a]=await Promise.all([r(o),r(`${o}.bundle.json`)]);return{version:n,publishedMrtds:s,bundle:a}}function rn(n,e){return`${n.replace(/\/+$/,"")}/api/tee/node-releases/${Y(e,"version")}`}async function pt(n){let e=Y(n.minReleaseVersion,"minReleaseVersion"),t=Y(n.release?.version,"The release version"),o=await Po(n.release.publishedMrtds,n.release.bundle,{expectedVersion:t,identity:n.identity,issuer:n.issuer});if(Me(t,e)<0)throw new Error(`Release ${t} is older than the minimum trusted, ${e}`);return Zt([o],{profile:n.profile,allowDebugProfile:n.allowDebugProfile})}function Gs(n){return Y(n.minReleaseVersion,"minReleaseVersion"),Object.assign(async t=>{let o=await pt({release:await n.release(),profile:n.profile,allowDebugProfile:n.allowDebugProfile,minReleaseVersion:n.minReleaseVersion,identity:n.identity,issuer:n.issuer});return pe({dcapVerify:n.dcapVerify,fetchCollateral:n.fetchCollateral,now:n.now,...o})(t)},{includeCollateral:!0})}var Ao=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Y(n,e){let t=typeof n=="string"?Ao.exec(n):null,o=t?.[4];if(!t||o!==void 0&&o.split(".").some(r=>r===""))throw new Error(`${e} is ${JSON.stringify(n)}, not a release version like 2.3.87`);return n}function Me(n,e){let[t,o]=bo(n),[r,s]=bo(e);for(let p=0;p<3;p+=1)if(t[p]!==r[p])return t[p]<r[p]?-1:1;if(o===void 0||s===void 0)return o===s?0:o===void 0?1:-1;let a=o.split("."),i=s.split(".");for(let p=0;p<Math.max(a.length,i.length);p+=1){let[l,u]=[a[p],i[p]];if(l===void 0||u===void 0)return l===void 0?-1:1;let[d,y]=[/^\d+$/.test(l),/^\d+$/.test(u)],h=d&&y?Math.sign(Number(l)-Number(u)):d!==y?d?-1:1:l<u?-1:l>u?1:0;if(h!==0)return h}return 0}function bo(n){let e=Ao.exec(n);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var Eo="MOCK_TDX_QUOTE_V1";function Hs(n){let e=atob(n),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);return t}function sn(n,e){if(n.length!==e.length)return!1;let t=0;for(let o=0;o<n.length;o++)t|=n[o]^e[o];return t===0}var ko;async function an(n){ko??(ko=import("@phala/dcap-qvl"));let e=await ko,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 Ro(n,e){let t=Y(e,"minReleaseVersion"),o=String(n.release?.version??"").trim().replace(/^mero-tee-v/,"").replace(/^v/,""),r=Y(o,"The release the node names");if(Me(r,t)<0)throw new Error(`mero-tee release ${r} is older than the minimum ${t}`);return r}async function Fs(n,e,t){let o=e.releaseSource;return typeof o=="function"?o(n):o==="github"?on(n,{fetch:t}):nn(rn(o??it,n),{fetch:t})}function Qs(n){let e=n.collateralSource??tn;return e==="intel"?async t=>(await an("getCollateralFromPcs"))(t):async t=>(await an("getCollateral"))(e,t)}function xo(n,e){let t=e.maxCollateralAgeDays;return t===void 0?n:async o=>{let r=await n(o),s;try{s=Date.parse(JSON.parse(r.tcb_info).issueDate??"")}catch{s=Number.NaN}if(!Number.isFinite(s))throw new Error("The quote's collateral names no TCB info issue date");let a=((e.now??Date.now)()-s)/864e5;if(a>t)throw new Error(`The quote's collateral was issued ${Math.floor(a)} days ago, more than the ${t} this client accepts`);return r}}async function zs(n,e,t,o){let r=Ro(n,t.minReleaseVersion),s=await pt({release:await Fs(r,t,o),profile:t.profile??ie,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer}),a=xo(t.fetchCollateral??Qs(t),t);return pe({dcapVerify:t.dcapVerify??await an("verify"),fetchCollateral:a,now:t.now,...s})(e)}async function pn(n,e,t=(o,r)=>fetch(o,r)){let o=w(crypto.getRandomValues(new Uint8Array(32))),r=new URL(`${n.replace(/\/+$/,"")}/attestation`);r.searchParams.set("nonce",o),e.appHash&&r.searchParams.set("appHash",e.appHash);let s=await t(r.toString());if(!s.ok)throw new Error(`The node refused to attest: HTTP ${s.status}`);let a=await s.json(),i=B(a.transportKey,"transportKey",32),p=e.appHash?B(e.appHash,"appHash",32):new Uint8Array(32),l=await zt(p,i),u=Hs(a.quote),d=new TextEncoder().encode(Eo);if(sn(u.slice(0,d.length),d)){if(!e.allowMock)throw new Error("mock quote refused: this client only trusts real TEEs");let f=u.slice(d.length,d.length+64);if(!sn(f.slice(0,32),B(o,"nonce",32))||!sn(f.slice(32),l))throw new Error("the quote does not bind this transport key, app and nonce");return i}let y={quoteB64:a.quote,nonce:o,reportDataSuffix:w(l)},h;if(e.verifyQuote)h=await e.verifyQuote(y);else if(e.release)h=await zs(a,y,e.release,t);else throw new Error("real quote refused: this client trusts no TD image (set policy.release)");if(!h)throw new Error("The attestation did not verify, so its transport key is not trusted");return i}var cn="https://manager.cloud.calimero.network/api/v2/directory";var $=class extends Error{constructor(t,o,r,s,a){super(`directory for cluster ${t}: ${r}`);this.cluster=t;this.reason=o;this.status=s;this.cause=a;this.name="DirectoryError"}};function Js(n,e){return`${n.replace(/\/+$/,"")}/${encodeURIComponent(e)}`}async function ln(n,e,t){let o;try{o=await t(Js(n,e),{method:"GET",headers:{accept:"application/json"}})}catch(u){throw new $(e,"unreachable",`could not be reached: ${String(u)}`,void 0,u)}if(o.status===404)throw new $(e,"not-found","unknown cluster",404);if(!o.ok)throw new $(e,"unreachable",`answered ${o.status}`,o.status);let r;try{r=await o.json()}catch(u){throw new $(e,"bad-response","answered something other than JSON",o.status,u)}let s=r;if(!s||typeof s!="object"||!Array.isArray(s.nodes))throw new $(e,"bad-response","answered no node list",o.status);let a=[],i=new Set;for(let u of s.nodes){let d=Ys(u);d&&!i.has(d.url)&&(i.add(d.url),a.push(d))}if(a.length===0)throw new $(e,"empty","lists no usable node",o.status);let p=s.refreshAfterSeconds,l=typeof p=="number"&&Number.isFinite(p)&&p>=1?p:60;return{nodes:a,refreshAfterSeconds:l}}function Ys(n){if(!n||typeof n!="object")return;let{url:e,zone:t,weight:o}=n;if(typeof e!="string"||typeof o!="number"||!Number.isInteger(o)||o<1)return;let r;try{r=new URL(e)}catch{return}if(!(r.protocol!=="https:"&&r.protocol!=="http:"))return{url:e.replace(/\/+$/,""),zone:typeof t=="string"?t:void 0,weight:o}}function dn(n,e,t){let o=e===void 0?[]:n.filter(s=>s.zone===e),r=e===void 0?n:n.filter(s=>s.zone!==e);return[...To(o,t),...To(r,t)]}function To(n,e){let t=[...n],o=[];for(;t.length>0;){let r=e()*t.reduce((a,i)=>a+i.weight,0),s=0;for(;s<t.length-1&&r>=t[s].weight;)r-=t[s++].weight;o.push(t.splice(s,1)[0].url)}return o}var g=class extends Error{constructor(t,o,r,s={}){super(`${t} ${o}: ${r}`);this.status=t;this.code=o;this.details=s;this.name="CalimeroError"}},W=class extends g{constructor(e,t={}){super(401,"UNAUTHENTICATED",e,t),this.name="LoginRequired"}},ct=class extends g{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"}},ce=class extends g{constructor(e,t={}){super(421,"WRONG_NODE",e,t),this.name="WrongNode"}},be=class extends g{constructor(e,t={}){super(404,"NOT_FOUND",e,t),this.name="NotFound"}},Pe=class extends g{constructor(e,t={}){super(412,"CONFIRM_REQUIRED",e,t),this.name="ConfirmRequired"}},qe=class extends Error{constructor(t){super("the passkey confirmation was cancelled");this.cause=t;this.name="ConfirmCancelled"}},Ne=class extends Error{constructor(t){super("the passkey prompt was blocked by the browser or a password manager");this.cause=t;this.name="ConfirmPromptBlocked"}},lt=class extends g{constructor(e,t={}){super(413,"ARGS_TOO_LARGE",e,t),this.name="ArgsTooLarge"}},dt=class extends g{constructor(e,t={}){super(409,"IDEMPOTENCY_MISMATCH",e,t),this.name="IdempotencyMismatch"}},ut=class extends g{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:""}},yt=class extends g{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:[]}},ht=class extends g{constructor(e,t={}){super(409,"CONSENT_STALE",e,t),this.name="ConsentStale"}},le=class extends g{constructor(e,t={}){let o=typeof t.origin=="string"?t.origin:"",r=typeof t.package=="string"?t.package:"",s=o?`this site (${o})`:"this site";super(403,"ORIGIN_NOT_REGISTERED",`${s} is not registered for ${r||"any package"}${e?` (${e})`:""}`,t),this.name="OriginNotRegistered",this.origin=o,this.package=r,this.nodeMessage=e}},ft=class extends g{constructor(e,t,o={}){super(400,e,t,o),this.name="BadOrigin"}},mt=class extends g{constructor(e,t={}){super(409,"ORIGIN_TAKEN",e,t),this.name="OriginTaken"}},gt=class extends g{constructor(e,t={}){super(400,"NOT_SERVING",e,t),this.name="NotServing"}},wt=class extends g{constructor(e,t={}){super(409,"CLUSTER_NOT_UPGRADED",e,t),this.name="ClusterNotUpgraded"}},bt=class extends g{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:""}},Pt=class extends g{constructor(e,t={}){super(409,"RECOVERY_NOT_READY",e,t),this.name="RecoveryNotReady",this.readyAt=typeof t.readyAt=="number"?t.readyAt:void 0}},De=class extends g{constructor(e,t={}){super(401,"UNAUTHENTICATED",e||"unknown or used recovery code",t),this.name="WrongRecoveryCode"}},_t=class extends g{constructor(e,t={}){super(403,"SIGN_UP_REFUSED",e,t),this.name="SignUpRefused",this.reason=Ws(e)}};function Ws(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 At=class extends g{constructor(e,t={}){super(429,"QUOTA_EXCEEDED",e,t),this.name="QuotaExceeded"}},kt=class extends g{constructor(e,t={}){super(422,"APP_ERROR",e,t),this.name="AppError";let{appCode:o,fields:r}=Xs(t);this.appCode=o,this.fields=r}},Et=class extends g{constructor(e,t={}){super(422,"TRAP",e,t),this.name="TrapError",this.kind=typeof t.kind=="string"?t.kind:""}},X=class extends g{constructor(e,t,o={},r,s){super(503,e,t,o),this.name="UnavailableError",this.reason=e.toLowerCase(),this.committed=e==="TIMEOUT"||e==="MIGRATING"?!1:"unknown",this.retryAfter=r,this.cause=s}};function Rt(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function Xs(n){let e=typeof n.code=="string"?n:Rt(n.error);return{appCode:typeof e.code=="string"?e.code:"",fields:{...Rt(e.fields)}}}function Zs(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 _e(n,e,t){let o=Rt(e),r=typeof o.error=="string"?o.error:"ERROR",s=typeof o.message=="string"?o.message:"",a=Rt(o.details);if(n===503)return new X(r,s,a,Zs(a,t));switch(`${n} ${r}`){case"401 UNAUTHENTICATED":return new W(s,a);case"401 PASSKEY_UNKNOWN_HERE":return new ct(s,a);case"421 WRONG_NODE":return new ce(s,a);case"404 NOT_FOUND":return new be(s,a);case"409 IDEMPOTENCY_MISMATCH":return new dt(s,a);case"409 RELEASE_DEADLINE":return new ut(s,a);case"409 RUNTIME_TOO_OLD":return new yt(s,a);case"409 CONSENT_STALE":return new ht(s,a);case"403 ORIGIN_NOT_REGISTERED":return new le(s,a);case"400 BAD_ORIGIN":case"400 BAD_RP_ID":return new ft(r,s,a);case"409 ORIGIN_TAKEN":return new mt(s,a);case"400 NOT_SERVING":return new gt(s,a);case"409 CLUSTER_NOT_UPGRADED":return new wt(s,a);case"409 FEATURE_NOT_ACTIVE":return new bt(s,a);case"429 QUOTA_EXCEEDED":return new At(s,a);case"409 RECOVERY_NOT_READY":return new Pt(s,a);case"403 SIGN_UP_REFUSED":return new _t(s,a);case"412 CONFIRM_REQUIRED":return new Pe(s,a);case"413 ARGS_TOO_LARGE":return new lt(s,a);case"422 APP_ERROR":return new kt(s,a);case"422 TRAP":return new Et(s,a);default:return new g(n,r,s,a)}}function k(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function O(n){let e=n.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((n.length+3)%4),t=atob(e),o=new Uint8Array(t.length);for(let r=0;r<t.length;r++)o[r]=t.charCodeAt(r);return o}var Ie=n=>n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);function un(n){let e=new Error(n);return e.name="NotAllowedError",e}async function jo(n,e,t,o){let r=navigator.credentials,a=globalThis.CredentialsContainer?.prototype?.[n]??r[n];try{return await a.call(r,t?{...e,signal:t}:e)}catch(i){throw t?.aborted||i?.name==="AbortError"?Object.assign(un(`${o} was cancelled`),{cause:i}):i}}function ea(n){let e=n.filter(t=>t.alg===-7);return e.length?e:n}function ta(){return{async create(n,e){let t=n,o=await jo("create",{publicKey:{challenge:Ie(O(t.challenge)),rp:t.rp,user:{...t.user,id:Ie(O(t.user.id))},pubKeyCredParams:ea(t.pubKeyCredParams),excludeCredentials:(t.excludeCredentials??[]).map(s=>({type:s.type,id:Ie(O(s.id))})),authenticatorSelection:t.authenticatorSelection,attestation:"none",timeout:t.timeout}},e?.signal,"passkey creation");if(!o)throw un("passkey creation was cancelled");let r=o.response;return{attestationObject:k(new Uint8Array(r.attestationObject)),clientDataJson:k(new Uint8Array(r.clientDataJSON))}},async get(n,e,t,o){let r=await jo("get",{publicKey:{challenge:Ie(n),rpId:e,userVerification:o?.userVerification??"preferred",allowCredentials:(t??[]).map(a=>({type:"public-key",id:Ie(O(a))}))}},o?.signal,"passkey sign-in");if(!r)throw un("passkey sign-in was cancelled");let s=r.response;return{credentialId:k(new Uint8Array(r.rawId)),authenticatorData:k(new Uint8Array(s.authenticatorData)),clientDataJson:k(new Uint8Array(s.clientDataJSON)),signature:k(new Uint8Array(s.signature))}}}}function na(n,e){return n==="required"||n==="preferred"||n==="discouraged"?n:e}function oa(n){let e=n,t=e?.name,o=typeof e?.message=="string"?e.message:"";return t==="InvalidStateError"||/not focused|already pending/i.test(o)?new Ne(n):t==="NotAllowedError"||t==="AbortError"?new qe(n):n}function Ke(n,e={}){return async t=>{try{return await n.get(O(t.challenge),t.rpId,t.allowCredentials,{userVerification:na(t.userVerification,e.userVerification??"required"),...e.signal?{signal:e.signal}:{}})}catch(o){throw oa(o)}}}var hn={retries:6,baseDelayMs:200,maxDelayMs:2e3};function Ve(n,e){return Math.min(e.baseDelayMs*2**n,e.maxDelayMs)}function ra(n){return n instanceof z&&n.status===413?_e(413,{error:"TOO_LARGE",message:n.message.replace(/^Sealed request refused: /,"")}):n}async function Z(n){let e=await n.text().catch(()=>""),t={};try{t=e?JSON.parse(e):{}}catch{t={message:e}}return _e(n.status,t,n.headers.get("retry-after"))}async function*vo(n){let e=n.getReader(),t=new TextDecoder,o="";for(;;){let{value:r,done:s}=await e.read();if(s)return;o+=t.decode(r,{stream:!0});let a;for(;(a=o.indexOf(`
|
|
2
2
|
|
|
3
3
|
`))>=0;){let i=o.slice(0,a);o=o.slice(a+2);let p="",l="",u="";for(let y of i.split(`
|
|
4
|
-
`))y.startsWith("id:")?p=y.slice(3).trim():y.startsWith("event:")?l=y.slice(6).trim():y.startsWith("data:")&&(u+=y.slice(5).trim());if(!l&&!u)continue;let d=u;try{d=JSON.parse(u)}catch{}yield{id:p,kind:l,data:d}}}}function rn(){return`node:c-${v(crypto.getRandomValues(new Uint8Array(16)))}`}function de(n,e={}){return n.replace(/\{([^}]+)\}/g,(t,o)=>{let r=e[o];if(r===void 0)throw new Error(`no value for path parameter ${o} of ${n}`);return encodeURIComponent(String(r))})}function nn(n){if(!n)return"";let e=new URLSearchParams;for(let[o,r]of Object.entries(n))for(let s of Array.isArray(r)?r:[r])s!=null&&e.append(o,String(s));let t=e.toString();return t?`?${t}`:""}function yo(n){return n==="auth/refresh"||n.startsWith("auth/passkey/")||Is.has(n)}var Is=new Set(["auth/recovery/begin","auth/recovery/start","auth/recovery/finish"]);function Me(n){return n.replace(/^\/+/,"")}var le=class{constructor(e){this.at=0;this.channels=new Map;this.networkFailures=new WeakSet;let t=s=>s.replace(/\/+$/,"");this.nodeUrls=[...new Set([e.baseUrl,...e.nodes??[]].map(t))],this.policy=e.policy,this.retry={...on,...e.retry};let o=e.fetch??((s,a)=>fetch(s,a)),r=async(s,a)=>{try{return await o(s,a)}catch(i){throw i instanceof TypeError&&this.networkFailures.add(i),i}};this.raw=r}isNetworkFailure(e){return e instanceof TypeError&&this.networkFailures.has(e)}useDirectory(e){this.source=e}get nodeUrl(){return this.nodeUrls[this.at]}get nodes(){return[...this.nodeUrls]}useApiKey(e){this.auth=e,this.current=void 0}useSession(e){this.auth=e.sessionToken,this.current=e}signOut(){this.auth=void 0,this.current=void 0}get session(){return this.current}channel(e){let t=this.channels.get(e);return t||(t=It({baseUrl:e,transportPublicKey:()=>Wt(e,this.policy,this.raw),fetch:this.raw}),this.channels.set(e,t)),t}moveOn(e){return this.nodeUrls.length<2?!1:(this.nodeUrl===e&&(this.at=(this.at+1)%this.nodeUrls.length),!0)}failOver(e,t){if(this.nodeUrl!==e&&!t.has(this.nodeUrl))return!0;let o=this.nodeUrls.length;for(let r=1;r<o;r++){let s=(this.at+r)%o;if(!t.has(this.nodeUrls[s]))return this.at=s,this.reread(),!0}return!1}reread(){let e=this.source;!e||e.reading||(e.reading=Zt(e.directory,e.cluster,this.raw).then(t=>{let o=this.nodeUrl,r=en(t.nodes,e.zone,e.random);this.nodeUrls=[o,...r.filter(s=>s!==o)],this.at=0,e.due=Date.now()+t.refreshAfterSeconds*1e3}).catch(()=>{}).finally(()=>{e.reading=void 0}))}async once(e,t,o){let r={};this.auth&&(r.authorization=`Bearer ${this.auth}`);let s;o.bytes?(r["content-type"]=o.contentType??"application/wasm",s=o.bytes):o.body!==void 0&&(r["content-type"]="application/json",s=JSON.stringify(o.body)),this.source&&Date.now()>=this.source.due&&this.reread();let a=this.nodeUrl;try{return await this.channel(a)(`${a}/${t}${nn(o.query)}`,{method:e,headers:r,body:s,signal:o.signal})}catch(i){throw Ds(i)}}async send(e,t,o){let r=await this.answer(e,t,o);if(!r.ok)throw await Z(r);return r}async answer(e,t,o){let r=!1,s=!1;for(;;){let[a,i]=[this.auth,this.nodeUrl],p=await this.once(e,t,o);if(p.ok||p.status!==401&&p.status!==421)return p;let l=await Z(p.clone());if(l instanceof pe&&!s){if(s=!0,this.moveOn(i)&&!yo(t))continue}else if(l instanceof J&&!r&&this.mayRefresh(a,t)){r=!0,await this.renew(a);continue}return p}}mayRefresh(e,t){return e!==void 0&&this.current!==void 0&&!yo(t)}async renew(e){this.auth===e&&await this.refresh()}async read(e,t,o){let s=await(await this.send(e,t,o)).text();return s?JSON.parse(s):{}}async retried(e,t,o,r){let s=await this.answerRetried(e,t,o,r);if(!s.ok)throw await Z(s);let a=await s.text();return a?JSON.parse(a):{}}async answerRetried(e,t,o,r){let s=r?0:this.retry.retries,a=new Set;for(;;){let i,p,l=this.nodeUrl;for(let u=0;;u++){l=this.nodeUrl,a.add(l);try{let y=await this.answer(e,t,o);if(y.status!==503)return y;p=y,i=await Z(y.clone())}catch(y){if(y instanceof TypeError&&this.networkFailures.has(y))p=void 0,i=new W("NETWORK",`the node could not be reached: ${y.message}`,{},void 0,y);else throw y}if(u>=s)break;let d=Ne(u,this.retry);await new Promise(y=>setTimeout(y,Math.max(d,(i.retryAfter??0)*1e3)))}if(r||!this.failOver(l,a)){if(p)return p;throw i}}}exchange(e,t,o={}){let r=Me(t);return o.retry?this.answerRetried(e,r,o,o.retry==="once"):this.answer(e,r,o)}attempt(e,t,o){if(!o.retry)return this.read(e,t,o);let r=o.body?.confirm!==void 0;return this.retried(e,t,o,o.retry==="once"||r)}async confirmed(e,t,o){let{passkey:r}=o;try{return await this.attempt(e,t,o)}catch(s){if(!(s instanceof be)||!r)throw s;let a=s.details,i=await qe(r,{userVerification:o.userVerification,signal:o.promptSignal??o.signal})(a,{request:new Request(`${this.nodeUrl}/${t}`,{method:e})}),p={...o.body,confirm:{challengeId:a.challengeId,assertion:i}};return this.attempt(e,t,{...o,body:p})}}request(e,t,o={}){return this.send(e,Me(t),o)}json(e,t,o={}){return this.confirmed(e,Me(t),o)}async*events(e,t={}){let o=await this.send("GET",Me(e),t);if(!o.body)throw new g(o.status,"EVENTS","the event stream has no body");yield*ho(o.body)}async unsealed(e,t={}){let o=await this.inTheClear(e,t);if(!o.ok)throw await Z(o);return o}inTheClear(e,t={}){return this.raw(`${this.nodeUrl}/${Me(e)}${nn(t.query)}`,{signal:t.signal})}refresh(){if(!this.refreshing){let e=this.exchangeRefresh();this.refreshing=e;let t=()=>{this.refreshing===e&&(this.refreshing=void 0)};e.then(t,t)}return this.refreshing}async exchangeRefresh(){let e=this.current;if(!e)throw new Error("no session to refresh");let t;for(let o=1;t===void 0;o++)try{t=await this.json("POST","auth/refresh",{body:{refreshToken:e.refreshToken}})}catch(r){if(!(r instanceof pe)||o>=this.nodeUrls.length)throw r}return this.current===e&&this.useSession(t),t}};async function sn(n){let e=n.random??Math.random,t=n.fetch??((i,p)=>fetch(i,p)),o=await Zt(n.directory,n.cluster,t),[r,...s]=en(o.nodes,n.zone,e),a=new le({baseUrl:r,nodes:s,policy:n.policy,fetch:n.fetch,retry:n.retry});return a.useDirectory({directory:n.directory,cluster:n.cluster,zone:n.zone,random:e,due:Date.now()+o.refreshAfterSeconds*1e3}),a}var Ls=/\{[^{}]+\}/g,Ks=()=>typeof process=="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici;function Vs(){return Math.random().toString(36).slice(2,11)}function wo(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:o=globalThis.fetch,querySerializer:r,bodySerializer:s,pathSerializer:a,headers:i,requestInitExt:p=void 0,...l}={...n};p=Ks()?p:void 0,e=go(e);let u=[];async function d(y,h){let{baseUrl:f,fetch:P=o,Request:j=t,headers:E,params:x={},parseAs:S="json",querySerializer:H,bodySerializer:ye=s??Gs,pathSerializer:U,body:L,middleware:oe=[],...G}=h||{},N=e;f&&(N=go(f)??e);let re=typeof r=="function"?r:fo(r);H&&(re=typeof H=="function"?H:fo({...typeof r=="object"?r:{},...H}));let Qe=U||a||Hs,D=L===void 0?void 0:ye(L,mo(i,E,x.header)),Re=mo(D===void 0||D instanceof FormData?{}:{"Content-Type":"application/json"},i,E,x.header),$=[...u,...oe],Tr={redirect:"follow",...l,...G,body:D,headers:Re},ze,Ye,F=new j($s(y,{baseUrl:N,params:x,querySerializer:re,pathSerializer:Qe}),Tr),k;for(let T in G)T in F||(F[T]=G[T]);if($.length){ze=Vs(),Ye=Object.freeze({baseUrl:N,fetch:P,parseAs:S,querySerializer:re,bodySerializer:ye,pathSerializer:Qe});for(let T of $)if(T&&typeof T=="object"&&typeof T.onRequest=="function"){let R=await T.onRequest({request:F,schemaPath:y,params:x,options:Ye,id:ze});if(R)if(R instanceof j)F=R;else if(R instanceof Response){k=R;break}else throw new Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!k){try{k=await P(F,p)}catch(T){let R=T;if($.length)for(let se=$.length-1;se>=0;se--){let Je=$[se];if(Je&&typeof Je=="object"&&typeof Je.onError=="function"){let Ee=await Je.onError({request:F,error:R,schemaPath:y,params:x,options:Ye,id:ze});if(Ee){if(Ee instanceof Response){R=void 0,k=Ee;break}if(Ee instanceof Error){R=Ee;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(R)throw R}if($.length)for(let T=$.length-1;T>=0;T--){let R=$[T];if(R&&typeof R=="object"&&typeof R.onResponse=="function"){let se=await R.onResponse({request:F,response:k,schemaPath:y,params:x,options:Ye,id:ze});if(se){if(!(se instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");k=se}}}}let Mn=k.headers.get("Content-Length");if(k.status===204||F.method==="HEAD"||Mn==="0"&&!k.headers.get("Transfer-Encoding")?.includes("chunked"))return k.ok?{data:void 0,response:k}:{error:void 0,response:k};if(k.ok)return{data:await(async()=>{if(S==="stream")return k.body;if(S==="json"&&!Mn){let R=await k.text();return R?JSON.parse(R):void 0}return await k[S]()})(),response:k};let Ct=await k.text();try{Ct=JSON.parse(Ct)}catch{}return{error:Ct,response:k}}return{request(y,h,f){return d(h,{...f,method:y.toUpperCase()})},GET(y,h){return d(y,{...h,method:"GET"})},PUT(y,h){return d(y,{...h,method:"PUT"})},POST(y,h){return d(y,{...h,method:"POST"})},DELETE(y,h){return d(y,{...h,method:"DELETE"})},OPTIONS(y,h){return d(y,{...h,method:"OPTIONS"})},HEAD(y,h){return d(y,{...h,method:"HEAD"})},PATCH(y,h){return d(y,{...h,method:"PATCH"})},TRACE(y,h){return d(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()`");u.push(h)}},eject(...y){for(let h of y){let f=u.indexOf(h);f!==-1&&u.splice(f,1)}}}}function bt(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 bo(n,e,t){if(!e||typeof e!="object")return"";let o=[],r={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(let i in e)o.push(i,t.allowReserved===!0?e[i]:encodeURIComponent(e[i]));let a=o.join(",");switch(t.style){case"form":return`${n}=${a}`;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return a}}for(let a in e){let i=t.style==="deepObject"?`${n}[${a}]`:a;o.push(bt(i,e[a],t))}let s=o.join(r);return t.style==="label"||t.style==="matrix"?`${r}${s}`:s}function Po(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){let s={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",a=(t.allowReserved===!0?e:e.map(i=>encodeURIComponent(i))).join(s);switch(t.style){case"simple":return a;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return`${n}=${a}`}}let o={simple:",",label:".",matrix:";"}[t.style]||"&",r=[];for(let s of e)t.style==="simple"||t.style==="label"?r.push(t.allowReserved===!0?s:encodeURIComponent(s)):r.push(bt(n,s,t));return t.style==="label"||t.style==="matrix"?`${o}${r.join(o)}`:r.join(o)}function fo(n){return function(t){let o=[];if(t&&typeof t=="object")for(let r in t){let s=t[r];if(s!=null){if(Array.isArray(s)){if(s.length===0)continue;o.push(Po(r,s,{style:"form",explode:!0,...n?.array,allowReserved:n?.allowReserved||!1}));continue}if(typeof s=="object"){o.push(bo(r,s,{style:"deepObject",explode:!0,...n?.object,allowReserved:n?.allowReserved||!1}));continue}o.push(bt(r,s,n))}}return o.join("&")}}function Hs(n,e){let t=n;for(let o of n.match(Ls)??[]){let r=o.substring(1,o.length-1),s=!1,a="simple";if(r.endsWith("*")&&(s=!0,r=r.substring(0,r.length-1)),r.startsWith(".")?(a="label",r=r.substring(1)):r.startsWith(";")&&(a="matrix",r=r.substring(1)),!e||e[r]===void 0||e[r]===null)continue;let i=e[r];if(Array.isArray(i)){t=t.replace(o,Po(r,i,{style:a,explode:s}));continue}if(typeof i=="object"){t=t.replace(o,bo(r,i,{style:a,explode:s}));continue}if(a==="matrix"){t=t.replace(o,`;${bt(r,i)}`);continue}t=t.replace(o,a==="label"?`.${encodeURIComponent(i)}`:encodeURIComponent(i))}return t}function Gs(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 $s(n,e){let t=`${e.baseUrl}${n}`;e.params?.path&&(t=e.pathSerializer(t,e.params.path));let o=e.querySerializer(e.params.query??{});return o.startsWith("?")&&(o=o.substring(1)),o&&(t+=`?${o}`),t}function mo(...n){let e=new Headers;for(let t of n){if(!t||typeof t!="object")continue;let o=t instanceof Headers?t.entries():Object.entries(t);for(let[r,s]of o)if(s===null)e.delete(r);else if(Array.isArray(s))for(let a of s)e.append(r,a);else s!==void 0&&e.set(r,s)}return e}function go(n){return n.endsWith("/")?n.substring(0,n.length-1):n}function _o(n,e,t){let o=new Map;return{onRequest({request:r,id:s}){let a=r.headers.get("content-type");(a===null||a.startsWith("application/json"))&&r.method!=="GET"&&r.method!=="HEAD"&&o.set(s,r.clone())},async onResponse({response:r,id:s,options:a}){let i=o.get(s);if(o.delete(s),r.status!==n||!i)return;let p=await r.clone().json().catch(()=>{});if(p?.error!==e)return;let l=await t(p.details??{},i),u=await i.text(),d=u?JSON.parse(u):{},y=new Headers(i.headers);y.set("content-type","application/json");let h=new Request(i.url,{method:i.method,headers:y,body:JSON.stringify({...d,...l}),signal:i.signal});return a.fetch(h)},onError({id:r}){o.delete(r)}}}function Pt(n){return _o(412,"CONFIRM_REQUIRED",async(e,t)=>({confirm:{challengeId:e.challengeId,assertion:await n(e,{request:t})}}))}function _t(n){return _o(428,"OPERATOR_SIGNATURE_REQUIRED",async(e,t)=>({operatorProof:await n(e,{request:t})}))}async function c(n,e,t,o={}){let r=t??{},s={},a={},i={};for(let[d,y]of Object.entries(r))e.pathParams.includes(d)?s[d]=y:e.queryWhole&&d==="query"?Object.assign(a,y):!e.queryWhole&&e.query.includes(d)?a[d]=y:i[d]=y;for(let d of e.pathParams)if(s[d]===void 0)throw new TypeError(`${e.method} ${e.path}: no value for ${d}`);let p={params:{path:s,query:a}};e.body==="fields"?Object.values(i).every(y=>y===void 0)&&e.optionalBody||(p.body=i):e.body==="whole"?(i.body!==void 0||!e.optionalBody)&&(p.body=i.body):e.body==="raw"&&(p.body=i.body,p.bodySerializer=d=>d,p.headers={"Content-Type":i.contentType??e.media??"application/octet-stream"}),e.reply==="bytes"?p.parseAs="blob":e.reply==="text"&&(p.parseAs="text");let l=[];if(o.confirm){let d=o.confirm,y=e.userVerification?(h,f)=>d({userVerification:e.userVerification,...h},f):d;l.push(Pt(y))}o.operatorProof&&l.push(_t(o.operatorProof)),l.length&&(p.middleware=l),o.signal&&(p.signal=o.signal);let u=n.request;return Ao(u(e.method.toLowerCase(),e.path,p))}function an(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:[],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),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),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),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 pn=[{method:"POST",path:"/apps/{app}/intents",requires:"idempotencyKey"},{method:"POST",path:"/apps/{app}/methods/{method}",requires:"idempotencyKey"},{method:"POST",path:"/apps/{app}/views"}];var ko="https://calimero-node.invalid",Fs=new Set(["attestation","health"]),Qs=pn.map(n=>({method:n.method,pattern:new RegExp(`^${n.path.replace(/^\//,"").replace(/\{[^}]+\}/g,"[^/]+")}$`)})),zs=new Set(pn.filter(n=>n.requires==="idempotencyKey").map(n=>`${n.method} ${n.path}`));function Ys(n){return async e=>{if(!e.url.startsWith(`${ko}/`))throw new Error(`not a route of the generated client: ${e.url}`);let t=new URL(e.url),o=t.pathname.replace(/^\/+/,""),r={};for(let[u,d]of t.searchParams)(r[u]??(r[u]=[])).push(d);let s=e.method;if(s==="GET"&&Fs.has(o)&&n.inTheClear)return n.inTheClear(o,{query:r,signal:e.signal});let a=e.headers.get("content-type")??void 0,i=s==="GET"?void 0:new Uint8Array(await e.arrayBuffer()),p=i&&i.length>0?i:void 0,l=!1;return Qs.some(u=>u.method===s&&u.pattern.test(o))&&(l=(p?JSON.parse(new TextDecoder().decode(p)):{}).confirm===void 0?!0:"once"),n.exchange(s,o,{query:r,...p?{bytes:p,contentType:a??"application/octet-stream"}:{},retry:l,signal:e.signal})}}var Js={async onRequest({request:n,schemaPath:e}){if(!zs.has(`${n.method} ${e}`))return;let t=await n.clone().text(),o=t?JSON.parse(t):{};if(o.idempotencyKey===void 0)return new Request(n,{body:JSON.stringify({...o,idempotencyKey:rn()})})}};function cn(n,e={}){let t=wo({baseUrl:ko,fetch:Ys(n)});return t.use(Js),e.confirm&&t.use(Pt(e.confirm)),e.operatorProof&&t.use(_t(e.operatorProof)),t}async function Ao(n){let{data:e,error:t,response:o}=await n;if(!o.ok)throw Ws(o,t);return e??{}}function Ws(n,e){let t=typeof e=="string"?e?{message:e}:{}:e;return Pe(n.status,t,n.headers.get("retry-after"))}var Xs=n=>n/2**32|0,Zs=n=>n>>>0;function Ro(n,e,t,o){let r=Xs(t),s=Zs(t);n.setUint32(e,o?s:r,o),n.setUint32(e+4,o?r:s,o)}function Eo(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}var ln=n=>n?`"${n}" `:"";function ea(n,e=""){if(typeof n!="number")throw new TypeError(ln(e)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(ln(e)+"expected integer >= 0, got "+n);return n}function dn(n,e,t=""){if(Eo(n)&&(e===void 0||n.length===e))return n;e!==void 0&&ea(e,"length");let o=Eo(n),r=e!==void 0?` of length ${e}`:"",s=o?`length=${n.length}`:`type=${typeof n}`,a=ln(t)+"expected Uint8Array"+r+", got "+s;throw o?new RangeError(a):new TypeError(a)}var ta=(n,e)=>{if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof n)},xo=(n,e)=>{ta(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 un(n,e=!0){if(n.destroyed)throw new Error("hash was destroyed");if(e&&n.finished)throw new Error("digest() was already called")}function To(n,e){dn(n,void 0,"output");let t=e.outputLen;if(!(n.length>=t))throw new RangeError('"output" expected length >= '+t)}function yn(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function At(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function M(n,e){return n<<32-e|n>>>e}function na(n,e,t="opts"){return xo(n,"defaults"),e!==void 0&&xo(e,t),Object.assign(Object.create(null),n,e)}function jo(n,e={}){if(typeof n!="function")throw new TypeError('"hashCons" expected function, got type='+typeof n);e=na({},e,"info");let t=(r,s)=>n(s).update(r).digest(),o=n(void 0);return t.outputLen=o.outputLen,t.blockLen=o.blockLen,t.canXOF=o.canXOF,t.create=r=>n(r),Object.assign(t,e),Object.freeze(t)}var Oo=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function vo(n,e,t){return n&e^~n&t}function So(n,e,t){return n&e^n&t^e&t}var kt=class{constructor(e,t,o,r){A(this,"blockLen");A(this,"outputLen");A(this,"canXOF",!1);A(this,"padOffset");A(this,"isLE");A(this,"buffer");A(this,"view");A(this,"finished",!1);A(this,"length",0);A(this,"pos",0);A(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=o,this.isLE=r,this.buffer=new Uint8Array(e),this.view=At(this.buffer)}update(e){un(this),dn(e);let{view:t,buffer:o,blockLen:r}=this,s=e.length,a=!1;for(let i=0;i<s;){let p=Math.min(r-this.pos,s-i);if(p===r){let l=At(e);for(;r<=s-i;i+=r)this.process(l,i);a=!0;continue}o.set(i===0&&p===s?e:e.subarray(i,i+p),this.pos),this.pos+=p,i+=p,this.pos===r&&(this.process(t,0),this.pos=0,a=!0)}return this.length+=e.length,a&&this.roundClean(),this}digestInto(e){un(this),To(e,this),this.finished=!0;let{buffer:t,view:o,blockLen:r,isLE:s}=this,{pos:a}=this;t[a++]=128,t.fill(0,a),this.padOffset>r-a&&(this.process(o,0),t.fill(0)),Ro(o,r-8,this.length*8,s),this.process(o,0),this.roundClean();let i=e===t?o:At(e),p=this.outputLen,l=p/4,u=this.get();if(p%4||l>u.length)throw new Error("invalid outputLen");for(let d=0;d<l;d++)i.setUint32(4*d,u[d],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let o=e.slice(0,t);return this.destroy(),o}_cloneIntoMeta(e){let{buffer:t,length:o,finished:r,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=r,e.length=o,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}},Uo=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var oa=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]),ee=new Uint32Array(64),hn=class extends kt{constructor(t,o){super(64,t,8,!1);A(this,"A",0);A(this,"B",0);A(this,"C",0);A(this,"D",0);A(this,"E",0);A(this,"F",0);A(this,"G",0);A(this,"H",0);this.A=o[0]|0,this.B=o[1]|0,this.C=o[2]|0,this.D=o[3]|0,this.E=o[4]|0,this.F=o[5]|0,this.G=o[6]|0,this.H=o[7]|0}get(){let{A:t,B:o,C:r,D:s,E:a,F:i,G:p,H:l}=this;return[t,o,r,s,a,i,p,l]}set(t,o,r,s,a,i,p,l){this.A=t|0,this.B=o|0,this.C=r|0,this.D=s|0,this.E=a|0,this.F=i|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,o){for(let y=0;y<16;y++,o+=4)ee[y]=t.getUint32(o,!1);for(let y=16;y<64;y++){let h=ee[y-15],f=ee[y-2],P=M(h,7)^M(h,18)^h>>>3,j=M(f,17)^M(f,19)^f>>>10;ee[y]=j+ee[y-7]+P+ee[y-16]|0}let{A:r,B:s,C:a,D:i,E:p,F:l,G:u,H:d}=this;for(let y=0;y<64;y++){let h=M(p,6)^M(p,11)^M(p,25),f=d+h+vo(p,l,u)+oa[y]+ee[y]|0,j=(M(r,2)^M(r,13)^M(r,22))+So(r,s,a)|0;d=u,u=l,l=p,p=i+f|0,i=a,a=s,s=r,r=f+j|0}r=r+this.A|0,s=s+this.B|0,a=a+this.C|0,i=i+this.D|0,p=p+this.E|0,l=l+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(r,s,a,i,p,l,u,d)}roundClean(){yn(ee)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),yn(this.buffer)}},fn=class extends hn{constructor(){super(32,Uo)}};var Co=jo(()=>new fn,Oo(1));var ra=64*1024,qo=16,Rt=ra+qo,Tt=256*Rt,Et=12,De=new TextEncoder,sa=De.encode("calimero.file.v1"),aa=De.encode("calimero.file.segments.v1\0"),ia=De.encode("calimero.export-wrap.v1"),pa=De.encode("calimero.sealed.derive.v1\0"),b=class extends Error{constructor(t,o){super(o);this.code=t;this.name="ExportError"}},Mo=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",n));function No(n){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n.length,!1),Mo(m(aa,e,...n))}function Bo(n){let e=De.encode(n),t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e.length,!1),m(t,e)}async function Do(n,e,t,o){if(o.length<Et)throw new b("TAMPERED","the wrapped key is truncated");let r=await K(n.privateKey,e);if(r.every(u=>u===0))throw new b("BAD_ANSWER","the ephemeral key is of low order");let s=m(e,n.publicKey,Bo(t.appId),Bo(t.fileId)),a=await crypto.subtle.importKey("raw",r,"HKDF",!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:ia,info:m(pa,s)},a,256),p=await crypto.subtle.importKey("raw",i,"AES-GCM",!1,["decrypt"]),l;try{l=await crypto.subtle.decrypt({name:"AES-GCM",iv:o.subarray(0,Et)},p,o.subarray(Et))}catch{throw new b("TAMPERED","the wrapped key does not open")}if(l.byteLength!==32)throw new b("TAMPERED","the wrapped key has the wrong length");return new Uint8Array(l)}var xt=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=Co.create()}static async create(e,t){let o=await crypto.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]);return new n(o,t.map(w))}async push(e,t){let o=this.segments[this.next];if(o===void 0)throw new b("TAMPERED",`the file has no segment ${this.next}`);if(this.next+1<this.segments.length&&e.length!==Tt)throw new b("TAMPERED",`segment ${this.next} is not a whole segment`);if(w(await Mo(e))!==o)throw new b("TAMPERED",`segment ${this.next} is not the one the file lists`);this.next+=1;let r=m(this.pending,e),s=0;for(;r.length-s>Rt;)await t(await this.open(r.subarray(s,s+Rt),!1)),s+=Rt;this.pending=r.slice(s)}async finishExpecting(e,t){if(this.next!==this.segments.length)throw new b("TAMPERED","the file is missing segments");if(this.pending.length<qo)throw new b("TAMPERED","the file is truncated");let o=await this.open(this.pending,!0);if(this.size!==e||w(this.hash.digest())!==t)throw new b("TAMPERED","the file is not the one that was sealed");return o}async open(e,t){let o=new Uint8Array(Et);new DataView(o.buffer).setBigUint64(4,BigInt(this.index),!1);let r;try{r=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:o,additionalData:m(sa,new Uint8Array([t?1:0]))},this.key,e))}catch{throw new b("TAMPERED",`chunk ${this.index} does not open: the file is altered, truncated or under another key`)}return this.hash.update(r),this.size+=r.length,this.index+=1,r}};function Ie(n,e,t){if(typeof n!="string")throw new b("BAD_ANSWER",`the node answered a bad ${e}`);try{return t===void 0?Nn(n,e):C(n,e,t)}catch{throw new b("BAD_ANSWER",`the node answered a bad ${e}`)}}function ca(n){let e=n;if(typeof e!="object"||e===null)throw new b("BAD_ANSWER","the node answered a bad export");if(typeof e.app!="string")throw new b("BAD_ANSWER","the node answered a bad app");if(typeof e.size!="number"||!Number.isSafeInteger(e.size)||e.size<0)throw new b("BAD_ANSWER","the node answered a bad size");if(!Array.isArray(e.segments))throw new b("BAD_ANSWER","the node answered a bad segment list");return{app:e.app,size:e.size,named:Ie(e.id,"file id",32),segments:e.segments.map(t=>Ie(t,"segment hash",32)),sha256:w(Ie(e.sha256,"sha256",32)),ephemeral:Ie(e.ephemeral,"ephemeral key",32),wrapped:Ie(e.wrapped,"wrapped key")}}var mn=()=>new b("ABORTED","the export was aborted");async function la(n,e){let t=Number(n.headers.get("content-length"));if(Number.isFinite(t)&&t>Tt)throw await n.body?.cancel(),new b("TOO_LARGE","a segment is longer than a whole segment");if(!n.body)return new Uint8Array;let o=n.body.getReader(),r=()=>{o.cancel()};e?.addEventListener("abort",r);let s=[],a=0;try{for(;;){let{done:i,value:p}=await o.read();if(i)break;if(a+=p.length,a>Tt)throw await o.cancel(),new b("TOO_LARGE","a segment is longer than a whole segment");s.push(p)}}finally{e?.removeEventListener("abort",r)}if(e?.aborted)throw mn();return m(...s)}async function gn(n,e,t,o,r,s){try{return await da(n,e,t,o,r,s)}catch(a){throw r?.aborted&&!(a instanceof b)?mn():a}}async function da(n,e,t,o,r,s){let a=await q(s),i=ca(await n.json("POST",de("apps/{app}/files/{id}/export",{app:e,id:t}),{body:{recipient:w(a.publicKey)},signal:r})),{segments:p,named:l}=i;if(p.length===0||w(await No(p))!==w(l)||w(l)!==t)throw new b("NOT_THE_FILE",`the node answered segments that are not the file ${t}`);let u=await Do(a,i.ephemeral,{appId:i.app,fileId:t},i.wrapped),d=await xt.create(u,p);for(let h=0;h<p.length;h+=1){if(r?.aborted)throw mn();let f=await n.request("GET",de("apps/{app}/files/{id}/segments/{k}",{app:e,id:t,k:h}),{signal:r});await d.push(await la(f,r),P=>o.write(P))}let y=await d.finishExpecting(i.size,i.sha256);return y.length>0&&await o.write(y),{size:i.size,sha256:i.sha256}}async function Io(n,e,t,o){let r=[];return await gn(n,e,t,{write:s=>{r.push(s)}},o),m(...r)}var Lo="calimero.org-recovery.v1\0",bn=64,wn=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function ua(){return crypto.getRandomValues(new Uint8Array(32))}function ya(n){Vo(n);let e=Array.from(n,o=>o.toString(16).padStart(2,"0")).join(""),t=[];for(let o=0;o<e.length;o+=8)t.push(e.slice(o,o+8));return t.join("-")}function ha(n){let e=n.replace(/[-\s]/g,"");if(!/^[0-9a-fA-F]{64}$/.test(e))throw new Error("a recovery seed is 64 hex digits");return Uint8Array.from({length:32},(t,o)=>parseInt(e.slice(2*o,2*o+2),16))}function Ko(n,e,t){return new TextEncoder().encode(`${Lo}${n}\0${e}\0${t}`)}async function fa(n){let e=await Ho(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 Pn(n,e,t,o){let r=new TextEncoder().encode(o).length;if(r===0||r>bn)throw new Error(`a recovery nonce is 1 to ${bn} bytes`);let s=await Ho(n,!1),a=await crypto.subtle.sign("Ed25519",s,Go(Ko(e,t,o)));return v(new Uint8Array(a))}function Vo(n){if(n.length!==32)throw new Error("a recovery seed is 32 bytes")}function Ho(n,e){Vo(n);let t=new Uint8Array(wn.length+32);return t.set(wn),t.set(n,wn.length),crypto.subtle.importKey("pkcs8",Go(t),{name:"Ed25519"},e,["sign"])}var Go=n=>n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);var _n=100;function An(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>_n)throw new RangeError(`limit is 1 to ${_n}`);e.set("limit",String(n.limit))}let t=e.toString();return t?`?${t}`:""}function Le(n,e){try{return ve(n,e)}catch{return n<e?-1:n>e?1:0}}function $o(n,e,t=Date.now()/1e3){if(n===null||n.length===0)return null;let o=n.reduce((s,a)=>Le(s,a)>=0?s:a),r=null;for(let s of e)s.afterSecs<=t&&Le(o,s.version)<0&&(r===null||Le(s.version,r.version)>0)&&(r=s);return r}function Fo(n,e,t,o){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:")&&(u+=y.slice(5).trim());if(!l&&!u)continue;let d=u;try{d=JSON.parse(u)}catch{}yield{id:p,kind:l,data:d}}}}function fn(){return`node:c-${k(crypto.getRandomValues(new Uint8Array(16)))}`}function ue(n,e={}){return n.replace(/\{([^}]+)\}/g,(t,o)=>{let r=e[o];if(r===void 0)throw new Error(`no value for path parameter ${o} of ${n}`);return encodeURIComponent(String(r))})}function yn(n){if(!n)return"";let e=new URLSearchParams;for(let[o,r]of Object.entries(n))for(let s of Array.isArray(r)?r:[r])s!=null&&e.append(o,String(s));let t=e.toString();return t?`?${t}`:""}function Oo(n){return n==="auth/refresh"||n.startsWith("auth/passkey/")||sa.has(n)}var sa=new Set(["auth/recovery/begin","auth/recovery/start","auth/recovery/finish"]);function Le(n){return n.replace(/^\/+/,"")}var de=class{constructor(e){this.at=0;this.channels=new Map;this.networkFailures=new WeakSet;let t=s=>s.replace(/\/+$/,"");this.nodeUrls=[...new Set([e.baseUrl,...e.nodes??[]].map(t))],this.policy=e.policy,this.retry={...hn,...e.retry};let o=e.fetch??((s,a)=>fetch(s,a)),r=async(s,a)=>{try{return await o(s,a)}catch(i){throw i instanceof TypeError&&this.networkFailures.add(i),i}};this.raw=r}isNetworkFailure(e){return e instanceof TypeError&&this.networkFailures.has(e)}useDirectory(e){this.source=e}get nodeUrl(){return this.nodeUrls[this.at]}get nodes(){return[...this.nodeUrls]}useApiKey(e){this.auth=e,this.current=void 0}useSession(e){this.auth=e.sessionToken,this.current=e}signOut(){this.auth=void 0,this.current=void 0}get session(){return this.current}channel(e){let t=this.channels.get(e);return t||(t=Jt({baseUrl:e,transportPublicKey:()=>pn(e,this.policy,this.raw),fetch:this.raw}),this.channels.set(e,t)),t}moveOn(e){return this.nodeUrls.length<2?!1:(this.nodeUrl===e&&(this.at=(this.at+1)%this.nodeUrls.length),!0)}failOver(e,t){if(this.nodeUrl!==e&&!t.has(this.nodeUrl))return!0;let o=this.nodeUrls.length;for(let r=1;r<o;r++){let s=(this.at+r)%o;if(!t.has(this.nodeUrls[s]))return this.at=s,this.reread(),!0}return!1}reread(){let e=this.source;!e||e.reading||(e.reading=ln(e.directory,e.cluster,this.raw).then(t=>{let o=this.nodeUrl,r=dn(t.nodes,e.zone,e.random);this.nodeUrls=[o,...r.filter(s=>s!==o)],this.at=0,e.due=Date.now()+t.refreshAfterSeconds*1e3}).catch(()=>{}).finally(()=>{e.reading=void 0}))}async once(e,t,o){let r={};this.auth&&(r.authorization=`Bearer ${this.auth}`);let s;o.bytes?(r["content-type"]=o.contentType??"application/wasm",s=o.bytes):o.body!==void 0&&(r["content-type"]="application/json",s=JSON.stringify(o.body)),this.source&&Date.now()>=this.source.due&&this.reread();let a=this.nodeUrl;try{return await this.channel(a)(`${a}/${t}${yn(o.query)}`,{method:e,headers:r,body:s,signal:o.signal})}catch(i){throw ra(i)}}async send(e,t,o){let r=await this.answer(e,t,o);if(!r.ok)throw await Z(r);return r}async answer(e,t,o){let r=!1,s=!1;for(;;){let[a,i]=[this.auth,this.nodeUrl],p=await this.once(e,t,o);if(p.ok||p.status!==401&&p.status!==421)return p;let l=await Z(p.clone());if(l instanceof ce&&!s){if(s=!0,this.moveOn(i)&&!Oo(t))continue}else if(l instanceof W&&!r&&this.mayRefresh(a,t)){r=!0,await this.renew(a);continue}return p}}mayRefresh(e,t){return e!==void 0&&this.current!==void 0&&!Oo(t)}async renew(e){this.auth===e&&await this.refresh()}async read(e,t,o){let s=await(await this.send(e,t,o)).text();return s?JSON.parse(s):{}}async retried(e,t,o,r){let s=await this.answerRetried(e,t,o,r);if(!s.ok)throw await Z(s);let a=await s.text();return a?JSON.parse(a):{}}async answerRetried(e,t,o,r){let s=r?0:this.retry.retries,a=new Set;for(;;){let i,p,l=this.nodeUrl;for(let u=0;;u++){l=this.nodeUrl,a.add(l);try{let y=await this.answer(e,t,o);if(y.status!==503)return y;p=y,i=await Z(y.clone())}catch(y){if(y instanceof TypeError&&this.networkFailures.has(y))p=void 0,i=new X("NETWORK",`the node could not be reached: ${y.message}`,{},void 0,y);else throw y}if(u>=s)break;let d=Ve(u,this.retry);await new Promise(y=>setTimeout(y,Math.max(d,(i.retryAfter??0)*1e3)))}if(r||!this.failOver(l,a)){if(p)return p;throw i}}}exchange(e,t,o={}){let r=Le(t);return o.retry?this.answerRetried(e,r,o,o.retry==="once"):this.answer(e,r,o)}attempt(e,t,o){if(!o.retry)return this.read(e,t,o);let r=o.body?.confirm!==void 0;return this.retried(e,t,o,o.retry==="once"||r)}async confirmed(e,t,o){let{passkey:r}=o;try{return await this.attempt(e,t,o)}catch(s){if(!(s instanceof Pe)||!r)throw s;let a=s.details,i=await Ke(r,{userVerification:o.userVerification,signal:o.promptSignal??o.signal})(a,{request:new Request(`${this.nodeUrl}/${t}`,{method:e})}),p={...o.body,confirm:{challengeId:a.challengeId,assertion:i}};return this.attempt(e,t,{...o,body:p})}}request(e,t,o={}){return this.send(e,Le(t),o)}json(e,t,o={}){return this.confirmed(e,Le(t),o)}async*events(e,t={}){let o=await this.send("GET",Le(e),t);if(!o.body)throw new g(o.status,"EVENTS","the event stream has no body");yield*vo(o.body)}async unsealed(e,t={}){let o=await this.inTheClear(e,t);if(!o.ok)throw await Z(o);return o}inTheClear(e,t={}){return this.raw(`${this.nodeUrl}/${Le(e)}${yn(t.query)}`,{signal:t.signal})}refresh(){if(!this.refreshing){let e=this.exchangeRefresh();this.refreshing=e;let t=()=>{this.refreshing===e&&(this.refreshing=void 0)};e.then(t,t)}return this.refreshing}async exchangeRefresh(){let e=this.current;if(!e)throw new Error("no session to refresh");let t;for(let o=1;t===void 0;o++)try{t=await this.json("POST","auth/refresh",{body:{refreshToken:e.refreshToken}})}catch(r){if(!(r instanceof ce)||o>=this.nodeUrls.length)throw r}return this.current===e&&this.useSession(t),t}};async function mn(n){let e=n.random??Math.random,t=n.fetch??((i,p)=>fetch(i,p)),o=await ln(n.directory,n.cluster,t),[r,...s]=dn(o.nodes,n.zone,e),a=new de({baseUrl:r,nodes:s,policy:n.policy,fetch:n.fetch,retry:n.retry});return a.useDirectory({directory:n.directory,cluster:n.cluster,zone:n.zone,random:e,due:Date.now()+o.refreshAfterSeconds*1e3}),a}var aa=/\{[^{}]+\}/g,ia=()=>typeof process=="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici;function pa(){return Math.random().toString(36).slice(2,11)}function Bo(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:o=globalThis.fetch,querySerializer:r,bodySerializer:s,pathSerializer:a,headers:i,requestInitExt:p=void 0,...l}={...n};p=ia()?p:void 0,e=Co(e);let u=[];async function d(y,h){let{baseUrl:f,fetch:P=o,Request:v=t,headers:x,params:T={},parseAs:U="json",querySerializer:G,bodySerializer:he=s??la,pathSerializer:C,body:L,middleware:re=[],...H}=h||{},D=e;f&&(D=Co(f)??e);let se=typeof r=="function"?r:So(r);G&&(se=typeof G=="function"?G:So({...typeof r=="object"?r:{},...G}));let et=C||a||ca,I=L===void 0?void 0:he(L,Uo(i,x,T.header)),Oe=Uo(I===void 0||I instanceof FormData?{}:{"Content-Type":"application/json"},i,x,T.header),F=[...u,...re],Qr={redirect:"follow",...l,...H,body:I,headers:Oe},tt,nt,Q=new v(da(y,{baseUrl:D,params:T,querySerializer:se,pathSerializer:et}),Qr),E;for(let j in H)j in Q||(Q[j]=H[j]);if(F.length){tt=pa(),nt=Object.freeze({baseUrl:D,fetch:P,parseAs:U,querySerializer:se,bodySerializer:he,pathSerializer:et});for(let j of F)if(j&&typeof j=="object"&&typeof j.onRequest=="function"){let R=await j.onRequest({request:Q,schemaPath:y,params:T,options:nt,id:tt});if(R)if(R instanceof v)Q=R;else if(R instanceof Response){E=R;break}else throw new Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!E){try{E=await P(Q,p)}catch(j){let R=j;if(F.length)for(let ae=F.length-1;ae>=0;ae--){let ot=F[ae];if(ot&&typeof ot=="object"&&typeof ot.onError=="function"){let ve=await ot.onError({request:Q,error:R,schemaPath:y,params:T,options:nt,id:tt});if(ve){if(ve instanceof Response){R=void 0,E=ve;break}if(ve instanceof Error){R=ve;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(R)throw R}if(F.length)for(let j=F.length-1;j>=0;j--){let R=F[j];if(R&&typeof R=="object"&&typeof R.onResponse=="function"){let ae=await R.onResponse({request:Q,response:E,schemaPath:y,params:T,options:nt,id:tt});if(ae){if(!(ae instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");E=ae}}}}let Xn=E.headers.get("Content-Length");if(E.status===204||Q.method==="HEAD"||Xn==="0"&&!E.headers.get("Transfer-Encoding")?.includes("chunked"))return E.ok?{data:void 0,response:E}:{error:void 0,response:E};if(E.ok)return{data:await(async()=>{if(U==="stream")return E.body;if(U==="json"&&!Xn){let R=await E.text();return R?JSON.parse(R):void 0}return await E[U]()})(),response:E};let $t=await E.text();try{$t=JSON.parse($t)}catch{}return{error:$t,response:E}}return{request(y,h,f){return d(h,{...f,method:y.toUpperCase()})},GET(y,h){return d(y,{...h,method:"GET"})},PUT(y,h){return d(y,{...h,method:"PUT"})},POST(y,h){return d(y,{...h,method:"POST"})},DELETE(y,h){return d(y,{...h,method:"DELETE"})},OPTIONS(y,h){return d(y,{...h,method:"OPTIONS"})},HEAD(y,h){return d(y,{...h,method:"HEAD"})},PATCH(y,h){return d(y,{...h,method:"PATCH"})},TRACE(y,h){return d(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()`");u.push(h)}},eject(...y){for(let h of y){let f=u.indexOf(h);f!==-1&&u.splice(f,1)}}}}function xt(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 Mo(n,e,t){if(!e||typeof e!="object")return"";let o=[],r={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(let i in e)o.push(i,t.allowReserved===!0?e[i]:encodeURIComponent(e[i]));let a=o.join(",");switch(t.style){case"form":return`${n}=${a}`;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return a}}for(let a in e){let i=t.style==="deepObject"?`${n}[${a}]`:a;o.push(xt(i,e[a],t))}let s=o.join(r);return t.style==="label"||t.style==="matrix"?`${r}${s}`:s}function qo(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){let s={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",a=(t.allowReserved===!0?e:e.map(i=>encodeURIComponent(i))).join(s);switch(t.style){case"simple":return a;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return`${n}=${a}`}}let o={simple:",",label:".",matrix:";"}[t.style]||"&",r=[];for(let s of e)t.style==="simple"||t.style==="label"?r.push(t.allowReserved===!0?s:encodeURIComponent(s)):r.push(xt(n,s,t));return t.style==="label"||t.style==="matrix"?`${o}${r.join(o)}`:r.join(o)}function So(n){return function(t){let o=[];if(t&&typeof t=="object")for(let r in t){let s=t[r];if(s!=null){if(Array.isArray(s)){if(s.length===0)continue;o.push(qo(r,s,{style:"form",explode:!0,...n?.array,allowReserved:n?.allowReserved||!1}));continue}if(typeof s=="object"){o.push(Mo(r,s,{style:"deepObject",explode:!0,...n?.object,allowReserved:n?.allowReserved||!1}));continue}o.push(xt(r,s,n))}}return o.join("&")}}function ca(n,e){let t=n;for(let o of n.match(aa)??[]){let r=o.substring(1,o.length-1),s=!1,a="simple";if(r.endsWith("*")&&(s=!0,r=r.substring(0,r.length-1)),r.startsWith(".")?(a="label",r=r.substring(1)):r.startsWith(";")&&(a="matrix",r=r.substring(1)),!e||e[r]===void 0||e[r]===null)continue;let i=e[r];if(Array.isArray(i)){t=t.replace(o,qo(r,i,{style:a,explode:s}));continue}if(typeof i=="object"){t=t.replace(o,Mo(r,i,{style:a,explode:s}));continue}if(a==="matrix"){t=t.replace(o,`;${xt(r,i)}`);continue}t=t.replace(o,a==="label"?`.${encodeURIComponent(i)}`:encodeURIComponent(i))}return t}function la(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 da(n,e){let t=`${e.baseUrl}${n}`;e.params?.path&&(t=e.pathSerializer(t,e.params.path));let o=e.querySerializer(e.params.query??{});return o.startsWith("?")&&(o=o.substring(1)),o&&(t+=`?${o}`),t}function Uo(...n){let e=new Headers;for(let t of n){if(!t||typeof t!="object")continue;let o=t instanceof Headers?t.entries():Object.entries(t);for(let[r,s]of o)if(s===null)e.delete(r);else if(Array.isArray(s))for(let a of s)e.append(r,a);else s!==void 0&&e.set(r,s)}return e}function Co(n){return n.endsWith("/")?n.substring(0,n.length-1):n}function No(n,e,t){let o=new Map;return{onRequest({request:r,id:s}){let a=r.headers.get("content-type");(a===null||a.startsWith("application/json"))&&r.method!=="GET"&&r.method!=="HEAD"&&o.set(s,r.clone())},async onResponse({response:r,id:s,options:a}){let i=o.get(s);if(o.delete(s),r.status!==n||!i)return;let p=await r.clone().json().catch(()=>{});if(p?.error!==e)return;let l=await t(p.details??{},i),u=await i.text(),d=u?JSON.parse(u):{},y=new Headers(i.headers);y.set("content-type","application/json");let h=new Request(i.url,{method:i.method,headers:y,body:JSON.stringify({...d,...l}),signal:i.signal});return a.fetch(h)},onError({id:r}){o.delete(r)}}}function Tt(n){return No(412,"CONFIRM_REQUIRED",async(e,t)=>({confirm:{challengeId:e.challengeId,assertion:await n(e,{request:t})}}))}function jt(n){return No(428,"OPERATOR_SIGNATURE_REQUIRED",async(e,t)=>({operatorProof:await n(e,{request:t})}))}async function c(n,e,t,o={}){let r=t??{},s={},a={},i={};for(let[d,y]of Object.entries(r))e.pathParams.includes(d)?s[d]=y:e.queryWhole&&d==="query"?Object.assign(a,y):!e.queryWhole&&e.query.includes(d)?a[d]=y:i[d]=y;for(let d of e.pathParams)if(s[d]===void 0)throw new TypeError(`${e.method} ${e.path}: no value for ${d}`);let p={params:{path:s,query:a}};e.body==="fields"?Object.values(i).every(y=>y===void 0)&&e.optionalBody||(p.body=i):e.body==="whole"?(i.body!==void 0||!e.optionalBody)&&(p.body=i.body):e.body==="raw"&&(p.body=i.body,p.bodySerializer=d=>d,p.headers={"Content-Type":i.contentType??e.media??"application/octet-stream"}),e.reply==="bytes"?p.parseAs="blob":e.reply==="text"&&(p.parseAs="text");let l=[];if(o.confirm){let d=o.confirm,y=e.userVerification?(h,f)=>d({userVerification:e.userVerification,...h},f):d;l.push(Tt(y))}o.operatorProof&&l.push(jt(o.operatorProof)),l.length&&(p.middleware=l),o.signal&&(p.signal=o.signal);let u=n.request;return Do(u(e.method.toLowerCase(),e.path,p))}function gn(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:[],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),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),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 wn=[{method:"POST",path:"/apps/{app}/intents",requires:"idempotencyKey"},{method:"POST",path:"/apps/{app}/methods/{method}",requires:"idempotencyKey"},{method:"POST",path:"/apps/{app}/views"}];var Io="https://calimero-node.invalid",ua=new Set(["attestation","health"]),ya=wn.map(n=>({method:n.method,pattern:new RegExp(`^${n.path.replace(/^\//,"").replace(/\{[^}]+\}/g,"[^/]+")}$`)})),ha=new Set(wn.filter(n=>n.requires==="idempotencyKey").map(n=>`${n.method} ${n.path}`));function fa(n){return async e=>{if(!e.url.startsWith(`${Io}/`))throw new Error(`not a route of the generated client: ${e.url}`);let t=new URL(e.url),o=t.pathname.replace(/^\/+/,""),r={};for(let[u,d]of t.searchParams)(r[u]??(r[u]=[])).push(d);let s=e.method;if(s==="GET"&&ua.has(o)&&n.inTheClear)return n.inTheClear(o,{query:r,signal:e.signal});let a=e.headers.get("content-type")??void 0,i=s==="GET"?void 0:new Uint8Array(await e.arrayBuffer()),p=i&&i.length>0?i:void 0,l=!1;return ya.some(u=>u.method===s&&u.pattern.test(o))&&(l=(p?JSON.parse(new TextDecoder().decode(p)):{}).confirm===void 0?!0:"once"),n.exchange(s,o,{query:r,...p?{bytes:p,contentType:a??"application/octet-stream"}:{},retry:l,signal:e.signal})}}var ma={async onRequest({request:n,schemaPath:e}){if(!ha.has(`${n.method} ${e}`))return;let t=await n.clone().text(),o=t?JSON.parse(t):{};if(o.idempotencyKey===void 0)return new Request(n,{body:JSON.stringify({...o,idempotencyKey:fn()})})}};function bn(n,e={}){let t=Bo({baseUrl:Io,fetch:fa(n)});return t.use(ma),e.confirm&&t.use(Tt(e.confirm)),e.operatorProof&&t.use(jt(e.operatorProof)),t}async function Do(n){let{data:e,error:t,response:o}=await n;if(!o.ok)throw ga(o,t);return e??{}}function ga(n,e){let t=typeof e=="string"?e?{message:e}:{}:e;return _e(n.status,t,n.headers.get("retry-after"))}var wa=n=>n/2**32|0,ba=n=>n>>>0;function Ko(n,e,t,o){let r=wa(t),s=ba(t);n.setUint32(e,o?s:r,o),n.setUint32(e+4,o?r:s,o)}function Lo(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}var Pn=n=>n?`"${n}" `:"";function Pa(n,e=""){if(typeof n!="number")throw new TypeError(Pn(e)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(Pn(e)+"expected integer >= 0, got "+n);return n}function _n(n,e,t=""){if(Lo(n)&&(e===void 0||n.length===e))return n;e!==void 0&&Pa(e,"length");let o=Lo(n),r=e!==void 0?` of length ${e}`:"",s=o?`length=${n.length}`:`type=${typeof n}`,a=Pn(t)+"expected Uint8Array"+r+", got "+s;throw o?new RangeError(a):new TypeError(a)}var _a=(n,e)=>{if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof n)},Vo=(n,e)=>{_a(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 An(n,e=!0){if(n.destroyed)throw new Error("hash was destroyed");if(e&&n.finished)throw new Error("digest() was already called")}function $o(n,e){_n(n,void 0,"output");let t=e.outputLen;if(!(n.length>=t))throw new RangeError('"output" expected length >= '+t)}function kn(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function Ot(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function N(n,e){return n<<32-e|n>>>e}function Aa(n,e,t="opts"){return Vo(n,"defaults"),e!==void 0&&Vo(e,t),Object.assign(Object.create(null),n,e)}function Go(n,e={}){if(typeof n!="function")throw new TypeError('"hashCons" expected function, got type='+typeof n);e=Aa({},e,"info");let t=(r,s)=>n(s).update(r).digest(),o=n(void 0);return t.outputLen=o.outputLen,t.blockLen=o.blockLen,t.canXOF=o.canXOF,t.create=r=>n(r),Object.assign(t,e),Object.freeze(t)}var Ho=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function Fo(n,e,t){return n&e^~n&t}function Qo(n,e,t){return n&e^n&t^e&t}var vt=class{constructor(e,t,o,r){A(this,"blockLen");A(this,"outputLen");A(this,"canXOF",!1);A(this,"padOffset");A(this,"isLE");A(this,"buffer");A(this,"view");A(this,"finished",!1);A(this,"length",0);A(this,"pos",0);A(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=o,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Ot(this.buffer)}update(e){An(this),_n(e);let{view:t,buffer:o,blockLen:r}=this,s=e.length,a=!1;for(let i=0;i<s;){let p=Math.min(r-this.pos,s-i);if(p===r){let l=Ot(e);for(;r<=s-i;i+=r)this.process(l,i);a=!0;continue}o.set(i===0&&p===s?e:e.subarray(i,i+p),this.pos),this.pos+=p,i+=p,this.pos===r&&(this.process(t,0),this.pos=0,a=!0)}return this.length+=e.length,a&&this.roundClean(),this}digestInto(e){An(this),$o(e,this),this.finished=!0;let{buffer:t,view:o,blockLen:r,isLE:s}=this,{pos:a}=this;t[a++]=128,t.fill(0,a),this.padOffset>r-a&&(this.process(o,0),t.fill(0)),Ko(o,r-8,this.length*8,s),this.process(o,0),this.roundClean();let i=e===t?o:Ot(e),p=this.outputLen,l=p/4,u=this.get();if(p%4||l>u.length)throw new Error("invalid outputLen");for(let d=0;d<l;d++)i.setUint32(4*d,u[d],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let o=e.slice(0,t);return this.destroy(),o}_cloneIntoMeta(e){let{buffer:t,length:o,finished:r,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=r,e.length=o,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}},zo=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ka=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]),ee=new Uint32Array(64),En=class extends vt{constructor(t,o){super(64,t,8,!1);A(this,"A",0);A(this,"B",0);A(this,"C",0);A(this,"D",0);A(this,"E",0);A(this,"F",0);A(this,"G",0);A(this,"H",0);this.A=o[0]|0,this.B=o[1]|0,this.C=o[2]|0,this.D=o[3]|0,this.E=o[4]|0,this.F=o[5]|0,this.G=o[6]|0,this.H=o[7]|0}get(){let{A:t,B:o,C:r,D:s,E:a,F:i,G:p,H:l}=this;return[t,o,r,s,a,i,p,l]}set(t,o,r,s,a,i,p,l){this.A=t|0,this.B=o|0,this.C=r|0,this.D=s|0,this.E=a|0,this.F=i|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,o){for(let y=0;y<16;y++,o+=4)ee[y]=t.getUint32(o,!1);for(let y=16;y<64;y++){let h=ee[y-15],f=ee[y-2],P=N(h,7)^N(h,18)^h>>>3,v=N(f,17)^N(f,19)^f>>>10;ee[y]=v+ee[y-7]+P+ee[y-16]|0}let{A:r,B:s,C:a,D:i,E:p,F:l,G:u,H:d}=this;for(let y=0;y<64;y++){let h=N(p,6)^N(p,11)^N(p,25),f=d+h+Fo(p,l,u)+ka[y]+ee[y]|0,v=(N(r,2)^N(r,13)^N(r,22))+Qo(r,s,a)|0;d=u,u=l,l=p,p=i+f|0,i=a,a=s,s=r,r=f+v|0}r=r+this.A|0,s=s+this.B|0,a=a+this.C|0,i=i+this.D|0,p=p+this.E|0,l=l+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(r,s,a,i,p,l,u,d)}roundClean(){kn(ee)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),kn(this.buffer)}},Rn=class extends En{constructor(){super(32,zo)}};var Ae=Go(()=>new Rn,Ho(1));var Ea=64*1024,Yo=16,St=Ea+Yo,Bt=256*St,Ut=12,$e=new TextEncoder,Ra=$e.encode("calimero.file.v1"),xa=$e.encode("calimero.file.segments.v1\0"),Ta=$e.encode("calimero.export-wrap.v1"),ja=$e.encode("calimero.sealed.derive.v1\0"),b=class extends Error{constructor(t,o){super(o);this.code=t;this.name="ExportError"}},Wo=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),Wo(m(xa,e,...n))}function Jo(n){let e=$e.encode(n),t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e.length,!1),m(t,e)}async function Zo(n,e,t,o){if(o.length<Ut)throw new b("TAMPERED","the wrapped key is truncated");let r=await V(n.privateKey,e);if(r.every(u=>u===0))throw new b("BAD_ANSWER","the ephemeral key is of low order");let s=m(e,n.publicKey,Jo(t.appId),Jo(t.fileId)),a=await crypto.subtle.importKey("raw",r,"HKDF",!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:Ta,info:m(ja,s)},a,256),p=await crypto.subtle.importKey("raw",i,"AES-GCM",!1,["decrypt"]),l;try{l=await crypto.subtle.decrypt({name:"AES-GCM",iv:o.subarray(0,Ut)},p,o.subarray(Ut))}catch{throw new b("TAMPERED","the wrapped key does not open")}if(l.byteLength!==32)throw new b("TAMPERED","the wrapped key has the wrong length");return new Uint8Array(l)}var Ct=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=Ae.create()}static async create(e,t){let o=await crypto.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]);return new n(o,t.map(w))}async push(e,t){let o=this.segments[this.next];if(o===void 0)throw new b("TAMPERED",`the file has no segment ${this.next}`);if(this.next+1<this.segments.length&&e.length!==Bt)throw new b("TAMPERED",`segment ${this.next} is not a whole segment`);if(w(await Wo(e))!==o)throw new b("TAMPERED",`segment ${this.next} is not the one the file lists`);this.next+=1;let r=m(this.pending,e),s=0;for(;r.length-s>St;)await t(await this.open(r.subarray(s,s+St),!1)),s+=St;this.pending=r.slice(s)}async finishExpecting(e,t){if(this.next!==this.segments.length)throw new b("TAMPERED","the file is missing segments");if(this.pending.length<Yo)throw new b("TAMPERED","the file is truncated");let o=await this.open(this.pending,!0);if(this.size!==e||w(this.hash.digest())!==t)throw new b("TAMPERED","the file is not the one that was sealed");return o}async open(e,t){let o=new Uint8Array(Ut);new DataView(o.buffer).setBigUint64(4,BigInt(this.index),!1);let r;try{r=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:o,additionalData:m(Ra,new Uint8Array([t?1:0]))},this.key,e))}catch{throw new b("TAMPERED",`chunk ${this.index} does not open: the file is altered, truncated or under another key`)}return this.hash.update(r),this.size+=r.length,this.index+=1,r}};function Ge(n,e,t){if(typeof n!="string")throw new b("BAD_ANSWER",`the node answered a bad ${e}`);try{return t===void 0?Zn(n,e):B(n,e,t)}catch{throw new b("BAD_ANSWER",`the node answered a bad ${e}`)}}function Oa(n){let e=n;if(typeof e!="object"||e===null)throw new b("BAD_ANSWER","the node answered a bad export");if(typeof e.app!="string")throw new b("BAD_ANSWER","the node answered a bad app");if(typeof e.size!="number"||!Number.isSafeInteger(e.size)||e.size<0)throw new b("BAD_ANSWER","the node answered a bad size");if(!Array.isArray(e.segments))throw new b("BAD_ANSWER","the node answered a bad segment list");return{app:e.app,size:e.size,named:Ge(e.id,"file id",32),segments:e.segments.map(t=>Ge(t,"segment hash",32)),sha256:w(Ge(e.sha256,"sha256",32)),ephemeral:Ge(e.ephemeral,"ephemeral key",32),wrapped:Ge(e.wrapped,"wrapped key")}}var xn=()=>new b("ABORTED","the export was aborted");async function va(n,e){let t=Number(n.headers.get("content-length"));if(Number.isFinite(t)&&t>Bt)throw await n.body?.cancel(),new b("TOO_LARGE","a segment is longer than a whole segment");if(!n.body)return new Uint8Array;let o=n.body.getReader(),r=()=>{o.cancel()};e?.addEventListener("abort",r);let s=[],a=0;try{for(;;){let{done:i,value:p}=await o.read();if(i)break;if(a+=p.length,a>Bt)throw await o.cancel(),new b("TOO_LARGE","a segment is longer than a whole segment");s.push(p)}}finally{e?.removeEventListener("abort",r)}if(e?.aborted)throw xn();return m(...s)}async function Tn(n,e,t,o,r,s){try{return await Sa(n,e,t,o,r,s)}catch(a){throw r?.aborted&&!(a instanceof b)?xn():a}}async function Sa(n,e,t,o,r,s){let a=await q(s),i=Oa(await n.json("POST",ue("apps/{app}/files/{id}/export",{app:e,id:t}),{body:{recipient:w(a.publicKey)},signal:r})),{segments:p,named:l}=i;if(p.length===0||w(await Xo(p))!==w(l)||w(l)!==t)throw new b("NOT_THE_FILE",`the node answered segments that are not the file ${t}`);let u=await Zo(a,i.ephemeral,{appId:i.app,fileId:t},i.wrapped),d=await Ct.create(u,p);for(let h=0;h<p.length;h+=1){if(r?.aborted)throw xn();let f=await n.request("GET",ue("apps/{app}/files/{id}/segments/{k}",{app:e,id:t,k:h}),{signal:r});await d.push(await va(f,r),P=>o.write(P))}let y=await d.finishExpecting(i.size,i.sha256);return y.length>0&&await o.write(y),{size:i.size,sha256:i.sha256}}async function er(n,e,t,o){let r=[];return await Tn(n,e,t,{write:s=>{r.push(s)}},o),m(...r)}var tr="calimero.org-recovery.v1\0",On=64,jn=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function Ua(){return crypto.getRandomValues(new Uint8Array(32))}function Ca(n){or(n);let e=Array.from(n,o=>o.toString(16).padStart(2,"0")).join(""),t=[];for(let o=0;o<e.length;o+=8)t.push(e.slice(o,o+8));return t.join("-")}function Ba(n){let e=n.replace(/[-\s]/g,"");if(!/^[0-9a-fA-F]{64}$/.test(e))throw new Error("a recovery seed is 64 hex digits");return Uint8Array.from({length:32},(t,o)=>parseInt(e.slice(2*o,2*o+2),16))}function nr(n,e,t){return new TextEncoder().encode(`${tr}${n}\0${e}\0${t}`)}async function Mt(n){let e=await ke(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 vn(n,e,t,o){let r=new TextEncoder().encode(o).length;if(r===0||r>On)throw new Error(`a recovery nonce is 1 to ${On} bytes`);let s=await ke(n,!1),a=await crypto.subtle.sign("Ed25519",s,te(nr(e,t,o)));return k(new Uint8Array(a))}function or(n){if(n.length!==32)throw new Error("a recovery seed is 32 bytes")}function ke(n,e){or(n);let t=new Uint8Array(jn.length+32);return t.set(jn),t.set(n,jn.length),crypto.subtle.importKey("pkcs8",te(t),{name:"Ed25519"},e,["sign"])}var te=n=>n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);var Sn=100;function Un(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>Sn)throw new RangeError(`limit is 1 to ${Sn}`);e.set("limit",String(n.limit))}let t=e.toString();return t?`?${t}`:""}function He(n,e){try{return Me(n,e)}catch{return n<e?-1:n>e?1:0}}function rr(n,e,t=Date.now()/1e3){if(n===null||n.length===0)return null;let o=n.reduce((s,a)=>He(s,a)>=0?s:a),r=null;for(let s of e)s.afterSecs<=t&&He(o,s.version)<0&&(r===null||He(s.version,r.version)>0)&&(r=s);return r}function sr(n,e,t,o){return`calimero-publisher-binding/v1
|
|
5
5
|
${n}
|
|
6
6
|
${e}
|
|
7
7
|
${t}
|
|
8
|
-
${o}`}function ma(n,e,t,o){return new TextEncoder().encode(Fo(n,e,t,o))}var ga="0123456789ABCDEFGHJKMNPQRSTVWXYZ";async function kn(n){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n))),t=(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0,o="";for(let r=0;r<6;r++)r===3&&(o+="-"),o+=ga[t>>>27-5*r&31];return o}function wa(n){let e=typeof n=="string"?new URL(n):n,t=e.searchParams.get("request_id"),o=e.searchParams.get("result");return!t||o!=="approved"&&o!=="declined"?null:{requestId:t,result:o}}function Rn(n){let e=new URL(String(n));return e.searchParams.delete("request_id"),e.searchParams.delete("result"),e.toString()}var _e="calimero.consent",Qo="https://mero-tee.vercel.app";function zo(n){return`https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(n)}`}function Yo(n){return`${Qo}/mero-tee?release_tag=${encodeURIComponent(`mero-tee-v${n}`)}`}function En(n,e,t=Date.now()/1e3){let o=p=>e.deadlines.find(l=>l.version===p)??null,r=n.governance.releases==="owner",s=n.governance.appUpgrades==="owner",a=n.clusterReleases.filter(p=>!p.approved).sort((p,l)=>Le(l.release,p.release)).map(p=>({version:p.release,nodes:p.nodes,actionable:r,releaseNotesUrl:zo(p.release),verifyUrl:Yo(p.release),deadline:o(p.release)})),i=[];for(let p of n.apps){let l=p.availableVersions??[];if(p.package===null||l.length===0)continue;let u=l[l.length-1],d=p.latestReachable===void 0?u:p.latestReachable;i.push({app:p.app,name:p.name??null,package:p.package.package,from:p.package.version,to:d??u,reachable:d!==null,blocked:p.latestBlocked??null,available:l,actionable:s})}return{scope:n.scope,governance:n.governance,approvedReleases:n.approvedReleases,releases:a,upgrades:i,stalledBy:$o(n.approvedReleases,e.deadlines,t),actionable:a.some(p=>p.actionable)||i.some(p=>p.actionable)}}function Jo(n,e,t,o={}){return{kind:"release",scope:n.kind==="org"?{org:n.org}:"account",subject:o.withdraw?{version:e,withdraw:!0}:{version:e},returnTo:t}}function ba(n,e,t){return Jo(n,e,t,{withdraw:!0})}function Pa(n,e,t){return{kind:"upgrade",subject:{app:n,toVersion:e},returnTo:t}}function _a(n,e){return{kind:"createOrg",subject:{name:n},returnTo:e}}function Aa(n,e){return{kind:"createInvite",subject:n,returnTo:e}}function ka(n,e){return{kind:"acceptInvite",subject:{token:n},returnTo:e}}function Ra(n,e){return{kind:"leaveOrg",subject:{org:n},returnTo:e}}function Ea(n,e,t){return{kind:"removeMember",subject:{org:n,account:e},returnTo:t}}function xa(n,e,t,o){return{kind:"setMemberRole",subject:{org:n,account:e,role:t},returnTo:o}}function Ta(n,e,t,o){return{kind:"setMemberTeams",subject:{org:n,account:e,teams:t},returnTo:o}}function ja(n,e,t,o){return{kind:"removeMemberTeams",subject:{org:n,account:e,teams:t},returnTo:o}}function Oa(n,e,t){return{kind:"revokeInvite",subject:{org:n,inviteKey:e},returnTo:t}}function va(n,e,t){return{kind:"renameOrg",subject:{org:n,name:e},returnTo:t}}function Sa(n,e){return{kind:"deleteOrg",subject:{org:n},returnTo:e}}function Ua(n,e){return{kind:"setCapabilities",subject:n,returnTo:e}}function Ca(n,e,t,o){return{kind:"setAllApps",subject:{org:n,account:e,allApps:t},returnTo:o}}var er=16*1024*1024,Ba=1,qa=8,Ma=16,Na=8;function Da(n){return"account"in n?`account:${n.account}`:`org:${n.org}`}async function Ia(n,e=fetch){let t=n??globalThis.location?.origin;if(!t)throw new Error("no page origin to read the frontend manifest from; pass `origin`");let o=await e(new URL("/.well-known/calimero.json",t).toString());if(!o.ok)throw await Z(o);let r=await o.json();return{...r,deployments:r.deployments??[]}}function La(n){let e=n??globalThis.location?.href;if(!e)return null;try{return new URL(e).searchParams.get("deployment")||null}catch{return null}}function Wo(n){return An(n),{after:n.after,limit:n.limit}}function Ka(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function Va(n){return n===null?null:Ka(n)}async function Xo(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 xn(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 Tn=class n{static async connect(e,t={}){let o=await sn({...e,directory:e.directory??Xt});return new n(o,t)}constructor(e,t={}){this.transport=e instanceof le?e:new le(e);let o=an(cn(this.transport,t));this.apps=o.apps,this.auth=o.auth,this.consent=o.consent,this.ops=o.ops,this.orgs=o.orgs,this.public=o.public,this.packages=o.packages,this.deployments=o.deployments}as(e){return e}confirmWith(e,t={}){return e?{confirm:qe(e,t)}:void 0}get nodeUrl(){return this.transport.nodeUrl}get nodes(){return this.transport.nodes}useApiKey(e){this.transport.useApiKey(e)}useSession(e){this.transport.useSession(e)}get session(){return this.transport.session}json(e,t,o){return this.transport.json(e,t,{body:o})}async signUp(e,t,o={}){let r=this.pageOrigin(o),s=o.invite?{invite:o.invite}:{},a=await this.begin(this.auth.registerBegin({...r===void 0?{name:t,...s}:{name:t,origin:r,...s}}),r),i=o.signal,p=await(i?e.create(a.options,{signal:i}):e.create(a.options)),l=await this.auth.registerFinish({challengeId:a.challengeId,registration:p,...s},this.confirmWith(e,{signal:i}));return this.useSession(l),l}async signIn(e,t={}){let o=this.pageOrigin(t),r=await this.begin(this.auth.loginBegin({...o===void 0?{}:{origin:o}}),o),s=r.options.rpId??r.options.rp?.id??"",a=X(r.options.challenge),i=await(t.signal?e.get(a,s,void 0,{signal:t.signal}):e.get(a,s)),p=await this.auth.loginFinish({challengeId:r.challengeId,assertion:i});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(r=>{try{return new URL(r).origin}catch{return r}})).has(t)?void 0:t}async begin(e,t){try{return await this.as(e)}catch(o){throw o instanceof ce&&!o.origin&&t!==void 0?new ce(o.nodeMessage,{...o.details,origin:t}):o}}refresh(){return this.transport.refresh()}async signOut(){await this.signingOut(this.auth.logout())}async signOutEverywhere(){await this.signingOut(this.auth.logoutAll())}async signingOut(e){try{await e}finally{this.transport.signOut()}}async addPasskey(e,t){let o=await this.as(this.auth.passkeyAddBegin()),r=await e.create(o.options),{credentialId:s}=await this.auth.passkeyAddFinish({challengeId:o.challengeId,registration:r},this.confirmWith(t));return s}async startAccountRecovery(e,t){try{let o=await this.as(this.auth.accountRecoveryBegin({code:e})),r=await t.create(o.options);return await this.auth.accountRecoveryStart({challengeId:o.challengeId,code:e,registration:r})}catch(o){throw o instanceof J?new Ce(o.message.replace(/^401 UNAUTHENTICATED: /,""),o.details):o}}async finishAccountRecovery(e,t){let o=await this.auth.accountRecoveryFinish({...t?{accountId:t}:{}},this.confirmWith(e));return this.useSession(o),o}async downloadBlob(e,t){return new Uint8Array(await(await this.apps.blobDownload({app:e,id:t})).arrayBuffer())}exportFileTo(e,t,o,r){return gn(this.transport,e,t,o,r)}exportFile(e,t,o){return Io(this.transport,e,t,o)}async downloadBlobGranted(e,t,o){return new Uint8Array(await(await this.apps.blobDownload({app:e,id:t,grant:o})).arrayBuffer())}async uploadFile(e,t){let o=t instanceof Blob?t.size:t.byteLength;if(o<=er)return this.apps.filesUpload({app:e,body:await Xo(t,0,o)});try{return await this.uploadSession(e,t,o)}catch(r){if(!(r instanceof g)||r.code!=="UPLOAD_UNKNOWN")throw r;return this.uploadSession(e,t,o)}}async uploadSession(e,t,o){let r=await this.untilAvailable(()=>this.apps.uploadBegin({app:e,size:o})),{uploadId:s,partBytes:a,parts:i}=r;if(!s||!a||a<=0||i!==Math.ceil(o/a))throw new Error(`the node began an upload it cannot take: ${JSON.stringify(r)}`);try{return await this.sendParts(e,s,t,o,a,i),await this.untilAvailable(()=>this.apps.uploadComplete({app:e,upload:s}))}catch(p){throw p instanceof g&&p.code==="UPLOAD_UNKNOWN"||await this.apps.uploadAbort({app:e,upload:s}).catch(()=>{}),p}}async sendParts(e,t,o,r,s,a){let[i,p,l]=[0,0,0];for(;i<a;)try{let u=await Xo(o,i*s,Math.min((i+1)*s,r));i=xn(await this.apps.uploadPart({app:e,upload:t,k:String(i),body:u}),a),p=0;continue}catch(u){if(u instanceof g&&u.code==="PART_OUT_OF_ORDER"){if(l+=1,l>Ma)throw u;i=xn(u.details,a);continue}if(!this.isTransient(u)||++p>qa)throw u;if(await new Promise(d=>setTimeout(d,Ne(p-1,this.transport.retry))),p>Ba)try{let d=xn(await this.apps.uploadStatus({app:e,upload:t}),a);d>i&&(p=0),i=d}catch(d){if(!this.isTransient(d))throw d}}}async untilAvailable(e){for(let t=0;;t++)try{return await e()}catch(o){if(!this.isTransient(o)||t>=Na)throw o;await new Promise(r=>setTimeout(r,Ne(t,this.transport.retry)))}}isTransient(e){return e instanceof W||this.transport.isNetworkFailure(e)}events(e,t=0,o){return this.transport.events(de("apps/{app}/events",{app:e}),{query:{from:t},signal:o})}presenceStream(e,t){return this.transport.events(de("apps/{app}/presence/stream",{app:e}),{signal:t})}async startRecovery(e,t){let o=(await this.auth.me()).accountId,r=v(crypto.getRandomValues(new Uint8Array(16))),s=await Pn(t,e,o,r);return this.orgs.recoveryStart({org:e,nonce:r,signature:s})}async appsReportAll(e){let t=(a={})=>e===null?this.auth.accountApps(Wo(a)):this.orgs.apps({org:e,...Wo(a)}),o=await t(),r=[...o.apps],s=o.next;for(;s!==null;){let a=await t({after:s});r.push(...a.apps),s=a.next}return{...o,apps:r,next:null}}async pendingApprovals(e=null){let[t,o]=await Promise.all([this.appsReportAll(e),this.public.releasesPublic()]);return En(t,o)}async openConsentPage(e,t={}){let o=typeof t=="function"?{navigate:t}:t,r=o.navigate??(a=>{let i=globalThis.window;if(!i)throw new Error("no window to open the consent page in; pass `navigate`");i.location.assign(a)}),s=await this.consent.pageCreate({body:e});if(s.code!==void 0){let a=await kn(s.requestId);if(s.code!==a)throw new g(200,"CONSENT_CODE_MISMATCH","the consent page code does not match the request",{requestId:s.requestId,code:s.code,expected:a})}if(o.confirm&&!await o.confirm(s))return s;try{jn()?.setItem(_e,s.requestId)}catch{}return r(s.url),s}async resumeConsent(e={}){let t=globalThis,o=e.href??t.location?.href;if(o===void 0)throw new Error("no page to read the consent return from; pass `href`");let r=new URL(o),s=r.searchParams.get("request_id");if(!s)return null;e.href===void 0&&t.history&&t.history.replaceState(t.history.state,"",Rn(r));let a=e.requestId;if(a===void 0)try{a=jn()?.getItem(_e)??void 0}catch{a=void 0}if(!a)throw new g(200,"CONSENT_NOT_STARTED","this page started no consent request",{returned:s});if(s!==a)throw new g(200,"CONSENT_REQUEST_MISMATCH","the consent page returned another request than this page started",{requestId:a,returned:s});let i;try{i=await this.consent.pageResult({request:a})}catch(p){throw p instanceof we?(Zo(a),new g(404,"CONSENT_REPLACED","this page's consent request was replaced by a newer one",{requestId:a})):p}if(i.requestId!==a)throw new g(200,"CONSENT_REQUEST_MISMATCH","the node answered another request",{requestId:a,returned:i.requestId});if(i.status==="pending")throw new g(200,"CONSENT_NOT_DECIDED","the consent page returned, but this request is still pending",{requestId:a});return Zo(a),i}async waitForConsent(e,t={}){let o=t.intervalMs??2e3;for(;;){let r=await this.consent.pageResult({request:e});if(r.status!=="pending"||t.signal?.aborted||t.expiresAt!==void 0&&Date.now()/1e3>=t.expiresAt)return r;await new Promise(s=>setTimeout(s,o))}}};function jn(){try{return globalThis.sessionStorage}catch{return}}function Zo(n){try{let e=jn();e?.getItem(_e)===n&&e.removeItem(_e)}catch{}}var On={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},Ha=On.JOIN_OPEN_TEAMS;function Ga(...n){return n.reduce((e,t)=>e|On[t],0)}function jt(n,e){return(n<<e|n>>>32-e)>>>0}function te(n,e,t,o,r){n[e]=n[e]+n[t]>>>0,n[r]=jt(n[r]^n[e],16),n[o]=n[o]+n[r]>>>0,n[t]=jt(n[t]^n[o],12),n[e]=n[e]+n[t]>>>0,n[r]=jt(n[r]^n[e],8),n[o]=n[o]+n[r]>>>0,n[t]=jt(n[t]^n[o],7)}function tr(n,e){return(n[e]|n[e+1]<<8|n[e+2]<<16|n[e+3]<<24)>>>0}function rr(n,e,t){let o=new Uint32Array(16);o[0]=1634760805,o[1]=857760878,o[2]=2036477234,o[3]=1797285236;for(let a=0;a<8;a+=1)o[4+a]=tr(n,a*4);o[12]=e>>>0;for(let a=0;a<3;a+=1)o[13+a]=tr(t,a*4);let r=o.slice();for(let a=0;a<10;a+=1)te(r,0,4,8,12),te(r,1,5,9,13),te(r,2,6,10,14),te(r,3,7,11,15),te(r,0,5,10,15),te(r,1,6,11,12),te(r,2,7,8,13),te(r,3,4,9,14);let s=new Uint8Array(64);for(let a=0;a<16;a+=1){let i=r[a]+o[a]>>>0;s[a*4]=i&255,s[a*4+1]=i>>>8&255,s[a*4+2]=i>>>16&255,s[a*4+3]=i>>>24&255}return s}function $a(n,e,t,o){let r=new Uint8Array(o.length);for(let s=0,a=e;s<o.length;s+=64,a+=1){let i=rr(n,a,t),p=Math.min(s+64,o.length);for(let l=s;l<p;l+=1)r[l]=o[l]^i[l-s]}return r}function vn(n){let e=0n;for(let t=n.length-1;t>=0;t-=1)e=e<<8n|BigInt(n[t]);return e}var Fa=(1n<<130n)-5n;function Qa(n,e){let t=vn(n.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,o=vn(n.subarray(16,32)),r=0n;for(let i=0;i<e.length;i+=16){let p=e.subarray(i,Math.min(i+16,e.length)),l=vn(p)+(1n<<BigInt(8*p.length));r=(r+l)*t%Fa}let s=r+o&(1n<<128n)-1n,a=new Uint8Array(16);for(let i=0;i<16;i+=1)a[i]=Number(s&0xffn),s>>=8n;return a}function nr(n){return new Uint8Array((16-n%16)%16)}function or(n){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(n),!0),e}function za(n,e){let t=[n,nr(n.length),e,nr(e.length),or(n.length),or(e.length)],o=new Uint8Array(t.reduce((s,a)=>s+a.length,0)),r=0;for(let s of t)o.set(s,r),r+=s.length;return o}function Ya(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 sr(n,e,t,o=new Uint8Array(0)){Ya(n,e);let r=rr(n,0,e).subarray(0,32),s=$a(n,1,e,t),a=Qa(r,za(o,s)),i=new Uint8Array(s.length+16);return i.set(s),i.set(a,s.length),i}var ir=32,Ja=1,Wa=3,Xa=2,Za=32,ei=32,ti=12,Ae=n=>new TextEncoder().encode(n),Ve=n=>new Uint8Array([n>>8&255,n&255]),ar=m(Ae("KEM"),Ve(ir)),Ke=m(Ae("HPKE"),Ve(ir),Ve(Ja),Ve(Wa));async function pr(n,e){let t=n.length===0?new Uint8Array(32):n,o=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",o,e))}async function ni(n,e,t){let o=new Uint8Array(t),r=new Uint8Array(0);for(let s=1,a=0;a<t;s+=1)r=await pr(n,m(r,e,new Uint8Array([s]))),o.set(r.subarray(0,Math.min(r.length,t-a)),a),a+=r.length;return o}function Ot(n,e,t,o){return pr(e,m(Ae("HPKE-v1"),n,Ae(t),o))}function Sn(n,e,t,o,r){return ni(e,m(Ve(r),Ae("HPKE-v1"),n,Ae(t),o),r)}async function oi(n,e){let t=await Ot(ar,new Uint8Array(0),"eae_prk",n);return Sn(ar,t,"shared_secret",e,Za)}async function ri(n,e){let t=new Uint8Array(0),o=await Ot(Ke,t,"psk_id_hash",t),r=await Ot(Ke,t,"info_hash",e),s=m(new Uint8Array([Xa]),o,r),a=await Ot(Ke,n,"secret",t);return{key:await Sn(Ke,a,"key",s,ei),nonce:await Sn(Ke,a,"base_nonce",s,ti)}}async function cr(n,e,t,o,r=new Uint8Array(0),s){if(n.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let a=await q(s),i=await q(e),p=m(await K(a.privateKey,n),await K(i.privateKey,n)),l=await oi(p,m(a.publicKey,n,i.publicKey)),{key:u,nonce:d}=await ri(l,t);return{enc:a.publicKey,ciphertext:sr(u,d,o,r)}}var ur="mero-agent-gate/attest/v3",yr="mero-agent-gate/provision/v2",si=/^[a-z0-9][a-z0-9-]{0,62}$/,ai=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,lr=64,dr=64*1024,ne=class extends Error{constructor(t,o,r){super(t);this.status=o;this.code=r;this.name="AgentGateError"}};function hr(n){if(!si.test(n))throw new Error(`Agent id ${JSON.stringify(n)} must match [a-z0-9][a-z0-9-]{0,62}`)}function He(n){return new TextEncoder().encode(n)}function fr(n){let e=He(n);return m(new Uint8Array([e.length]),e)}function ue(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}function vt(n,e,t){let o;try{o=Uint8Array.from(atob(n.trim()),r=>r.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(t!==void 0&&o.length!==t)throw new Error(`${e} is not ${t} bytes`);return o}async function mr(n,e,t,o){let r=new Uint8Array(32),s=m(He(ur),n,fr(e),t??r,o??r);return new Uint8Array(await crypto.subtle.digest("SHA-256",s))}function gr(n,e){return m(He(yr),n,fr(e))}async function ii(){let n=crypto.getRandomValues(new Uint8Array(32));return{secret:n,publicKey:await St(n)}}async function St(n){if(n.length!==32)throw new Error("An owner key is 32 bytes");return ue((await q(n)).publicKey)}function wr(n,e){return`${n.replace(/\/+$/,"")}${e}`}async function br(n,e,t){let o=await n(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),r=await o.text(),s;try{s=r?JSON.parse(r):void 0}catch{}if(!o.ok){let a=s;throw new ne(`The gate answered ${o.status}${a?.error?` ${a.error}`:""}: ${a?.details??r.slice(0,200)}`,o.status,a?.error)}return s}async function Un(n){let e=n.agentId??"";e&&hr(e);let t=crypto.getRandomValues(new Uint8Array(32)),o=await br(n.fetch??fetch,wr(n.gateUrl,"/attest"),{nonceB64:ue(t),...e?{agentId:e}:{}});if((o?.agentId??"")!==e)throw new Error(`Asked about agent ${JSON.stringify(e)}, the gate answered for ${JSON.stringify(o?.agentId)}`);let r=vt(o.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),s=o.signingPublicKeyB64?vt(o.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,a=o.ownerPublicKeyB64?vt(o.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!s!=!a)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let i=await mr(r,e,s,a);return await n.verifier({quoteB64:o.quoteB64,nonce:w(t),reportDataSuffix:w(i)}),{agentId:e,provisioningPublicKey:ue(r),...s?{signingPublicKey:ue(s)}:{},...a?{ownerPublicKey:ue(a)}:{}}}async function Pr(n,e){let t=await St(e);if(n.ownerPublicKey&&n.ownerPublicKey!==t)throw new ne(`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 pi(n){let e=Object.keys(n);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>lr)throw new Error(`At most ${lr} secrets at once`);for(let t of e){if(!ai.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(He(n[t]).length>dr)throw new Error(`Secret ${t} is over ${dr} bytes`)}}async function _r(n,e,t,o,r,s){if(!o.agentId)throw new Error("This quote names no agent; attest with the agent id");let a=await Pr(o,r),i=vt(o.provisioningPublicKey,"provisioningPublicKey",32),p=await cr(i,r,gr(i,o.agentId),He(JSON.stringify(s)));return br(n,wr(e,t),{agentId:o.agentId,provisioningPublicKeyB64:o.provisioningPublicKey,senderPublicKeyB64:a,encappedKeyB64:ue(p.enc),ciphertextB64:ue(p.ciphertext)})}async function ci(n){pi(n.secrets);let e=n.fetch??fetch,t=await _r(e,n.gateUrl,"/provision",n.agent,n.ownerSecret,{secrets:n.secrets}),o=await Un({gateUrl:n.gateUrl,agentId:n.agent.agentId,verifier:n.verifier,fetch:e}),r=await St(n.ownerSecret);if(o.ownerPublicKey!==r||!o.signingPublicKey)throw new ne("The gate accepted the secrets, but its quote does not name your key as owner");if(n.agent.signingPublicKey&&n.agent.signingPublicKey!==o.signingPublicKey)throw new ne("The agent's signing key changed while provisioning");return{agentId:o.agentId,provisioningPublicKey:o.provisioningPublicKey,signingPublicKey:o.signingPublicKey,ownerPublicKey:r,written:t?.written??[],claimed:t?.claimed===!0}}async function li(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 _r(e,n.gateUrl,"/release",n.agent,n.ownerSecret,{release:!0}),(await Un({gateUrl:n.gateUrl,agentId:n.agent.agentId,verifier:n.verifier,fetch:e})).ownerPublicKey)throw new ne("The gate says it released the agent, but its quote still names an owner")}var Cn=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),di=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function ui(n,e,t={}){let o=typeof n=="string"?new TextEncoder().encode(n):n;await Ze(o,e,{identity:t.identity??Cn.identity,issuer:t.issuer??Cn.issuer});let r;try{r=JSON.parse(new TextDecoder().decode(o))}catch{throw new Error("The signed agent policy is not JSON")}let s=t.role??"agent";if(r?.role!==s)throw new Error(`The signed file is a ${JSON.stringify(r?.role)} policy, not an ${s} one`);let a=t.profile??ae;if(r.profile!==a)throw new Error(`The signed agent policy is for the ${JSON.stringify(r.profile)} profile, not ${a}`);if(t.expectedVersion!==void 0&&r.version!==t.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(r.version)}, not ${t.expectedVersion}`);return Ar(r),r}function Ar(n){for(let e of di)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 yi=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function hi(n){let e=yi.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 Ge=n=>n.trim().replace(/^0x/i,"");function fi(n,e){return Ar(n),ie({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:n.allowed_tcb_statuses.map(hi),allowedMrtd:n.allowed_mrtd.map(Ge),allowedRtmr0:n.allowed_rtmr0.map(Ge),allowedRtmr1:n.allowed_rtmr1.map(Ge),allowedRtmr2:n.allowed_rtmr2.map(Ge),allowedRtmr3:n.allowed_rtmr3.map(Ge)})}var kr=1,mi=new TextEncoder().encode("calimero.recovery-backup.v1\0"),gi=new TextEncoder().encode("calimero.recovery-backup.v1"),wi=new TextEncoder().encode("calimero.recovery-backup.key.v1"),Er=32,bi=1,Pi=2,_i=0,B=n=>new TextEncoder().encode(n),Fe=n=>new Uint8Array([n>>8&255,n&255]),Rr=m(B("KEM"),Fe(Er)),$e=m(B("HPKE"),Fe(Er),Fe(bi),Fe(Pi));function ke(n){return n.kind==="operator"?"operator":`${n.kind}:${n.id}`}async function Hc(){let n=crypto.getRandomValues(new Uint8Array(32));return{secret:n,publicKey:await Ai(n)}}async function Ai(n){return w((await q(n)).publicKey)}async function ki(n){let e=B(n.header),t=JSON.parse(n.header);if(typeof t.format!="number"||t.format>kr)throw new Error(`recovery file format ${t.format} is not one this release reads (${kr})`);let o=await crypto.subtle.importKey("raw",C(t.signingKey,"signing key",32),{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify("Ed25519",o,C(n.signature,"signature",64),m(mi,e)))throw new Error("the node's signature over the header does not hold");return t}async function xr(n,e){let t=n.length===0?new Uint8Array(32):n,o=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",o,e))}async function Ri(n,e,t){let o=new Uint8Array(t),r=new Uint8Array(0);for(let s=1,a=0;a<t;s+=1)r=await xr(n,m(r,e,new Uint8Array([s]))),o.set(r.subarray(0,Math.min(r.length,t-a)),a),a+=r.length;return o}var Ut=(n,e,t,o)=>xr(e,m(B("HPKE-v1"),n,B(t),o)),Bn=(n,e,t,o,r)=>Ri(e,m(Fe(r),B("HPKE-v1"),n,B(t),o),r);async function Ei(n,e){let t=await q(e);if(w(t.publicKey)!==n.recipient)throw new Error("this key is not the one the file was sealed to");let o=C(n.enc,"encapsulated key",32),r=await K(t.privateKey,o),s=new Uint8Array(0),a=await Ut(Rr,s,"eae_prk",r),i=await Bn(Rr,a,"shared_secret",m(o,t.publicKey),32),p=await Ut($e,s,"psk_id_hash",s),l=await Ut($e,s,"info_hash",gi),u=m(new Uint8Array([_i]),p,l),d=await Ut($e,i,"secret",s),y=await Bn($e,d,"key",u,32),h=await Bn($e,d,"base_nonce",u,12),f=await crypto.subtle.importKey("raw",y,"AES-GCM",!1,["decrypt"]),P;try{P=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:h,additionalData:wi},f,C(n.wrappedKey,"wrapped key",48)))}catch{throw new Error("this key does not open the file")}if(P.length!==32)throw new Error("the data key is not 32 bytes");return P}async function Gc(n,e,t,o={}){let r=[];for(let p of[...e].sort((l,u)=>l.name.localeCompare(u.name))){let l=await ki(p);if(o.verifyQuote&&await ji(l,o.verifyQuote),ke(l.holder)!==ke(n))throw new Error(`${p.name} is ${ke(l.holder)}'s, not ${ke(n)}'s`);r.push({name:p.name,header:l})}let s=async p=>({file:p.name,key:w(await Ei(p.header,t))}),a=r.filter(p=>p.header.kind==="holder").pop();if(!a)throw new Error(`no holder file of ${ke(n)}`);let i=new Map;for(let p of r)p.header.kind==="app"&&p.header.app&&(!o.apps||o.apps.includes(p.header.app))&&i.set(p.header.app,p);return{holder:ke(n),slice:await s(a),apps:await Promise.all([...i.values()].map(s)),code:await Promise.all(r.filter(p=>p.header.kind==="code").map(s))}}async function qn(n){return new Uint8Array(await crypto.subtle.digest("SHA-256",n))}async function xi(n,e){let t=B(n),o=new Uint8Array(4);new DataView(o.buffer).setUint32(0,t.length,!1);let r=new Uint8Array(8);return new DataView(r.buffer).setBigUint64(0,BigInt(e),!1),w(await qn(m(B("calimero.recovery-backup.attest.v1\0"),o,t,r)))}async function Ti(n,e,t,o){let r=await qn(B(JSON.stringify(e))),s=B(t),a=new Uint8Array(4);new DataView(a.buffer).setUint32(0,s.length,!1);let i=new Uint8Array(8);return new DataView(i.buffer).setBigUint64(0,BigInt(o),!1),w(await qn(m(B("calimero.tee-attest.receipt-key.v3"),n,r,a,s,i)))}async function ji(n,e){let t=n.attestation;if(!t||typeof t.quote!="string")throw new Error("the file carries no attestation");if(t.cluster!==n.cluster||t.node!==n.node)throw new Error("the attestation is another node's");if(t.receiptKey!==n.signingKey)throw new Error("the attested key is not the one that signed the file");let o=await xi(n.cluster,n.node);if(t.nonce!==o)throw new Error("the attestation is not over the recovery nonce");let r=await Ti(C(n.signingKey,"signing key",32),t.governance,n.cluster,n.node);if(!await e({quoteB64:t.quote,nonce:o,reportDataSuffix:r}))throw new Error("the quote was not accepted")}export{ur as AGENT_ATTEST_DOMAIN,yr as AGENT_PROVISION_INFO_DOMAIN,ne as AgentGateError,mt as AppError,ot as ArgsTooLarge,pt as BadOrigin,_e as CONSENT_STORAGE_KEY,Tn as CalimeroClient,g as CalimeroError,dt as ClusterNotUpgraded,Se as ConfirmCancelled,Ue as ConfirmPromptBlocked,be as ConfirmRequired,it as ConsentStale,$t as DEFAULT_COLLATERAL_MIRROR,Xt as DEFAULT_DIRECTORY,Ha as DEFAULT_ORG_CAPABILITIES,et as DEFAULT_RELEASE_MIRROR,on as DEFAULT_RETRY,V as DirectoryError,b as ExportError,er as FILE_PART_BYTES,ut as FeatureNotActive,ro as GITHUB_RELEASES,Gn as HANDSHAKE_PATH,wi as HPKE_AAD,gi as HPKE_INFO,rt as IdempotencyMismatch,Cn as KMS_RELEASE_SIGNER,J as LoginRequired,bn as MAX_RECOVERY_NONCE_BYTES,_n as MAX_REPORT_PAGE,io as MOCK_QUOTE_HEADER,Gt as NODE_RELEASE_SIGNER,le as NodeTransport,we as NotFound,lt as NotServing,On as ORG_CAPABILITIES,ce as OriginNotRegistered,ct as OriginTaken,ae as PRODUCTION_PROFILE,nt as PasskeyUnknownHere,ft as QuotaExceeded,Lo as RECOVERY_DOMAIN,kr as RECOVERY_FORMAT,Qo as RELEASE_VERIFIER,yt as RecoveryNotReady,st as ReleaseDeadlineError,at as RuntimeTooOld,Te as SEALED_CONTENT_TYPE,$n as SEALED_PATH,mi as SIGNING_LABEL,Q as SealedTransportError,ht as SignUpRefused,je as StaleTransportKeyError,gt as TrapError,W as UnavailableError,pe as WrongNode,Ce as WrongRecoveryCode,ka as acceptInviteConsent,mr as agentKeyBinding,fi as agentQuoteVerifier,Un as attestAgent,v as b64url,Ai as backupPublicKey,qs as browserPasskey,Pr as checkOwner,po as claimedRelease,zt as cloudNodeReleaseUrl,Le as compareVersions,kn as confirmationCode,wa as consentReturn,Aa as createInviteConsent,_a as createOrgConsent,ie as createQuoteVerifier,cn as createRouteClient,an as createRoutes,It as createSealedFetch,Rs as createSignedReleaseVerifier,Sa as deleteOrgConsent,Da as deployerKey,sn as directoryTransport,Pe as errorFrom,Wt as fetchAttestedKey,Qt as fetchGithubNodeRelease,Ft as fetchNodeRelease,co as freshCollateral,X as fromB64url,Ia as frontendManifest,ii as generateOwnerKey,ke as holderKey,Gc as holderRecoveryBody,Ra as leaveOrgConsent,Hc as newBackupKeyPair,rn as newIdempotencyKey,ua as newRecoverySeed,Ei as openDataKey,Ga as orgCapabilities,St as ownerPublicKey,La as pageDeployment,An as pageQuery,ha as parseRecoverySeed,qe as passkeyConfirm,En as pendingApprovalsFrom,Va as presenceState,ci as provisionAgent,gr as provisionInfo,ma as publisherBindingBytes,Fo as publisherBindingMessage,nn as queryString,Ti as receiptKeyBinding,xi as recoveryAttestationNonce,Ko as recoveryMessage,fa as recoveryPublicKey,ya as recoverySeedText,Z as refusal,li as releaseAgent,Jo as releaseConsent,zo as releaseNotesUrl,Ea as removeMemberConsent,ja as removeMemberTeamsConsent,va as renameOrgConsent,Ne as retryDelayMs,Oa as revokeInviteConsent,de as routePath,Ca as setAllAppsConsent,Ua as setCapabilitiesConsent,xa as setMemberRoleConsent,Ta as setMemberTeamsConsent,Pn as signRecovery,ho as sseFrames,$o as stalledBy,Dt as transportKeyBinding,tt as trustSignedRelease,Ht as trustedMeasurementsFromReleases,Pa as upgradeConsent,hr as validateAgentId,ji as verifyRecoveryAttestation,ki as verifyRecoveryHeader,Yo as verifyReleaseUrl,ui as verifySignedAgentPolicy,oo as verifySignedNodeRelease,ba as withdrawConsent,Rn as withoutConsentReturn};
|
|
8
|
+
${o}`}function Ma(n,e,t,o){return new TextEncoder().encode(sr(n,e,t,o))}var qa="0123456789ABCDEFGHJKMNPQRSTVWXYZ";async function Cn(n){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n))),t=(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0,o="";for(let r=0;r<6;r++)r===3&&(o+="-"),o+=qa[t>>>27-5*r&31];return o}function Na(n){let e=typeof n=="string"?new URL(n):n,t=e.searchParams.get("request_id"),o=e.searchParams.get("result");return!t||o!=="approved"&&o!=="declined"?null:{requestId:t,result:o}}function Bn(n){let e=new URL(String(n));return e.searchParams.delete("request_id"),e.searchParams.delete("result"),e.toString()}var Ee="calimero.consent",ar="https://mero-tee.vercel.app";function ir(n){return`https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(n)}`}function pr(n){return`${ar}/mero-tee?release_tag=${encodeURIComponent(`mero-tee-v${n}`)}`}function Mn(n,e,t=Date.now()/1e3){let o=p=>e.deadlines.find(l=>l.version===p)??null,r=n.governance.releases==="owner",s=n.governance.appUpgrades==="owner",a=n.clusterReleases.filter(p=>!p.approved).sort((p,l)=>He(l.release,p.release)).map(p=>({version:p.release,nodes:p.nodes,actionable:r,releaseNotesUrl:ir(p.release),verifyUrl:pr(p.release),deadline:o(p.release)})),i=[];for(let p of n.apps){let l=p.availableVersions??[];if(p.package===null||l.length===0)continue;let u=l[l.length-1],d=p.latestReachable===void 0?u:p.latestReachable;i.push({app:p.app,name:p.name??null,package:p.package.package,from:p.package.version,to:d??u,reachable:d!==null,blocked:p.latestBlocked??null,available:l,actionable:s})}return{scope:n.scope,governance:n.governance,approvedReleases:n.approvedReleases,releases:a,upgrades:i,stalledBy:rr(n.approvedReleases,e.deadlines,t),actionable:a.some(p=>p.actionable)||i.some(p=>p.actionable)}}function cr(n,e,t,o={}){return{kind:"release",scope:n.kind==="org"?{org:n.org}:"account",subject:o.withdraw?{version:e,withdraw:!0}:{version:e},returnTo:t}}function Da(n,e,t){return cr(n,e,t,{withdraw:!0})}function Ia(n,e,t){return{kind:"upgrade",subject:{app:n,toVersion:e},returnTo:t}}function Ka(n,e){return{kind:"createOrg",subject:{name:n},returnTo:e}}function La(n,e){return{kind:"createInvite",subject:n,returnTo:e}}function Va(n,e){return{kind:"acceptInvite",subject:{token:n},returnTo:e}}function $a(n,e){return{kind:"leaveOrg",subject:{org:n},returnTo:e}}function Ga(n,e,t){return{kind:"removeMember",subject:{org:n,account:e},returnTo:t}}function Ha(n,e,t,o){return{kind:"setMemberRole",subject:{org:n,account:e,role:t},returnTo:o}}function Fa(n,e,t,o){return{kind:"setMemberTeams",subject:{org:n,account:e,teams:t},returnTo:o}}function Qa(n,e,t,o){return{kind:"removeMemberTeams",subject:{org:n,account:e,teams:t},returnTo:o}}function za(n,e,t){return{kind:"revokeInvite",subject:{org:n,inviteKey:e},returnTo:t}}function Ja(n,e,t){return{kind:"renameOrg",subject:{org:n,name:e},returnTo:t}}function Ya(n,e){return{kind:"deleteOrg",subject:{org:n},returnTo:e}}function Wa(n,e){return{kind:"setCapabilities",subject:n,returnTo:e}}function Xa(n,e,t,o){return{kind:"setAllApps",subject:{org:n,account:e,allApps:t},returnTo:o}}var yr=16*1024*1024,Za=1,ei=8,ti=16,ni=8;function oi(n){return"account"in n?`account:${n.account}`:`org:${n.org}`}async function ri(n,e=fetch){let t=n??globalThis.location?.origin;if(!t)throw new Error("no page origin to read the frontend manifest from; pass `origin`");let o=await e(new URL("/.well-known/calimero.json",t).toString());if(!o.ok)throw await Z(o);let r=await o.json();return{...r,deployments:r.deployments??[]}}function si(n){let e=n??globalThis.location?.href;if(!e)return null;try{return new URL(e).searchParams.get("deployment")||null}catch{return null}}function lr(n){return Un(n),{after:n.after,limit:n.limit}}function ai(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function ii(n){return n===null?null:ai(n)}async function dr(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 qn(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 Nn=class n{static async connect(e,t={}){let o=await mn({...e,directory:e.directory??cn});return new n(o,t)}constructor(e,t={}){this.transport=e instanceof de?e:new de(e);let o=gn(bn(this.transport,t));this.apps=o.apps,this.auth=o.auth,this.consent=o.consent,this.ops=o.ops,this.orgs=o.orgs,this.public=o.public,this.packages=o.packages,this.deployments=o.deployments}as(e){return e}confirmWith(e,t={}){return e?{confirm:Ke(e,t)}:void 0}get nodeUrl(){return this.transport.nodeUrl}get nodes(){return this.transport.nodes}useApiKey(e){this.transport.useApiKey(e)}useSession(e){this.transport.useSession(e)}get session(){return this.transport.session}json(e,t,o){return this.transport.json(e,t,{body:o})}async signUp(e,t,o={}){let r=this.pageOrigin(o),s=o.invite?{invite:o.invite}:{},a=await this.begin(this.auth.registerBegin({...r===void 0?{name:t,...s}:{name:t,origin:r,...s}}),r),i=o.signal,p=await(i?e.create(a.options,{signal:i}):e.create(a.options)),l=await this.auth.registerFinish({challengeId:a.challengeId,registration:p,...s},this.confirmWith(e,{signal:i}));return this.useSession(l),l}async signIn(e,t={}){let o=this.pageOrigin(t),r=await this.begin(this.auth.loginBegin({...o===void 0?{}:{origin:o}}),o),s=r.options.rpId??r.options.rp?.id??"",a=O(r.options.challenge),i=await(t.signal?e.get(a,s,void 0,{signal:t.signal}):e.get(a,s)),p=await this.auth.loginFinish({challengeId:r.challengeId,assertion:i});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(r=>{try{return new URL(r).origin}catch{return r}})).has(t)?void 0:t}async begin(e,t){try{return await this.as(e)}catch(o){throw o instanceof le&&!o.origin&&t!==void 0?new le(o.nodeMessage,{...o.details,origin:t}):o}}refresh(){return this.transport.refresh()}async signOut(){await this.signingOut(this.auth.logout())}async signOutEverywhere(){await this.signingOut(this.auth.logoutAll())}async signingOut(e){try{await e}finally{this.transport.signOut()}}async addPasskey(e,t){let o=await this.as(this.auth.passkeyAddBegin()),r=await e.create(o.options),{credentialId:s}=await this.auth.passkeyAddFinish({challengeId:o.challengeId,registration:r},this.confirmWith(t));return s}async startAccountRecovery(e,t){try{let o=await this.as(this.auth.accountRecoveryBegin({code:e})),r=await t.create(o.options);return await this.auth.accountRecoveryStart({challengeId:o.challengeId,code:e,registration:r})}catch(o){throw o instanceof W?new De(o.message.replace(/^401 UNAUTHENTICATED: /,""),o.details):o}}async finishAccountRecovery(e,t){let o=await this.auth.accountRecoveryFinish({...t?{accountId:t}:{}},this.confirmWith(e));return this.useSession(o),o}async downloadBlob(e,t){return new Uint8Array(await(await this.apps.blobDownload({app:e,id:t})).arrayBuffer())}exportFileTo(e,t,o,r){return Tn(this.transport,e,t,o,r)}exportFile(e,t,o){return er(this.transport,e,t,o)}async downloadBlobGranted(e,t,o){return new Uint8Array(await(await this.apps.blobDownload({app:e,id:t,grant:o})).arrayBuffer())}async uploadFile(e,t){let o=t instanceof Blob?t.size:t.byteLength;if(o<=yr)return this.apps.filesUpload({app:e,body:await dr(t,0,o)});try{return await this.uploadSession(e,t,o)}catch(r){if(!(r instanceof g)||r.code!=="UPLOAD_UNKNOWN")throw r;return this.uploadSession(e,t,o)}}async uploadSession(e,t,o){let r=await this.untilAvailable(()=>this.apps.uploadBegin({app:e,size:o})),{uploadId:s,partBytes:a,parts:i}=r;if(!s||!a||a<=0||i!==Math.ceil(o/a))throw new Error(`the node began an upload it cannot take: ${JSON.stringify(r)}`);try{return await this.sendParts(e,s,t,o,a,i),await this.untilAvailable(()=>this.apps.uploadComplete({app:e,upload:s}))}catch(p){throw p instanceof g&&p.code==="UPLOAD_UNKNOWN"||await this.apps.uploadAbort({app:e,upload:s}).catch(()=>{}),p}}async sendParts(e,t,o,r,s,a){let[i,p,l]=[0,0,0];for(;i<a;)try{let u=await dr(o,i*s,Math.min((i+1)*s,r));i=qn(await this.apps.uploadPart({app:e,upload:t,k:String(i),body:u}),a),p=0;continue}catch(u){if(u instanceof g&&u.code==="PART_OUT_OF_ORDER"){if(l+=1,l>ti)throw u;i=qn(u.details,a);continue}if(!this.isTransient(u)||++p>ei)throw u;if(await new Promise(d=>setTimeout(d,Ve(p-1,this.transport.retry))),p>Za)try{let d=qn(await this.apps.uploadStatus({app:e,upload:t}),a);d>i&&(p=0),i=d}catch(d){if(!this.isTransient(d))throw d}}}async untilAvailable(e){for(let t=0;;t++)try{return await e()}catch(o){if(!this.isTransient(o)||t>=ni)throw o;await new Promise(r=>setTimeout(r,Ve(t,this.transport.retry)))}}isTransient(e){return e instanceof X||this.transport.isNetworkFailure(e)}events(e,t=0,o){return this.transport.events(ue("apps/{app}/events",{app:e}),{query:{from:t},signal:o})}presenceStream(e,t){return this.transport.events(ue("apps/{app}/presence/stream",{app:e}),{signal:t})}async startRecovery(e,t){let o=(await this.auth.me()).accountId,r=k(crypto.getRandomValues(new Uint8Array(16))),s=await vn(t,e,o,r);return this.orgs.recoveryStart({org:e,nonce:r,signature:s})}async appsReportAll(e){let t=(a={})=>e===null?this.auth.accountApps(lr(a)):this.orgs.apps({org:e,...lr(a)}),o=await t(),r=[...o.apps],s=o.next;for(;s!==null;){let a=await t({after:s});r.push(...a.apps),s=a.next}return{...o,apps:r,next:null}}async pendingApprovals(e=null){let[t,o]=await Promise.all([this.appsReportAll(e),this.public.releasesPublic()]);return Mn(t,o)}async openConsentPage(e,t={}){let o=typeof t=="function"?{navigate:t}:t,r=o.navigate??(a=>{let i=globalThis.window;if(!i)throw new Error("no window to open the consent page in; pass `navigate`");i.location.assign(a)}),s=await this.consent.pageCreate({body:e});if(s.code!==void 0){let a=await Cn(s.requestId);if(s.code!==a)throw new g(200,"CONSENT_CODE_MISMATCH","the consent page code does not match the request",{requestId:s.requestId,code:s.code,expected:a})}if(o.confirm&&!await o.confirm(s))return s;try{Dn()?.setItem(Ee,s.requestId)}catch{}return r(s.url),s}async resumeConsent(e={}){let t=globalThis,o=e.href??t.location?.href;if(o===void 0)throw new Error("no page to read the consent return from; pass `href`");let r=new URL(o),s=r.searchParams.get("request_id");if(!s)return null;e.href===void 0&&t.history&&t.history.replaceState(t.history.state,"",Bn(r));let a=e.requestId;if(a===void 0)try{a=Dn()?.getItem(Ee)??void 0}catch{a=void 0}if(!a)throw new g(200,"CONSENT_NOT_STARTED","this page started no consent request",{returned:s});if(s!==a)throw new g(200,"CONSENT_REQUEST_MISMATCH","the consent page returned another request than this page started",{requestId:a,returned:s});let i;try{i=await this.consent.pageResult({request:a})}catch(p){throw p instanceof be?(ur(a),new g(404,"CONSENT_REPLACED","this page's consent request was replaced by a newer one",{requestId:a})):p}if(i.requestId!==a)throw new g(200,"CONSENT_REQUEST_MISMATCH","the node answered another request",{requestId:a,returned:i.requestId});if(i.status==="pending")throw new g(200,"CONSENT_NOT_DECIDED","the consent page returned, but this request is still pending",{requestId:a});return ur(a),i}async waitForConsent(e,t={}){let o=t.intervalMs??2e3;for(;;){let r=await this.consent.pageResult({request:e});if(r.status!=="pending"||t.signal?.aborted||t.expiresAt!==void 0&&Date.now()/1e3>=t.expiresAt)return r;await new Promise(s=>setTimeout(s,o))}}};function Dn(){try{return globalThis.sessionStorage}catch{return}}function ur(n){try{let e=Dn();e?.getItem(Ee)===n&&e.removeItem(Ee)}catch{}}var In={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},pi=In.JOIN_OPEN_TEAMS;function ci(...n){return n.reduce((e,t)=>e|In[t],0)}function qt(n,e){return(n<<e|n>>>32-e)>>>0}function ne(n,e,t,o,r){n[e]=n[e]+n[t]>>>0,n[r]=qt(n[r]^n[e],16),n[o]=n[o]+n[r]>>>0,n[t]=qt(n[t]^n[o],12),n[e]=n[e]+n[t]>>>0,n[r]=qt(n[r]^n[e],8),n[o]=n[o]+n[r]>>>0,n[t]=qt(n[t]^n[o],7)}function hr(n,e){return(n[e]|n[e+1]<<8|n[e+2]<<16|n[e+3]<<24)>>>0}function gr(n,e,t){let o=new Uint32Array(16);o[0]=1634760805,o[1]=857760878,o[2]=2036477234,o[3]=1797285236;for(let a=0;a<8;a+=1)o[4+a]=hr(n,a*4);o[12]=e>>>0;for(let a=0;a<3;a+=1)o[13+a]=hr(t,a*4);let r=o.slice();for(let a=0;a<10;a+=1)ne(r,0,4,8,12),ne(r,1,5,9,13),ne(r,2,6,10,14),ne(r,3,7,11,15),ne(r,0,5,10,15),ne(r,1,6,11,12),ne(r,2,7,8,13),ne(r,3,4,9,14);let s=new Uint8Array(64);for(let a=0;a<16;a+=1){let i=r[a]+o[a]>>>0;s[a*4]=i&255,s[a*4+1]=i>>>8&255,s[a*4+2]=i>>>16&255,s[a*4+3]=i>>>24&255}return s}function li(n,e,t,o){let r=new Uint8Array(o.length);for(let s=0,a=e;s<o.length;s+=64,a+=1){let i=gr(n,a,t),p=Math.min(s+64,o.length);for(let l=s;l<p;l+=1)r[l]=o[l]^i[l-s]}return r}function Kn(n){let e=0n;for(let t=n.length-1;t>=0;t-=1)e=e<<8n|BigInt(n[t]);return e}var di=(1n<<130n)-5n;function ui(n,e){let t=Kn(n.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,o=Kn(n.subarray(16,32)),r=0n;for(let i=0;i<e.length;i+=16){let p=e.subarray(i,Math.min(i+16,e.length)),l=Kn(p)+(1n<<BigInt(8*p.length));r=(r+l)*t%di}let s=r+o&(1n<<128n)-1n,a=new Uint8Array(16);for(let i=0;i<16;i+=1)a[i]=Number(s&0xffn),s>>=8n;return a}function fr(n){return new Uint8Array((16-n%16)%16)}function mr(n){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(n),!0),e}function yi(n,e){let t=[n,fr(n.length),e,fr(e.length),mr(n.length),mr(e.length)],o=new Uint8Array(t.reduce((s,a)=>s+a.length,0)),r=0;for(let s of t)o.set(s,r),r+=s.length;return o}function hi(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 wr(n,e,t,o=new Uint8Array(0)){hi(n,e);let r=gr(n,0,e).subarray(0,32),s=li(n,1,e,t),a=ui(r,yi(o,s)),i=new Uint8Array(s.length+16);return i.set(s),i.set(a,s.length),i}var Pr=32,fi=1,mi=3,gi=2,wi=32,bi=32,Pi=12,Re=n=>new TextEncoder().encode(n),Qe=n=>new Uint8Array([n>>8&255,n&255]),br=m(Re("KEM"),Qe(Pr)),Fe=m(Re("HPKE"),Qe(Pr),Qe(fi),Qe(mi));async function _r(n,e){let t=n.length===0?new Uint8Array(32):n,o=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",o,e))}async function _i(n,e,t){let o=new Uint8Array(t),r=new Uint8Array(0);for(let s=1,a=0;a<t;s+=1)r=await _r(n,m(r,e,new Uint8Array([s]))),o.set(r.subarray(0,Math.min(r.length,t-a)),a),a+=r.length;return o}function Nt(n,e,t,o){return _r(e,m(Re("HPKE-v1"),n,Re(t),o))}function Ln(n,e,t,o,r){return _i(e,m(Qe(r),Re("HPKE-v1"),n,Re(t),o),r)}async function Ai(n,e){let t=await Nt(br,new Uint8Array(0),"eae_prk",n);return Ln(br,t,"shared_secret",e,wi)}async function ki(n,e){let t=new Uint8Array(0),o=await Nt(Fe,t,"psk_id_hash",t),r=await Nt(Fe,t,"info_hash",e),s=m(new Uint8Array([gi]),o,r),a=await Nt(Fe,n,"secret",t);return{key:await Ln(Fe,a,"key",s,bi),nonce:await Ln(Fe,a,"base_nonce",s,Pi)}}async function Ar(n,e,t,o,r=new Uint8Array(0),s){if(n.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let a=await q(s),i=await q(e),p=m(await V(a.privateKey,n),await V(i.privateKey,n)),l=await Ai(p,m(a.publicKey,n,i.publicKey)),{key:u,nonce:d}=await ki(l,t);return{enc:a.publicKey,ciphertext:wr(u,d,o,r)}}var Rr="mero-agent-gate/attest/v3",xr="mero-agent-gate/provision/v2",Ei=/^[a-z0-9][a-z0-9-]{0,62}$/,Ri=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,kr=64,Er=64*1024,oe=class extends Error{constructor(t,o,r){super(t);this.status=o;this.code=r;this.name="AgentGateError"}};function Tr(n){if(!Ei.test(n))throw new Error(`Agent id ${JSON.stringify(n)} must match [a-z0-9][a-z0-9-]{0,62}`)}function ze(n){return new TextEncoder().encode(n)}function jr(n){let e=ze(n);return m(new Uint8Array([e.length]),e)}function ye(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}function Dt(n,e,t){let o;try{o=Uint8Array.from(atob(n.trim()),r=>r.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(t!==void 0&&o.length!==t)throw new Error(`${e} is not ${t} bytes`);return o}async function Or(n,e,t,o){let r=new Uint8Array(32),s=m(ze(Rr),n,jr(e),t??r,o??r);return new Uint8Array(await crypto.subtle.digest("SHA-256",s))}function vr(n,e){return m(ze(xr),n,jr(e))}async function xi(){let n=crypto.getRandomValues(new Uint8Array(32));return{secret:n,publicKey:await It(n)}}async function It(n){if(n.length!==32)throw new Error("An owner key is 32 bytes");return ye((await q(n)).publicKey)}function Sr(n,e){return`${n.replace(/\/+$/,"")}${e}`}async function Ur(n,e,t){let o=await n(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),r=await o.text(),s;try{s=r?JSON.parse(r):void 0}catch{}if(!o.ok){let a=s;throw new oe(`The gate answered ${o.status}${a?.error?` ${a.error}`:""}: ${a?.details??r.slice(0,200)}`,o.status,a?.error)}return s}async function Vn(n){let e=n.agentId??"";e&&Tr(e);let t=crypto.getRandomValues(new Uint8Array(32)),o=await Ur(n.fetch??fetch,Sr(n.gateUrl,"/attest"),{nonceB64:ye(t),...e?{agentId:e}:{}});if((o?.agentId??"")!==e)throw new Error(`Asked about agent ${JSON.stringify(e)}, the gate answered for ${JSON.stringify(o?.agentId)}`);let r=Dt(o.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),s=o.signingPublicKeyB64?Dt(o.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,a=o.ownerPublicKeyB64?Dt(o.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!s!=!a)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let i=await Or(r,e,s,a);return await n.verifier({quoteB64:o.quoteB64,nonce:w(t),reportDataSuffix:w(i)}),{agentId:e,provisioningPublicKey:ye(r),...s?{signingPublicKey:ye(s)}:{},...a?{ownerPublicKey:ye(a)}:{}}}async function Cr(n,e){let t=await It(e);if(n.ownerPublicKey&&n.ownerPublicKey!==t)throw new oe(`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 Ti(n){let e=Object.keys(n);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>kr)throw new Error(`At most ${kr} secrets at once`);for(let t of e){if(!Ri.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(ze(n[t]).length>Er)throw new Error(`Secret ${t} is over ${Er} bytes`)}}async function Br(n,e,t,o,r,s){if(!o.agentId)throw new Error("This quote names no agent; attest with the agent id");let a=await Cr(o,r),i=Dt(o.provisioningPublicKey,"provisioningPublicKey",32),p=await Ar(i,r,vr(i,o.agentId),ze(JSON.stringify(s)));return Ur(n,Sr(e,t),{agentId:o.agentId,provisioningPublicKeyB64:o.provisioningPublicKey,senderPublicKeyB64:a,encappedKeyB64:ye(p.enc),ciphertextB64:ye(p.ciphertext)})}async function ji(n){Ti(n.secrets);let e=n.fetch??fetch,t=await Br(e,n.gateUrl,"/provision",n.agent,n.ownerSecret,{secrets:n.secrets}),o=await Vn({gateUrl:n.gateUrl,agentId:n.agent.agentId,verifier:n.verifier,fetch:e}),r=await It(n.ownerSecret);if(o.ownerPublicKey!==r||!o.signingPublicKey)throw new oe("The gate accepted the secrets, but its quote does not name your key as owner");if(n.agent.signingPublicKey&&n.agent.signingPublicKey!==o.signingPublicKey)throw new oe("The agent's signing key changed while provisioning");return{agentId:o.agentId,provisioningPublicKey:o.provisioningPublicKey,signingPublicKey:o.signingPublicKey,ownerPublicKey:r,written:t?.written??[],claimed:t?.claimed===!0}}async function Oi(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 Br(e,n.gateUrl,"/release",n.agent,n.ownerSecret,{release:!0}),(await Vn({gateUrl:n.gateUrl,agentId:n.agent.agentId,verifier:n.verifier,fetch:e})).ownerPublicKey)throw new oe("The gate says it released the agent, but its quote still names an owner")}var $n=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),vi=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function Si(n,e,t={}){let o=typeof n=="string"?new TextEncoder().encode(n):n;await at(o,e,{identity:t.identity??$n.identity,issuer:t.issuer??$n.issuer});let r;try{r=JSON.parse(new TextDecoder().decode(o))}catch{throw new Error("The signed agent policy is not JSON")}let s=t.role??"agent";if(r?.role!==s)throw new Error(`The signed file is a ${JSON.stringify(r?.role)} policy, not an ${s} one`);let a=t.profile??ie;if(r.profile!==a)throw new Error(`The signed agent policy is for the ${JSON.stringify(r.profile)} profile, not ${a}`);if(t.expectedVersion!==void 0&&r.version!==t.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(r.version)}, not ${t.expectedVersion}`);return Mr(r),r}function Mr(n){for(let e of vi)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 Ui=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function Ci(n){let e=Ui.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 Je=n=>n.trim().replace(/^0x/i,"");function Bi(n,e){return Mr(n),pe({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:n.allowed_tcb_statuses.map(Ci),allowedMrtd:n.allowed_mrtd.map(Je),allowedRtmr0:n.allowed_rtmr0.map(Je),allowedRtmr1:n.allowed_rtmr1.map(Je),allowedRtmr2:n.allowed_rtmr2.map(Je),allowedRtmr3:n.allowed_rtmr3.map(Je)})}var qr=1,Mi=new TextEncoder().encode("calimero.recovery-backup.v1\0"),qi=new TextEncoder().encode("calimero.recovery-backup.v1"),Ni=new TextEncoder().encode("calimero.recovery-backup.key.v1"),Dr=32,Di=1,Ii=2,Ki=0,M=n=>new TextEncoder().encode(n),We=n=>new Uint8Array([n>>8&255,n&255]),Nr=m(M("KEM"),We(Dr)),Ye=m(M("HPKE"),We(Dr),We(Di),We(Ii));function xe(n){return n.kind==="operator"?"operator":`${n.kind}:${n.id}`}async function Cl(){let n=crypto.getRandomValues(new Uint8Array(32));return{secret:n,publicKey:await Li(n)}}async function Li(n){return w((await q(n)).publicKey)}async function Vi(n){let e=M(n.header),t=JSON.parse(n.header);if(typeof t.format!="number"||t.format>qr)throw new Error(`recovery file format ${t.format} is not one this release reads (${qr})`);let o=await crypto.subtle.importKey("raw",B(t.signingKey,"signing key",32),{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify("Ed25519",o,B(n.signature,"signature",64),m(Mi,e)))throw new Error("the node's signature over the header does not hold");return t}async function Ir(n,e){let t=n.length===0?new Uint8Array(32):n,o=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",o,e))}async function $i(n,e,t){let o=new Uint8Array(t),r=new Uint8Array(0);for(let s=1,a=0;a<t;s+=1)r=await Ir(n,m(r,e,new Uint8Array([s]))),o.set(r.subarray(0,Math.min(r.length,t-a)),a),a+=r.length;return o}var Kt=(n,e,t,o)=>Ir(e,m(M("HPKE-v1"),n,M(t),o)),Gn=(n,e,t,o,r)=>$i(e,m(We(r),M("HPKE-v1"),n,M(t),o),r);async function Gi(n,e){let t=await q(e);if(w(t.publicKey)!==n.recipient)throw new Error("this key is not the one the file was sealed to");let o=B(n.enc,"encapsulated key",32),r=await V(t.privateKey,o),s=new Uint8Array(0),a=await Kt(Nr,s,"eae_prk",r),i=await Gn(Nr,a,"shared_secret",m(o,t.publicKey),32),p=await Kt(Ye,s,"psk_id_hash",s),l=await Kt(Ye,s,"info_hash",qi),u=m(new Uint8Array([Ki]),p,l),d=await Kt(Ye,i,"secret",s),y=await Gn(Ye,d,"key",u,32),h=await Gn(Ye,d,"base_nonce",u,12),f=await crypto.subtle.importKey("raw",y,"AES-GCM",!1,["decrypt"]),P;try{P=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:h,additionalData:Ni},f,B(n.wrappedKey,"wrapped key",48)))}catch{throw new Error("this key does not open the file")}if(P.length!==32)throw new Error("the data key is not 32 bytes");return P}async function Bl(n,e,t,o={}){let r=[];for(let p of[...e].sort((l,u)=>l.name.localeCompare(u.name))){let l=await Vi(p);if(o.verifyQuote&&await Qi(l,o.verifyQuote),xe(l.holder)!==xe(n))throw new Error(`${p.name} is ${xe(l.holder)}'s, not ${xe(n)}'s`);r.push({name:p.name,header:l})}let s=async p=>({file:p.name,key:w(await Gi(p.header,t))}),a=r.filter(p=>p.header.kind==="holder").pop();if(!a)throw new Error(`no holder file of ${xe(n)}`);let i=new Map;for(let p of r)p.header.kind==="app"&&p.header.app&&(!o.apps||o.apps.includes(p.header.app))&&i.set(p.header.app,p);return{holder:xe(n),slice:await s(a),apps:await Promise.all([...i.values()].map(s)),code:await Promise.all(r.filter(p=>p.header.kind==="code").map(s))}}async function Hn(n){return new Uint8Array(await crypto.subtle.digest("SHA-256",n))}async function Hi(n,e){let t=M(n),o=new Uint8Array(4);new DataView(o.buffer).setUint32(0,t.length,!1);let r=new Uint8Array(8);return new DataView(r.buffer).setBigUint64(0,BigInt(e),!1),w(await Hn(m(M("calimero.recovery-backup.attest.v1\0"),o,t,r)))}async function Fi(n,e,t,o){let r=await Hn(M(JSON.stringify(e))),s=M(t),a=new Uint8Array(4);new DataView(a.buffer).setUint32(0,s.length,!1);let i=new Uint8Array(8);return new DataView(i.buffer).setBigUint64(0,BigInt(o),!1),w(await Hn(m(M("calimero.tee-attest.receipt-key.v3"),n,r,a,s,i)))}async function Qi(n,e){let t=n.attestation;if(!t||typeof t.quote!="string")throw new Error("the file carries no attestation");if(t.cluster!==n.cluster||t.node!==n.node)throw new Error("the attestation is another node's");if(t.receiptKey!==n.signingKey)throw new Error("the attested key is not the one that signed the file");let o=await Hi(n.cluster,n.node);if(t.nonce!==o)throw new Error("the attestation is not over the recovery nonce");let r=await Fi(B(n.signingKey,"signing key",32),t.governance,n.cluster,n.node);if(!await e({quoteB64:t.quote,nonce:o,reportDataSuffix:r}))throw new Error("the quote was not accepted")}var Fn=1024*1024,Qn=16,zn=64*1024,Jn=512*1024*1024,Yn=(64*1024*1024-1024*1024)/4*3,zi="did:key:z6MknF3p5L5FDHJQ7FREUapuX4Wmp4MtF6WrHYaXS2B3eZQd",Ji=new TextEncoder().encode("calimero.bundle.manifest.v1\0"),Yi="0.1.0",Wi=[237,1],Xi="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Zi=[0,97,115,109,13,0,1,0],ep=/^pipelines\/[A-Za-z0-9._-]+\.yaml$/,tp=/^[A-Za-z0-9_-]{43}$/,np=/^(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-]+)*))?$/,Te=n=>new TextEncoder().encode(n),Lt=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),Vt=(...n)=>{let e=new Uint8Array(n.reduce((o,r)=>o+r.length,0)),t=0;for(let o of n)e.set(o,t),t+=o.length;return e};async function Ze(){let n=new Error("this runtime cannot sign Ed25519 packages (WebCrypto Ed25519 is missing)");if(!globalThis.crypto?.subtle)throw n;try{await ke(new Uint8Array(32),!1)}catch{throw n}}async function $r(n){if(await Ze(),n.length!==32)throw new Error("a publisher seed is 32 bytes");let e=O(await Mt(n));return{seed:Uint8Array.from(n),publicKey:e}}async function op(){return await Ze(),$r(crypto.getRandomValues(new Uint8Array(32)))}async function rp(n){return await Ze(),{privateKey:await ke(Uint8Array.from(n.seed),!1),publicKey:Uint8Array.from(n.publicKey)}}function sp(n){let e=0n;for(let o of n)e=e<<8n|BigInt(o);let t="";for(;e>0n;e/=58n)t=Xi[Number(e%58n)]+t;return"1".repeat(n.findIndex(o=>o!==0)===-1?n.length:n.findIndex(o=>o!==0))+t}function je(n){return`did:key:z${sp(Vt(Uint8Array.from(Wi),n.publicKey))}`}function ap(n){return je(n)===zi}function ip(n){return Te(JSON.stringify({private_key:k(n.seed),public_key:k(n.publicKey),signer_id:je(n)},null,2))}async function pp(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"||!tp.test(t)||k(O(t))!==t)throw new Error("the backup private_key is not an unpadded base64url 32-byte seed");let o=await $r(O(t));if(e.public_key!==void 0&&e.public_key!==k(o.publicKey))throw new Error("the backup public_key is not the seed's");if(e.signer_id!==void 0&&e.signer_id!==je(o))throw new Error("the backup signer_id is not the seed's");return o}function Gr(n){let e=Object.fromEntries(Object.entries(n).filter(([t])=>t!=="signature"&&!t.startsWith("_")));return Te(Xe(e))}function Xe(n){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(!Number.isSafeInteger(n))throw new Error("only safe integers can be canonicalized");return String(n)}return n===null||typeof n=="boolean"?String(n):Array.isArray(n)?`[${n.map(Xe).join(",")}]`:`{${Object.keys(n).sort().map(e=>`${Xe(e)}:${Xe(n[e])}`).join(",")}}`}async function Wn(n){return Ae(Vt(Ji,Gr(n)))}async function cp(n){await Ze();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=O(e.publicKey??""),o=O(e.signature??"");if(t.length!==32||o.length!==64)throw new Error("malformed signature field");let r=await crypto.subtle.importKey("raw",te(t),{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify("Ed25519",r,te(o),te(await Wn(n))))throw new Error("Ed25519 signature verification failed");let a=je({publicKey:t});if(n.signerId!==a)throw new Error(`signerId mismatch: manifest declares '${n.signerId}' but signature public key derives to '${a}'`);return a}function Kr(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 lp(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(!ep.test(n)||Te(n).length>100)throw new Error(`${e} must be pipelines/<name>.yaml (A-Z a-z 0-9 . _ -), at most 100 bytes`)}var Lr=["name","description","author","icon","license","category","guide"];function dp(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([...Lr,"tags"]),o=Object.keys(n).find(s=>!t.has(s));if(o!==void 0)throw e(`has an unknown field '${o}'`);let r={};for(let s of Lr){let a=n[s];if(a!==void 0){if(typeof a!="string")throw e(`${s} must be a string`);r[s]=a}}if(typeof r.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");r.tags=[...n.tags]}return r}var Vr=(n,e)=>({path:n,hash:Lt(Ae(e)),size:e.length}),Hr=n=>512+Math.ceil(n/512)*512;function up(n,e){let t=new Uint8Array(512),o=(r,s)=>t.set(Te(s),r);return o(0,n),o(100,"0000644\0"),o(108,"0000000\0"),o(116,"0000000\0"),o(124,`${e.length.toString(8).padStart(11,"0")}\0`),o(136,"00000000000\0"),o(148," "),o(156,"0"),o(257,"ustar\0"),o(263,"00"),o(148,`${t.reduce((r,s)=>r+s,0).toString(8).padStart(6,"0")}\0 `),Vt(t,e,new Uint8Array((512-e.length%512)%512))}function yp(n){let e=new Map,t=(o,r)=>new TextDecoder().decode(n.subarray(o,r)).replace(/\0.*$/s,"");for(let o=0;o+512<=n.length&&n[o]!==0;){let r=t(o,o+100),s=parseInt(t(o+124,o+136).trim(),8);if(e.has(r))throw new Error(`the archive has more than one entry at '${r}'`);e.set(r,n.subarray(o+512,o+512+s)),o+=Hr(s)}return e}async function hp(n,e){let t=yp(n),o=t.get("manifest.json");if(!o)throw new Error("manifest.json not found in bundle");let r=JSON.parse(new TextDecoder().decode(o));if(await cp(r),r.signature.publicKey!==k(e))throw new Error("the manifest is not signed by the publisher key");let s=[r.compute,...r.pipelines??[]],a=["manifest.json",...s.map(i=>i.path)];if(a.length!==t.size||a.some(i=>!t.has(i)))throw new Error("the archive does not hold exactly the files its manifest declares");for(let i of s){let p=t.get(i.path);if(!p||p.length!==i.size||Lt(Ae(p))!==i.hash)throw new Error(`bundle artifact '${i.path}' failed its integrity check`)}}async function fp(n){if(typeof CompressionStream>"u")throw new Error("this runtime cannot gzip packages (no CompressionStream)");let e=new Blob([te(n)]).stream().pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(e).arrayBuffer())}async function mp(n,e,t){if(e){let r=O(await Mt(e));if(Lt(r)!==Lt(t))throw new Error("the publisher key's publicKey is not its seed's");return{signing:await ke(e,!1),publicKey:r}}let o=n.privateKey;if(o?.algorithm?.name!=="Ed25519"||o.type!=="private"||!o.usages.includes("sign"))throw new Error("the publisher key is not an Ed25519 signing key");return{signing:o,publicKey:t}}async function gp(n,e){let t="seed"in e&&e.seed?Uint8Array.from(e.seed):void 0,o=Uint8Array.from(e.publicKey),r=wp(n);await Ze();let{signing:s,publicKey:a}=await mp(e,t,o),i={...r.manifest,signerId:je({publicKey:a})},p=await crypto.subtle.sign("Ed25519",s,te(await Wn(i)));i.signature={algorithm:"ed25519",publicKey:k(a),signature:k(new Uint8Array(p))};let l=Te(Xe(i));if(l.length>Fn)throw new Error(`bundle manifest.json exceeds the ${Fn} byte cap`);let u=[["manifest.json",l],["compute.wasm",r.compute],...r.files];Fr(u.map(([,h])=>h.length));let d=Vt(...u.map(([h,f])=>up(h,f)),new Uint8Array(1024));await hp(d,a);let y=await fp(d);if(y.length>Yn)throw new Error(`a package is limited to ${Yn>>20} MiB`);return y}function Fr(n){if(n.reduce((e,t)=>e+Hr(t),1024)>Jn)throw new Error(`bundle archive exceeds the ${Jn} byte decompressed cap`)}function wp(n){if(Kr(n.package,"package"),Kr(n.version,"appVersion"),!np.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>Qn)throw new Error(`bundle declares ${n.pipelines.length} pipelines, at most ${Qn} are allowed`);Fr([n.compute.length]);let e=Uint8Array.from(n.compute);if(Zi.some((i,p)=>e[p]!==i))throw new Error("compute: not a WASM component (an SDK 0.12 core module is refused by the node)");let t=n.pipelines.map((i,p)=>(lp(i.path,`pipelines[${p}].path`),[i.path,Te(i.source)])),o=t.find(([,i])=>i.length>zn);if(o)throw new Error(`pipeline '${o[0]}' exceeds the ${zn} byte cap`);let r=t.map(([i])=>i.toLowerCase());if(new Set(r).size!==t.length)throw new Error("two pipelines have the same path");let s=n.metadata===void 0?void 0:dp(n.metadata);return{manifest:{version:"1.0",package:n.package,appVersion:n.version,minRuntimeVersion:Yi,...s?{metadata:s}:{},compute:Vr("compute.wasm",e),...t.length?{pipelines:t.map(([i,p])=>Vr(i,p))}:{}},compute:e,files:t}}export{Rr as AGENT_ATTEST_DOMAIN,xr as AGENT_PROVISION_INFO_DOMAIN,oe as AgentGateError,kt as AppError,lt as ArgsTooLarge,ft as BadOrigin,Ee as CONSENT_STORAGE_KEY,Nn as CalimeroClient,g as CalimeroError,wt as ClusterNotUpgraded,qe as ConfirmCancelled,Ne as ConfirmPromptBlocked,Pe as ConfirmRequired,ht as ConsentStale,tn as DEFAULT_COLLATERAL_MIRROR,cn as DEFAULT_DIRECTORY,pi as DEFAULT_ORG_CAPABILITIES,it as DEFAULT_RELEASE_MIRROR,hn as DEFAULT_RETRY,$ as DirectoryError,b as ExportError,yr as FILE_PART_BYTES,bt as FeatureNotActive,_o as GITHUB_RELEASES,ao as HANDSHAKE_PATH,Ni as HPKE_AAD,qi as HPKE_INFO,dt as IdempotencyMismatch,$n as KMS_RELEASE_SIGNER,W as LoginRequired,Jn as MAX_ARCHIVE_BYTES,Fn as MAX_MANIFEST_BYTES,Yn as MAX_MPK_BYTES,Qn as MAX_PIPELINES_PER_PACKAGE,zn as MAX_PIPELINE_BYTES,On as MAX_RECOVERY_NONCE_BYTES,Sn as MAX_REPORT_PAGE,Eo as MOCK_QUOTE_HEADER,en as NODE_RELEASE_SIGNER,de as NodeTransport,be as NotFound,gt as NotServing,In as ORG_CAPABILITIES,le as OriginNotRegistered,mt as OriginTaken,ie as PRODUCTION_PROFILE,ct as PasskeyUnknownHere,At as QuotaExceeded,tr as RECOVERY_DOMAIN,qr as RECOVERY_FORMAT,ar as RELEASE_VERIFIER,Pt as RecoveryNotReady,ut as ReleaseDeadlineError,yt as RuntimeTooOld,Ue as SEALED_CONTENT_TYPE,io as SEALED_PATH,Mi as SIGNING_LABEL,z as SealedTransportError,_t as SignUpRefused,Ce as StaleTransportKeyError,Et as TrapError,X as UnavailableError,ce as WrongNode,De as WrongRecoveryCode,Va as acceptInviteConsent,Or as agentKeyBinding,Bi as agentQuoteVerifier,Vn as attestAgent,k as b64url,Li as backupPublicKey,ta as browserPasskey,Gr as canonicalizeManifest,Cr as checkOwner,Ro as claimedRelease,rn as cloudNodeReleaseUrl,He as compareVersions,Cn as confirmationCode,Na as consentReturn,La as createInviteConsent,Ka as createOrgConsent,pe as createQuoteVerifier,bn as createRouteClient,gn as createRoutes,Jt as createSealedFetch,Gs as createSignedReleaseVerifier,Ya as deleteOrgConsent,oi as deployerKey,mn as directoryTransport,_e as errorFrom,ip as exportPublisherKey,pn as fetchAttestedKey,on as fetchGithubNodeRelease,nn as fetchNodeRelease,xo as freshCollateral,O as fromB64url,ri as frontendManifest,xi as generateOwnerKey,op as generatePublisherKey,xe as holderKey,Bl as holderRecoveryBody,pp as importPublisherKey,ap as isDevPublisherKey,$a as leaveOrgConsent,Cl as newBackupKeyPair,fn as newIdempotencyKey,Ua as newRecoverySeed,Gi as openDataKey,ci as orgCapabilities,It as ownerPublicKey,gp as packComputePackage,si as pageDeployment,Un as pageQuery,Ba as parseRecoverySeed,Ke as passkeyConfirm,Mn as pendingApprovalsFrom,ii as presenceState,ji as provisionAgent,vr as provisionInfo,Ma as publisherBindingBytes,sr as publisherBindingMessage,yn as queryString,Fi as receiptKeyBinding,Hi as recoveryAttestationNonce,nr as recoveryMessage,Mt as recoveryPublicKey,Ca as recoverySeedText,Z as refusal,Oi as releaseAgent,cr as releaseConsent,ir as releaseNotesUrl,Ga as removeMemberConsent,Qa as removeMemberTeamsConsent,Ja as renameOrgConsent,Ve as retryDelayMs,za as revokeInviteConsent,ue as routePath,Xa as setAllAppsConsent,Wa as setCapabilitiesConsent,Ha as setMemberRoleConsent,Fa as setMemberTeamsConsent,vn as signRecovery,je as signerIdOf,Wn as signingPayload,vo as sseFrames,rr as stalledBy,zt as transportKeyBinding,pt as trustSignedRelease,Zt as trustedMeasurementsFromReleases,Ia as upgradeConsent,Tr as validateAgentId,Qi as verifyRecoveryAttestation,Vi as verifyRecoveryHeader,pr as verifyReleaseUrl,Si as verifySignedAgentPolicy,Po as verifySignedNodeRelease,rp as webCryptoPublisherKey,Da as withdrawConsent,Bn as withoutConsentReturn};
|
|
9
9
|
//# sourceMappingURL=index.browser.mjs.map
|