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