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