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