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