@calimero-network/mero-js 29.15.0 → 29.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -0
- package/dist/cloud-v2/client.d.ts +20 -129
- package/dist/cloud-v2/client.js +43 -452
- package/dist/index.browser.mjs +5 -5
- package/dist/index.browser.mjs.map +4 -4
- package/dist/index.cjs +503 -383
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.js +4 -0
- package/dist/index.mjs +503 -383
- package/dist/index.mjs.map +4 -4
- package/dist/runtime/index.d.ts +10 -0
- package/dist/runtime/index.js +21 -0
- package/dist/runtime/transport.d.ts +311 -0
- package/dist/runtime/transport.js +576 -0
- package/dist/runtime.browser.mjs +67 -0
- package/dist/runtime.cjs +67 -0
- package/dist/runtime.mjs +67 -0
- package/package.json +9 -2
package/dist/index.browser.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
function E(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function me(t,e,r){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length!==r*2)throw new Error(`${e} must be ${r*2} hex characters, got ${n.length}`);let i=new Uint8Array(r);for(let s=0;s<r;s+=1)i[s]=Number.parseInt(n.slice(s*2,s*2+2),16);return i}function h(...t){let e=new Uint8Array(t.reduce((n,i)=>n+i.length,0)),r=0;for(let n of t)e.set(n,r),r+=n.length;return e}var Gt="Noise_NK_25519_AESGCM_SHA256",Je=32,Ht=16,Ft=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Ze=class t{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(Gt),r=new Uint8Array(32);return r.set(e),new t(r)}async mixHash(e){this.h=await jt(h(this.h,e))}async mixKey(e){let[r,n]=await Or(this.ck,e);this.ck=r,this.k=await crypto.subtle.importKey("raw",n,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:Cr(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(r),r}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let r=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Cr(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),r}split(){return Or(this.ck,new Uint8Array)}};async function Ir(t,e,r){let n=await Ze.initialize();await n.mixHash(e),await n.mixHash(t);let i=await q(r);return await n.mixHash(i.publicKey),await n.mixKey(await ee(i.privateKey,t)),{message1:h(i.publicKey,await n.encryptAndHash(new Uint8Array)),async finish(o){if(o.length<Je+Ht)throw new Error("Noise: message 2 is too short");let a=o.slice(0,Je);return await n.mixHash(a),await n.mixKey(await ee(i.privateKey,a)),{payload:await n.decryptAndHash(o.slice(Je)),split:await n.split()}}}}async function q(t){if(!t){let n;try{n=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 i=new Uint8Array(await crypto.subtle.exportKey("raw",n.publicKey));return{privateKey:n.privateKey,publicKey:i}}let e=await crypto.subtle.importKey("pkcs8",h(Ft,t),{name:"X25519"},!0,["deriveBits"]),r=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:qt(r.x)}}async function ee(t,e){let r=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:r},t,256))}function Cr(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}async function jt(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}async function ze(t,e){let r=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",r,e))}async function Or(t,e){let r=await ze(t,e),n=await ze(r,new Uint8Array([1])),i=await ze(r,h(n,new Uint8Array([2])));return[n,i]}function qt(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(r,n=>n.charCodeAt(0))}var _r="/sealed/v2/handshake",$r="/sealed/v2",te="application/vnd.calimero.sealed",Xe=2,Qt=new TextEncoder().encode("calimero/sealed-http/v2"),re=16,Yt=1+re+8,Jt=0,zt=1,Zt=2,Xt=1+64*1024+16,Wt=1024,en=6e4,rn="calimero.tee-attest.transport-key.v1",tn=[101,204,205,304],Br=new TextEncoder,ne=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},T=class extends Error{constructor(r,n,i,s){super(i);this.status=r;this.code=n;this.retryAfterMs=s;this.name="SealedTransportError"}};async function We(t,e){let r=await crypto.subtle.digest("SHA-256",h(Br.encode(rn),t,e));return new Uint8Array(r)}function er(t){let e=new URL(t.baseUrl),r=e.pathname.replace(/\/+$/,""),n=`${e.origin}${r}`,i=t.fetch??((g,p)=>fetch(g,p)),s=typeof t.transportPublicKey=="function"?t.transportPublicKey:void 0,o=s?Promise.resolve().then(s):Promise.resolve(t.transportPublicKey);o.catch(()=>{});let a,c=async()=>{try{return await Nr(i,n,await Dr(o))}catch(g){if(!(g instanceof ne)||!s)throw g;return o=Promise.resolve().then(s),Nr(i,n,await Dr(o))}},d=async()=>{let g=a??u(void 0),p=await g;if(Date.now()<p.renewAt)return[p,g];let m=u(g);return[await m,m]},u=g=>{if(a===g){let p=c();a=p,p.catch(()=>{a===p&&(a=void 0)})}return a};return async(g,p)=>{let m=new Request(g,p),f=new URL(m.url);if(f.origin!==e.origin||!f.pathname.startsWith(`${r}/`))throw new Error(`Refusing to send ${f.href} outside the sealed node at ${t.baseUrl}`);let b=[];m.headers.forEach((v,H)=>b.push([H,v]));let N={method:m.method,path:f.pathname.slice(r.length)+f.search,headers:b},R=new Uint8Array(await m.arrayBuffer()),k=p?.signal??(g instanceof Request?g.signal:void 0),M=async v=>{let{requestId:H,header:W,envelope:he}=await sn(v,N,R),F=await i(`${n}${$r}`,{method:"POST",headers:{"content-type":te},body:he,signal:k});if(F.headers.get("content-type")!==te)throw await Vr(F);return an(F,v.responseKey,W,H)},[je,qe]=await d();try{return await M(je)}catch(v){if(!(v instanceof T)||v.code!=="unknown_session")throw v;return M(await u(qe))}}}async function Dr(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function Nr(t,e,r){try{return await Mr(t,e,r)}catch(n){if(!(n instanceof T)||n.code!=="busy")throw n;return await new Promise(i=>setTimeout(i,n.retryAfterMs??1e3)),Mr(t,e,r)}}async function Mr(t,e,r){let n=await Ir(r,Qt),i=await t(`${e}${_r}`,{method:"POST",headers:{"content-type":te},body:h(new Uint8Array([Xe]),r,n.message1)});if(i.headers.get("content-type")!==te)throw await Vr(i);let s=await ln(i,Wt);return nn(n,s)}async function nn(t,e){if(e[0]!==Xe)throw new Error("The handshake reply is malformed");let r;try{r=await t.finish(e.slice(1))}catch{throw new Error("The handshake reply did not open: it did not come from the attested node")}let{payload:n,split:i}=r;if(n.length!==re+4)throw new Error("The handshake reply is malformed");let s=n.slice(0,re),o=new DataView(n.buffer,n.byteOffset).getUint32(re,!1),[a,c]=await Promise.all([crypto.subtle.importKey("raw",i[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",i[1],"AES-GCM",!1,["decrypt"])]);return i[0].fill(0),i[1].fill(0),{requestKey:a,responseKey:c,nextRequestId:1,renewAt:Date.now()+o*1e3-en,header(d){let u=new Uint8Array(Yt);return u[0]=Xe,u.set(s,1),new DataView(u.buffer).setBigUint64(1+re,BigInt(d),!1),u}}}async function sn(t,e,r){let n=t.nextRequestId;t.nextRequestId+=1;let i=t.header(n),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:Kr(n,0),additionalData:i},t.requestKey,on(e,r));return{requestId:n,header:i,envelope:h(i,new Uint8Array(s))}}function Kr(t,e){let r=new Uint8Array(12),n=new DataView(r.buffer);return n.setBigUint64(0,BigInt(t),!1),n.setUint32(8,e,!1),r}function on(t,e){let r=Br.encode(JSON.stringify(t)),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,r.length,!1),h(n,r,e)}async function an(t,e,r,n){if(!t.body)throw new Error("The sealed response has no body");let i=cn(t.body.getReader()),s=0,o=async()=>{let u=await i.next();if(!u)return null;let g;try{g=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Kr(n,s),additionalData:r},e,u))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return s+=1,{kind:g[0],data:g.slice(1)}},a=await o();if(!a||a.kind!==Jt)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(tn.includes(c.status))return await i.cancel(),new Response(null,{status:c.status,headers:c.headers});let d=new ReadableStream({async pull(u){try{let g=await o();g?g.kind===zt?u.enqueue(g.data):g.kind===Zt?(u.close(),await i.cancel()):u.error(new Error("The sealed response is malformed")):u.error(new Error("The sealed response was cut short"))}catch(g){u.error(g)}},cancel(){return i.cancel()}});return new Response(d,{status:c.status,headers:c.headers})}function cn(t){let e=new Uint8Array,r=async n=>{for(;e.length<n;){let{done:i,value:s}=await t.read();if(i)return!1;e=h(e,s)}return!0};return{async next(){if(!await r(4))return null;let n=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(n>Xt)throw await t.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await r(4+n))return null;let i=e.slice(4,4+n);return e=e.slice(4+n),i},cancel:()=>t.cancel()}}async function ln(t,e){if(!t.body)return new Uint8Array;let r=t.body.getReader(),n=new Uint8Array;for(;;){let{done:i,value:s}=await r.read();if(i)return n;if(n=h(n,s),n.length>e)throw await r.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function Vr(t){let e,r=`Sealed request refused: HTTP ${t.status}`;try{let s=await t.json();e=s?.error?.code,s?.error?.message&&(r=`Sealed request refused: ${s.error.message}`)}catch{}if(e==="stale_transport_key")return new ne;let n=Number(t.headers.get("retry-after")),i=Number.isFinite(n)&&n>0?Math.min(n,5)*1e3:void 0;return new T(t.status,e,r,i)}var Lr=[{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"]}],Gr=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var dn="1.2.840.10045.2.1",un={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},gn={"P-256":32,"P-384":48},pn={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function Hr(t,e,r){if(e+2>r)throw new Error("it is truncated");let n=t[e];if((n&31)===31)throw new Error("it uses a tag this parser does not read");let i=t[e+1],s=e+2;if(i&128){let a=i&127;if(a===0||a>4||s+a>r)throw new Error("it has a length this parser does not read");i=0;for(let c=0;c<a;c+=1)i=i*256+t[s+c];s+=a}let o=s+i;if(o>r)throw new Error("it is truncated");return{tag:n,bytes:t,offset:e,start:s,end:o}}function Y(t){let e=Hr(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function A(t){let e=[];for(let r=t.start;r<t.end;){let n=Hr(t.bytes,r,t.end);e.push(n),r=n.end}return e}function w(t,e,r){if(!t||t.tag!==e)throw new Error(`${r} is not where it should be`);return t}function S(t){return t.bytes.slice(t.start,t.end)}function we(t){return t.bytes.slice(t.offset,t.end)}function Q(t){let e=S(w(t,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let r=[],n=0;for(let o of e)n=n*128+(o&127),o&128||(r.push(n),n=0);let i=r.shift();return[...i<80?[Math.floor(i/40),i%40]:[2,i-80],...r].join(".")}function fn(t){let e=new TextDecoder().decode(S(t)),r=t.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,n=t.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,i=r??n;if(!i)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let s=Number(i[1]);r&&(s+=s<50?2e3:1900);let[o,a,c,d,u]=i.slice(2).map(Number);return Date.UTC(s,o-1,a,c,d,u)}function rr(t){try{let[e,r,n,...i]=A(w(Y(t),48,"The certificate"));if(i.length>0)throw new Error("it has fields after its signature");let s=A(w(e,48,"The signed part")),o=s[0]?.tag===160?1:0,[a,c,d,u,g,p,...m]=s.slice(o);w(a,2,"The serial number");let f=Q(A(w(r,48,"The signature algorithm"))[0]);if(Q(A(w(c,48,"The signature algorithm"))[0])!==f)throw new Error("it names two different signature algorithms");let N=pn[f];if(!N)throw new Error(`it is signed with ${f}, not ECDSA with SHA-256 or SHA-384`);let[R,k]=A(w(u,48,"The validity")).map(fn);if(k===void 0)throw new Error("its validity is incomplete");let[M,je]=A(w(p,48,"The public key"));w(je,3,"The public key");let[qe,v]=A(w(M,48,"The key algorithm"));if(Q(qe)!==dn)throw new Error("its key is not an elliptic-curve key");let H=un[Q(v)];if(!H)throw new Error("its key is on a curve other than P-256 or P-384");let W=new Map,he=m.find(Qe=>Qe.tag===163);if(he){let[Qe]=A(he);for(let Lt of A(w(Qe,48,"The extensions"))){let j=A(w(Lt,48,"An extension"));if(j.length===3)w(j[1],1,"An extension's critical flag");else if(j.length!==2)throw new Error("it has a malformed extension");let Ye=Q(j[0]);if(W.has(Ye))throw new Error(`it has extension ${Ye} twice`);W.set(Ye,S(w(j[j.length-1],4,"An extension value")))}}let F=S(w(n,3,"The signature"));if(F[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:we(e),signatureHash:N,signature:F.slice(1),issuer:we(w(d,48,"The issuer")),subject:we(w(g,48,"The subject")),notBefore:R,notAfter:k,spki:we(p),curve:H,extensions:W}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function Fr(t){return A(w(Y(t),48,"The list")).map(Q)}function yn(t,e){let r=gn[e],n=A(w(Y(t),48,"The signature"));if(n.length!==2)throw new Error("The signature is not an ECDSA signature");let i=new Uint8Array(r*2);return n.forEach((s,o)=>{let a=S(w(s,2,"The signature"));if(a.length===0||a[0]&128)throw new Error("The signature is not an ECDSA signature");for(;a.length>1&&a[0]===0;)a=a.subarray(1);if(a.length>r)throw new Error("The signature is not an ECDSA signature");i.set(a,o*r+r-a.length)}),i}async function Ae(t,e,r,n,i){let s;try{s=yn(n,e)}catch{return!1}let o=await crypto.subtle.importKey("spki",t,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:r},o,s,i)}function x(t,e){let r=t.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(r)||r.length%4!==0)throw new Error(`${e} is not base64`);let n=atob(r),i=new Uint8Array(n.length);for(let s=0;s<n.length;s+=1)i[s]=n.charCodeAt(s);return i}function tr(t,e){let r=[...t.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(r.length!==1||t.replace(r[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return x(r[0][1],e)}var hn="2.5.29.17",mn="2.5.29.37",wn="1.3.6.1.5.5.7.3.3",An="1.3.6.1.4.1.57264.1.8",bn="1.3.6.1.4.1.57264.1.1",Rn=134,En=12,Pn=48,vn=new TextEncoder,J=t=>new TextDecoder().decode(t);async function be(t,e,r,n){let{base64Signature:i,cert:s,rekorBundle:o}=Tn(e),a=o.Payload;if(n!==void 0&&n.trim()!==i.trim())throw new Error("The detached signature is not the one in the bundle");let c=x(i,"The bundle signature"),d=tr(J(x(s,"The bundle certificate")),"The bundle certificate"),u=rr(d),g=Gr.find(k=>k.logId===a.logID.toLowerCase());if(!g)throw new Error(`The bundle names Rekor log ${a.logID}, which the Sigstore trust root does not know`);let p=vn.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await Ae(x(g.publicKey,"The Rekor key"),"P-256","SHA-256",x(o.SignedEntryTimestamp,"The signed entry timestamp"),p))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let f=a.integratedTime*1e3;if(!Qr(f,g.validFor))throw new Error(`Rekor log ${g.baseUrl} was not in use at ${ie(f)}, when the entry says it was logged`);let b=Sn(a.body),N=E(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(b.hash!==N)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!nr(x(b.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let R=tr(J(x(b.publicKey,"The logged certificate")),"The logged certificate");if(!nr(R,d))throw new Error("The bundle's certificate is not the one Rekor logged");if(u.curve!=="P-256"||!await Ae(u.spki,"P-256","SHA-256",c,t))throw new Error("The signature over the file does not verify with the bundle's certificate");return await xn(u,f),Un(u,r),{integratedTime:a.integratedTime}}async function xn(t,e){if(!qr(t,e))throw new Error(`The signing certificate was valid ${ie(t.notBefore)} to ${ie(t.notAfter)}, not at ${ie(e)} when Rekor logged it`);let r=[];for(let n of Lr){let i=n.certChain.map(o=>rr(x(o,"A Fulcio certificate")));if(!await jr(t,i[0]))continue;let s=await kn(i,n.validFor,e);if(!s)return;r.push(`${n.uri} (valid from ${n.validFor.start}): ${s}`)}throw new Error(r.length>0?`The signing certificate's CA is not trusted at ${ie(e)}: ${r.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function kn(t,e,r){if(!Qr(r,e))return"the trust root says it was not issuing certificates then";for(let[n,i]of t.entries()){if(!qr(i,r))return`its certificate ${n} was not valid then`;let s=t[n+1]??i;if(!await jr(i,s))return`its certificate ${n} is not signed by the next`}}async function jr(t,e){return nr(t.issuer,e.subject)?Ae(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function Un(t,e){let r=t.extensions.get(hn);if(!r)throw new Error("The signing certificate names no identity");let n=A(w(Y(r),Pn,"The subject alternative name")),i=n.filter(d=>d.tag===Rn).map(d=>J(S(d)));if(i.length!==1||n.length!==1||i[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(i.length===1?i[0]:i)}, not by ${e.identity}`);let s=t.extensions.get(An),o=t.extensions.get(bn),a=s?J(S(w(Y(s),En,"The OIDC issuer"))):o?J(o):void 0;if(a!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${a===void 0?"missing":JSON.stringify(a)}, not ${e.issuer}`);let c=t.extensions.get(mn);if(!c||!Fr(c).includes(wn))throw new Error("The signing certificate is not for code signing")}function Tn(t){let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let r=e,n=r?.rekorBundle?.Payload;if(!(typeof r?.base64Signature=="string"&&typeof r.cert=="string"&&typeof r.rekorBundle?.SignedEntryTimestamp=="string"&&typeof n?.body=="string"&&typeof n.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(n.logID)&&Number.isSafeInteger(n.integratedTime)&&n.integratedTime>=0&&Number.isSafeInteger(n.logIndex)&&n.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return r}function Sn(t){let e;try{e=JSON.parse(J(x(t,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let r=e?.spec?.data?.hash,n=e?.spec?.signature;if(e?.kind!=="hashedrekord"||r?.algorithm!=="sha256"||typeof r.value!="string"||typeof n?.content!="string"||typeof n.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:r.value.toLowerCase(),signature:n.content,publicKey:n.publicKey.content}}function qr(t,e){return t.notBefore<=e&&e<=t.notAfter}function Qr(t,e){return Date.parse(e.start)<=t&&(e.end===void 0||t<=Date.parse(e.end))}function ie(t){return new Date(t).toISOString()}function nr(t,e){return t.length===e.length&&t.every((r,n)=>r===e[n])}var Cn=/^[0-9a-f]{96}$/,On=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function $(t){let e=z(t.allowedMrtd??[],"allowedMrtd"),r=(t.allowedMeasurements??[]).map((a,c)=>{let d=`allowedMeasurements[${c}]`;return On.map(u=>z([a?.[u]??""],`${d}.${u}`)[0]).join()}),n=[z(t.allowedRtmr0??[],"allowedRtmr0"),z(t.allowedRtmr1??[],"allowedRtmr1"),z(t.allowedRtmr2??[],"allowedRtmr2"),z(t.allowedRtmr3??[],"allowedRtmr3")];if(t.allowedMeasurements!==void 0&&r.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(r.length===0){if(e.length===0)throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");if(n.slice(1).some(a=>a.length===0))throw new Error("allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too")}let i=t.allowedTcbStatuses??["UpToDate"],s=t.now??Date.now;return Object.assign(async({quoteB64:a,nonce:c,reportDataSuffix:d,collateral:u})=>{let g=Dn(a),p=u??await t.fetchCollateral?.(g);if(!p)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let m;try{m=t.dcapVerify(g,p,Math.floor(s()/1e3))}catch(R){throw new Error(`The quote did not verify: ${R?.message??String(R)}`)}if(m.status==="Revoked"||!i.includes(m.status))throw new Error(`The platform's TCB status is ${m.status}, which is not accepted`);let f=In(m.report);if(f.tdAttributes?.length!==8||(f.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let b=[f.mrTd,f.rtMr0,f.rtMr1,f.rtMr2,f.rtMr3].map(R=>E(R));if(r.length>0&&!r.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([f.rtMr0,f.rtMr1,f.rtMr2,f.rtMr3].forEach((R,k)=>{let M=n[k];if(M.length>0&&!M.includes(E(R)))throw new Error(`RTMR${k} ${E(R)} is not one this verifier trusts`)}),E(f.reportData)!==`${c}${d}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function z(t,e){return t.map(r=>{let n=r.trim().toLowerCase();if(!Cn.test(n))throw new Error(`${e} holds ${JSON.stringify(r)}, which is not a 48-byte hex measurement`);return n})}function In(t){let e=t.data;if(t.type==="td10"&&e)return e;if(t.type==="td15"&&e?.base)return e.base;throw new Error(`The quote is a ${t.type} quote, not a TDX one`)}function Dn(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)r[n]=e.charCodeAt(n);return r}var Nn=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],_="locked-read-only";function ir(t,{profile:e,allowDebugProfile:r=!1}){if(t.length===0)throw new Error("No release given, so no image would be trusted");let n,i=t.map((s,o)=>{let a=s?.tag??`releases[${o}]`;if(s?.role!==void 0&&s.role!=="node")throw new Error(`${a} lists the measurements of a ${s.role}, not of a node image`);let c=s?.profiles?.[e];if(!c){let u=Object.keys(s?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${u})`)}if(e!==_&&!r)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(_)}, or pass allowDebugProfile to test`);let d=(c.allowed_tcb_statuses??["uptodate"]).map(u=>Mn(u,a));return n=n===void 0?d:n.filter(u=>d.includes(u)),{mrtd:c.mrtd,rtmr0:c.rtmr0,rtmr1:c.rtmr1,rtmr2:c.rtmr2,rtmr3:c.rtmr3}});if(!n||n.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:i,allowedTcbStatuses:n}}function Mn(t,e){let r=Nn.find(n=>n.toLowerCase()===String(t).toLowerCase());if(!r)throw new Error(`${e} accepts TCB status ${JSON.stringify(t)}, which this verifier does not know`);return r}var sr=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"}),_n=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],Re="https://cloud.calimero.network",or=`${Re}/api/tee/pcs`;async function Jr(t,e,r={}){let n=typeof t=="string"?new TextEncoder().encode(t):t;await be(n,e,{identity:r.identity??sr.identity,issuer:r.issuer??sr.issuer},r.signature);let i;try{i=JSON.parse(new TextDecoder().decode(n))}catch{throw new Error("The signed release is not JSON")}if(i?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(i?.role)} release, not a node one`);let s=Object.values(i.profiles??{}),o=a=>_n.every(c=>/^[0-9a-f]{96}$/i.test(String(a?.[c])));if(typeof i.tag!="string"||s.length===0||!s.every(o))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(r.expectedVersion!==void 0&&i.tag!==r.expectedVersion)throw new Error(`The signed release is ${i.tag}, not ${r.expectedVersion}`);return i}async function ar(t,e={}){let r=await(e.fetch??fetch)(t,{headers:{accept:"application/json"}});if(!r.ok)throw new Error(`Fetching the node release from ${t} failed: HTTP ${r.status}`);let n;try{n=(await r.json())?.data}catch{throw new Error(`${t} did not answer with JSON`)}if(typeof n?.version!="string"||typeof n.publishedMrtds!="string"||typeof n.bundle!="string")throw new Error(`${t} did not answer with a signed node release`);return{version:n.version,publishedMrtds:n.publishedMrtds,bundle:n.bundle}}var zr="https://github.com/calimero-network/mero-tee/releases/download";async function cr(t,e={}){let r=`mero-tee-v${C(t,"version")}`,n=`${(e.base??zr).replace(/\/+$/,"")}/${r}/published-mrtds.json`,i=async a=>{let c=await(e.fetch??fetch)(a);if(!c.ok)throw new Error(`Fetching ${a} failed: HTTP ${c.status}`);return c.text()},[s,o]=await Promise.all([i(n),i(`${n}.bundle.json`)]);return{version:t,publishedMrtds:s,bundle:o}}function lr(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${C(e,"version")}`}async function Ee(t){let e=C(t.minReleaseVersion,"minReleaseVersion"),r=C(t.release?.version,"The release version"),n=await Jr(t.release.publishedMrtds,t.release.bundle,{expectedVersion:r,identity:t.identity,issuer:t.issuer});if(se(r,e)<0)throw new Error(`Release ${r} is older than the minimum trusted, ${e}`);return ir([n],{profile:t.profile,allowDebugProfile:t.allowDebugProfile})}function $n(t){return C(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async r=>{let n=await Ee({release:await t.release(),profile:t.profile,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer});return $({dcapVerify:t.dcapVerify,fetchCollateral:t.fetchCollateral,now:t.now,...n})(r)},{includeCollateral:!0})}var Zr=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function C(t,e){let r=typeof t=="string"?Zr.exec(t):null,n=r?.[4];if(!r||n!==void 0&&n.split(".").some(i=>i===""))throw new Error(`${e} is ${JSON.stringify(t)}, not a release version like 2.3.87`);return t}function se(t,e){let[r,n]=Yr(t),[i,s]=Yr(e);for(let c=0;c<3;c+=1)if(r[c]!==i[c])return r[c]<i[c]?-1:1;if(n===void 0||s===void 0)return n===s?0:n===void 0?1:-1;let o=n.split("."),a=s.split(".");for(let c=0;c<Math.max(o.length,a.length);c+=1){let[d,u]=[o[c],a[c]];if(d===void 0||u===void 0)return d===void 0?-1:1;let[g,p]=[/^\d+$/.test(d),/^\d+$/.test(u)],m=g&&p?Math.sign(Number(d)-Number(u)):g!==p?g?-1:1:d<u?-1:d>u?1:0;if(m!==0)return m}return 0}function Yr(t){let e=Zr.exec(t);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var Wr="MOCK_TDX_QUOTE_V1";function Bn(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function dr(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}var Xr;async function ur(t){Xr??(Xr=import("@phala/dcap-qvl"));let e=await Xr,r=typeof e[t]=="function"?e[t]:e.default?.[t];if(typeof r!="function")throw new TypeError(`@phala/dcap-qvl loaded without ${t}`);return r}function et(t,e){let r=C(e,"minReleaseVersion"),n=String(t.release?.version??"").trim().replace(/^mero-tee-v/,"").replace(/^v/,""),i=C(n,"The release the node names");if(se(i,r)<0)throw new Error(`mero-tee release ${i} is older than the minimum ${r}`);return i}async function Kn(t,e,r){let n=e.releaseSource;return typeof n=="function"?n(t):n==="github"?cr(t,{fetch:r}):ar(lr(n??Re,t),{fetch:r})}function Vn(t){let e=t.collateralSource??or;return e==="intel"?async r=>(await ur("getCollateralFromPcs"))(r):async r=>(await ur("getCollateral"))(e,r)}function rt(t,e){let r=e.maxCollateralAgeDays;return r===void 0?t:async n=>{let i=await t(n),s;try{s=Date.parse(JSON.parse(i.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 o=((e.now??Date.now)()-s)/864e5;if(o>r)throw new Error(`The quote's collateral was issued ${Math.floor(o)} days ago, more than the ${r} this client accepts`);return i}}async function Ln(t,e,r,n){let i=et(t,r.minReleaseVersion),s=await Ee({release:await Kn(i,r,n),profile:r.profile??_,allowDebugProfile:r.allowDebugProfile,minReleaseVersion:r.minReleaseVersion,identity:r.identity,issuer:r.issuer}),o=rt(r.fetchCollateral??Vn(r),r);return $({dcapVerify:r.dcapVerify??await ur("verify"),fetchCollateral:o,now:r.now,...s})(e)}async function gr(t,e,r=(n,i)=>fetch(n,i)){let n=E(crypto.getRandomValues(new Uint8Array(32))),i=new URL(`${t.replace(/\/+$/,"")}/attestation`);i.searchParams.set("nonce",n),e.appHash&&i.searchParams.set("appHash",e.appHash);let s=await r(i.toString());if(!s.ok)throw new Error(`The node refused to attest: HTTP ${s.status}`);let o=await s.json(),a=me(o.transportKey,"transportKey",32),c=e.appHash?me(e.appHash,"appHash",32):new Uint8Array(32),d=await We(c,a),u=Bn(o.quote),g=new TextEncoder().encode(Wr);if(dr(u.slice(0,g.length),g)){if(!e.allowMock)throw new Error("mock quote refused: this client only trusts real TEEs");let f=u.slice(g.length,g.length+64);if(!dr(f.slice(0,32),me(n,"nonce",32))||!dr(f.slice(32),d))throw new Error("the quote does not bind this transport key, app and nonce");return a}let p={quoteB64:o.quote,nonce:n,reportDataSuffix:E(d)},m;if(e.verifyQuote)m=await e.verifyQuote(p);else if(e.release)m=await Ln(o,p,e.release,r);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 a}var pr="https://manager.cloud.calimero.network/api/v2/directory";var U=class extends Error{constructor(r,n,i,s,o){super(`directory for cluster ${r}: ${i}`);this.cluster=r;this.reason=n;this.status=s;this.cause=o;this.name="DirectoryError"}};function Gn(t,e){return`${t.replace(/\/+$/,"")}/${encodeURIComponent(e)}`}async function fr(t,e,r){let n;try{n=await r(Gn(t,e),{method:"GET",headers:{accept:"application/json"}})}catch(u){throw new U(e,"unreachable",`could not be reached: ${String(u)}`,void 0,u)}if(n.status===404)throw new U(e,"not-found","unknown cluster",404);if(!n.ok)throw new U(e,"unreachable",`answered ${n.status}`,n.status);let i;try{i=await n.json()}catch(u){throw new U(e,"bad-response","answered something other than JSON",n.status,u)}let s=i;if(!s||typeof s!="object"||!Array.isArray(s.nodes))throw new U(e,"bad-response","answered no node list",n.status);let o=[],a=new Set;for(let u of s.nodes){let g=Hn(u);g&&!a.has(g.url)&&(a.add(g.url),o.push(g))}if(o.length===0)throw new U(e,"empty","lists no usable node",n.status);let c=s.refreshAfterSeconds,d=typeof c=="number"&&Number.isFinite(c)&&c>=1?c:60;return{nodes:o,refreshAfterSeconds:d}}function Hn(t){if(!t||typeof t!="object")return;let{url:e,zone:r,weight:n}=t;if(typeof e!="string"||typeof n!="number"||!Number.isInteger(n)||n<1)return;let i;try{i=new URL(e)}catch{return}if(!(i.protocol!=="https:"&&i.protocol!=="http:"))return{url:e.replace(/\/+$/,""),zone:typeof r=="string"?r:void 0,weight:n}}function yr(t,e,r){let n=e===void 0?[]:t.filter(s=>s.zone===e),i=e===void 0?t:t.filter(s=>s.zone!==e);return[...tt(n,r),...tt(i,r)]}function tt(t,e){let r=[...t],n=[];for(;r.length>0;){let i=e()*r.reduce((o,a)=>o+a.weight,0),s=0;for(;s<r.length-1&&i>=r[s].weight;)i-=r[s++].weight;n.push(r.splice(s,1)[0].url)}return n}var y=class extends Error{constructor(r,n,i,s={}){super(`${r} ${n}: ${i}`);this.status=r;this.code=n;this.details=s;this.name="CalimeroError"}},B=class extends y{constructor(e,r={}){super(401,"UNAUTHENTICATED",e,r),this.name="LoginRequired"}},Pe=class extends y{constructor(e,r={}){super(401,"PASSKEY_UNKNOWN_HERE",e||"this passkey belongs to another Calimero cluster or was removed from this one",r),this.name="PasskeyUnknownHere"}},K=class extends y{constructor(e,r={}){super(421,"WRONG_NODE",e,r),this.name="WrongNode"}},ve=class extends y{constructor(e,r={}){super(404,"NOT_FOUND",e,r),this.name="NotFound"}},Z=class extends y{constructor(e,r={}){super(412,"CONFIRM_REQUIRED",e,r),this.name="ConfirmRequired"}},oe=class extends Error{constructor(r){super("the passkey confirmation was cancelled");this.cause=r;this.name="ConfirmCancelled"}},ae=class extends Error{constructor(r){super("the passkey prompt was blocked by the browser or a password manager");this.cause=r;this.name="ConfirmPromptBlocked"}},xe=class extends y{constructor(e,r={}){super(413,"ARGS_TOO_LARGE",e,r),this.name="ArgsTooLarge"}},ke=class extends y{constructor(e,r={}){super(409,"IDEMPOTENCY_MISMATCH",e,r),this.name="IdempotencyMismatch"}},Ue=class extends y{constructor(e,r={}){super(409,"RELEASE_DEADLINE",e,r),this.name="ReleaseDeadlineError",this.release=typeof r.release=="string"?r.release:"",this.after=typeof r.after=="string"?r.after:""}},Te=class extends y{constructor(e,r={}){super(409,"RUNTIME_TOO_OLD",e,r),this.name="RuntimeTooOld",this.minRuntimeVersion=typeof r.minRuntimeVersion=="string"?r.minRuntimeVersion:"",this.nodes=Array.isArray(r.nodes)?r.nodes:[]}},Se=class extends y{constructor(e,r={}){super(409,"CONSENT_STALE",e,r),this.name="ConsentStale"}},V=class extends y{constructor(e,r={}){let n=typeof r.origin=="string"?r.origin:"",i=typeof r.package=="string"?r.package:"",s=n?`this site (${n})`:"this site";super(403,"ORIGIN_NOT_REGISTERED",`${s} is not registered for ${i||"any package"}${e?` (${e})`:""}`,r),this.name="OriginNotRegistered",this.origin=n,this.package=i,this.nodeMessage=e}},Ce=class extends y{constructor(e,r,n={}){super(400,e,r,n),this.name="BadOrigin"}},Oe=class extends y{constructor(e,r={}){super(409,"ORIGIN_TAKEN",e,r),this.name="OriginTaken"}},Ie=class extends y{constructor(e,r={}){super(400,"NOT_SERVING",e,r),this.name="NotServing"}},De=class extends y{constructor(e,r={}){super(409,"CLUSTER_NOT_UPGRADED",e,r),this.name="ClusterNotUpgraded"}},Ne=class extends y{constructor(e,r={}){super(409,"RECOVERY_NOT_READY",e,r),this.name="RecoveryNotReady",this.readyAt=typeof r.readyAt=="number"?r.readyAt:void 0}},ce=class extends y{constructor(e,r={}){super(401,"UNAUTHENTICATED",e||"unknown or used recovery code",r),this.name="WrongRecoveryCode"}},Me=class extends y{constructor(e,r={}){super(403,"SIGN_UP_REFUSED",e,r),this.name="SignUpRefused",this.reason=Fn(e)}};function Fn(t){return/invite only/.test(t)?"invite-only":/pre-authorized|sign-up invite/.test(t)?"closed":/unknown invite/.test(t)?"unknown-invite":/invite has expired/.test(t)?"expired-invite":/organization is gone/.test(t)?"org-gone":"other"}var _e=class extends y{constructor(e,r={}){super(429,"QUOTA_EXCEEDED",e,r),this.name="QuotaExceeded"}},$e=class extends y{constructor(e,r={}){super(422,"APP_ERROR",e,r),this.name="AppError";let{appCode:n,fields:i}=jn(r);this.appCode=n,this.fields=i}},Be=class extends y{constructor(e,r={}){super(422,"TRAP",e,r),this.name="TrapError",this.kind=typeof r.kind=="string"?r.kind:""}},L=class extends y{constructor(e,r,n={},i,s){super(503,e,r,n),this.name="UnavailableError",this.reason=e.toLowerCase(),this.committed=e==="TIMEOUT"||e==="MIGRATING"?!1:"unknown",this.retryAfter=i,this.cause=s}};function Ke(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function jn(t){let e=typeof t.code=="string"?t:Ke(t.error);return{appCode:typeof e.code=="string"?e.code:"",fields:{...Ke(e.fields)}}}function qn(t,e){for(let r of[t.retryAfter,e==null?void 0:Number(e)])if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}function Ve(t,e,r){let n=Ke(e),i=typeof n.error=="string"?n.error:"ERROR",s=typeof n.message=="string"?n.message:"",o=Ke(n.details);if(t===503)return new L(i,s,o,qn(o,r));switch(`${t} ${i}`){case"401 UNAUTHENTICATED":return new B(s,o);case"401 PASSKEY_UNKNOWN_HERE":return new Pe(s,o);case"421 WRONG_NODE":return new K(s,o);case"404 NOT_FOUND":return new ve(s,o);case"409 IDEMPOTENCY_MISMATCH":return new ke(s,o);case"409 RELEASE_DEADLINE":return new Ue(s,o);case"409 RUNTIME_TOO_OLD":return new Te(s,o);case"409 CONSENT_STALE":return new Se(s,o);case"403 ORIGIN_NOT_REGISTERED":return new V(s,o);case"400 BAD_ORIGIN":case"400 BAD_RP_ID":return new Ce(i,s,o);case"409 ORIGIN_TAKEN":return new Oe(s,o);case"400 NOT_SERVING":return new Ie(s,o);case"409 CLUSTER_NOT_UPGRADED":return new De(s,o);case"429 QUOTA_EXCEEDED":return new _e(s,o);case"409 RECOVERY_NOT_READY":return new Ne(s,o);case"403 SIGN_UP_REFUSED":return new Me(s,o);case"412 CONFIRM_REQUIRED":return new Z(s,o);case"413 ARGS_TOO_LARGE":return new xe(s,o);case"422 APP_ERROR":return new $e(s,o);case"422 TRAP":return new Be(s,o);default:return new y(t,i,s,o)}}function P(t){let e="";for(let r of t)e+=String.fromCharCode(r);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function O(t){let e=t.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((t.length+3)%4),r=atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return n}var le=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);function hr(t){let e=new Error(t);return e.name="NotAllowedError",e}async function nt(t,e,r,n){let i=navigator.credentials,o=globalThis.CredentialsContainer?.prototype?.[t]??i[t];try{return await o.call(i,r?{...e,signal:r}:e)}catch(a){throw r?.aborted||a?.name==="AbortError"?Object.assign(hr(`${n} was cancelled`),{cause:a}):a}}function Qn(t){let e=t.filter(r=>r.alg===-7);return e.length?e:t}function Yn(){return{async create(t,e){let r=t,n=await nt("create",{publicKey:{challenge:le(O(r.challenge)),rp:r.rp,user:{...r.user,id:le(O(r.user.id))},pubKeyCredParams:Qn(r.pubKeyCredParams),excludeCredentials:(r.excludeCredentials??[]).map(s=>({type:s.type,id:le(O(s.id))})),authenticatorSelection:r.authenticatorSelection,attestation:"none",timeout:r.timeout}},e?.signal,"passkey creation");if(!n)throw hr("passkey creation was cancelled");let i=n.response;return{attestationObject:P(new Uint8Array(i.attestationObject)),clientDataJson:P(new Uint8Array(i.clientDataJSON))}},async get(t,e,r,n){let i=await nt("get",{publicKey:{challenge:le(t),rpId:e,userVerification:n?.userVerification??"preferred",allowCredentials:(r??[]).map(o=>({type:"public-key",id:le(O(o))}))}},n?.signal,"passkey sign-in");if(!i)throw hr("passkey sign-in was cancelled");let s=i.response;return{credentialId:P(new Uint8Array(i.rawId)),authenticatorData:P(new Uint8Array(s.authenticatorData)),clientDataJson:P(new Uint8Array(s.clientDataJSON)),signature:P(new Uint8Array(s.signature))}}}}var it="calimero.org-recovery.v1\0",wr=64,mr=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function Jn(){return crypto.getRandomValues(new Uint8Array(32))}function zn(t){ot(t);let e=Array.from(t,n=>n.toString(16).padStart(2,"0")).join(""),r=[];for(let n=0;n<e.length;n+=8)r.push(e.slice(n,n+8));return r.join("-")}function Zn(t){let e=t.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},(r,n)=>parseInt(e.slice(2*n,2*n+2),16))}function st(t,e,r){return new TextEncoder().encode(`${it}${t}\0${e}\0${r}`)}async function Xn(t){let e=await at(t,!0),r=await crypto.subtle.exportKey("jwk",e);if(!r.x)throw new Error("this runtime cannot export an Ed25519 public key");return r.x}async function Ar(t,e,r,n){let i=new TextEncoder().encode(n).length;if(i===0||i>wr)throw new Error(`a recovery nonce is 1 to ${wr} bytes`);let s=await at(t,!1),o=await crypto.subtle.sign("Ed25519",s,ct(st(e,r,n)));return P(new Uint8Array(o))}function ot(t){if(t.length!==32)throw new Error("a recovery seed is 32 bytes")}function at(t,e){ot(t);let r=new Uint8Array(mr.length+32);return r.set(mr),r.set(t,mr.length),crypto.subtle.importKey("pkcs8",ct(r),{name:"Ed25519"},e,["sign"])}var ct=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);var br=100;function ue(t={}){let e=new URLSearchParams;if(t.after!==void 0&&e.set("after",t.after),t.limit!==void 0){if(!Number.isInteger(t.limit)||t.limit<1||t.limit>br)throw new RangeError(`limit is 1 to ${br}`);e.set("limit",String(t.limit))}let r=e.toString();return r?`?${r}`:""}function de(t,e){try{return se(t,e)}catch{return t<e?-1:t>e?1:0}}function lt(t,e,r=Date.now()/1e3){if(t===null||t.length===0)return null;let n=t.reduce((s,o)=>de(s,o)>=0?s:o),i=null;for(let s of e)s.afterSecs<=r&&de(n,s.version)<0&&(i===null||de(s.version,i.version)>0)&&(i=s);return i}function dt(t,e,r,n){return`calimero-publisher-binding/v1
|
|
1
|
+
function E(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function Ae(t,e,r){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length!==r*2)throw new Error(`${e} must be ${r*2} hex characters, got ${n.length}`);let s=new Uint8Array(r);for(let i=0;i<r;i+=1)s[i]=Number.parseInt(n.slice(i*2,i*2+2),16);return s}function m(...t){let e=new Uint8Array(t.reduce((n,s)=>n+s.length,0)),r=0;for(let n of t)e.set(n,r),r+=n.length;return e}var Jt="Noise_NK_25519_AESGCM_SHA256",We=32,zt=16,Zt=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),rr=class t{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(Jt),r=new Uint8Array(32);return r.set(e),new t(r)}async mixHash(e){this.h=await Xt(m(this.h,e))}async mixKey(e){let[r,n]=await Br(this.ck,e);this.ck=r,this.k=await crypto.subtle.importKey("raw",n,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:$r(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(r),r}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let r=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:$r(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),r}split(){return Br(this.ck,new Uint8Array)}};async function Kr(t,e,r){let n=await rr.initialize();await n.mixHash(e),await n.mixHash(t);let s=await Q(r);return await n.mixHash(s.publicKey),await n.mixKey(await re(s.privateKey,t)),{message1:m(s.publicKey,await n.encryptAndHash(new Uint8Array)),async finish(o){if(o.length<We+zt)throw new Error("Noise: message 2 is too short");let a=o.slice(0,We);return await n.mixHash(a),await n.mixKey(await re(s.privateKey,a)),{payload:await n.decryptAndHash(o.slice(We)),split:await n.split()}}}}async function Q(t){if(!t){let n;try{n=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"])}catch(i){throw new Error(`Sealed transport needs WebCrypto with X25519, which this runtime lacks (${i?.name??"no crypto.subtle"}). Current browsers and Node have it; in React Native, install react-native-quick-crypto as the global crypto.`)}let s=new Uint8Array(await crypto.subtle.exportKey("raw",n.publicKey));return{privateKey:n.privateKey,publicKey:s}}let e=await crypto.subtle.importKey("pkcs8",m(Zt,t),{name:"X25519"},!0,["deriveBits"]),r=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Wt(r.x)}}async function re(t,e){let r=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:r},t,256))}function $r(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}async function Xt(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}async function er(t,e){let r=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",r,e))}async function Br(t,e){let r=await er(t,e),n=await er(r,new Uint8Array([1])),s=await er(r,m(n,new Uint8Array([2])));return[n,s]}function Wt(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(r,n=>n.charCodeAt(0))}var qr="/sealed/v2/handshake",Gr="/sealed/v2",ne="application/vnd.calimero.sealed",tr=2,en=new TextEncoder().encode("calimero/sealed-http/v2"),te=16,rn=1+te+8,tn=0,nn=1,sn=2,on=1+64*1024+16,an=1024,cn=6e4,ln="calimero.tee-attest.transport-key.v1",un=[101,204,205,304],Fr=new TextEncoder,se=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},S=class extends Error{constructor(r,n,s,i){super(s);this.status=r;this.code=n;this.retryAfterMs=i;this.name="SealedTransportError"}};async function nr(t,e){let r=await crypto.subtle.digest("SHA-256",m(Fr.encode(ln),t,e));return new Uint8Array(r)}function sr(t){let e=new URL(t.baseUrl),r=e.pathname.replace(/\/+$/,""),n=`${e.origin}${r}`,s=t.fetch??((g,p)=>fetch(g,p)),i=typeof t.transportPublicKey=="function"?t.transportPublicKey:void 0,o=i?Promise.resolve().then(i):Promise.resolve(t.transportPublicKey);o.catch(()=>{});let a,c=async()=>{try{return await Lr(s,n,await Vr(o))}catch(g){if(!(g instanceof se)||!i)throw g;return o=Promise.resolve().then(i),Lr(s,n,await Vr(o))}},u=async()=>{let g=a??d(void 0),p=await g;if(Date.now()<p.renewAt)return[p,g];let h=d(g);return[await h,h]},d=g=>{if(a===g){let p=c();a=p,p.catch(()=>{a===p&&(a=void 0)})}return a};return async(g,p)=>{let h=new Request(g,p),y=new URL(h.url);if(y.origin!==e.origin||!y.pathname.startsWith(`${r}/`))throw new Error(`Refusing to send ${y.href} outside the sealed node at ${t.baseUrl}`);let b=[];h.headers.forEach((v,G)=>b.push([G,v]));let M={method:h.method,path:y.pathname.slice(r.length)+y.search,headers:b},R=new Uint8Array(await h.arrayBuffer()),k=p?.signal??(g instanceof Request?g.signal:void 0),_=async v=>{let{requestId:G,header:ee,envelope:we}=await gn(v,M,R),F=await s(`${n}${Gr}`,{method:"POST",headers:{"content-type":ne},body:we,signal:k});if(F.headers.get("content-type")!==ne)throw await Qr(F);return fn(F,v.responseKey,ee,G)},[Je,ze]=await u();try{return await _(Je)}catch(v){if(!(v instanceof S)||v.code!=="unknown_session")throw v;return _(await d(ze))}}}async function Vr(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function Lr(t,e,r){try{return await Hr(t,e,r)}catch(n){if(!(n instanceof S)||n.code!=="busy")throw n;return await new Promise(s=>setTimeout(s,n.retryAfterMs??1e3)),Hr(t,e,r)}}async function Hr(t,e,r){let n=await Kr(r,en),s=await t(`${e}${qr}`,{method:"POST",headers:{"content-type":ne},body:m(new Uint8Array([tr]),r,n.message1)});if(s.headers.get("content-type")!==ne)throw await Qr(s);let i=await mn(s,an);return dn(n,i)}async function dn(t,e){if(e[0]!==tr)throw new Error("The handshake reply is malformed");let r;try{r=await t.finish(e.slice(1))}catch{throw new Error("The handshake reply did not open: it did not come from the attested node")}let{payload:n,split:s}=r;if(n.length!==te+4)throw new Error("The handshake reply is malformed");let i=n.slice(0,te),o=new DataView(n.buffer,n.byteOffset).getUint32(te,!1),[a,c]=await Promise.all([crypto.subtle.importKey("raw",s[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",s[1],"AES-GCM",!1,["decrypt"])]);return s[0].fill(0),s[1].fill(0),{requestKey:a,responseKey:c,nextRequestId:1,renewAt:Date.now()+o*1e3-cn,header(u){let d=new Uint8Array(rn);return d[0]=tr,d.set(i,1),new DataView(d.buffer).setBigUint64(1+te,BigInt(u),!1),d}}}async function gn(t,e,r){let n=t.nextRequestId;t.nextRequestId+=1;let s=t.header(n),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:jr(n,0),additionalData:s},t.requestKey,pn(e,r));return{requestId:n,header:s,envelope:m(s,new Uint8Array(i))}}function jr(t,e){let r=new Uint8Array(12),n=new DataView(r.buffer);return n.setBigUint64(0,BigInt(t),!1),n.setUint32(8,e,!1),r}function pn(t,e){let r=Fr.encode(JSON.stringify(t)),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,r.length,!1),m(n,r,e)}async function fn(t,e,r,n){if(!t.body)throw new Error("The sealed response has no body");let s=yn(t.body.getReader()),i=0,o=async()=>{let d=await s.next();if(!d)return null;let g;try{g=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:jr(n,i),additionalData:r},e,d))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return i+=1,{kind:g[0],data:g.slice(1)}},a=await o();if(!a||a.kind!==tn)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(un.includes(c.status))return await s.cancel(),new Response(null,{status:c.status,headers:c.headers});let u=new ReadableStream({async pull(d){try{let g=await o();g?g.kind===nn?d.enqueue(g.data):g.kind===sn?(d.close(),await s.cancel()):d.error(new Error("The sealed response is malformed")):d.error(new Error("The sealed response was cut short"))}catch(g){d.error(g)}},cancel(){return s.cancel()}});return new Response(u,{status:c.status,headers:c.headers})}function yn(t){let e=new Uint8Array,r=async n=>{for(;e.length<n;){let{done:s,value:i}=await t.read();if(s)return!1;e=m(e,i)}return!0};return{async next(){if(!await r(4))return null;let n=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(n>on)throw await t.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await r(4+n))return null;let s=e.slice(4,4+n);return e=e.slice(4+n),s},cancel:()=>t.cancel()}}async function mn(t,e){if(!t.body)return new Uint8Array;let r=t.body.getReader(),n=new Uint8Array;for(;;){let{done:s,value:i}=await r.read();if(s)return n;if(n=m(n,i),n.length>e)throw await r.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function Qr(t){let e,r=`Sealed request refused: HTTP ${t.status}`;try{let i=await t.json();e=i?.error?.code,i?.error?.message&&(r=`Sealed request refused: ${i.error.message}`)}catch{}if(e==="stale_transport_key")return new se;let n=Number(t.headers.get("retry-after")),s=Number.isFinite(n)&&n>0?Math.min(n,5)*1e3:void 0;return new S(t.status,e,r,s)}var Yr=[{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"]}],Jr=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var hn="1.2.840.10045.2.1",wn={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},An={"P-256":32,"P-384":48},bn={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function zr(t,e,r){if(e+2>r)throw new Error("it is truncated");let n=t[e];if((n&31)===31)throw new Error("it uses a tag this parser does not read");let s=t[e+1],i=e+2;if(s&128){let a=s&127;if(a===0||a>4||i+a>r)throw new Error("it has a length this parser does not read");s=0;for(let c=0;c<a;c+=1)s=s*256+t[i+c];i+=a}let o=i+s;if(o>r)throw new Error("it is truncated");return{tag:n,bytes:t,offset:e,start:i,end:o}}function J(t){let e=zr(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function A(t){let e=[];for(let r=t.start;r<t.end;){let n=zr(t.bytes,r,t.end);e.push(n),r=n.end}return e}function w(t,e,r){if(!t||t.tag!==e)throw new Error(`${r} is not where it should be`);return t}function C(t){return t.bytes.slice(t.start,t.end)}function be(t){return t.bytes.slice(t.offset,t.end)}function Y(t){let e=C(w(t,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let r=[],n=0;for(let o of e)n=n*128+(o&127),o&128||(r.push(n),n=0);let s=r.shift();return[...s<80?[Math.floor(s/40),s%40]:[2,s-80],...r].join(".")}function Rn(t){let e=new TextDecoder().decode(C(t)),r=t.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,n=t.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,s=r??n;if(!s)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let i=Number(s[1]);r&&(i+=i<50?2e3:1900);let[o,a,c,u,d]=s.slice(2).map(Number);return Date.UTC(i,o-1,a,c,u,d)}function ir(t){try{let[e,r,n,...s]=A(w(J(t),48,"The certificate"));if(s.length>0)throw new Error("it has fields after its signature");let i=A(w(e,48,"The signed part")),o=i[0]?.tag===160?1:0,[a,c,u,d,g,p,...h]=i.slice(o);w(a,2,"The serial number");let y=Y(A(w(r,48,"The signature algorithm"))[0]);if(Y(A(w(c,48,"The signature algorithm"))[0])!==y)throw new Error("it names two different signature algorithms");let M=bn[y];if(!M)throw new Error(`it is signed with ${y}, not ECDSA with SHA-256 or SHA-384`);let[R,k]=A(w(d,48,"The validity")).map(Rn);if(k===void 0)throw new Error("its validity is incomplete");let[_,Je]=A(w(p,48,"The public key"));w(Je,3,"The public key");let[ze,v]=A(w(_,48,"The key algorithm"));if(Y(ze)!==hn)throw new Error("its key is not an elliptic-curve key");let G=wn[Y(v)];if(!G)throw new Error("its key is on a curve other than P-256 or P-384");let ee=new Map,we=h.find(Ze=>Ze.tag===163);if(we){let[Ze]=A(we);for(let Yt of A(w(Ze,48,"The extensions"))){let j=A(w(Yt,48,"An extension"));if(j.length===3)w(j[1],1,"An extension's critical flag");else if(j.length!==2)throw new Error("it has a malformed extension");let Xe=Y(j[0]);if(ee.has(Xe))throw new Error(`it has extension ${Xe} twice`);ee.set(Xe,C(w(j[j.length-1],4,"An extension value")))}}let F=C(w(n,3,"The signature"));if(F[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:be(e),signatureHash:M,signature:F.slice(1),issuer:be(w(u,48,"The issuer")),subject:be(w(g,48,"The subject")),notBefore:R,notAfter:k,spki:be(p),curve:G,extensions:ee}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function Zr(t){return A(w(J(t),48,"The list")).map(Y)}function En(t,e){let r=An[e],n=A(w(J(t),48,"The signature"));if(n.length!==2)throw new Error("The signature is not an ECDSA signature");let s=new Uint8Array(r*2);return n.forEach((i,o)=>{let a=C(w(i,2,"The signature"));if(a.length===0||a[0]&128)throw new Error("The signature is not an ECDSA signature");for(;a.length>1&&a[0]===0;)a=a.subarray(1);if(a.length>r)throw new Error("The signature is not an ECDSA signature");s.set(a,o*r+r-a.length)}),s}async function Re(t,e,r,n,s){let i;try{i=En(n,e)}catch{return!1}let o=await crypto.subtle.importKey("spki",t,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:r},o,i,s)}function x(t,e){let r=t.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(r)||r.length%4!==0)throw new Error(`${e} is not base64`);let n=atob(r),s=new Uint8Array(n.length);for(let i=0;i<n.length;i+=1)s[i]=n.charCodeAt(i);return s}function or(t,e){let r=[...t.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(r.length!==1||t.replace(r[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return x(r[0][1],e)}var Pn="2.5.29.17",vn="2.5.29.37",xn="1.3.6.1.5.5.7.3.3",kn="1.3.6.1.4.1.57264.1.8",Tn="1.3.6.1.4.1.57264.1.1",Un=134,Sn=12,Cn=48,On=new TextEncoder,z=t=>new TextDecoder().decode(t);async function Ee(t,e,r,n){let{base64Signature:s,cert:i,rekorBundle:o}=Mn(e),a=o.Payload;if(n!==void 0&&n.trim()!==s.trim())throw new Error("The detached signature is not the one in the bundle");let c=x(s,"The bundle signature"),u=or(z(x(i,"The bundle certificate")),"The bundle certificate"),d=ir(u),g=Jr.find(k=>k.logId===a.logID.toLowerCase());if(!g)throw new Error(`The bundle names Rekor log ${a.logID}, which the Sigstore trust root does not know`);let p=On.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await Re(x(g.publicKey,"The Rekor key"),"P-256","SHA-256",x(o.SignedEntryTimestamp,"The signed entry timestamp"),p))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let y=a.integratedTime*1e3;if(!et(y,g.validFor))throw new Error(`Rekor log ${g.baseUrl} was not in use at ${ie(y)}, when the entry says it was logged`);let b=_n(a.body),M=E(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(b.hash!==M)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!ar(x(b.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let R=or(z(x(b.publicKey,"The logged certificate")),"The logged certificate");if(!ar(R,u))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await Re(d.spki,"P-256","SHA-256",c,t))throw new Error("The signature over the file does not verify with the bundle's certificate");return await In(d,y),Nn(d,r),{integratedTime:a.integratedTime}}async function In(t,e){if(!Wr(t,e))throw new Error(`The signing certificate was valid ${ie(t.notBefore)} to ${ie(t.notAfter)}, not at ${ie(e)} when Rekor logged it`);let r=[];for(let n of Yr){let s=n.certChain.map(o=>ir(x(o,"A Fulcio certificate")));if(!await Xr(t,s[0]))continue;let i=await Dn(s,n.validFor,e);if(!i)return;r.push(`${n.uri} (valid from ${n.validFor.start}): ${i}`)}throw new Error(r.length>0?`The signing certificate's CA is not trusted at ${ie(e)}: ${r.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function Dn(t,e,r){if(!et(r,e))return"the trust root says it was not issuing certificates then";for(let[n,s]of t.entries()){if(!Wr(s,r))return`its certificate ${n} was not valid then`;let i=t[n+1]??s;if(!await Xr(s,i))return`its certificate ${n} is not signed by the next`}}async function Xr(t,e){return ar(t.issuer,e.subject)?Re(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function Nn(t,e){let r=t.extensions.get(Pn);if(!r)throw new Error("The signing certificate names no identity");let n=A(w(J(r),Cn,"The subject alternative name")),s=n.filter(u=>u.tag===Un).map(u=>z(C(u)));if(s.length!==1||n.length!==1||s[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(s.length===1?s[0]:s)}, not by ${e.identity}`);let i=t.extensions.get(kn),o=t.extensions.get(Tn),a=i?z(C(w(J(i),Sn,"The OIDC issuer"))):o?z(o):void 0;if(a!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${a===void 0?"missing":JSON.stringify(a)}, not ${e.issuer}`);let c=t.extensions.get(vn);if(!c||!Zr(c).includes(xn))throw new Error("The signing certificate is not for code signing")}function Mn(t){let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let r=e,n=r?.rekorBundle?.Payload;if(!(typeof r?.base64Signature=="string"&&typeof r.cert=="string"&&typeof r.rekorBundle?.SignedEntryTimestamp=="string"&&typeof n?.body=="string"&&typeof n.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(n.logID)&&Number.isSafeInteger(n.integratedTime)&&n.integratedTime>=0&&Number.isSafeInteger(n.logIndex)&&n.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return r}function _n(t){let e;try{e=JSON.parse(z(x(t,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let r=e?.spec?.data?.hash,n=e?.spec?.signature;if(e?.kind!=="hashedrekord"||r?.algorithm!=="sha256"||typeof r.value!="string"||typeof n?.content!="string"||typeof n.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:r.value.toLowerCase(),signature:n.content,publicKey:n.publicKey.content}}function Wr(t,e){return t.notBefore<=e&&e<=t.notAfter}function et(t,e){return Date.parse(e.start)<=t&&(e.end===void 0||t<=Date.parse(e.end))}function ie(t){return new Date(t).toISOString()}function ar(t,e){return t.length===e.length&&t.every((r,n)=>r===e[n])}var $n=/^[0-9a-f]{96}$/,Bn=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function B(t){let e=Z(t.allowedMrtd??[],"allowedMrtd"),r=(t.allowedMeasurements??[]).map((a,c)=>{let u=`allowedMeasurements[${c}]`;return Bn.map(d=>Z([a?.[d]??""],`${u}.${d}`)[0]).join()}),n=[Z(t.allowedRtmr0??[],"allowedRtmr0"),Z(t.allowedRtmr1??[],"allowedRtmr1"),Z(t.allowedRtmr2??[],"allowedRtmr2"),Z(t.allowedRtmr3??[],"allowedRtmr3")];if(t.allowedMeasurements!==void 0&&r.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(r.length===0){if(e.length===0)throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");if(n.slice(1).some(a=>a.length===0))throw new Error("allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too")}let s=t.allowedTcbStatuses??["UpToDate"],i=t.now??Date.now;return Object.assign(async({quoteB64:a,nonce:c,reportDataSuffix:u,collateral:d})=>{let g=Vn(a),p=d??await t.fetchCollateral?.(g);if(!p)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let h;try{h=t.dcapVerify(g,p,Math.floor(i()/1e3))}catch(R){throw new Error(`The quote did not verify: ${R?.message??String(R)}`)}if(h.status==="Revoked"||!s.includes(h.status))throw new Error(`The platform's TCB status is ${h.status}, which is not accepted`);let y=Kn(h.report);if(y.tdAttributes?.length!==8||(y.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let b=[y.mrTd,y.rtMr0,y.rtMr1,y.rtMr2,y.rtMr3].map(R=>E(R));if(r.length>0&&!r.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([y.rtMr0,y.rtMr1,y.rtMr2,y.rtMr3].forEach((R,k)=>{let _=n[k];if(_.length>0&&!_.includes(E(R)))throw new Error(`RTMR${k} ${E(R)} is not one this verifier trusts`)}),E(y.reportData)!==`${c}${u}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function Z(t,e){return t.map(r=>{let n=r.trim().toLowerCase();if(!$n.test(n))throw new Error(`${e} holds ${JSON.stringify(r)}, which is not a 48-byte hex measurement`);return n})}function Kn(t){let e=t.data;if(t.type==="td10"&&e)return e;if(t.type==="td15"&&e?.base)return e.base;throw new Error(`The quote is a ${t.type} quote, not a TDX one`)}function Vn(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)r[n]=e.charCodeAt(n);return r}var Ln=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],$="locked-read-only";function cr(t,{profile:e,allowDebugProfile:r=!1}){if(t.length===0)throw new Error("No release given, so no image would be trusted");let n,s=t.map((i,o)=>{let a=i?.tag??`releases[${o}]`;if(i?.role!==void 0&&i.role!=="node")throw new Error(`${a} lists the measurements of a ${i.role}, not of a node image`);let c=i?.profiles?.[e];if(!c){let d=Object.keys(i?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${d})`)}if(e!==$&&!r)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify($)}, or pass allowDebugProfile to test`);let u=(c.allowed_tcb_statuses??["uptodate"]).map(d=>Hn(d,a));return n=n===void 0?u:n.filter(d=>u.includes(d)),{mrtd:c.mrtd,rtmr0:c.rtmr0,rtmr1:c.rtmr1,rtmr2:c.rtmr2,rtmr3:c.rtmr3}});if(!n||n.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:s,allowedTcbStatuses:n}}function Hn(t,e){let r=Ln.find(n=>n.toLowerCase()===String(t).toLowerCase());if(!r)throw new Error(`${e} accepts TCB status ${JSON.stringify(t)}, which this verifier does not know`);return r}var lr=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"}),qn=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],Pe="https://cloud.calimero.network",ur=`${Pe}/api/tee/pcs`;async function tt(t,e,r={}){let n=typeof t=="string"?new TextEncoder().encode(t):t;await Ee(n,e,{identity:r.identity??lr.identity,issuer:r.issuer??lr.issuer},r.signature);let s;try{s=JSON.parse(new TextDecoder().decode(n))}catch{throw new Error("The signed release is not JSON")}if(s?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(s?.role)} release, not a node one`);let i=Object.values(s.profiles??{}),o=a=>qn.every(c=>/^[0-9a-f]{96}$/i.test(String(a?.[c])));if(typeof s.tag!="string"||i.length===0||!i.every(o))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(r.expectedVersion!==void 0&&s.tag!==r.expectedVersion)throw new Error(`The signed release is ${s.tag}, not ${r.expectedVersion}`);return s}async function dr(t,e={}){let r=await(e.fetch??fetch)(t,{headers:{accept:"application/json"}});if(!r.ok)throw new Error(`Fetching the node release from ${t} failed: HTTP ${r.status}`);let n;try{n=(await r.json())?.data}catch{throw new Error(`${t} did not answer with JSON`)}if(typeof n?.version!="string"||typeof n.publishedMrtds!="string"||typeof n.bundle!="string")throw new Error(`${t} did not answer with a signed node release`);return{version:n.version,publishedMrtds:n.publishedMrtds,bundle:n.bundle}}var nt="https://github.com/calimero-network/mero-tee/releases/download";async function gr(t,e={}){let r=`mero-tee-v${O(t,"version")}`,n=`${(e.base??nt).replace(/\/+$/,"")}/${r}/published-mrtds.json`,s=async a=>{let c=await(e.fetch??fetch)(a);if(!c.ok)throw new Error(`Fetching ${a} failed: HTTP ${c.status}`);return c.text()},[i,o]=await Promise.all([s(n),s(`${n}.bundle.json`)]);return{version:t,publishedMrtds:i,bundle:o}}function pr(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${O(e,"version")}`}async function ve(t){let e=O(t.minReleaseVersion,"minReleaseVersion"),r=O(t.release?.version,"The release version"),n=await tt(t.release.publishedMrtds,t.release.bundle,{expectedVersion:r,identity:t.identity,issuer:t.issuer});if(oe(r,e)<0)throw new Error(`Release ${r} is older than the minimum trusted, ${e}`);return cr([n],{profile:t.profile,allowDebugProfile:t.allowDebugProfile})}function Gn(t){return O(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async r=>{let n=await ve({release:await t.release(),profile:t.profile,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer});return B({dcapVerify:t.dcapVerify,fetchCollateral:t.fetchCollateral,now:t.now,...n})(r)},{includeCollateral:!0})}var st=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function O(t,e){let r=typeof t=="string"?st.exec(t):null,n=r?.[4];if(!r||n!==void 0&&n.split(".").some(s=>s===""))throw new Error(`${e} is ${JSON.stringify(t)}, not a release version like 2.3.87`);return t}function oe(t,e){let[r,n]=rt(t),[s,i]=rt(e);for(let c=0;c<3;c+=1)if(r[c]!==s[c])return r[c]<s[c]?-1:1;if(n===void 0||i===void 0)return n===i?0:n===void 0?1:-1;let o=n.split("."),a=i.split(".");for(let c=0;c<Math.max(o.length,a.length);c+=1){let[u,d]=[o[c],a[c]];if(u===void 0||d===void 0)return u===void 0?-1:1;let[g,p]=[/^\d+$/.test(u),/^\d+$/.test(d)],h=g&&p?Math.sign(Number(u)-Number(d)):g!==p?g?-1:1:u<d?-1:u>d?1:0;if(h!==0)return h}return 0}function rt(t){let e=st.exec(t);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var ot="MOCK_TDX_QUOTE_V1";function Fn(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function fr(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}var it;async function yr(t){it??(it=import("@phala/dcap-qvl"));let e=await it,r=typeof e[t]=="function"?e[t]:e.default?.[t];if(typeof r!="function")throw new TypeError(`@phala/dcap-qvl loaded without ${t}`);return r}function at(t,e){let r=O(e,"minReleaseVersion"),n=String(t.release?.version??"").trim().replace(/^mero-tee-v/,"").replace(/^v/,""),s=O(n,"The release the node names");if(oe(s,r)<0)throw new Error(`mero-tee release ${s} is older than the minimum ${r}`);return s}async function jn(t,e,r){let n=e.releaseSource;return typeof n=="function"?n(t):n==="github"?gr(t,{fetch:r}):dr(pr(n??Pe,t),{fetch:r})}function Qn(t){let e=t.collateralSource??ur;return e==="intel"?async r=>(await yr("getCollateralFromPcs"))(r):async r=>(await yr("getCollateral"))(e,r)}function ct(t,e){let r=e.maxCollateralAgeDays;return r===void 0?t:async n=>{let s=await t(n),i;try{i=Date.parse(JSON.parse(s.tcb_info).issueDate??"")}catch{i=Number.NaN}if(!Number.isFinite(i))throw new Error("The quote's collateral names no TCB info issue date");let o=((e.now??Date.now)()-i)/864e5;if(o>r)throw new Error(`The quote's collateral was issued ${Math.floor(o)} days ago, more than the ${r} this client accepts`);return s}}async function Yn(t,e,r,n){let s=at(t,r.minReleaseVersion),i=await ve({release:await jn(s,r,n),profile:r.profile??$,allowDebugProfile:r.allowDebugProfile,minReleaseVersion:r.minReleaseVersion,identity:r.identity,issuer:r.issuer}),o=ct(r.fetchCollateral??Qn(r),r);return B({dcapVerify:r.dcapVerify??await yr("verify"),fetchCollateral:o,now:r.now,...i})(e)}async function mr(t,e,r=(n,s)=>fetch(n,s)){let n=E(crypto.getRandomValues(new Uint8Array(32))),s=new URL(`${t.replace(/\/+$/,"")}/attestation`);s.searchParams.set("nonce",n),e.appHash&&s.searchParams.set("appHash",e.appHash);let i=await r(s.toString());if(!i.ok)throw new Error(`The node refused to attest: HTTP ${i.status}`);let o=await i.json(),a=Ae(o.transportKey,"transportKey",32),c=e.appHash?Ae(e.appHash,"appHash",32):new Uint8Array(32),u=await nr(c,a),d=Fn(o.quote),g=new TextEncoder().encode(ot);if(fr(d.slice(0,g.length),g)){if(!e.allowMock)throw new Error("mock quote refused: this client only trusts real TEEs");let y=d.slice(g.length,g.length+64);if(!fr(y.slice(0,32),Ae(n,"nonce",32))||!fr(y.slice(32),u))throw new Error("the quote does not bind this transport key, app and nonce");return a}let p={quoteB64:o.quote,nonce:n,reportDataSuffix:E(u)},h;if(e.verifyQuote)h=await e.verifyQuote(p);else if(e.release)h=await Yn(o,p,e.release,r);else throw new Error("real quote refused: this client trusts no TD image (set policy.release)");if(!h)throw new Error("The attestation did not verify, so its transport key is not trusted");return a}var hr="https://manager.cloud.calimero.network/api/v2/directory";var T=class extends Error{constructor(r,n,s,i,o){super(`directory for cluster ${r}: ${s}`);this.cluster=r;this.reason=n;this.status=i;this.cause=o;this.name="DirectoryError"}};function Jn(t,e){return`${t.replace(/\/+$/,"")}/${encodeURIComponent(e)}`}async function wr(t,e,r){let n;try{n=await r(Jn(t,e),{method:"GET",headers:{accept:"application/json"}})}catch(d){throw new T(e,"unreachable",`could not be reached: ${String(d)}`,void 0,d)}if(n.status===404)throw new T(e,"not-found","unknown cluster",404);if(!n.ok)throw new T(e,"unreachable",`answered ${n.status}`,n.status);let s;try{s=await n.json()}catch(d){throw new T(e,"bad-response","answered something other than JSON",n.status,d)}let i=s;if(!i||typeof i!="object"||!Array.isArray(i.nodes))throw new T(e,"bad-response","answered no node list",n.status);let o=[],a=new Set;for(let d of i.nodes){let g=zn(d);g&&!a.has(g.url)&&(a.add(g.url),o.push(g))}if(o.length===0)throw new T(e,"empty","lists no usable node",n.status);let c=i.refreshAfterSeconds,u=typeof c=="number"&&Number.isFinite(c)&&c>=1?c:60;return{nodes:o,refreshAfterSeconds:u}}function zn(t){if(!t||typeof t!="object")return;let{url:e,zone:r,weight:n}=t;if(typeof e!="string"||typeof n!="number"||!Number.isInteger(n)||n<1)return;let s;try{s=new URL(e)}catch{return}if(!(s.protocol!=="https:"&&s.protocol!=="http:"))return{url:e.replace(/\/+$/,""),zone:typeof r=="string"?r:void 0,weight:n}}function Ar(t,e,r){let n=e===void 0?[]:t.filter(i=>i.zone===e),s=e===void 0?t:t.filter(i=>i.zone!==e);return[...lt(n,r),...lt(s,r)]}function lt(t,e){let r=[...t],n=[];for(;r.length>0;){let s=e()*r.reduce((o,a)=>o+a.weight,0),i=0;for(;i<r.length-1&&s>=r[i].weight;)s-=r[i++].weight;n.push(r.splice(i,1)[0].url)}return n}var f=class extends Error{constructor(r,n,s,i={}){super(`${r} ${n}: ${s}`);this.status=r;this.code=n;this.details=i;this.name="CalimeroError"}},I=class extends f{constructor(e,r={}){super(401,"UNAUTHENTICATED",e,r),this.name="LoginRequired"}},xe=class extends f{constructor(e,r={}){super(401,"PASSKEY_UNKNOWN_HERE",e||"this passkey belongs to another Calimero cluster or was removed from this one",r),this.name="PasskeyUnknownHere"}},K=class extends f{constructor(e,r={}){super(421,"WRONG_NODE",e,r),this.name="WrongNode"}},ke=class extends f{constructor(e,r={}){super(404,"NOT_FOUND",e,r),this.name="NotFound"}},X=class extends f{constructor(e,r={}){super(412,"CONFIRM_REQUIRED",e,r),this.name="ConfirmRequired"}},ae=class extends Error{constructor(r){super("the passkey confirmation was cancelled");this.cause=r;this.name="ConfirmCancelled"}},ce=class extends Error{constructor(r){super("the passkey prompt was blocked by the browser or a password manager");this.cause=r;this.name="ConfirmPromptBlocked"}},Te=class extends f{constructor(e,r={}){super(413,"ARGS_TOO_LARGE",e,r),this.name="ArgsTooLarge"}},Ue=class extends f{constructor(e,r={}){super(409,"IDEMPOTENCY_MISMATCH",e,r),this.name="IdempotencyMismatch"}},Se=class extends f{constructor(e,r={}){super(409,"RELEASE_DEADLINE",e,r),this.name="ReleaseDeadlineError",this.release=typeof r.release=="string"?r.release:"",this.after=typeof r.after=="string"?r.after:""}},Ce=class extends f{constructor(e,r={}){super(409,"RUNTIME_TOO_OLD",e,r),this.name="RuntimeTooOld",this.minRuntimeVersion=typeof r.minRuntimeVersion=="string"?r.minRuntimeVersion:"",this.nodes=Array.isArray(r.nodes)?r.nodes:[]}},Oe=class extends f{constructor(e,r={}){super(409,"CONSENT_STALE",e,r),this.name="ConsentStale"}},V=class extends f{constructor(e,r={}){let n=typeof r.origin=="string"?r.origin:"",s=typeof r.package=="string"?r.package:"",i=n?`this site (${n})`:"this site";super(403,"ORIGIN_NOT_REGISTERED",`${i} is not registered for ${s||"any package"}${e?` (${e})`:""}`,r),this.name="OriginNotRegistered",this.origin=n,this.package=s,this.nodeMessage=e}},Ie=class extends f{constructor(e,r,n={}){super(400,e,r,n),this.name="BadOrigin"}},De=class extends f{constructor(e,r={}){super(409,"ORIGIN_TAKEN",e,r),this.name="OriginTaken"}},Ne=class extends f{constructor(e,r={}){super(400,"NOT_SERVING",e,r),this.name="NotServing"}},Me=class extends f{constructor(e,r={}){super(409,"CLUSTER_NOT_UPGRADED",e,r),this.name="ClusterNotUpgraded"}},_e=class extends f{constructor(e,r={}){super(409,"RECOVERY_NOT_READY",e,r),this.name="RecoveryNotReady",this.readyAt=typeof r.readyAt=="number"?r.readyAt:void 0}},le=class extends f{constructor(e,r={}){super(401,"UNAUTHENTICATED",e||"unknown or used recovery code",r),this.name="WrongRecoveryCode"}},$e=class extends f{constructor(e,r={}){super(403,"SIGN_UP_REFUSED",e,r),this.name="SignUpRefused",this.reason=Zn(e)}};function Zn(t){return/invite only/.test(t)?"invite-only":/pre-authorized|sign-up invite/.test(t)?"closed":/unknown invite/.test(t)?"unknown-invite":/invite has expired/.test(t)?"expired-invite":/organization is gone/.test(t)?"org-gone":"other"}var Be=class extends f{constructor(e,r={}){super(429,"QUOTA_EXCEEDED",e,r),this.name="QuotaExceeded"}},Ke=class extends f{constructor(e,r={}){super(422,"APP_ERROR",e,r),this.name="AppError";let{appCode:n,fields:s}=Xn(r);this.appCode=n,this.fields=s}},Ve=class extends f{constructor(e,r={}){super(422,"TRAP",e,r),this.name="TrapError",this.kind=typeof r.kind=="string"?r.kind:""}},L=class extends f{constructor(e,r,n={},s,i){super(503,e,r,n),this.name="UnavailableError",this.reason=e.toLowerCase(),this.committed=e==="TIMEOUT"||e==="MIGRATING"?!1:"unknown",this.retryAfter=s,this.cause=i}};function Le(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Xn(t){let e=typeof t.code=="string"?t:Le(t.error);return{appCode:typeof e.code=="string"?e.code:"",fields:{...Le(e.fields)}}}function Wn(t,e){for(let r of[t.retryAfter,e==null?void 0:Number(e)])if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}function He(t,e,r){let n=Le(e),s=typeof n.error=="string"?n.error:"ERROR",i=typeof n.message=="string"?n.message:"",o=Le(n.details);if(t===503)return new L(s,i,o,Wn(o,r));switch(`${t} ${s}`){case"401 UNAUTHENTICATED":return new I(i,o);case"401 PASSKEY_UNKNOWN_HERE":return new xe(i,o);case"421 WRONG_NODE":return new K(i,o);case"404 NOT_FOUND":return new ke(i,o);case"409 IDEMPOTENCY_MISMATCH":return new Ue(i,o);case"409 RELEASE_DEADLINE":return new Se(i,o);case"409 RUNTIME_TOO_OLD":return new Ce(i,o);case"409 CONSENT_STALE":return new Oe(i,o);case"403 ORIGIN_NOT_REGISTERED":return new V(i,o);case"400 BAD_ORIGIN":case"400 BAD_RP_ID":return new Ie(s,i,o);case"409 ORIGIN_TAKEN":return new De(i,o);case"400 NOT_SERVING":return new Ne(i,o);case"409 CLUSTER_NOT_UPGRADED":return new Me(i,o);case"429 QUOTA_EXCEEDED":return new Be(i,o);case"409 RECOVERY_NOT_READY":return new _e(i,o);case"403 SIGN_UP_REFUSED":return new $e(i,o);case"412 CONFIRM_REQUIRED":return new X(i,o);case"413 ARGS_TOO_LARGE":return new Te(i,o);case"422 APP_ERROR":return new Ke(i,o);case"422 TRAP":return new Ve(i,o);default:return new f(t,s,i,o)}}function P(t){let e="";for(let r of t)e+=String.fromCharCode(r);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function U(t){let e=t.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((t.length+3)%4),r=atob(e),n=new Uint8Array(r.length);for(let s=0;s<r.length;s++)n[s]=r.charCodeAt(s);return n}var ue=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);function br(t){let e=new Error(t);return e.name="NotAllowedError",e}async function ut(t,e,r,n){let s=navigator.credentials,o=globalThis.CredentialsContainer?.prototype?.[t]??s[t];try{return await o.call(s,r?{...e,signal:r}:e)}catch(a){throw r?.aborted||a?.name==="AbortError"?Object.assign(br(`${n} was cancelled`),{cause:a}):a}}function es(t){let e=t.filter(r=>r.alg===-7);return e.length?e:t}function rs(){return{async create(t,e){let r=t,n=await ut("create",{publicKey:{challenge:ue(U(r.challenge)),rp:r.rp,user:{...r.user,id:ue(U(r.user.id))},pubKeyCredParams:es(r.pubKeyCredParams),excludeCredentials:(r.excludeCredentials??[]).map(i=>({type:i.type,id:ue(U(i.id))})),authenticatorSelection:r.authenticatorSelection,attestation:"none",timeout:r.timeout}},e?.signal,"passkey creation");if(!n)throw br("passkey creation was cancelled");let s=n.response;return{attestationObject:P(new Uint8Array(s.attestationObject)),clientDataJson:P(new Uint8Array(s.clientDataJSON))}},async get(t,e,r,n){let s=await ut("get",{publicKey:{challenge:ue(t),rpId:e,userVerification:n?.userVerification??"preferred",allowCredentials:(r??[]).map(o=>({type:"public-key",id:ue(U(o))}))}},n?.signal,"passkey sign-in");if(!s)throw br("passkey sign-in was cancelled");let i=s.response;return{credentialId:P(new Uint8Array(s.rawId)),authenticatorData:P(new Uint8Array(i.authenticatorData)),clientDataJson:P(new Uint8Array(i.clientDataJSON)),signature:P(new Uint8Array(i.signature))}}}}var Er={retries:6,baseDelayMs:200,maxDelayMs:2e3};function Pr(t,e){return Math.min(e.baseDelayMs*2**t,e.maxDelayMs)}function ts(t,e){return t==="required"||t==="preferred"||t==="discouraged"?t:e}function ns(t){let e=t,r=e?.name,n=typeof e?.message=="string"?e.message:"";return r==="InvalidStateError"||/not focused|already pending/i.test(n)?new ce(t):r==="NotAllowedError"||r==="AbortError"?new ae(t):t}function ss(t){return t instanceof S&&t.status===413?He(413,{error:"TOO_LARGE",message:t.message.replace(/^Sealed request refused: /,"")}):t}async function de(t){let e=await t.text().catch(()=>""),r={};try{r=e?JSON.parse(e):{}}catch{r={message:e}}return He(t.status,r,t.headers.get("retry-after"))}async function*gt(t){let e=t.getReader(),r=new TextDecoder,n="";for(;;){let{value:s,done:i}=await e.read();if(i)return;n+=r.decode(s,{stream:!0});let o;for(;(o=n.indexOf(`
|
|
2
|
+
|
|
3
|
+
`))>=0;){let a=n.slice(0,o);n=n.slice(o+2);let c="",u="",d="";for(let p of a.split(`
|
|
4
|
+
`))p.startsWith("id:")?c=p.slice(3).trim():p.startsWith("event:")?u=p.slice(6).trim():p.startsWith("data:")&&(d+=p.slice(5).trim());if(!u&&!d)continue;let g=d;try{g=JSON.parse(d)}catch{}yield{id:c,kind:u,data:g}}}}function Ge(){return`node:c-${P(crypto.getRandomValues(new Uint8Array(16)))}`}function is(t,e={}){return t.replace(/\{([^}]+)\}/g,(r,n)=>{let s=e[n];if(s===void 0)throw new Error(`no value for path parameter ${n} of ${t}`);return encodeURIComponent(String(s))})}function Rr(t){if(!t)return"";let e=new URLSearchParams;for(let[n,s]of Object.entries(t))for(let i of Array.isArray(s)?s:[s])i!=null&&e.append(n,String(i));let r=e.toString();return r?`?${r}`:""}function dt(t){return t==="auth/refresh"||t.startsWith("auth/passkey/")||os.has(t)}var os=new Set(["auth/recovery/begin","auth/recovery/start","auth/recovery/finish"]);function qe(t){return t.replace(/^\/+/,"")}var H=class{constructor(e){this.at=0;this.channels=new Map;this.networkFailures=new WeakSet;let r=i=>i.replace(/\/+$/,"");this.nodeUrls=[...new Set([e.baseUrl,...e.nodes??[]].map(r))],this.policy=e.policy,this.retry={...Er,...e.retry};let n=e.fetch??((i,o)=>fetch(i,o)),s=async(i,o)=>{try{return await n(i,o)}catch(a){throw a instanceof TypeError&&this.networkFailures.add(a),a}};this.raw=s}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 r=this.channels.get(e);return r||(r=sr({baseUrl:e,transportPublicKey:()=>mr(e,this.policy,this.raw),fetch:this.raw}),this.channels.set(e,r)),r}moveOn(e){return this.nodeUrls.length<2?!1:(this.nodeUrl===e&&(this.at=(this.at+1)%this.nodeUrls.length),!0)}failOver(e,r){if(this.nodeUrl!==e&&!r.has(this.nodeUrl))return!0;let n=this.nodeUrls.length;for(let s=1;s<n;s++){let i=(this.at+s)%n;if(!r.has(this.nodeUrls[i]))return this.at=i,this.reread(),!0}return!1}reread(){let e=this.source;!e||e.reading||(e.reading=wr(e.directory,e.cluster,this.raw).then(r=>{let n=this.nodeUrl,s=Ar(r.nodes,e.zone,e.random);this.nodeUrls=[n,...s.filter(i=>i!==n)],this.at=0,e.due=Date.now()+r.refreshAfterSeconds*1e3}).catch(()=>{}).finally(()=>{e.reading=void 0}))}async once(e,r,n){let s={};this.auth&&(s.authorization=`Bearer ${this.auth}`);let i;n.bytes?(s["content-type"]=n.contentType??"application/wasm",i=n.bytes):n.body!==void 0&&(s["content-type"]="application/json",i=JSON.stringify(n.body)),this.source&&Date.now()>=this.source.due&&this.reread();let o=this.nodeUrl;try{return await this.channel(o)(`${o}/${r}${Rr(n.query)}`,{method:e,headers:s,body:i,signal:n.signal})}catch(a){throw ss(a)}}async send(e,r,n){let s=!1,i=!1;for(;;){let[o,a]=[this.auth,this.nodeUrl],c=await this.once(e,r,n);if(c.ok)return c;let u=await de(c);if(u instanceof K&&!i){if(i=!0,this.moveOn(a)&&!dt(r))continue}else if(u instanceof I&&!s&&this.mayRefresh(o,r)){s=!0,await this.renew(o);continue}throw u}}mayRefresh(e,r){return e!==void 0&&this.current!==void 0&&!dt(r)}async renew(e){this.auth===e&&await this.refresh()}async read(e,r,n){let i=await(await this.send(e,r,n)).text();return i?JSON.parse(i):{}}async retried(e,r,n,s){let i=s?0:this.retry.retries,o=new Set;for(;;){let a,c=this.nodeUrl;for(let u=0;;u++){c=this.nodeUrl,o.add(c);try{return await this.read(e,r,n)}catch(g){if(g instanceof L)a=g;else if(g instanceof TypeError&&this.networkFailures.has(g))a=new L("NETWORK",`the node could not be reached: ${g.message}`,{},void 0,g);else throw g}if(u>=i)break;let d=Pr(u,this.retry);await new Promise(g=>setTimeout(g,Math.max(d,(a.retryAfter??0)*1e3)))}if(s||!this.failOver(c,o))throw a}}attempt(e,r,n){if(!n.retry)return this.read(e,r,n);let s=n.body?.confirm!==void 0;return this.retried(e,r,n,n.retry==="once"||s)}async confirmed(e,r,n){let{passkey:s}=n,i=n.promptSignal??n.signal;try{return await this.attempt(e,r,n)}catch(o){if(!(o instanceof X)||!s)throw o;let a=o.details,c;try{c=await s.get(U(a.challenge),a.rpId,a.allowCredentials,{userVerification:ts(a.userVerification,n.userVerification??"required"),...i?{signal:i}:{}})}catch(d){throw ns(d)}let u={...n.body,confirm:{challengeId:a.challengeId,assertion:c}};return this.attempt(e,r,{...n,body:u})}}request(e,r,n={}){return this.send(e,qe(r),n)}json(e,r,n={}){return this.confirmed(e,qe(r),n)}async*events(e,r={}){let n=await this.send("GET",qe(e),r);if(!n.body)throw new f(n.status,"EVENTS","the event stream has no body");yield*gt(n.body)}async unsealed(e,r={}){let n=await this.raw(`${this.nodeUrl}/${qe(e)}${Rr(r.query)}`);if(!n.ok)throw await de(n);return n}refresh(){if(!this.refreshing){let e=this.exchangeRefresh();this.refreshing=e;let r=()=>{this.refreshing===e&&(this.refreshing=void 0)};e.then(r,r)}return this.refreshing}async exchangeRefresh(){let e=this.current;if(!e)throw new Error("no session to refresh");let r;for(let n=1;r===void 0;n++)try{r=await this.json("POST","auth/refresh",{body:{refreshToken:e.refreshToken}})}catch(s){if(!(s instanceof K)||n>=this.nodeUrls.length)throw s}return this.current===e&&this.useSession(r),r}};async function vr(t){let e=t.random??Math.random,r=t.fetch??((a,c)=>fetch(a,c)),n=await wr(t.directory,t.cluster,r),[s,...i]=Ar(n.nodes,t.zone,e),o=new H({baseUrl:s,nodes:i,policy:t.policy,fetch:t.fetch,retry:t.retry});return o.useDirectory({directory:t.directory,cluster:t.cluster,zone:t.zone,random:e,due:Date.now()+n.refreshAfterSeconds*1e3}),o}var pt="calimero.org-recovery.v1\0",kr=64,xr=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 cs(t){yt(t);let e=Array.from(t,n=>n.toString(16).padStart(2,"0")).join(""),r=[];for(let n=0;n<e.length;n+=8)r.push(e.slice(n,n+8));return r.join("-")}function ls(t){let e=t.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},(r,n)=>parseInt(e.slice(2*n,2*n+2),16))}function ft(t,e,r){return new TextEncoder().encode(`${pt}${t}\0${e}\0${r}`)}async function us(t){let e=await mt(t,!0),r=await crypto.subtle.exportKey("jwk",e);if(!r.x)throw new Error("this runtime cannot export an Ed25519 public key");return r.x}async function Tr(t,e,r,n){let s=new TextEncoder().encode(n).length;if(s===0||s>kr)throw new Error(`a recovery nonce is 1 to ${kr} bytes`);let i=await mt(t,!1),o=await crypto.subtle.sign("Ed25519",i,ht(ft(e,r,n)));return P(new Uint8Array(o))}function yt(t){if(t.length!==32)throw new Error("a recovery seed is 32 bytes")}function mt(t,e){yt(t);let r=new Uint8Array(xr.length+32);return r.set(xr),r.set(t,xr.length),crypto.subtle.importKey("pkcs8",ht(r),{name:"Ed25519"},e,["sign"])}var ht=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);var Ur=100;function pe(t={}){let e=new URLSearchParams;if(t.after!==void 0&&e.set("after",t.after),t.limit!==void 0){if(!Number.isInteger(t.limit)||t.limit<1||t.limit>Ur)throw new RangeError(`limit is 1 to ${Ur}`);e.set("limit",String(t.limit))}let r=e.toString();return r?`?${r}`:""}function ge(t,e){try{return oe(t,e)}catch{return t<e?-1:t>e?1:0}}function wt(t,e,r=Date.now()/1e3){if(t===null||t.length===0)return null;let n=t.reduce((i,o)=>ge(i,o)>=0?i:o),s=null;for(let i of e)i.afterSecs<=r&&ge(n,i.version)<0&&(s===null||ge(i.version,s.version)>0)&&(s=i);return s}function At(t,e,r,n){return`calimero-publisher-binding/v1
|
|
2
5
|
${t}
|
|
3
6
|
${e}
|
|
4
7
|
${r}
|
|
5
|
-
${n}`}function Wn(t,e,r,n){return new TextEncoder().encode(dt(t,e,r,n))}var ei="0123456789ABCDEFGHJKMNPQRSTVWXYZ";async function Rr(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t))),r=(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0,n="";for(let i=0;i<6;i++)i===3&&(n+="-"),n+=ei[r>>>27-5*i&31];return n}function ri(t){let e=typeof t=="string"?new URL(t):t,r=e.searchParams.get("request_id"),n=e.searchParams.get("result");return!r||n!=="approved"&&n!=="declined"?null:{requestId:r,result:n}}var ut="https://mero-tee.vercel.app";function gt(t){return`https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(t)}`}function pt(t){return`${ut}/mero-tee?release_tag=${encodeURIComponent(`mero-tee-v${t}`)}`}function Er(t,e,r=Date.now()/1e3){let n=c=>e.deadlines.find(d=>d.version===c)??null,i=t.governance.releases==="owner",s=t.governance.appUpgrades==="owner",o=t.clusterReleases.filter(c=>!c.approved).sort((c,d)=>de(d.release,c.release)).map(c=>({version:c.release,nodes:c.nodes,actionable:i,releaseNotesUrl:gt(c.release),verifyUrl:pt(c.release),deadline:n(c.release)})),a=[];for(let c of t.apps){let d=c.availableVersions??[];if(c.package===null||d.length===0)continue;let u=d[d.length-1],g=c.latestReachable===void 0?u:c.latestReachable;a.push({app:c.app,name:c.name??null,package:c.package.package,from:c.package.version,to:g??u,reachable:g!==null,blocked:c.latestBlocked??null,available:d,actionable:s})}return{scope:t.scope,governance:t.governance,approvedReleases:t.approvedReleases,releases:o,upgrades:a,stalledBy:lt(t.approvedReleases,e.deadlines,r),actionable:o.some(c=>c.actionable)||a.some(c=>c.actionable)}}function ft(t,e,r,n={}){return{kind:"release",scope:t.kind==="org"?{org:t.org}:"account",subject:n.withdraw?{version:e,withdraw:!0}:{version:e},returnTo:r}}function ti(t,e,r){return ft(t,e,r,{withdraw:!0})}function ni(t,e,r){return{kind:"upgrade",subject:{app:t,toVersion:e},returnTo:r}}function wt(t){return"account"in t?`account:${t.account}`:`org:${t.org}`}async function ii(t,e=fetch){let r=t??globalThis.location?.origin;if(!r)throw new Error("no page origin to read the frontend manifest from; pass `origin`");let n=await e(new URL("/.well-known/calimero.json",r).toString());if(!n.ok)throw await Pr(n);let i=await n.json();return{...i,deployments:i.deployments??[]}}function si(t){let e=t??globalThis.location?.href;if(!e)return null;try{return new URL(e).searchParams.get("deployment")||null}catch{return null}}function oi(t,e){return t==="required"||t==="preferred"||t==="discouraged"?t:e}function ai(t){let e=t,r=e?.name,n=typeof e?.message=="string"?e.message:"";return r==="InvalidStateError"||/not focused|already pending/i.test(n)?new ae(t):r==="NotAllowedError"||r==="AbortError"?new oe(t):t}function l(t){return encodeURIComponent(t)}function ci(t){return t instanceof T&&t.status===413?Ve(413,{error:"TOO_LARGE",message:t.message.replace(/^Sealed request refused: /,"")}):t}async function Pr(t){let e=await t.text().catch(()=>""),r={};try{r=e?JSON.parse(e):{}}catch{r={message:e}}return Ve(t.status,r,t.headers.get("retry-after"))}async function*li(t){let e=t.getReader(),r=new TextDecoder,n="";for(;;){let{value:i,done:s}=await e.read();if(s)return;n+=r.decode(i,{stream:!0});let o;for(;(o=n.indexOf(`
|
|
6
|
-
|
|
7
|
-
`))>=0;){let a=n.slice(0,o);n=n.slice(o+2);let c="",d="",u="";for(let p of a.split(`
|
|
8
|
-
`))p.startsWith("id:")?c=p.slice(3).trim():p.startsWith("event:")?d=p.slice(6).trim():p.startsWith("data:")&&(u+=p.slice(5).trim());if(!d&&!u)continue;let g=u;try{g=JSON.parse(u)}catch{}yield{id:c,kind:d,data:g}}}}function yt(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function ht(){return`node:c-${P(crypto.getRandomValues(new Uint8Array(16)))}`}var di={retries:6,baseDelayMs:200,maxDelayMs:2e3};function ui(t,e){return Math.min(e.baseDelayMs*2**t,e.maxDelayMs)}function mt(t){return t==="auth/refresh"||t.startsWith("auth/passkey/")||gi.has(t)}var gi=new Set(["auth/recovery/begin","auth/recovery/start","auth/recovery/finish"]),vr=class t{constructor(e){this.at=0;this.channels=new Map;this.networkFailures=new WeakSet;this.packageOrigins={list:async e=>{let{origins:r}=await this.get(`package-origins/${l(e)}`);return r??[]},add:(e,r,n,i={})=>this.confirmed("POST",`package-origins/${l(e)}`,{origin:r,...i.rpId===void 0?{}:{rpId:i.rpId},...i.served?{served:!0}:{}},n),remove:(e,r,n)=>this.confirmed("DELETE",`package-origins/${l(e)}`,{origin:r},n)};let r=s=>s.replace(/\/+$/,"");this.nodeUrls=[...new Set([e.baseUrl,...e.nodes??[]].map(r))],this.policy=e.policy,this.retry={...di,...e.retry};let n=e.fetch??((s,o)=>fetch(s,o)),i=async(s,o)=>{try{return await n(s,o)}catch(a){throw a instanceof TypeError&&this.networkFailures.add(a),a}};this.raw=i}static async connect(e){let r=e.directory??pr,n=e.random??Math.random,i=e.fetch??((d,u)=>fetch(d,u)),s=await fr(r,e.cluster,i),[o,...a]=yr(s.nodes,e.zone,n),c=new t({baseUrl:o,nodes:a,policy:e.policy,fetch:e.fetch,retry:e.retry});return c.source={directory:r,cluster:e.cluster,zone:e.zone,random:n,due:Date.now()+s.refreshAfterSeconds*1e3},c}get nodeUrl(){return this.nodeUrls[this.at]}get nodes(){return[...this.nodeUrls]}channel(e){let r=this.channels.get(e);return r||(r=er({baseUrl:e,transportPublicKey:()=>gr(e,this.policy,this.raw),fetch:this.raw}),this.channels.set(e,r)),r}moveOn(e){return this.nodeUrls.length<2?!1:(this.nodeUrl===e&&(this.at=(this.at+1)%this.nodeUrls.length),!0)}failOver(e,r){if(this.nodeUrl!==e&&!r.has(this.nodeUrl))return!0;let n=this.nodeUrls.length;for(let i=1;i<n;i++){let s=(this.at+i)%n;if(!r.has(this.nodeUrls[s]))return this.at=s,this.reread(),!0}return!1}reread(){let e=this.source;!e||e.reading||(e.reading=fr(e.directory,e.cluster,this.raw).then(r=>{let n=this.nodeUrl,i=yr(r.nodes,e.zone,e.random);this.nodeUrls=[n,...i.filter(s=>s!==n)],this.at=0,e.due=Date.now()+r.refreshAfterSeconds*1e3}).catch(()=>{}).finally(()=>{e.reading=void 0}))}useApiKey(e){this.auth=e,this.current=void 0}useSession(e){this.auth=e.sessionToken,this.current=e}get session(){return this.current}async request(e,r,n,i,s="application/wasm",o){let a={};this.auth&&(a.authorization=`Bearer ${this.auth}`);let c;i?(a["content-type"]=s,c=i):n!==void 0&&(a["content-type"]="application/json",c=JSON.stringify(n)),this.source&&Date.now()>=this.source.due&&this.reread();let d=this.nodeUrl;try{return await this.channel(d)(`${d}/${r}`,{method:e,headers:a,body:c,signal:o})}catch(u){throw ci(u)}}async send(e,r,n,i,s,o){let a=!1,c=!1;for(;;){let[d,u]=[this.auth,this.nodeUrl],g=await this.request(e,r,n,i,s,o);if(g.ok)return g;let p=await Pr(g);if(p instanceof K&&!c){if(c=!0,this.moveOn(u)&&!mt(r))continue}else if(p instanceof B&&!a&&this.mayRefresh(d,r)){a=!0,await this.renew(d);continue}throw p}}mayRefresh(e,r){return e!==void 0&&this.current!==void 0&&!mt(r)}async renew(e){this.auth===e&&await this.refresh()}async json(e,r,n,i,s){let a=await(await this.send(e,r,n,i,s)).text();return a?JSON.parse(a):{}}async retried(e,r,n,i=!1){let s=i?0:this.retry.retries,o=new Set;for(;;){let a,c=this.nodeUrl;for(let d=0;;d++){c=this.nodeUrl,o.add(c);try{return await this.json(e,r,n)}catch(g){if(g instanceof L)a=g;else if(g instanceof TypeError&&this.networkFailures.has(g))a=new L("NETWORK",`the node could not be reached: ${g.message}`,{},void 0,g);else throw g}if(d>=s)break;let u=ui(d,this.retry);await new Promise(g=>setTimeout(g,Math.max(u,(a.retryAfter??0)*1e3)))}if(i||!this.failOver(c,o))throw a}}post(e,r={}){return this.json("POST",e,r)}get(e){return this.json("GET",e)}put(e,r={}){return this.json("PUT",e,r)}delete(e,r){return this.json("DELETE",e,r)}async signUp(e,r,n={}){let i=this.pageOrigin(n),s=n.invite?{invite:n.invite}:{},o=await this.begin("auth/passkey/register/begin",i===void 0?{name:r,...s}:{name:r,origin:i,...s},i),a=n.signal,c=await(a?e.create(o.options,{signal:a}):e.create(o.options)),d=await this.confirmed("POST","auth/passkey/register/finish",{challengeId:o.challengeId,registration:c,...s},e,void 0,"preferred",a);return this.useSession(d),d}signUpPolicy(){return this.get("sign-up")}async signIn(e,r={}){let n=this.pageOrigin(r),i=await this.begin("auth/passkey/login/begin",n===void 0?void 0:{origin:n},n),s=i.options.rpId??i.options.rp?.id??"",o=O(i.options.challenge),a=await(r.signal?e.get(o,s,void 0,{signal:r.signal}):e.get(o,s)),c=await this.post("auth/passkey/login/finish",{challengeId:i.challengeId,assertion:a});return this.useSession(c),c}pageOrigin(e){if(e.origin!==void 0)return e.origin??void 0;let r=globalThis.location?.origin;return!r||r==="null"||new Set(this.nodeUrls.map(i=>{try{return new URL(i).origin}catch{return i}})).has(r)?void 0:r}async begin(e,r,n){try{return await this.post(e,r)}catch(i){throw i instanceof V&&!i.origin&&n!==void 0?new V(i.nodeMessage,{...i.details,origin:n}):i}}refresh(){if(!this.refreshing){let e=this.exchangeRefresh();this.refreshing=e;let r=()=>{this.refreshing===e&&(this.refreshing=void 0)};e.then(r,r)}return this.refreshing}async exchangeRefresh(){let e=this.current;if(!e)throw new Error("no session to refresh");let r;for(let n=1;r===void 0;n++)try{r=await this.post("auth/refresh",{refreshToken:e.refreshToken})}catch(i){if(!(i instanceof K)||n>=this.nodeUrls.length)throw i}return this.current===e&&this.useSession(r),r}async signOut(){await this.signingOut("auth/logout")}async signOutEverywhere(){await this.signingOut("auth/logout-all")}async listSessions(){let{sessions:e}=await this.get("auth/sessions");return e}async revokeSession(e){await this.delete(`auth/sessions/${l(e)}`)}async listActivity(e){let r=e===void 0?"":`?after=${encodeURIComponent(String(e))}`,{activity:n}=await this.get(`auth/activity${r}`);return n}async signingOut(e){try{await this.post(e)}finally{this.auth=void 0,this.current=void 0}}me(){return this.get("auth/me")}async addPasskey(e,r){let n=await this.post("auth/passkeys/add/begin"),i=await e.create(n.options),{credentialId:s}=await this.postConfirmed("auth/passkeys/add/finish",{challengeId:n.challengeId,registration:i},r);return s}async removePasskey(e,r){await this.deleteConfirmed(`auth/passkeys/${l(e)}`,r)}async labelPasskey(e,r){await this.post(`auth/passkeys/${l(e)}`,{label:r})}async createRecoveryCode(e){let{code:r}=await this.postConfirmed("auth/recovery",{},e);return r}async removeRecoveryCode(e){await this.deleteConfirmed("auth/recovery",e)}async startAccountRecovery(e,r){try{let n=await this.post("auth/recovery/begin",{code:e}),i=await r.create(n.options);return await this.post("auth/recovery/start",{challengeId:n.challengeId,code:e,registration:i})}catch(n){throw n instanceof B?new ce(n.message.replace(/^401 UNAUTHENTICATED: /,""),n.details):n}}async cancelAccountRecovery(e){await this.postConfirmed("auth/recovery/cancel",{},e)}async finishAccountRecovery(e,r){let n=await this.postConfirmed("auth/recovery/finish",r?{accountId:r}:{},e);return this.useSession(n),n}usage(){return this.get("auth/usage")}async attestation(){let e=yt(crypto.getRandomValues(new Uint8Array(32))),r=await this.raw(`${this.nodeUrl}/attestation?nonce=${e}`);if(!r.ok)throw await Pr(r);return await r.json()}async listApiKeys(){let{keys:e}=await this.get("auth/apikeys");return e}async revokeApiKey(e,r){await this.deleteConfirmed(`auth/apikeys/${l(e)}`,r)}createApiKey(e,r){return this.postConfirmed("auth/apikeys",{...e},r)}async uploadBundle(e){let{hash:r}=await this.json("POST","bundles",void 0,e);return r}uploadBlob(e,r,n={}){let i=(typeof n=="string"?n:n.contentType)??"application/octet-stream";return this.json("POST",`apps/${l(e)}/blobs`,void 0,r,i)}async downloadBlob(e,r){return(await this.blobContent(e,r)).data}async downloadBlobGranted(e,r,n){return(await this.blobContent(e,r,{grant:n})).data}async blobContent(e,r,n={}){let i=n.grant===void 0?"":`?grant=${encodeURIComponent(n.grant)}`,s=await this.send("GET",`apps/${l(e)}/blobs/${l(r)}${i}`);return{data:new Uint8Array(await s.arrayBuffer()),contentType:s.headers.get("content-type")??"application/octet-stream"}}async listBlobs(e){let{blobs:r}=await this.get(`apps/${l(e)}/blobs`);return r}blobInfo(e,r){return this.get(`apps/${l(e)}/blobs/${l(r)}/info`)}async deleteBlob(e,r){await this.delete(`apps/${l(e)}/blobs/${l(r)}`)}uploadPackage(e){return this.json("POST","packages",void 0,e,"application/octet-stream")}installPackage(e,r){return this.post("packages/install",{package:e,version:r})}async packages(){let{packages:e}=await this.get("packages");return e}package(e){return this.get(`packages/${l(e)}`)}uninstallPackage(e,r){return this.delete(r===void 0?`packages/${l(e)}`:`packages/${l(e)}/${l(r)}`)}async listApps(e={}){let r=new URLSearchParams;e.package&&r.set("package",e.package),e.bundle&&r.set("bundle",e.bundle);let n=r.toString(),{apps:i}=await this.get(n?`apps?${n}`:"apps");return i}getApp(e){return this.get(`apps/${l(e)}`)}async deleteApp(e){await this.delete(`apps/${l(e)}`)}async setAccess(e,r){await this.post(`apps/${l(e)}/access`,{access:r})}async setAppMetadata(e,r){await this.post(`apps/${l(e)}/metadata`,{metadata:r})}appXcalls(e){return this.get(`apps/${l(e)}/xcalls`)}appStorage(e){return this.get(`apps/${l(e)}/storage`)}appAbi(e){return this.get(`apps/${l(e)}/abi`)}async transferApp(e,r,n){await this.postConfirmed(`apps/${l(e)}/transfer`,{to:r},n)}moveApp(e,r,n={},i){let s=`apps/${l(e)}/move`,o={toOrg:r,bringMembers:n.bringMembers??!1};return i?this.postConfirmed(s,o,i):this.post(s,o)}upgradeApp(e,r,n){let i=`apps/${l(e)}/upgrade`;return n?this.postConfirmed(i,r,n):this.post(i,r)}postConfirmed(e,r,n){return this.confirmed("POST",e,r,n)}deleteConfirmed(e,r,n={}){return this.confirmed("DELETE",e,n,r)}async confirmed(e,r,n,i,s=c=>this.json(e,r,c),o="required",a){try{return await s(n)}catch(c){if(!(c instanceof Z)||!i)throw c;let d=c.details,u;try{u=await i.get(O(d.challenge),d.rpId,d.allowCredentials,{userVerification:oi(d.userVerification,o),...a?{signal:a}:{}})}catch(g){throw ai(g)}return s({...n,confirm:{challengeId:d.challengeId,assertion:u}})}}async createApp(e,r,n={}){let i=typeof r=="string"?{bundle:r}:r,{appId:s}=await this.post("apps",{name:e,...i,...n});return s}call(e,r,n={},i){let s=i??ht();return this.retried("POST",`apps/${l(e)}/intents`,{method:r,args:n,idempotencyKey:s})}async callConfirmed(e,r,n,i,s){let o=`apps/${l(e)}/intents`,a=s??ht();return this.confirmed("POST",o,{method:r,args:n,idempotencyKey:a},i,c=>this.retried("POST",o,c,c.confirm!==void 0))}view(e,r,n={},i={}){return this.retried("POST",`apps/${l(e)}/views`,{method:r,args:n,consistency:i.stale?"stale":"strong",minIndex:i.minIndex??0})}events(e,r=0,n){return this.stream(`apps/${l(e)}/events?from=${r}`,n)}async*stream(e,r){let n=await this.send("GET",e,void 0,void 0,void 0,r);if(!n.body)throw new y(n.status,"EVENTS","the event stream has no body");yield*li(n.body)}async publishPresence(e,r,n){await this.post(`apps/${l(e)}/presence`,{seq:r,state:n===null?null:yt(n)})}async presence(e){let{present:r}=await this.get(`apps/${l(e)}/presence`);return r}presenceStream(e,r){return this.stream(`apps/${l(e)}/presence/stream`,r)}async setAlias(e,r){await this.put(`auth/aliases/${l(e)}`,{app:r})}async aliases(){let{aliases:e}=await this.get("auth/aliases");return e}async alias(e){let{appId:r}=await this.get(`auth/aliases/${l(e)}`);return r}async deleteAlias(e){await this.delete(`auth/aliases/${l(e)}`)}async createOrg(e,r={}){let n={name:e};r.recoveryKey!==void 0&&(n.recoveryKey=r.recoveryKey);let{orgId:i}=await this.post("orgs",n);return i}async setRecoveryKey(e,r,n){await this.postConfirmed(`orgs/${l(e)}/recovery`,{publicKey:r},n)}async startRecovery(e,r){let n=(await this.me()).accountId,i=P(crypto.getRandomValues(new Uint8Array(16))),s=await Ar(r,e,n,i);return this.post(`orgs/${l(e)}/recovery/start`,{nonce:i,signature:s})}async cancelRecovery(e,r){await this.postConfirmed(`orgs/${l(e)}/recovery/cancel`,{},r)}finishRecovery(e,r){return this.postConfirmed(`orgs/${l(e)}/recovery/finish`,{},r)}getOrg(e){return this.get(`orgs/${l(e)}`)}async orgMembersSecurity(e){let{members:r}=await this.get(`orgs/${l(e)}/members?detail=security`);return r}async deleteOrg(e,r){await this.deleteConfirmed(`orgs/${l(e)}`,r)}async setOrgMetadata(e,r){await this.post(`orgs/${l(e)}/metadata`,{metadata:r})}async setMemberMetadata(e,r,n){await this.post(`orgs/${l(e)}/members/${l(r)}/metadata`,{metadata:n})}upgradeOrg(e,r,n){return this.postConfirmed(`orgs/${l(e)}/upgrade`,{...r},n)}upgradeRun(e,r){return this.get(`orgs/${l(e)}/upgrades/${l(r)}`)}retryUpgradeRun(e,r,n){return this.postConfirmed(`orgs/${l(e)}/upgrades/${l(r)}/retry`,{},n)}async approveRelease(e,r,n,i=!0){let s=e===null?"auth/releases":`orgs/${l(e)}/releases`;return this.postConfirmed(s,{version:r,approved:i},n)}async approveOutbound(e,r,n,i={}){let s=e===null?"auth/outbound":`orgs/${l(e)}/outbound`;return this.postConfirmed(s,{package:r,prefixes:i.prefixes??"manifest",replace:i.replace??!1},n)}appsReport(e,r={}){let n=e===null?"auth/apps":`orgs/${l(e)}/apps`;return this.get(`${n}${ue(r)}`)}async appsReportAll(e){let r=await this.appsReport(e),n=[...r.apps],i=r.next;for(;i!==null;){let s=await this.appsReport(e,{after:i});n.push(...s.apps),i=s.next}return{...r,apps:n,next:null}}releaseRules(){return this.get("releases")}async pendingApprovals(e=null){let[r,n]=await Promise.all([this.appsReportAll(e),this.releaseRules()]);return Er(r,n)}requestConsent(e){return this.post("consent/requests",e)}async openConsentPage(e,r={}){let n=typeof r=="function"?{navigate:r}:r,i=n.navigate??(o=>{let a=globalThis.window;if(!a)throw new Error("no window to open the consent page in; pass `navigate`");a.location.assign(o)}),s=await this.requestConsent(e);if(s.code!==void 0){let o=await Rr(s.requestId);if(s.code!==o)throw new y(200,"CONSENT_CODE_MISMATCH","the consent page code does not match the request",{requestId:s.requestId,code:s.code,expected:o})}return n.confirm&&!await n.confirm(s)||i(s.url),s}consentResult(e){return this.get(`consent/${l(e)}/result`)}async waitForConsent(e,r={}){let n=r.intervalMs??2e3;for(;;){let i=await this.consentResult(e);if(i.status!=="pending"||r.signal?.aborted||r.expiresAt!==void 0&&Date.now()/1e3>=r.expiresAt)return i;await new Promise(s=>setTimeout(s,n))}}publisherBinding(e){return this.get(`publishers/${l(e)}`)}bindPublisher(e,r,n){return this.postConfirmed(`orgs/${l(e)}/publishers`,{...r},n)}upgradePublished(e,r,n,i){return this.postConfirmed(`orgs/${l(e)}/packages/${l(r)}/upgrade`,{...n},i)}opsApps(e={}){return this.get(`ops/apps${ue(e)}`)}opsOrgs(e={}){return this.get(`ops/orgs${ue(e)}`)}opsServedOrigins(){return this.get("ops/served-origins")}async setReleaseDeadline(e,r){let n=typeof r=="string"?r:r.toISOString();await this.post(`ops/releases/${l(e)}/deadline`,{after:n})}async liftReleaseDeadline(e){await this.delete(`ops/releases/${l(e)}/deadline`)}async setMember(e,r,n,i){await this.postConfirmed(`orgs/${l(e)}/members`,{account:r,role:n},i)}removeMember(e,r,n){return this.deleteConfirmed(`orgs/${l(e)}/members/${l(r)}`,n)}async setCapabilities(e,r,n,i={}){await this.postConfirmed(`orgs/${l(e)}/capabilities`,{capabilities:r,...i},n)}async setAllApps(e,r,n,i){await this.postConfirmed(`orgs/${l(e)}/all-apps`,{account:r,allApps:n},i)}async setTeamDefaultCapabilities(e,r,n,i){await this.postConfirmed(`orgs/${l(e)}/capabilities`,{team:r,capabilities:n},i)}async createTeam(e,r,n,i){let{teamId:s}=await this.post(`orgs/${l(e)}/teams`,{name:r,join:n,parent:i});return s}getTeam(e,r){return this.get(`orgs/${l(e)}/teams/${l(r)}`)}async updateTeam(e,r,n){await this.post(`orgs/${l(e)}/teams/${l(r)}`,n)}async deleteTeam(e,r,n){let i=`orgs/${l(e)}/teams/${l(r)}`;await(n?this.deleteConfirmed(i,n):this.delete(i))}async setTeamMember(e,r,n,i,s={}){await this.postConfirmed(`orgs/${l(e)}/teams/${l(r)}/members`,{account:n,...s},i)}async removeTeamMember(e,r,n,i){await this.deleteConfirmed(`orgs/${l(e)}/teams/${l(r)}/members/${l(n)}`,i)}async invite(e,r,n,i=[],s={}){let{token:o}=await this.postConfirmed(`orgs/${l(e)}/invites`,{role:r,teams:i,...s},n);return o}redeemInvite(e){return this.post(`invites/${l(e)}/redeem`)}async listInvites(e){let{invites:r}=await this.get(`orgs/${l(e)}/invites`);return r}async revokeInvite(e,r,n){await this.deleteConfirmed(`orgs/${l(e)}/invites/${l(r)}`,n)}listAppTeams(e){return this.get(`orgs/${l(e)}/app-teams`)}scopeApps(e,r,n={}){let i={};return n.apps!==void 0&&(i.apps=n.apps),n.shared!==void 0&&(i.shared=n.shared),this.postConfirmed(`orgs/${l(e)}/app-teams`,i,r)}grantDeployer(e,r,n={}){let i=n.until instanceof Date?n.until.toISOString():n.until;return this.postConfirmed("deployers",{deployer:e,...i===void 0?{}:{until:i}},r)}deployers(){return this.get("deployers")}async revokeDeployer(e,r){let n=typeof e=="string"?e:wt(e);await this.deleteConfirmed(`deployers/${l(n)}`,r)}async createDeployment(e,r,n){let{id:i}=await this.postConfirmed("deployments",{name:e,owner:r},n);return i}async deployments(){let{deployments:e}=await this.get("deployments");return e}deployment(e){return this.get(`deployments/${l(e)}`)}async deleteDeployment(e,r){await this.deleteConfirmed(`deployments/${l(e)}`,r)}offerApp(e,r,n){return this.postConfirmed(`deployments/${l(e)}/apps`,{...r},n)}async withdrawApp(e,r,n){await this.deleteConfirmed(`deployments/${l(e)}/apps/${l(r)}`,n)}deploymentOrgs(e){return this.get(`deployments/${l(e)}/orgs`)}};var xr={CREATE_APP:1,INVITE_MEMBERS:2,JOIN_OPEN_TEAMS:4,MANAGE_MEMBERS:8,MANAGE_APPLICATION:16,CREATE_TEAM:32,DELETE_TEAM:64,MANAGE_VISIBILITY:128,MANAGE_METADATA:256,APPROVE_RELEASES:1024},pi=xr.JOIN_OPEN_TEAMS;function fi(...t){return t.reduce((e,r)=>e|xr[r],0)}function Le(t,e){return(t<<e|t>>>32-e)>>>0}function I(t,e,r,n,i){t[e]=t[e]+t[r]>>>0,t[i]=Le(t[i]^t[e],16),t[n]=t[n]+t[i]>>>0,t[r]=Le(t[r]^t[n],12),t[e]=t[e]+t[r]>>>0,t[i]=Le(t[i]^t[e],8),t[n]=t[n]+t[i]>>>0,t[r]=Le(t[r]^t[n],7)}function At(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function Et(t,e,r){let n=new Uint32Array(16);n[0]=1634760805,n[1]=857760878,n[2]=2036477234,n[3]=1797285236;for(let o=0;o<8;o+=1)n[4+o]=At(t,o*4);n[12]=e>>>0;for(let o=0;o<3;o+=1)n[13+o]=At(r,o*4);let i=n.slice();for(let o=0;o<10;o+=1)I(i,0,4,8,12),I(i,1,5,9,13),I(i,2,6,10,14),I(i,3,7,11,15),I(i,0,5,10,15),I(i,1,6,11,12),I(i,2,7,8,13),I(i,3,4,9,14);let s=new Uint8Array(64);for(let o=0;o<16;o+=1){let a=i[o]+n[o]>>>0;s[o*4]=a&255,s[o*4+1]=a>>>8&255,s[o*4+2]=a>>>16&255,s[o*4+3]=a>>>24&255}return s}function yi(t,e,r,n){let i=new Uint8Array(n.length);for(let s=0,o=e;s<n.length;s+=64,o+=1){let a=Et(t,o,r),c=Math.min(s+64,n.length);for(let d=s;d<c;d+=1)i[d]=n[d]^a[d-s]}return i}function kr(t){let e=0n;for(let r=t.length-1;r>=0;r-=1)e=e<<8n|BigInt(t[r]);return e}var hi=(1n<<130n)-5n;function mi(t,e){let r=kr(t.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,n=kr(t.subarray(16,32)),i=0n;for(let a=0;a<e.length;a+=16){let c=e.subarray(a,Math.min(a+16,e.length)),d=kr(c)+(1n<<BigInt(8*c.length));i=(i+d)*r%hi}let s=i+n&(1n<<128n)-1n,o=new Uint8Array(16);for(let a=0;a<16;a+=1)o[a]=Number(s&0xffn),s>>=8n;return o}function bt(t){return new Uint8Array((16-t%16)%16)}function Rt(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function wi(t,e){let r=[t,bt(t.length),e,bt(e.length),Rt(t.length),Rt(e.length)],n=new Uint8Array(r.reduce((s,o)=>s+o.length,0)),i=0;for(let s of r)n.set(s,i),i+=s.length;return n}function Ai(t,e){if(t.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 Pt(t,e,r,n=new Uint8Array(0)){Ai(t,e);let i=Et(t,0,e).subarray(0,32),s=yi(t,1,e,r),o=mi(i,wi(n,s)),a=new Uint8Array(s.length+16);return a.set(s),a.set(o,s.length),a}var xt=32,bi=1,Ri=3,Ei=2,Pi=32,vi=32,xi=12,X=t=>new TextEncoder().encode(t),pe=t=>new Uint8Array([t>>8&255,t&255]),vt=h(X("KEM"),pe(xt)),ge=h(X("HPKE"),pe(xt),pe(bi),pe(Ri));async function kt(t,e){let r=t.length===0?new Uint8Array(32):t,n=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",n,e))}async function ki(t,e,r){let n=new Uint8Array(r),i=new Uint8Array(0);for(let s=1,o=0;o<r;s+=1)i=await kt(t,h(i,e,new Uint8Array([s]))),n.set(i.subarray(0,Math.min(i.length,r-o)),o),o+=i.length;return n}function Ge(t,e,r,n){return kt(e,h(X("HPKE-v1"),t,X(r),n))}function Ur(t,e,r,n,i){return ki(e,h(pe(i),X("HPKE-v1"),t,X(r),n),i)}async function Ui(t,e){let r=await Ge(vt,new Uint8Array(0),"eae_prk",t);return Ur(vt,r,"shared_secret",e,Pi)}async function Ti(t,e){let r=new Uint8Array(0),n=await Ge(ge,r,"psk_id_hash",r),i=await Ge(ge,r,"info_hash",e),s=h(new Uint8Array([Ei]),n,i),o=await Ge(ge,t,"secret",r);return{key:await Ur(ge,o,"key",s,vi),nonce:await Ur(ge,o,"base_nonce",s,xi)}}async function Ut(t,e,r,n,i=new Uint8Array(0),s){if(t.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let o=await q(s),a=await q(e),c=h(await ee(o.privateKey,t),await ee(a.privateKey,t)),d=await Ui(c,h(o.publicKey,t,a.publicKey)),{key:u,nonce:g}=await Ti(d,r);return{enc:o.publicKey,ciphertext:Pt(u,g,n,i)}}var Ct="mero-agent-gate/attest/v3",Ot="mero-agent-gate/provision/v2",Si=/^[a-z0-9][a-z0-9-]{0,62}$/,Ci=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,Tt=64,St=64*1024,D=class extends Error{constructor(r,n,i){super(r);this.status=n;this.code=i;this.name="AgentGateError"}};function It(t){if(!Si.test(t))throw new Error(`Agent id ${JSON.stringify(t)} must match [a-z0-9][a-z0-9-]{0,62}`)}function fe(t){return new TextEncoder().encode(t)}function Dt(t){let e=fe(t);return h(new Uint8Array([e.length]),e)}function G(t){let e="";for(let r of t)e+=String.fromCharCode(r);return btoa(e)}function He(t,e,r){let n;try{n=Uint8Array.from(atob(t.trim()),i=>i.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(r!==void 0&&n.length!==r)throw new Error(`${e} is not ${r} bytes`);return n}async function Nt(t,e,r,n){let i=new Uint8Array(32),s=h(fe(Ct),t,Dt(e),r??i,n??i);return new Uint8Array(await crypto.subtle.digest("SHA-256",s))}function Mt(t,e){return h(fe(Ot),t,Dt(e))}async function Oi(){let t=crypto.getRandomValues(new Uint8Array(32));return{secret:t,publicKey:await Fe(t)}}async function Fe(t){if(t.length!==32)throw new Error("An owner key is 32 bytes");return G((await q(t)).publicKey)}function _t(t,e){return`${t.replace(/\/+$/,"")}${e}`}async function $t(t,e,r){let n=await t(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)}),i=await n.text(),s;try{s=i?JSON.parse(i):void 0}catch{}if(!n.ok){let o=s;throw new D(`The gate answered ${n.status}${o?.error?` ${o.error}`:""}: ${o?.details??i.slice(0,200)}`,n.status,o?.error)}return s}async function Tr(t){let e=t.agentId??"";e&&It(e);let r=crypto.getRandomValues(new Uint8Array(32)),n=await $t(t.fetch??fetch,_t(t.gateUrl,"/attest"),{nonceB64:G(r),...e?{agentId:e}:{}});if((n?.agentId??"")!==e)throw new Error(`Asked about agent ${JSON.stringify(e)}, the gate answered for ${JSON.stringify(n?.agentId)}`);let i=He(n.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),s=n.signingPublicKeyB64?He(n.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,o=n.ownerPublicKeyB64?He(n.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!s!=!o)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let a=await Nt(i,e,s,o);return await t.verifier({quoteB64:n.quoteB64,nonce:E(r),reportDataSuffix:E(a)}),{agentId:e,provisioningPublicKey:G(i),...s?{signingPublicKey:G(s)}:{},...o?{ownerPublicKey:G(o)}:{}}}async function Bt(t,e){let r=await Fe(e);if(t.ownerPublicKey&&t.ownerPublicKey!==r)throw new D(`This agent is claimed by another key (${t.ownerPublicKey}); it is not yours. Send it nothing and do not authorize its signing key`,void 0,"not_yours");return r}function Ii(t){let e=Object.keys(t);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>Tt)throw new Error(`At most ${Tt} secrets at once`);for(let r of e){if(!Ci.test(r))throw new Error(`Secret name ${JSON.stringify(r)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);if(typeof t[r]!="string")throw new Error(`Secret ${r} is not a string`);if(fe(t[r]).length>St)throw new Error(`Secret ${r} is over ${St} bytes`)}}async function Kt(t,e,r,n,i,s){if(!n.agentId)throw new Error("This quote names no agent; attest with the agent id");let o=await Bt(n,i),a=He(n.provisioningPublicKey,"provisioningPublicKey",32),c=await Ut(a,i,Mt(a,n.agentId),fe(JSON.stringify(s)));return $t(t,_t(e,r),{agentId:n.agentId,provisioningPublicKeyB64:n.provisioningPublicKey,senderPublicKeyB64:o,encappedKeyB64:G(c.enc),ciphertextB64:G(c.ciphertext)})}async function Di(t){Ii(t.secrets);let e=t.fetch??fetch,r=await Kt(e,t.gateUrl,"/provision",t.agent,t.ownerSecret,{secrets:t.secrets}),n=await Tr({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e}),i=await Fe(t.ownerSecret);if(n.ownerPublicKey!==i||!n.signingPublicKey)throw new D("The gate accepted the secrets, but its quote does not name your key as owner");if(t.agent.signingPublicKey&&t.agent.signingPublicKey!==n.signingPublicKey)throw new D("The agent's signing key changed while provisioning");return{agentId:n.agentId,provisioningPublicKey:n.provisioningPublicKey,signingPublicKey:n.signingPublicKey,ownerPublicKey:i,written:r?.written??[],claimed:r?.claimed===!0}}async function Ni(t){if(!t.agent.ownerPublicKey)throw new Error("This agent is not claimed; there is nothing to release");let e=t.fetch??fetch;if(await Kt(e,t.gateUrl,"/release",t.agent,t.ownerSecret,{release:!0}),(await Tr({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e})).ownerPublicKey)throw new D("The gate says it released the agent, but its quote still names an owner")}var Sr=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),Mi=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function _i(t,e,r={}){let n=typeof t=="string"?new TextEncoder().encode(t):t;await be(n,e,{identity:r.identity??Sr.identity,issuer:r.issuer??Sr.issuer});let i;try{i=JSON.parse(new TextDecoder().decode(n))}catch{throw new Error("The signed agent policy is not JSON")}let s=r.role??"agent";if(i?.role!==s)throw new Error(`The signed file is a ${JSON.stringify(i?.role)} policy, not an ${s} one`);let o=r.profile??_;if(i.profile!==o)throw new Error(`The signed agent policy is for the ${JSON.stringify(i.profile)} profile, not ${o}`);if(r.expectedVersion!==void 0&&i.version!==r.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(i.version)}, not ${r.expectedVersion}`);return Vt(i),i}function Vt(t){for(let e of Mi)if(!Array.isArray(t?.[e])||t[e].length===0)throw new Error(`The agent policy's ${e} is empty, so no agent would be accepted`)}var $i=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function Bi(t){let e=$i.find(r=>r.toLowerCase()===t.trim().toLowerCase());if(!e)throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(t)}`);return e}var ye=t=>t.trim().replace(/^0x/i,"");function Ki(t,e){return Vt(t),$({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:t.allowed_tcb_statuses.map(Bi),allowedMrtd:t.allowed_mrtd.map(ye),allowedRtmr0:t.allowed_rtmr0.map(ye),allowedRtmr1:t.allowed_rtmr1.map(ye),allowedRtmr2:t.allowed_rtmr2.map(ye),allowedRtmr3:t.allowed_rtmr3.map(ye)})}export{Ct as AGENT_ATTEST_DOMAIN,Ot as AGENT_PROVISION_INFO_DOMAIN,D as AgentGateError,$e as AppError,xe as ArgsTooLarge,Ce as BadOrigin,vr as CalimeroClient,y as CalimeroError,De as ClusterNotUpgraded,oe as ConfirmCancelled,ae as ConfirmPromptBlocked,Z as ConfirmRequired,Se as ConsentStale,or as DEFAULT_COLLATERAL_MIRROR,pr as DEFAULT_DIRECTORY,pi as DEFAULT_ORG_CAPABILITIES,Re as DEFAULT_RELEASE_MIRROR,U as DirectoryError,zr as GITHUB_RELEASES,_r as HANDSHAKE_PATH,ke as IdempotencyMismatch,Sr as KMS_RELEASE_SIGNER,B as LoginRequired,wr as MAX_RECOVERY_NONCE_BYTES,br as MAX_REPORT_PAGE,Wr as MOCK_QUOTE_HEADER,sr as NODE_RELEASE_SIGNER,ve as NotFound,Ie as NotServing,xr as ORG_CAPABILITIES,V as OriginNotRegistered,Oe as OriginTaken,_ as PRODUCTION_PROFILE,Pe as PasskeyUnknownHere,_e as QuotaExceeded,it as RECOVERY_DOMAIN,ut as RELEASE_VERIFIER,Ne as RecoveryNotReady,Ue as ReleaseDeadlineError,Te as RuntimeTooOld,te as SEALED_CONTENT_TYPE,$r as SEALED_PATH,T as SealedTransportError,Me as SignUpRefused,ne as StaleTransportKeyError,Be as TrapError,L as UnavailableError,K as WrongNode,ce as WrongRecoveryCode,Nt as agentKeyBinding,Ki as agentQuoteVerifier,Tr as attestAgent,P as b64url,Yn as browserPasskey,Bt as checkOwner,et as claimedRelease,lr as cloudNodeReleaseUrl,de as compareVersions,Rr as confirmationCode,ri as consentReturn,$ as createQuoteVerifier,er as createSealedFetch,$n as createSignedReleaseVerifier,wt as deployerKey,Ve as errorFrom,gr as fetchAttestedKey,cr as fetchGithubNodeRelease,ar as fetchNodeRelease,rt as freshCollateral,O as fromB64url,ii as frontendManifest,Oi as generateOwnerKey,Jn as newRecoverySeed,fi as orgCapabilities,Fe as ownerPublicKey,si as pageDeployment,ue as pageQuery,Zn as parseRecoverySeed,Er as pendingApprovalsFrom,Di as provisionAgent,Mt as provisionInfo,Wn as publisherBindingBytes,dt as publisherBindingMessage,st as recoveryMessage,Xn as recoveryPublicKey,zn as recoverySeedText,Ni as releaseAgent,ft as releaseConsent,gt as releaseNotesUrl,Ar as signRecovery,lt as stalledBy,We as transportKeyBinding,Ee as trustSignedRelease,ir as trustedMeasurementsFromReleases,ni as upgradeConsent,It as validateAgentId,pt as verifyReleaseUrl,_i as verifySignedAgentPolicy,Jr as verifySignedNodeRelease,ti as withdrawConsent};
|
|
8
|
+
${n}`}function ds(t,e,r,n){return new TextEncoder().encode(At(t,e,r,n))}var gs="0123456789ABCDEFGHJKMNPQRSTVWXYZ";async function Sr(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t))),r=(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0,n="";for(let s=0;s<6;s++)s===3&&(n+="-"),n+=gs[r>>>27-5*s&31];return n}function ps(t){let e=typeof t=="string"?new URL(t):t,r=e.searchParams.get("request_id"),n=e.searchParams.get("result");return!r||n!=="approved"&&n!=="declined"?null:{requestId:r,result:n}}var bt="https://mero-tee.vercel.app";function Rt(t){return`https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(t)}`}function Et(t){return`${bt}/mero-tee?release_tag=${encodeURIComponent(`mero-tee-v${t}`)}`}function Cr(t,e,r=Date.now()/1e3){let n=c=>e.deadlines.find(u=>u.version===c)??null,s=t.governance.releases==="owner",i=t.governance.appUpgrades==="owner",o=t.clusterReleases.filter(c=>!c.approved).sort((c,u)=>ge(u.release,c.release)).map(c=>({version:c.release,nodes:c.nodes,actionable:s,releaseNotesUrl:Rt(c.release),verifyUrl:Et(c.release),deadline:n(c.release)})),a=[];for(let c of t.apps){let u=c.availableVersions??[];if(c.package===null||u.length===0)continue;let d=u[u.length-1],g=c.latestReachable===void 0?d:c.latestReachable;a.push({app:c.app,name:c.name??null,package:c.package.package,from:c.package.version,to:g??d,reachable:g!==null,blocked:c.latestBlocked??null,available:u,actionable:i})}return{scope:t.scope,governance:t.governance,approvedReleases:t.approvedReleases,releases:o,upgrades:a,stalledBy:wt(t.approvedReleases,e.deadlines,r),actionable:o.some(c=>c.actionable)||a.some(c=>c.actionable)}}function Pt(t,e,r,n={}){return{kind:"release",scope:t.kind==="org"?{org:t.org}:"account",subject:n.withdraw?{version:e,withdraw:!0}:{version:e},returnTo:r}}function fs(t,e,r){return Pt(t,e,r,{withdraw:!0})}function ys(t,e,r){return{kind:"upgrade",subject:{app:t,toVersion:e},returnTo:r}}function xt(t){return"account"in t?`account:${t.account}`:`org:${t.org}`}async function ms(t,e=fetch){let r=t??globalThis.location?.origin;if(!r)throw new Error("no page origin to read the frontend manifest from; pass `origin`");let n=await e(new URL("/.well-known/calimero.json",r).toString());if(!n.ok)throw await de(n);let s=await n.json();return{...s,deployments:s.deployments??[]}}function hs(t){let e=t??globalThis.location?.href;if(!e)return null;try{return new URL(e).searchParams.get("deployment")||null}catch{return null}}function l(t){return encodeURIComponent(t)}function vt(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}var Or=class t{constructor(e){this.packageOrigins={list:async e=>{let{origins:r}=await this.get(`package-origins/${l(e)}`);return r??[]},add:(e,r,n,s={})=>this.confirmed("POST",`package-origins/${l(e)}`,{origin:r,...s.rpId===void 0?{}:{rpId:s.rpId},...s.served?{served:!0}:{}},n),remove:(e,r,n)=>this.confirmed("DELETE",`package-origins/${l(e)}`,{origin:r},n)};this.transport=e instanceof H?e:new H(e)}static async connect(e){let r=await vr({...e,directory:e.directory??hr});return new t(r)}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,r,n,s,i){let o=s?{bytes:s,...i===void 0?{}:{contentType:i}}:{body:n};return this.transport.json(e,r,o)}post(e,r={}){return this.json("POST",e,r)}get(e){return this.json("GET",e)}put(e,r={}){return this.json("PUT",e,r)}delete(e,r){return this.json("DELETE",e,r)}async signUp(e,r,n={}){let s=this.pageOrigin(n),i=n.invite?{invite:n.invite}:{},o=await this.begin("auth/passkey/register/begin",s===void 0?{name:r,...i}:{name:r,origin:s,...i},s),a=n.signal,c=await(a?e.create(o.options,{signal:a}):e.create(o.options)),u=await this.confirmed("POST","auth/passkey/register/finish",{challengeId:o.challengeId,registration:c,...i},e,"preferred",a);return this.useSession(u),u}signUpPolicy(){return this.get("sign-up")}async signIn(e,r={}){let n=this.pageOrigin(r),s=await this.begin("auth/passkey/login/begin",n===void 0?void 0:{origin:n},n),i=s.options.rpId??s.options.rp?.id??"",o=U(s.options.challenge),a=await(r.signal?e.get(o,i,void 0,{signal:r.signal}):e.get(o,i)),c=await this.post("auth/passkey/login/finish",{challengeId:s.challengeId,assertion:a});return this.useSession(c),c}pageOrigin(e){if(e.origin!==void 0)return e.origin??void 0;let r=globalThis.location?.origin;return!r||r==="null"||new Set(this.transport.nodes.map(s=>{try{return new URL(s).origin}catch{return s}})).has(r)?void 0:r}async begin(e,r,n){try{return await this.post(e,r)}catch(s){throw s instanceof V&&!s.origin&&n!==void 0?new V(s.nodeMessage,{...s.details,origin:n}):s}}refresh(){return this.transport.refresh()}async signOut(){await this.signingOut("auth/logout")}async signOutEverywhere(){await this.signingOut("auth/logout-all")}async listSessions(){let{sessions:e}=await this.get("auth/sessions");return e}async revokeSession(e){await this.delete(`auth/sessions/${l(e)}`)}async listActivity(e){let r=e===void 0?"":`?after=${encodeURIComponent(String(e))}`,{activity:n}=await this.get(`auth/activity${r}`);return n}async signingOut(e){try{await this.post(e)}finally{this.transport.signOut()}}me(){return this.get("auth/me")}async addPasskey(e,r){let n=await this.post("auth/passkeys/add/begin"),s=await e.create(n.options),{credentialId:i}=await this.postConfirmed("auth/passkeys/add/finish",{challengeId:n.challengeId,registration:s},r);return i}async removePasskey(e,r){await this.deleteConfirmed(`auth/passkeys/${l(e)}`,r)}async labelPasskey(e,r){await this.post(`auth/passkeys/${l(e)}`,{label:r})}async createRecoveryCode(e){let{code:r}=await this.postConfirmed("auth/recovery",{},e);return r}async removeRecoveryCode(e){await this.deleteConfirmed("auth/recovery",e)}async startAccountRecovery(e,r){try{let n=await this.post("auth/recovery/begin",{code:e}),s=await r.create(n.options);return await this.post("auth/recovery/start",{challengeId:n.challengeId,code:e,registration:s})}catch(n){throw n instanceof I?new le(n.message.replace(/^401 UNAUTHENTICATED: /,""),n.details):n}}async cancelAccountRecovery(e){await this.postConfirmed("auth/recovery/cancel",{},e)}async finishAccountRecovery(e,r){let n=await this.postConfirmed("auth/recovery/finish",r?{accountId:r}:{},e);return this.useSession(n),n}usage(){return this.get("auth/usage")}async attestation(){let e=vt(crypto.getRandomValues(new Uint8Array(32)));return await(await this.transport.unsealed("attestation",{query:{nonce:e}})).json()}async listApiKeys(){let{keys:e}=await this.get("auth/apikeys");return e}async revokeApiKey(e,r){await this.deleteConfirmed(`auth/apikeys/${l(e)}`,r)}createApiKey(e,r){return this.postConfirmed("auth/apikeys",{...e},r)}async uploadBundle(e){let{hash:r}=await this.json("POST","bundles",void 0,e);return r}uploadBlob(e,r,n={}){let s=(typeof n=="string"?n:n.contentType)??"application/octet-stream";return this.json("POST",`apps/${l(e)}/blobs`,void 0,r,s)}async downloadBlob(e,r){return(await this.blobContent(e,r)).data}async downloadBlobGranted(e,r,n){return(await this.blobContent(e,r,{grant:n})).data}async blobContent(e,r,n={}){let s=await this.transport.request("GET",`apps/${l(e)}/blobs/${l(r)}`,{query:{grant:n.grant}});return{data:new Uint8Array(await s.arrayBuffer()),contentType:s.headers.get("content-type")??"application/octet-stream"}}async listBlobs(e){let{blobs:r}=await this.get(`apps/${l(e)}/blobs`);return r}blobInfo(e,r){return this.get(`apps/${l(e)}/blobs/${l(r)}/info`)}async deleteBlob(e,r){await this.delete(`apps/${l(e)}/blobs/${l(r)}`)}uploadPackage(e){return this.json("POST","packages",void 0,e,"application/octet-stream")}installPackage(e,r){return this.post("packages/install",{package:e,version:r})}async packages(){let{packages:e}=await this.get("packages");return e}package(e){return this.get(`packages/${l(e)}`)}uninstallPackage(e,r){return this.delete(r===void 0?`packages/${l(e)}`:`packages/${l(e)}/${l(r)}`)}async listApps(e={}){let r=new URLSearchParams;e.package&&r.set("package",e.package),e.bundle&&r.set("bundle",e.bundle);let n=r.toString(),{apps:s}=await this.get(n?`apps?${n}`:"apps");return s}getApp(e){return this.get(`apps/${l(e)}`)}async deleteApp(e){await this.delete(`apps/${l(e)}`)}async setAccess(e,r){await this.post(`apps/${l(e)}/access`,{access:r})}async setAppMetadata(e,r){await this.post(`apps/${l(e)}/metadata`,{metadata:r})}appXcalls(e){return this.get(`apps/${l(e)}/xcalls`)}appStorage(e){return this.get(`apps/${l(e)}/storage`)}appAbi(e){return this.get(`apps/${l(e)}/abi`)}async transferApp(e,r,n){await this.postConfirmed(`apps/${l(e)}/transfer`,{to:r},n)}moveApp(e,r,n={},s){let i=`apps/${l(e)}/move`,o={toOrg:r,bringMembers:n.bringMembers??!1};return s?this.postConfirmed(i,o,s):this.post(i,o)}upgradeApp(e,r,n){let s=`apps/${l(e)}/upgrade`;return n?this.postConfirmed(s,r,n):this.post(s,r)}postConfirmed(e,r,n){return this.confirmed("POST",e,r,n)}deleteConfirmed(e,r,n={}){return this.confirmed("DELETE",e,n,r)}confirmed(e,r,n,s,i,o){return this.transport.json(e,r,{body:n,passkey:s,userVerification:i,promptSignal:o})}async createApp(e,r,n={}){let s=typeof r=="string"?{bundle:r}:r,{appId:i}=await this.post("apps",{name:e,...s,...n});return i}call(e,r,n={},s){let i=s??Ge();return this.transport.json("POST",`apps/${l(e)}/intents`,{body:{method:r,args:n,idempotencyKey:i},retry:!0})}async callConfirmed(e,r,n,s,i){let o=`apps/${l(e)}/intents`,a=i??Ge();return this.transport.json("POST",o,{body:{method:r,args:n,idempotencyKey:a},passkey:s,retry:!0})}view(e,r,n={},s={}){return this.transport.json("POST",`apps/${l(e)}/views`,{body:{method:r,args:n,consistency:s.stale?"stale":"strong",minIndex:s.minIndex??0},retry:!0})}events(e,r=0,n){return this.transport.events(`apps/${l(e)}/events`,{query:{from:r},signal:n})}async publishPresence(e,r,n){await this.post(`apps/${l(e)}/presence`,{seq:r,state:n===null?null:vt(n)})}async presence(e){let{present:r}=await this.get(`apps/${l(e)}/presence`);return r}presenceStream(e,r){return this.transport.events(`apps/${l(e)}/presence/stream`,{signal:r})}async setAlias(e,r){await this.put(`auth/aliases/${l(e)}`,{app:r})}async aliases(){let{aliases:e}=await this.get("auth/aliases");return e}async alias(e){let{appId:r}=await this.get(`auth/aliases/${l(e)}`);return r}async deleteAlias(e){await this.delete(`auth/aliases/${l(e)}`)}async createOrg(e,r={}){let n={name:e};r.recoveryKey!==void 0&&(n.recoveryKey=r.recoveryKey);let{orgId:s}=await this.post("orgs",n);return s}async setRecoveryKey(e,r,n){await this.postConfirmed(`orgs/${l(e)}/recovery`,{publicKey:r},n)}async startRecovery(e,r){let n=(await this.me()).accountId,s=P(crypto.getRandomValues(new Uint8Array(16))),i=await Tr(r,e,n,s);return this.post(`orgs/${l(e)}/recovery/start`,{nonce:s,signature:i})}async cancelRecovery(e,r){await this.postConfirmed(`orgs/${l(e)}/recovery/cancel`,{},r)}finishRecovery(e,r){return this.postConfirmed(`orgs/${l(e)}/recovery/finish`,{},r)}getOrg(e){return this.get(`orgs/${l(e)}`)}async orgMembersSecurity(e){let{members:r}=await this.get(`orgs/${l(e)}/members?detail=security`);return r}async deleteOrg(e,r){await this.deleteConfirmed(`orgs/${l(e)}`,r)}async setOrgMetadata(e,r){await this.post(`orgs/${l(e)}/metadata`,{metadata:r})}async setMemberMetadata(e,r,n){await this.post(`orgs/${l(e)}/members/${l(r)}/metadata`,{metadata:n})}upgradeOrg(e,r,n){return this.postConfirmed(`orgs/${l(e)}/upgrade`,{...r},n)}upgradeRun(e,r){return this.get(`orgs/${l(e)}/upgrades/${l(r)}`)}retryUpgradeRun(e,r,n){return this.postConfirmed(`orgs/${l(e)}/upgrades/${l(r)}/retry`,{},n)}async approveRelease(e,r,n,s=!0){let i=e===null?"auth/releases":`orgs/${l(e)}/releases`;return this.postConfirmed(i,{version:r,approved:s},n)}async approveOutbound(e,r,n,s={}){let i=e===null?"auth/outbound":`orgs/${l(e)}/outbound`;return this.postConfirmed(i,{package:r,prefixes:s.prefixes??"manifest",replace:s.replace??!1},n)}appsReport(e,r={}){let n=e===null?"auth/apps":`orgs/${l(e)}/apps`;return this.get(`${n}${pe(r)}`)}async appsReportAll(e){let r=await this.appsReport(e),n=[...r.apps],s=r.next;for(;s!==null;){let i=await this.appsReport(e,{after:s});n.push(...i.apps),s=i.next}return{...r,apps:n,next:null}}releaseRules(){return this.get("releases")}async pendingApprovals(e=null){let[r,n]=await Promise.all([this.appsReportAll(e),this.releaseRules()]);return Cr(r,n)}requestConsent(e){return this.post("consent/requests",e)}async openConsentPage(e,r={}){let n=typeof r=="function"?{navigate:r}:r,s=n.navigate??(o=>{let a=globalThis.window;if(!a)throw new Error("no window to open the consent page in; pass `navigate`");a.location.assign(o)}),i=await this.requestConsent(e);if(i.code!==void 0){let o=await Sr(i.requestId);if(i.code!==o)throw new f(200,"CONSENT_CODE_MISMATCH","the consent page code does not match the request",{requestId:i.requestId,code:i.code,expected:o})}return n.confirm&&!await n.confirm(i)||s(i.url),i}consentResult(e){return this.get(`consent/${l(e)}/result`)}async waitForConsent(e,r={}){let n=r.intervalMs??2e3;for(;;){let s=await this.consentResult(e);if(s.status!=="pending"||r.signal?.aborted||r.expiresAt!==void 0&&Date.now()/1e3>=r.expiresAt)return s;await new Promise(i=>setTimeout(i,n))}}publisherBinding(e){return this.get(`publishers/${l(e)}`)}bindPublisher(e,r,n){return this.postConfirmed(`orgs/${l(e)}/publishers`,{...r},n)}upgradePublished(e,r,n,s){return this.postConfirmed(`orgs/${l(e)}/packages/${l(r)}/upgrade`,{...n},s)}opsApps(e={}){return this.get(`ops/apps${pe(e)}`)}opsOrgs(e={}){return this.get(`ops/orgs${pe(e)}`)}opsServedOrigins(){return this.get("ops/served-origins")}async setReleaseDeadline(e,r){let n=typeof r=="string"?r:r.toISOString();await this.post(`ops/releases/${l(e)}/deadline`,{after:n})}async liftReleaseDeadline(e){await this.delete(`ops/releases/${l(e)}/deadline`)}async setMember(e,r,n,s){await this.postConfirmed(`orgs/${l(e)}/members`,{account:r,role:n},s)}removeMember(e,r,n){return this.deleteConfirmed(`orgs/${l(e)}/members/${l(r)}`,n)}async setCapabilities(e,r,n,s={}){await this.postConfirmed(`orgs/${l(e)}/capabilities`,{capabilities:r,...s},n)}async setAllApps(e,r,n,s){await this.postConfirmed(`orgs/${l(e)}/all-apps`,{account:r,allApps:n},s)}async setTeamDefaultCapabilities(e,r,n,s){await this.postConfirmed(`orgs/${l(e)}/capabilities`,{team:r,capabilities:n},s)}async createTeam(e,r,n,s){let{teamId:i}=await this.post(`orgs/${l(e)}/teams`,{name:r,join:n,parent:s});return i}getTeam(e,r){return this.get(`orgs/${l(e)}/teams/${l(r)}`)}async updateTeam(e,r,n){await this.post(`orgs/${l(e)}/teams/${l(r)}`,n)}async deleteTeam(e,r,n){let s=`orgs/${l(e)}/teams/${l(r)}`;await(n?this.deleteConfirmed(s,n):this.delete(s))}async setTeamMember(e,r,n,s,i={}){await this.postConfirmed(`orgs/${l(e)}/teams/${l(r)}/members`,{account:n,...i},s)}async removeTeamMember(e,r,n,s){await this.deleteConfirmed(`orgs/${l(e)}/teams/${l(r)}/members/${l(n)}`,s)}async invite(e,r,n,s=[],i={}){let{token:o}=await this.postConfirmed(`orgs/${l(e)}/invites`,{role:r,teams:s,...i},n);return o}redeemInvite(e){return this.post(`invites/${l(e)}/redeem`)}async listInvites(e){let{invites:r}=await this.get(`orgs/${l(e)}/invites`);return r}async revokeInvite(e,r,n){await this.deleteConfirmed(`orgs/${l(e)}/invites/${l(r)}`,n)}listAppTeams(e){return this.get(`orgs/${l(e)}/app-teams`)}scopeApps(e,r,n={}){let s={};return n.apps!==void 0&&(s.apps=n.apps),n.shared!==void 0&&(s.shared=n.shared),this.postConfirmed(`orgs/${l(e)}/app-teams`,s,r)}grantDeployer(e,r,n={}){let s=n.until instanceof Date?n.until.toISOString():n.until;return this.postConfirmed("deployers",{deployer:e,...s===void 0?{}:{until:s}},r)}deployers(){return this.get("deployers")}async revokeDeployer(e,r){let n=typeof e=="string"?e:xt(e);await this.deleteConfirmed(`deployers/${l(n)}`,r)}async createDeployment(e,r,n){let{id:s}=await this.postConfirmed("deployments",{name:e,owner:r},n);return s}async deployments(){let{deployments:e}=await this.get("deployments");return e}deployment(e){return this.get(`deployments/${l(e)}`)}async deleteDeployment(e,r){await this.deleteConfirmed(`deployments/${l(e)}`,r)}offerApp(e,r,n){return this.postConfirmed(`deployments/${l(e)}/apps`,{...r},n)}async withdrawApp(e,r,n){await this.deleteConfirmed(`deployments/${l(e)}/apps/${l(r)}`,n)}deploymentOrgs(e){return this.get(`deployments/${l(e)}/orgs`)}};var Ir={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},ws=Ir.JOIN_OPEN_TEAMS;function As(...t){return t.reduce((e,r)=>e|Ir[r],0)}function Fe(t,e){return(t<<e|t>>>32-e)>>>0}function D(t,e,r,n,s){t[e]=t[e]+t[r]>>>0,t[s]=Fe(t[s]^t[e],16),t[n]=t[n]+t[s]>>>0,t[r]=Fe(t[r]^t[n],12),t[e]=t[e]+t[r]>>>0,t[s]=Fe(t[s]^t[e],8),t[n]=t[n]+t[s]>>>0,t[r]=Fe(t[r]^t[n],7)}function kt(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function St(t,e,r){let n=new Uint32Array(16);n[0]=1634760805,n[1]=857760878,n[2]=2036477234,n[3]=1797285236;for(let o=0;o<8;o+=1)n[4+o]=kt(t,o*4);n[12]=e>>>0;for(let o=0;o<3;o+=1)n[13+o]=kt(r,o*4);let s=n.slice();for(let o=0;o<10;o+=1)D(s,0,4,8,12),D(s,1,5,9,13),D(s,2,6,10,14),D(s,3,7,11,15),D(s,0,5,10,15),D(s,1,6,11,12),D(s,2,7,8,13),D(s,3,4,9,14);let i=new Uint8Array(64);for(let o=0;o<16;o+=1){let a=s[o]+n[o]>>>0;i[o*4]=a&255,i[o*4+1]=a>>>8&255,i[o*4+2]=a>>>16&255,i[o*4+3]=a>>>24&255}return i}function bs(t,e,r,n){let s=new Uint8Array(n.length);for(let i=0,o=e;i<n.length;i+=64,o+=1){let a=St(t,o,r),c=Math.min(i+64,n.length);for(let u=i;u<c;u+=1)s[u]=n[u]^a[u-i]}return s}function Dr(t){let e=0n;for(let r=t.length-1;r>=0;r-=1)e=e<<8n|BigInt(t[r]);return e}var Rs=(1n<<130n)-5n;function Es(t,e){let r=Dr(t.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,n=Dr(t.subarray(16,32)),s=0n;for(let a=0;a<e.length;a+=16){let c=e.subarray(a,Math.min(a+16,e.length)),u=Dr(c)+(1n<<BigInt(8*c.length));s=(s+u)*r%Rs}let i=s+n&(1n<<128n)-1n,o=new Uint8Array(16);for(let a=0;a<16;a+=1)o[a]=Number(i&0xffn),i>>=8n;return o}function Tt(t){return new Uint8Array((16-t%16)%16)}function Ut(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function Ps(t,e){let r=[t,Tt(t.length),e,Tt(e.length),Ut(t.length),Ut(e.length)],n=new Uint8Array(r.reduce((i,o)=>i+o.length,0)),s=0;for(let i of r)n.set(i,s),s+=i.length;return n}function vs(t,e){if(t.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 Ct(t,e,r,n=new Uint8Array(0)){vs(t,e);let s=St(t,0,e).subarray(0,32),i=bs(t,1,e,r),o=Es(s,Ps(n,i)),a=new Uint8Array(i.length+16);return a.set(i),a.set(o,i.length),a}var It=32,xs=1,ks=3,Ts=2,Us=32,Ss=32,Cs=12,W=t=>new TextEncoder().encode(t),ye=t=>new Uint8Array([t>>8&255,t&255]),Ot=m(W("KEM"),ye(It)),fe=m(W("HPKE"),ye(It),ye(xs),ye(ks));async function Dt(t,e){let r=t.length===0?new Uint8Array(32):t,n=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",n,e))}async function Os(t,e,r){let n=new Uint8Array(r),s=new Uint8Array(0);for(let i=1,o=0;o<r;i+=1)s=await Dt(t,m(s,e,new Uint8Array([i]))),n.set(s.subarray(0,Math.min(s.length,r-o)),o),o+=s.length;return n}function je(t,e,r,n){return Dt(e,m(W("HPKE-v1"),t,W(r),n))}function Nr(t,e,r,n,s){return Os(e,m(ye(s),W("HPKE-v1"),t,W(r),n),s)}async function Is(t,e){let r=await je(Ot,new Uint8Array(0),"eae_prk",t);return Nr(Ot,r,"shared_secret",e,Us)}async function Ds(t,e){let r=new Uint8Array(0),n=await je(fe,r,"psk_id_hash",r),s=await je(fe,r,"info_hash",e),i=m(new Uint8Array([Ts]),n,s),o=await je(fe,t,"secret",r);return{key:await Nr(fe,o,"key",i,Ss),nonce:await Nr(fe,o,"base_nonce",i,Cs)}}async function Nt(t,e,r,n,s=new Uint8Array(0),i){if(t.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let o=await Q(i),a=await Q(e),c=m(await re(o.privateKey,t),await re(a.privateKey,t)),u=await Is(c,m(o.publicKey,t,a.publicKey)),{key:d,nonce:g}=await Ds(u,r);return{enc:o.publicKey,ciphertext:Ct(d,g,n,s)}}var $t="mero-agent-gate/attest/v3",Bt="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}$/,Mt=64,_t=64*1024,N=class extends Error{constructor(r,n,s){super(r);this.status=n;this.code=s;this.name="AgentGateError"}};function Kt(t){if(!Ns.test(t))throw new Error(`Agent id ${JSON.stringify(t)} must match [a-z0-9][a-z0-9-]{0,62}`)}function me(t){return new TextEncoder().encode(t)}function Vt(t){let e=me(t);return m(new Uint8Array([e.length]),e)}function q(t){let e="";for(let r of t)e+=String.fromCharCode(r);return btoa(e)}function Qe(t,e,r){let n;try{n=Uint8Array.from(atob(t.trim()),s=>s.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(r!==void 0&&n.length!==r)throw new Error(`${e} is not ${r} bytes`);return n}async function Lt(t,e,r,n){let s=new Uint8Array(32),i=m(me($t),t,Vt(e),r??s,n??s);return new Uint8Array(await crypto.subtle.digest("SHA-256",i))}function Ht(t,e){return m(me(Bt),t,Vt(e))}async function _s(){let t=crypto.getRandomValues(new Uint8Array(32));return{secret:t,publicKey:await Ye(t)}}async function Ye(t){if(t.length!==32)throw new Error("An owner key is 32 bytes");return q((await Q(t)).publicKey)}function qt(t,e){return`${t.replace(/\/+$/,"")}${e}`}async function Gt(t,e,r){let n=await t(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)}),s=await n.text(),i;try{i=s?JSON.parse(s):void 0}catch{}if(!n.ok){let o=i;throw new N(`The gate answered ${n.status}${o?.error?` ${o.error}`:""}: ${o?.details??s.slice(0,200)}`,n.status,o?.error)}return i}async function Mr(t){let e=t.agentId??"";e&&Kt(e);let r=crypto.getRandomValues(new Uint8Array(32)),n=await Gt(t.fetch??fetch,qt(t.gateUrl,"/attest"),{nonceB64:q(r),...e?{agentId:e}:{}});if((n?.agentId??"")!==e)throw new Error(`Asked about agent ${JSON.stringify(e)}, the gate answered for ${JSON.stringify(n?.agentId)}`);let s=Qe(n.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),i=n.signingPublicKeyB64?Qe(n.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,o=n.ownerPublicKeyB64?Qe(n.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!i!=!o)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let a=await Lt(s,e,i,o);return await t.verifier({quoteB64:n.quoteB64,nonce:E(r),reportDataSuffix:E(a)}),{agentId:e,provisioningPublicKey:q(s),...i?{signingPublicKey:q(i)}:{},...o?{ownerPublicKey:q(o)}:{}}}async function Ft(t,e){let r=await Ye(e);if(t.ownerPublicKey&&t.ownerPublicKey!==r)throw new N(`This agent is claimed by another key (${t.ownerPublicKey}); it is not yours. Send it nothing and do not authorize its signing key`,void 0,"not_yours");return r}function $s(t){let e=Object.keys(t);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>Mt)throw new Error(`At most ${Mt} secrets at once`);for(let r of e){if(!Ms.test(r))throw new Error(`Secret name ${JSON.stringify(r)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);if(typeof t[r]!="string")throw new Error(`Secret ${r} is not a string`);if(me(t[r]).length>_t)throw new Error(`Secret ${r} is over ${_t} bytes`)}}async function jt(t,e,r,n,s,i){if(!n.agentId)throw new Error("This quote names no agent; attest with the agent id");let o=await Ft(n,s),a=Qe(n.provisioningPublicKey,"provisioningPublicKey",32),c=await Nt(a,s,Ht(a,n.agentId),me(JSON.stringify(i)));return Gt(t,qt(e,r),{agentId:n.agentId,provisioningPublicKeyB64:n.provisioningPublicKey,senderPublicKeyB64:o,encappedKeyB64:q(c.enc),ciphertextB64:q(c.ciphertext)})}async function Bs(t){$s(t.secrets);let e=t.fetch??fetch,r=await jt(e,t.gateUrl,"/provision",t.agent,t.ownerSecret,{secrets:t.secrets}),n=await Mr({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e}),s=await Ye(t.ownerSecret);if(n.ownerPublicKey!==s||!n.signingPublicKey)throw new N("The gate accepted the secrets, but its quote does not name your key as owner");if(t.agent.signingPublicKey&&t.agent.signingPublicKey!==n.signingPublicKey)throw new N("The agent's signing key changed while provisioning");return{agentId:n.agentId,provisioningPublicKey:n.provisioningPublicKey,signingPublicKey:n.signingPublicKey,ownerPublicKey:s,written:r?.written??[],claimed:r?.claimed===!0}}async function Ks(t){if(!t.agent.ownerPublicKey)throw new Error("This agent is not claimed; there is nothing to release");let e=t.fetch??fetch;if(await jt(e,t.gateUrl,"/release",t.agent,t.ownerSecret,{release:!0}),(await Mr({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e})).ownerPublicKey)throw new N("The gate says it released the agent, but its quote still names an owner")}var _r=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),Vs=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function Ls(t,e,r={}){let n=typeof t=="string"?new TextEncoder().encode(t):t;await Ee(n,e,{identity:r.identity??_r.identity,issuer:r.issuer??_r.issuer});let s;try{s=JSON.parse(new TextDecoder().decode(n))}catch{throw new Error("The signed agent policy is not JSON")}let i=r.role??"agent";if(s?.role!==i)throw new Error(`The signed file is a ${JSON.stringify(s?.role)} policy, not an ${i} one`);let o=r.profile??$;if(s.profile!==o)throw new Error(`The signed agent policy is for the ${JSON.stringify(s.profile)} profile, not ${o}`);if(r.expectedVersion!==void 0&&s.version!==r.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(s.version)}, not ${r.expectedVersion}`);return Qt(s),s}function Qt(t){for(let e of Vs)if(!Array.isArray(t?.[e])||t[e].length===0)throw new Error(`The agent policy's ${e} is empty, so no agent would be accepted`)}var Hs=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function qs(t){let e=Hs.find(r=>r.toLowerCase()===t.trim().toLowerCase());if(!e)throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(t)}`);return e}var he=t=>t.trim().replace(/^0x/i,"");function Gs(t,e){return Qt(t),B({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:t.allowed_tcb_statuses.map(qs),allowedMrtd:t.allowed_mrtd.map(he),allowedRtmr0:t.allowed_rtmr0.map(he),allowedRtmr1:t.allowed_rtmr1.map(he),allowedRtmr2:t.allowed_rtmr2.map(he),allowedRtmr3:t.allowed_rtmr3.map(he)})}export{$t as AGENT_ATTEST_DOMAIN,Bt as AGENT_PROVISION_INFO_DOMAIN,N as AgentGateError,Ke as AppError,Te as ArgsTooLarge,Ie as BadOrigin,Or as CalimeroClient,f as CalimeroError,Me as ClusterNotUpgraded,ae as ConfirmCancelled,ce as ConfirmPromptBlocked,X as ConfirmRequired,Oe as ConsentStale,ur as DEFAULT_COLLATERAL_MIRROR,hr as DEFAULT_DIRECTORY,ws as DEFAULT_ORG_CAPABILITIES,Pe as DEFAULT_RELEASE_MIRROR,Er as DEFAULT_RETRY,T as DirectoryError,nt as GITHUB_RELEASES,qr as HANDSHAKE_PATH,Ue as IdempotencyMismatch,_r as KMS_RELEASE_SIGNER,I as LoginRequired,kr as MAX_RECOVERY_NONCE_BYTES,Ur as MAX_REPORT_PAGE,ot as MOCK_QUOTE_HEADER,lr as NODE_RELEASE_SIGNER,H as NodeTransport,ke as NotFound,Ne as NotServing,Ir as ORG_CAPABILITIES,V as OriginNotRegistered,De as OriginTaken,$ as PRODUCTION_PROFILE,xe as PasskeyUnknownHere,Be as QuotaExceeded,pt as RECOVERY_DOMAIN,bt as RELEASE_VERIFIER,_e as RecoveryNotReady,Se as ReleaseDeadlineError,Ce as RuntimeTooOld,ne as SEALED_CONTENT_TYPE,Gr as SEALED_PATH,S as SealedTransportError,$e as SignUpRefused,se as StaleTransportKeyError,Ve as TrapError,L as UnavailableError,K as WrongNode,le as WrongRecoveryCode,Lt as agentKeyBinding,Gs as agentQuoteVerifier,Mr as attestAgent,P as b64url,rs as browserPasskey,Ft as checkOwner,at as claimedRelease,pr as cloudNodeReleaseUrl,ge as compareVersions,Sr as confirmationCode,ps as consentReturn,B as createQuoteVerifier,sr as createSealedFetch,Gn as createSignedReleaseVerifier,xt as deployerKey,vr as directoryTransport,He as errorFrom,mr as fetchAttestedKey,gr as fetchGithubNodeRelease,dr as fetchNodeRelease,ct as freshCollateral,U as fromB64url,ms as frontendManifest,_s as generateOwnerKey,Ge as newIdempotencyKey,as as newRecoverySeed,As as orgCapabilities,Ye as ownerPublicKey,hs as pageDeployment,pe as pageQuery,ls as parseRecoverySeed,Cr as pendingApprovalsFrom,Bs as provisionAgent,Ht as provisionInfo,ds as publisherBindingBytes,At as publisherBindingMessage,Rr as queryString,ft as recoveryMessage,us as recoveryPublicKey,cs as recoverySeedText,de as refusal,Ks as releaseAgent,Pt as releaseConsent,Rt as releaseNotesUrl,Pr as retryDelayMs,is as routePath,Tr as signRecovery,gt as sseFrames,wt as stalledBy,nr as transportKeyBinding,ve as trustSignedRelease,cr as trustedMeasurementsFromReleases,ys as upgradeConsent,Kt as validateAgentId,Et as verifyReleaseUrl,Ls as verifySignedAgentPolicy,tt as verifySignedNodeRelease,fs as withdrawConsent};
|
|
9
9
|
//# sourceMappingURL=index.browser.mjs.map
|