@calimero-network/mero-js 26.5.0 → 26.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.
@@ -1,3 +1,3 @@
1
- function cr(t){let e=t.filter(Boolean);if(e.length===0)return;let n=AbortSignal;if(typeof n.any=="function")try{return n.any(e)}catch{}let r=new AbortController,o=i=>{r.abort(i.target.reason);for(let s of e)s.removeEventListener("abort",o)};for(let i of e){if(i.aborted)return AbortSignal.abort(i.reason);i.addEventListener("abort",o,{once:!0})}return r.signal}function lr(t){if(typeof AbortSignal.timeout=="function")return AbortSignal.timeout(t);let e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("Timeout","TimeoutError"))},t),e.signal}var Mo=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function R(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),e}function y(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function m(t,e,n){let r=t.trim();if(!/^[0-9a-fA-F]*$/.test(r)||r.length!==n*2)throw new Error(`${e} must be ${n*2} hex characters, got ${r.length}`);let o=new Uint8Array(n);for(let i=0;i<n;i+=1)o[i]=Number.parseInt(r.slice(i*2,i*2+2),16);return o}function j(t,e){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2!==0)throw new Error(`${e} must be an even number of hex characters`);let r=new Uint8Array(n.length/2);for(let o=0;o<r.length;o+=1)r[o]=Number.parseInt(n.slice(o*2,o*2+2),16);return r}function C(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function f(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}async function E(t,e){let n=[C(t.length),t];for(let r of e)n.push(C(r.length),r);return new Uint8Array(await crypto.subtle.digest("SHA-256",f(...n)))}async function ne(t){let e=m(t,"deviceSecret",32),n=f(Mo,e);try{return await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!1,["sign"])}catch(r){let o=r instanceof Error?`: ${r.message}`:"";throw new Error("this runtime has no WebCrypto Ed25519, so a warrant cannot be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it; otherwise mint the warrant with `merod account warrant`"+o)}}async function Go(t,e,n){let r=await crypto.subtle.importKey("raw",m(t,"publicKey",32),{name:"Ed25519"},!1,["verify"]);return crypto.subtle.verify({name:"Ed25519"},r,e,n)}async function re(t){let e=m(t,"deviceSecret",32),n=f(Mo,e),r=await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),i=(await crypto.subtle.exportKey("jwk",r)).x;return Uint8Array.from(atob(i.replace(/-/g,"+").replace(/_/g,"/")),s=>s.charCodeAt(0))}var ur=new TextEncoder().encode("calimero.auth.request.v2"),Va=new TextEncoder().encode("calimero.auth.request.body.v1");function Ko(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}async function ot(t=new Uint8Array(0)){let e=typeof t=="string"?new TextEncoder().encode(t):t;return E(Va,[e])}async function Ht(t){let e=await ne(t.signerSecret),n=await ot(t.body),r=C(t.issuedAt),o=C(t.expiresAt),i=new TextEncoder,s=await E(ur,[i.encode(t.method),i.encode(t.path),n,r,o]),a=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},e,s));return y(f(Ko(t.method),Ko(t.path),n,r,o,a))}var Ee=t=>new TextEncoder().encode(t),Ie="X-Calimero-Proof",Wa=300;async function dr(t){let{method:e,path:n,credential:r}=t;if(!e)throw new Error("signRequestProof needs the method the request will use");if(!n.startsWith("/"))throw new Error(`signRequestProof needs a path, got ${JSON.stringify(n)}`);let o=await ot(t.body),i=Math.floor(t.now??Date.now()/1e3),s=i+(t.validForSeconds??Wa),a=await E(ur,[Ee(e),Ee(n),o,C(i),C(s)]),c=await Ja(a,t);if(c.length!==64)throw new Error(`the signer returned ${c.length} bytes, not a 64-byte signature`);let u=f(R(Ee(e).length),Ee(e),R(Ee(n).length),Ee(n),o,C(i),C(s),c),d=za(r,"credential");return y(f(d,new Uint8Array([0]),u))}async function Ja(t,e){if(e.signer)return e.signer.sign(t);if(!e.deviceSecret)throw new Error("signRequestProof needs either `deviceSecret` or `signer`");let n=await ne(e.deviceSecret);return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,t))}function za(t,e){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2!==0)throw new Error(`${e} is not an even-length hex string`);return m(n,e,n.length/2)}function pr(t){if(!t.credential)throw new Error("a proof authorizer needs the `credential` from signDeviceCert");if(!t.deviceSecret&&!t.signer)throw new Error("a proof authorizer needs either `deviceSecret` or `signer`");return async({method:e,path:n,body:r})=>{let o=await dr({method:e,path:n,body:r,credential:t.credential,deviceSecret:t.deviceSecret,signer:t.signer,validForSeconds:t.validForSeconds});return{[Ie]:o}}}function de(t){let e=new URL(t,globalThis.location?.href??"http://localhost");return e.pathname+e.search}var Qa=new Set(["token_reuse","token_revoked"]);function Ya(t){if(t)try{let e=JSON.parse(t),n=e?.error;if(typeof n=="string"&&n.trim()!=="")return n;let r=n?.message;if(typeof r=="string"&&r.trim()!=="")return r;let o=e?.detail;if(typeof o=="string"&&o.trim()!=="")return o}catch{}}var O=class extends Error{constructor(n,r,o,i,s){let a=Ya(s)??(n===0&&s?.trim()?s.trim():void 0);super(a?`HTTP ${n} ${r}: ${a}`:`HTTP ${n} ${r}`);this.status=n;this.statusText=r;this.url=o;this.headers=i;this.bodyText=s;this.name="HTTPError";this.explanation=a}toJSON(){return{status:this.status,statusText:this.statusText,url:this.url,headers:$o(this.headers),bodyText:this.bodyText}}},oe=class extends O{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.reason=n;this.name="AuthRevokedError";this.message=`Authentication revoked (${n}): HTTP ${r} ${o}`}};function $o(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function Xa(t){let e;try{e=new URL(t,globalThis.location?.href)}catch{return t}return e.search===""&&(e.search=""),e.href}function Bt(t){return Object.keys(t).some(e=>e.toLowerCase()===Ie.toLowerCase())}function qt(t,e){if(t.type==="opaqueredirect"||t.status>=300&&t.status<400)throw new O(0,"Redirect Not Followed",e,t.headers,`the node answered with a redirect; a request carrying ${Ie} is not followed to another location`)}var it=class{constructor(e){this.transport=e;this.refreshTokenPromise=null;this.onTokenRefreshPromise=null}async get(e,n){return this.request(e,{...n,method:"GET"})}async post(e,n,r){return this.request(e,{...r,method:"POST",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async put(e,n,r){return this.request(e,{...r,method:"PUT",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async delete(e,n){return this.request(e,{...n,method:"DELETE"})}async patch(e,n,r){return this.request(e,{...r,method:"PATCH",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async head(e,n){let r=await this.makeRequest(e,{...n,method:"HEAD",parse:"response"});return{headers:$o(r.headers),status:r.status}}async request(e,n){return this.makeRequest(e,n)}async makeRequest(e,n,r=0,o){let s=Xa(this.buildUrl(e)),a=o??Date.now(),c=this.createAbortSignal(n),u=await this.buildHeaders(n?.headers),d;u instanceof Headers?(d={},u.forEach((b,k)=>{d[k]=b})):d=u;let l=n?.method||"GET";if(this.transport.authorizeRequest){let b=n?.body;if(b!==void 0&&typeof b!="string"&&!(b instanceof Uint8Array))throw new Error("this transport authorizes each request against its body, so the body must be a string or Uint8Array \u2014 a stream cannot be signed, because the signature would have to read bytes the request then cannot send.");Object.assign(d,await this.transport.authorizeRequest({method:l,path:de(s),body:b}))}let p={method:l,headers:d},x=n?.body instanceof ReadableStream||typeof n?.body=="object"&&n?.body!==null&&"getReader"in n.body&&!(n.body instanceof Blob);(n?.body!==void 0&&!x||n?.body!==void 0&&x&&r===0)&&(p.body=n.body);let v;if(r>0&&o!==void 0){let b=n?.timeoutMs||this.transport.timeoutMs;if(b){let k=Date.now()-a,T=Math.max(0,b-k);v=this.createAbortSignal({...n,timeoutMs:T})}else v=this.createAbortSignal(n)}else v=c;if(v&&(p.signal=v),this.transport.credentials!==void 0&&(p.credentials=this.transport.credentials),n?.mode!==void 0&&(p.mode=n.mode),n?.cache!==void 0&&(p.cache=n.cache),n?.redirect!==void 0&&(p.redirect=n.redirect),n?.referrer!==void 0&&(p.referrer=n.referrer),n?.referrerPolicy!==void 0&&(p.referrerPolicy=n.referrerPolicy),n?.integrity!==void 0&&(p.integrity=n.integrity),n?.keepalive!==void 0&&(p.keepalive=n.keepalive),this.transport.getProof){let b=await this.transport.getProof({method:p.method??"GET",path:de(s),body:p.body});b&&(d["X-Calimero-Proof"]=b)}let P=Bt(d);P&&p.redirect!=="error"&&(p.redirect="manual");try{let b=await this.transport.fetch(s,p);if(P&&qt(b,s),!b.ok){let k=await this.getBodyText(b),T=new O(b.status,b.statusText,s,b.headers,k),H=b.headers.get("x-auth-error");if((b.status===401||b.status===403)&&H&&Qa.has(H)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new oe(H,b.status,b.statusText,s,b.headers,k)}let z=n?.signal?.aborted===!0;if(b.status===401&&this.transport.refreshToken&&H==="token_expired"&&r<1&&!x&&!z)try{let h=this.refreshTokenPromise;h||(h=this.transport.refreshToken(),this.refreshTokenPromise=h);let w=await h;if(!w||w.trim()==="")throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("Refresh token returned empty token");if(!this.transport.onTokenRefresh)throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("onTokenRefresh callback is required when refreshToken is provided. The callback must update the token storage so getAuthToken() returns the new token.");let S=this.onTokenRefreshPromise;S||(S=this.transport.onTokenRefresh(w),this.onTokenRefreshPromise=S),await S,this.refreshTokenPromise=null,this.onTokenRefreshPromise=null;let U=n?.timeoutMs||this.transport.timeoutMs;if(U&&o!==void 0){let M=Date.now()-a;if(U-M<=0)throw T}return this.makeRequest(e,n,r+1,a)}catch(h){throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,h instanceof Error&&h.message.includes("onTokenRefresh")?h:T}throw T}return this.parseResponse(b,n?.parse)}catch(b){throw b instanceof O||b instanceof Error&&b.message.includes("onTokenRefresh")?b:new O(0,"Network Error",s,new Headers,b instanceof Error?b.message:"Unknown error")}}buildUrl(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;let n=this.transport.baseUrl;return e.startsWith("/")?`${n.endsWith("/")?n.slice(0,-1):n}${e}`:`${n.endsWith("/")?n:`${n}/`}${e}`}createAbortSignal(e){let n=[];this.transport.defaultAbortSignal&&n.push(this.transport.defaultAbortSignal),e?.signal&&n.push(e.signal);let r=e?.timeoutMs||this.transport.timeoutMs;return r&&n.push(lr(r)),n.length>0?cr(n):void 0}async buildHeaders(e){let n={...this.transport.defaultHeaders};if(this.transport.getAuthToken)try{let r=await this.transport.getAuthToken();r&&r.trim()!==""&&(n.Authorization=`Bearer ${r}`)}catch{}return e&&(e instanceof Headers?e.forEach((r,o)=>{n[o]=r}):Array.isArray(e)?e.forEach(([r,o])=>{n[r]=o}):Object.assign(n,e)),n}async parseResponse(e,n){switch(n){case"text":return await e.text();case"blob":return await e.blob();case"arrayBuffer":return await e.arrayBuffer();case"response":return e;default:{let r=await e.text();if(!r)return null;try{return JSON.parse(r)}catch{throw new Error(`Expected a JSON response (status ${e.status}) but body was not JSON: ${r.slice(0,200)}`)}}}}async getBodyText(e){try{let n=await e.text();return n.length>65536?n.slice(0,65536)+"...":n}catch{return""}}};function st(t){return new it(t)}function Pe(t){let e={fetch:(n,r)=>t.fetch?t.fetch(n,r):globalThis.fetch(n,r),baseUrl:t.baseUrl,getAuthToken:t.getAuthToken,getProof:t.getProof,onTokenRefresh:t.onTokenRefresh,refreshToken:t.refreshToken,onAuthRevoked:t.onAuthRevoked,defaultHeaders:t.defaultHeaders,timeoutMs:t.timeoutMs,credentials:t.credentials,defaultAbortSignal:t.defaultAbortSignal};return st(e)}function jt(t){let e=t.fetch??globalThis.fetch;if(!e)throw new Error("No fetch implementation available. Please provide a fetch implementation (e.g., undici.fetch) or use Node.js 18+ which has native fetch support.");let r={fetch:e===globalThis.fetch?(o,i)=>globalThis.fetch(o,i):(o,i)=>e(o,i),baseUrl:t.baseUrl,getAuthToken:t.getAuthToken,getProof:t.getProof,onTokenRefresh:t.onTokenRefresh,refreshToken:t.refreshToken,onAuthRevoked:t.onAuthRevoked,defaultHeaders:t.defaultHeaders,timeoutMs:t.timeoutMs,credentials:t.credentials,defaultAbortSignal:t.defaultAbortSignal};return st(r)}function gr(t){return typeof window<"u"?Pe(t):jt(t)}function Za(t,e){if(e<=0)return!1;let r=t?.name;if(r==="TimeoutError")return!0;if(r==="AbortError")return!1;let o=t;if("status"in o&&typeof o.status=="number"){let i=o.status;return i>=500||i===429}return r==="TypeError"}function ec(t){let n=250*Math.pow(2,t-1),r=(Math.random()-.5)*.4*n;return Math.max(0,n+r)}async function Ft(t,e={}){let{attempts:n=3}=e,r;for(let o=1;o<=n;o++)try{return await t(o)}catch(i){if(r=i,!Za(r,n-o))throw r;let s=ec(o),u=r.headers?.get?.("Retry-After");if(u){let d=parseInt(u,10);if(!isNaN(d))s=Math.max(s,d*1e3);else{let l=new Date(u);if(!isNaN(l.getTime())){let p=Math.max(0,l.getTime()-Date.now());s=Math.max(s,Math.min(p,6e4))}}}await new Promise(d=>setTimeout(d,s))}throw r||new Error("Retry failed without error")}function tc(t,e={}){return async(...n)=>Ft(()=>t(...n),e)}function g(t){if(t===""||t==="."||t==="..")throw new TypeError(`invalid request path segment: ${JSON.stringify(t)}`);return encodeURIComponent(t)}var pe=class{constructor(e){this.httpClient=e}async getHealth(){let e=await this.httpClient.get("/auth/health");if(!e.data)throw new Error("Health response data is null");return e.data}async getIdentity(){let e=await this.httpClient.get("/admin/identity");if(!e.data)throw new Error("Identity response data is null");return e.data}async getProviders(){let e=await this.httpClient.get("/auth/providers");if(!e.data)throw new Error("Providers response data is null");return e.data}async getLoginPage(){return this.httpClient.get("/auth/login",{parse:"text"})}async generateTokens(e){return this.httpClient.post("/auth/token",e)}async refreshToken(e){return this.httpClient.post("/auth/refresh",e)}async generateMockTokens(e){return this.httpClient.post("/auth/mock-token",e)}async validateToken(e){try{let n=await this.validateTokenGet(e);return{valid:n.status===200,headers:n.headers,status:n.status}}catch{return{valid:!1,headers:{},status:401}}}async validateTokenGet(e){let n=await this.httpClient.head("/auth/validate",{headers:{Authorization:`Bearer ${e}`}});return{status:n.status,headers:n.headers}}async revokeTokens(e){let n=await this.httpClient.post("/admin/revoke",e);if(!n.data)throw new Error("Revoke tokens response data is null");return n.data}async listRootKeys(){let e=await this.httpClient.get("/admin/keys");if(!e.data)throw new Error("Root keys response data is null");return e.data}async createRootKey(e){let n=await this.httpClient.post("/admin/keys",e);if(!n.data)throw new Error("Create root key response data is null");return n.data}async deleteRootKey(e){return this.httpClient.delete(`/admin/keys/${g(e)}`)}async listClientKeys(){let e=await this.httpClient.get("/admin/keys/clients");if(!e.data)throw new Error("Client keys response data is null");return e.data}async generateClientKey(e){return this.httpClient.post("/admin/client-key",e)}async deleteClientKey(e,n){return this.httpClient.delete(`/admin/keys/${g(e)}/clients/${g(n)}`)}async getKeyPermissions(e){return this.httpClient.get(`/admin/keys/${g(e)}/permissions`)}async updateKeyPermissions(e,n){return this.httpClient.put(`/admin/keys/${g(e)}/permissions`,{add:n.add,remove:n.remove})}};var at=class{async get(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async post(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async put(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async delete(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async patch(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async head(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async request(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}};function yp(t){let e=new at;return new pe(e)}function bp(t){let e=new at;return new pe(e)}function wp(t){let e=new at;return new pe(e)}function Lo(t,e){return new pe(t)}var _={CAN_CREATE_CONTEXT:1,CAN_INVITE_MEMBERS:2,CAN_JOIN_OPEN_SUBGROUPS:4,MANAGE_MEMBERS:8,MANAGE_APPLICATION:16,CAN_CREATE_SUBGROUP:32,CAN_DELETE_SUBGROUP:64,CAN_MANAGE_VISIBILITY:128,CAN_MANAGE_METADATA:256,CAN_AUTHOR_ON_BEHALF:512},xp={NONE:0,JOIN_ONLY:_.CAN_JOIN_OPEN_SUBGROUPS,CONTRIBUTOR:_.CAN_CREATE_CONTEXT|_.CAN_INVITE_MEMBERS|_.CAN_JOIN_OPEN_SUBGROUPS,COLLABORATOR:_.CAN_CREATE_CONTEXT|_.CAN_INVITE_MEMBERS|_.CAN_JOIN_OPEN_SUBGROUPS|_.CAN_CREATE_SUBGROUP|_.CAN_DELETE_SUBGROUP|_.CAN_MANAGE_VISIBILITY};function vp(...t){let e=0;for(let n of t)if(typeof n=="number")e|=n;else if(Object.prototype.hasOwnProperty.call(_,n))e|=_[n];else throw new Error(`unknown capability: ${String(n)}`);return e>>>0}function Rp(t){return Object.keys(_).filter(e=>ge(t,_[e]))}function ge(t,e){let n=e>>>0;return(t&n)>>>0===n}function mr(t,e){return(t|e)>>>0}function Cp(t,e){return(t&~e)>>>0}var nc={invalid:!1,unauthorized:!0,forbidden:!1,"not-found":!0,conflict:!1,gone:!1,"too-large":!1,"rate-limited":!0,unavailable:!0,server:!0,unreachable:!0,unknown:!0};function rc(t){switch(t){case 0:return"unreachable";case 400:return"invalid";case 401:return"unauthorized";case 403:return"forbidden";case 404:return"not-found";case 409:return"conflict";case 410:return"gone";case 413:return"too-large";case 429:return"rate-limited";case 503:case 504:return"unavailable"}return t>=500&&t<600?"server":t>=400&&t<500?"invalid":"unknown"}function oc(t){if(!t||typeof t!="object")return;let e=t;for(let n of[e.status,e.response?.status,e.statusCode])if(typeof n=="number"&&Number.isFinite(n))return n}function fr(t,e="Request failed"){if(typeof t=="string")return t.trim()||e;if(!t||typeof t!="object")return e;let n=t;for(let r of[n.explanation,n.response?.data?.error,n.response?.data?.message,n.data?.message,n.error,n.message])if(typeof r=="string"&&r.trim())return r;return e}function hr(t){let e=oc(t),n;return e!==void 0?n=rc(e):t instanceof TypeError?n="unreachable":n="unknown",{kind:n,status:e,retryable:nc[n],message:fr(t)}}function ic(t){return t.status!=="failed"||!t.retryable}function Ip(t){return!ic(t)}var sc={invitation_expired:"expired",invitation_invalid:"invalid",invitation_already_used:"already-used",removed_from_group:"removed",reentry_blocked:"refused"};function ac(t){if(!t||typeof t!="object")return;let e=t;if(typeof e.response?.data?.code=="string")return e.response.data.code;if(typeof e.bodyText=="string")try{let n=JSON.parse(e.bodyText);return typeof n?.code=="string"?n.code:void 0}catch{return}}function cc(t){let e=t.toLowerCase();return e.includes("invitation has expired")||e.includes("invitation expired")||/\binvitation for group .+? expired at \d+/.test(e)?"expired":e.includes("malformed")||e.includes("does not match namespace_id")||e.includes("invalid invitation")||/\binvitation for group .+? is invalid:/.test(e)?"invalid":e.includes("has already used this invitation")?"already-used":/\bwas removed from group\b/.test(e)?"removed":null}var lc=new Set(["already-used","removed"]);function uc(t,e){let{kind:n,status:r}=hr(t),o=cc(e),i=ac(t),s=i?sc[i]:void 0;return s?{reason:s,retryable:!1}:o&&lc.has(o)?{reason:o,retryable:!1}:i==="join_refused_by_member"?{reason:"unknown",retryable:!0}:r===401?{reason:"signed-out",retryable:!0}:r===400?{reason:o??"invalid",retryable:!1}:r===410?{reason:"expired",retryable:!1}:r===403?{reason:"refused",retryable:!1}:r===409?{reason:o??"refused",retryable:!1}:n==="unavailable"?{reason:"no-one-online",retryable:!0}:n==="unreachable"?{reason:"node-unreachable",retryable:!0}:o?{reason:o,retryable:!1}:{reason:"unknown",retryable:!0}}async function Ho(t,e){let{namespaceId:n,invitation:r,teamName:o}=t,i=null;try{await e.join(n,r)}catch(d){i=d}let s=null;try{s=(await e.memberships()).includes(n)}catch{s=null}if(i===null)return{status:"joined",namespaceId:n,teamName:o};if(s===!0)return{status:"already-member",namespaceId:n,teamName:o};let a=fr(i,"Could not join. Check the invitation."),{reason:c,retryable:u}=uc(i,a);return{status:"failed",namespaceId:n,message:a,reason:c,retryable:u}}function A(t){return t?.data}function dc(t,e){let[n,r]=Bo(t),[o,i]=Bo(e),s=n.split("."),a=o.split("."),c=Math.max(s.length,a.length);for(let p=0;p<c;p++){let x=qo(s[p]??"0",a[p]??"0");if(x!==0)return x}if(r===void 0&&i===void 0)return 0;if(r===void 0)return 1;if(i===void 0)return-1;let u=r.split("."),d=i.split("."),l=Math.max(u.length,d.length);for(let p=0;p<l;p++){if(p>=u.length)return-1;if(p>=d.length)return 1;let x=qo(u[p],d[p]);if(x!==0)return x}return 0}function Bo(t){let e=t.split("+",1)[0],n=e.indexOf("-");return n===-1?[e,void 0]:[e.slice(0,n),e.slice(n+1)]}function qo(t,e){let n=/^\d+$/.test(t),r=/^\d+$/.test(e);if(n&&r){let o=Number(t)-Number(e);return o<0?-1:o>0?1:0}return n?-1:r?1:t<e?-1:t>e?1:0}async function pc(t,e,n){return Ft(async()=>{let r=await fetch(t,{signal:AbortSignal.timeout(1e4)});if(!r.ok){let o=new Error(`registry ${e} fetch failed (${r.status}) for ${n}`);throw o.status=r.status,o}return r},{attempts:3})}var me=class{constructor(e){this.httpClient=e}async healthCheck(){return A(await this.httpClient.get("/admin-api/health"))}async readinessCheck(){return A(await this.httpClient.get("/admin-api/ready"))}async isAuthed(){return this.httpClient.get("/admin-api/is-authed")}async installApplication(e){return A(await this.httpClient.post("/admin-api/install-application",e))}async getRegistryVersions(e,n){let r=new URL("/api/v2/bundles",new URL(e).origin);r.searchParams.set("package",n);let i=await(await pc(r.toString(),"versions",n)).json();return(Array.isArray(i)?i:[]).map(s=>s.appVersion).filter(s=>typeof s=="string").sort((s,a)=>dc(a,s))}async installDevApplication(e){return A(await this.httpClient.post("/admin-api/install-dev-application",e))}async uninstallApplication(e){return A(await this.httpClient.delete(`/admin-api/applications/${g(e)}`))}async listApplications(){return A(await this.httpClient.get("/admin-api/applications"))}async getApplication(e){return A(await this.httpClient.get(`/admin-api/applications/${g(e)}`))}async listApplicationVersions(e){return A(await this.httpClient.get(`/admin-api/applications/${g(e)}/versions`))}async getApplicationAbi(e,n){let r=n?`?service_name=${encodeURIComponent(n)}`:"";return A(await this.httpClient.get(`/admin-api/applications/${g(e)}/abi${r}`))}async listPackages(){let e=await this.httpClient.get("/admin-api/packages");return e?.data??e}async listPackageVersions(e){let n=await this.httpClient.get(`/admin-api/packages/${g(e)}/versions`);return n?.data??n}async getLatestPackageVersion(e){return this.httpClient.get(`/admin-api/packages/${g(e)}/latest`)}async createContext(e){let n={...e,initializationParams:e.initializationParams??[]};return A(await this.httpClient.post("/admin-api/contexts",n))}async deleteContext(e){return A(await this.httpClient.delete(`/admin-api/contexts/${g(e)}`))}async getContexts(){return A(await this.httpClient.get("/admin-api/contexts"))}async getContext(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}`))}async getContextsForApplication(e){return A(await this.httpClient.get(`/admin-api/contexts/for-application/${g(e)}`))}async generateContextIdentity(){return A(await this.httpClient.post("/admin-api/identity/context",{}))}async getContextIdentities(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/identities`))}async getContextIdentitiesOwned(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/identities-owned`))}async joinContext(e){return A(await this.httpClient.post(`/admin-api/contexts/${g(e)}/join`,{}))}async getContextGroup(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/group`))}async getContextStorage(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/storage`))}async syncContext(e){let n=e?`/admin-api/contexts/sync/${g(e)}`:"/admin-api/contexts/sync";await this.httpClient.post(n,{})}async resyncContext(e,n={}){return await this.httpClient.post(`/admin-api/contexts/${g(e)}/resync`,n)??{contextId:e,resyncStarted:!0}}async updateContextApplication(e,n){await this.httpClient.post(`/admin-api/contexts/${g(e)}/application`,n)}async getContextsWithExecutorsForApplication(e){let n=await this.httpClient.get(`/admin-api/contexts/with-executors/for-application/${g(e)}`);return Array.isArray(n)?n:n?.contexts??n?.data??[]}async uploadBlob(e){let n=new URLSearchParams;e.hash&&n.set("hash",e.hash),e.contextId&&n.set("context_id",e.contextId);let r=n.toString(),o=r?`/admin-api/blobs?${r}`:"/admin-api/blobs",i=A(await this.httpClient.request(o,{method:"PUT",body:e.data,headers:{"Content-Type":"application/octet-stream"}}));return{blobId:i.blob_id,size:i.size}}async deleteBlob(e){let n=await this.httpClient.delete(`/admin-api/blobs/${g(e)}`);return{blobId:n.blob_id,deleted:n.deleted}}async listBlobs(){return{blobs:A(await this.httpClient.get("/admin-api/blobs")).blobs.map(n=>({blobId:n.blob_id,size:n.size}))}}blobPath(e,n){if(!n?.contextId)return`/admin-api/blobs/${g(e)}`;let r=new URLSearchParams({context_id:n.contextId});return`/admin-api/blobs/${g(e)}?${r.toString()}`}async getBlob(e,n){return this.httpClient.get(this.blobPath(e,n),{parse:"arrayBuffer"})}async getBlobInfo(e,n){let{headers:r}=await this.httpClient.head(this.blobPath(e,n)),o=Number(r["content-length"]);return{blobId:r["x-blob-id"]??e,size:Number.isFinite(o)?o:0,hash:r["x-blob-hash"],mimeType:r["x-blob-mime-type"],source:r["x-blob-source"]}}async createContextAlias(e){return A(await this.httpClient.post("/admin-api/alias/create/context",{alias:e.alias,contextId:e.contextId}))}async createApplicationAlias(e){return A(await this.httpClient.post("/admin-api/alias/create/application",{alias:e.alias,applicationId:e.applicationId}))}async lookupContextAlias(e){return A(await this.httpClient.post(`/admin-api/alias/lookup/context/${g(e)}`,{}))}async lookupApplicationAlias(e){return A(await this.httpClient.post(`/admin-api/alias/lookup/application/${g(e)}`,{}))}async deleteContextAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/context/${g(e)}`,{}))}async deleteApplicationAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/application/${g(e)}`,{}))}async listContextAliases(){return A(await this.httpClient.get("/admin-api/alias/list/context"))}async listApplicationAliases(){return A(await this.httpClient.get("/admin-api/alias/list/application"))}async createDeviceAlias(e){return A(await this.httpClient.post("/admin-api/alias/create/device",{alias:e.alias,deviceId:e.deviceId}))}async lookupDeviceAlias(e){return A(await this.httpClient.post(`/admin-api/alias/lookup/device/${g(e)}`,{}))}async deleteDeviceAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/device/${g(e)}`,{}))}async listDeviceAliases(){return A(await this.httpClient.get("/admin-api/alias/list/device"))}async listNamespaces(){return A(await this.httpClient.get("/admin-api/namespaces"))}async getNamespace(e){return A(await this.httpClient.get(`/admin-api/namespaces/${g(e)}`))}async getNodeIdentity(){return A(await this.httpClient.get("/admin-api/identity"))}async performIntent(e,n){return A(await this.httpClient.post(`/admin-api/contexts/${g(e)}/intents`,n))}async queryContext(e,n){return A(await this.httpClient.post(`/admin-api/contexts/${g(e)}/query`,n))}async getIntentRelay(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/intents`))}async listNamespacesForApplication(e){return A(await this.httpClient.get(`/admin-api/namespaces/for-application/${g(e)}`))}async createNamespace(e){return A(await this.httpClient.post("/admin-api/namespaces",e))}async deleteNamespace(e){return A(await this.httpClient.request(`/admin-api/namespaces/${g(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async createNamespaceInvitation(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/invite`,n??{}))}async admitJoin(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/admit`,n,{timeoutMs:65e3}))}async joinNamespace(e,n){let r=A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/join`,n,{timeoutMs:65e3}));return r&&r.namespaceId===void 0&&r.groupId!==void 0?{...r,namespaceId:r.groupId}:r}async redeemInvitation(e,n,r={}){let{groupName:o,teamName:i}=r;return Ho({namespaceId:e,invitation:n,teamName:i},{join:async()=>{await this.joinNamespace(e,o===void 0?{invitation:n}:{invitation:n,groupName:o})},memberships:async()=>(await this.listNamespaces()??[]).map(s=>s.namespaceId)})}async createGroupInNamespace(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/groups`,n??{}))}async listNamespaceGroups(e){return A(await this.httpClient.get(`/admin-api/namespaces/${g(e)}/groups`))}async initAccountPairing(e){return A(await this.httpClient.post("/admin-api/account/pair-init",e))}async completeAccountPairing(e){return A(await this.httpClient.post("/admin-api/account/pair-complete",e))}async relinkAccountDevice(e,n){return A(await this.httpClient.post(`/admin-api/account/devices/${g(e)}/relink`,n??{}))}async rescopeAccountDevice(e,n){return A(await this.httpClient.put(`/admin-api/account/devices/${g(e)}/scope`,n))}async signWithAccountRoot(e){return A(await this.httpClient.post("/admin-api/account/sign-with-root",e))}async labelAccountDevice(e,n){return A(await this.httpClient.put(`/admin-api/account/devices/${g(e)}/label`,n))}async listAccountDevices(){return(await this.httpClient.get("/admin-api/account/devices")).devices}async listAccountApplications(){return(await this.httpClient.get("/admin-api/account/applications")).applications}async revokeAccountDevice(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/account/revoke`,n))}async linkAccountDevice(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/account/link-device`,n))}async getGroupInfo(e){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}`))}async getDefaultCapabilities(e){return(await this.getGroupInfo(e)).defaultCapabilities}async getSubgroupVisibility(e){return(await this.getGroupInfo(e)).subgroupVisibility}async deleteGroup(e){return A(await this.httpClient.request(`/admin-api/groups/${g(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async listGroupMembers(e){let n=await this.httpClient.get(`/admin-api/groups/${g(e)}/members`);if(!Array.isArray(n?.members)){let r=String(e).replace(/[\r\n\t\s]/g,"").slice(0,64);throw new Error(`Invalid listGroupMembers response for group ${r}: missing or non-array \`members\` field`)}return n}async listGroupMemberDevices(e,n){let r=new URLSearchParams;n?.offset!==void 0&&r.set("offset",String(n.offset)),n?.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${g(e)}/member-devices`;return(await this.httpClient.get(o?`${i}?${o}`:i)).members}async listMemberDevices(e,n={}){let r=new URLSearchParams;n.offset!==void 0&&r.set("offset",String(n.offset)),n.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${g(e)}/member-devices${o?`?${o}`:""}`;return this.httpClient.get(i)}async sealToAccount(e,n,r){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/accounts/${g(n)}/seal`,r))}async listGroupContexts(e){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}/contexts`))}async addGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${g(e)}/members`,n)}async removeGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${g(e)}/members/remove`,n)}async updateMemberRole(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/members/${g(n)}/role`,r)}async getMemberCapabilities(e,n){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}/members/${g(n)}/capabilities`))}async setMemberCapabilities(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/members/${g(n)}/capabilities`,r)}async setDefaultCapabilities(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/settings/default-capabilities`,n)}async openToDelegatedExecution(e){let n=await this.getDefaultCapabilities(e);if(ge(n,_.CAN_AUTHOR_ON_BEHALF))return{changed:!1,defaultCapabilities:n};let r=mr(n,_.CAN_AUTHOR_ON_BEHALF);return await this.setDefaultCapabilities(e,{defaultCapabilities:r}),{changed:!0,defaultCapabilities:r}}async grantAuthorship(e,n){let{capabilities:r}=await this.getMemberCapabilities(e,n);if(ge(r,_.CAN_AUTHOR_ON_BEHALF))return{changed:!1,capabilities:r};let o=mr(r,_.CAN_AUTHOR_ON_BEHALF);return await this.setMemberCapabilities(e,n,{capabilities:o}),{changed:!0,capabilities:o}}async setSubgroupVisibility(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/settings/subgroup-visibility`,n)}async setTeeAdmissionPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/settings/tee-admission-policy`,n)}async getTeeAdmissionPolicy(e){let n=await this.httpClient.get(`/admin-api/groups/${g(e)}/settings/tee-admission-policy`);return n.data??n}async setTeeAuthoringPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/settings/tee-authoring-policy`,n)}async disableTeeAuthoringPolicy(e,n={}){let r=`/admin-api/groups/${g(e)}/settings/tee-authoring-policy`;if(n.rootProof===void 0){await this.httpClient.delete(r);return}await this.httpClient.request(r,{method:"DELETE",body:JSON.stringify({rootProof:n.rootProof}),headers:{"Content-Type":"application/json"}})}async transferOwnership(e,n){await this.httpClient.post(`/admin-api/groups/${g(e)}/transfer-ownership`,n)}async changeNamespaceAdmin(e,n){await this.httpClient.post(`/admin-api/namespaces/${g(e)}/admin`,n)}async ownerDeleteGroup(e,n={}){await this.httpClient.post(`/admin-api/groups/${g(e)}/owner-delete`,n)}async setGroupMetadata(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/metadata`,n)}async getGroupMetadata(e){return(await this.httpClient.get(`/admin-api/groups/${g(e)}/metadata`))?.data??null}async setMemberMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/members/${g(n)}/metadata`,r)}async getMemberMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${g(e)}/members/${g(n)}/metadata`))?.data??null}async setContextMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/contexts/${g(n)}/metadata`,r)}async getContextMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${g(e)}/contexts/${g(n)}/metadata`))?.data??null}async syncGroup(e){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/sync`,{}))}async upgradeGroup(e,n){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/upgrade`,n))}async getGroupUpgradeStatus(e){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}/upgrade/status`))}async getMigrationStatus(e){return this.httpClient.get(`/admin-api/groups/${g(e)}/migration-status`)}async listNamespaceRevokedDevices(e){return this.httpClient.get(`/admin-api/namespaces/${g(e)}/revoked-devices`)}async getCascadeStatus(e){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}/cascade-status`))}async activateGroupUpgrade(e,n={}){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/upgrade/activate`,n))}async retryGroupUpgrade(e){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/upgrade/retry`,{}))}async reparentGroup(e,n){let r=await this.httpClient.post(`/admin-api/groups/${g(e)}/reparent`,n);return r?.data??r}async listSubgroups(e){let n=await this.httpClient.get(`/admin-api/groups/${g(e)}/subgroups`);return n.subgroups??n.data??[]}async detachContextFromGroup(e,n){await this.httpClient.post(`/admin-api/groups/${g(e)}/contexts/${g(n)}/remove`,{})}async createGroupInvitation(e,n){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/invite`,n??{}))}async joinGroup(e){return A(await this.httpClient.post("/admin-api/groups/join",e))}async joinSubgroupInheritance(e){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/join-via-inheritance`,{}))}async getTeeInfo(){return A(await this.httpClient.get("/admin-api/tee/info"))}async teeAttest(e){return A(await this.httpClient.post("/admin-api/tee/attest",e))}async getPeersCount(){return this.httpClient.get("/admin-api/peers")}async getNetworkStatus(){return this.httpClient.get("/admin-api/network/status")}async getUsage(){return this.httpClient.get("/admin-api/usage")}async createGroup(e){return A(await this.httpClient.post("/admin-api/groups",e))}async leaveGroup(e){await this.httpClient.post(`/admin-api/groups/${g(e)}/leave`,{})}async leaveContext(e){await this.httpClient.post(`/admin-api/contexts/${g(e)}/leave`,{})}async leaveNamespace(e){await this.httpClient.post(`/admin-api/namespaces/${g(e)}/leave`,{})}async issueOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${g(e)}/issue-ownership-proof`,n)}async issueNamespaceOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${g(e)}/issue-namespace-ownership-proof`,n)}async setMemberAutoFollow(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/members/${g(n)}/auto-follow`,r)}async abortMigration(e){return this.httpClient.post(`/admin-api/groups/${g(e)}/migration/abort`,{})}};function Mp(t){return Array.from(new TextEncoder().encode(t),e=>e.toString(16).padStart(2,"0")).join("")}function Hp(t){return new me(Pe(t))}function Bp(t){return new me(jt(t))}function jo(t){return new me(gr(t))}function Vt(t,e){return new me(t)}var Fo="calimero.cloud.link.pending",yr="link_state",gc=600*1e3,br=/^[0-9a-f]{64}$/,mc=20,fc=32,wr=/^[0-9a-f]{64}$/,hc="account-link-grant";function Vo(t,e){try{let n=localStorage.getItem(t),r=n?JSON.parse(n):{};return Object.fromEntries(Object.entries(r).filter(([,o])=>o&&typeof o.expiresAt=="number"&&o.expiresAt>e))}catch{return{}}}function Wo(t,e){try{localStorage.setItem(t,JSON.stringify(e))}catch{}}function ct(t,e){let n=Date.now(),r=Vo(t,n),o=y(crypto.getRandomValues(new Uint8Array(16)));return r[o]={...e,expiresAt:n+gc},Wo(t,Object.fromEntries(Object.entries(r).slice(-mc))),o}function Te(t,e){let n=Vo(t,Date.now());if(!e||!Object.prototype.hasOwnProperty.call(n,e))return null;let r=n[e];return delete n[e],Wo(t,n),r}async function Ar(t){let e=Uint8Array.from(t.match(/../g)??[],n=>parseInt(n,16));return y(new Uint8Array(await crypto.subtle.digest("SHA-256",e)))}async function Wt(t,e){if(!br.test(t))throw new Error("accountId must be 64 lowercase hex characters");let n=new URL(e),r=y(crypto.getRandomValues(new Uint8Array(fc))),o=await Ar(r);return n.searchParams.set(yr,ct(Fo,{account:t,verifier:r})),{callbackUrl:n.toString(),challenge:o}}function De(t,e){let n=Te(Fo,new URLSearchParams(t).get(yr));return!n||n.account!==e?null:typeof n.verifier=="string"&&wr.test(n.verifier)?n.verifier:null}function lt(t){try{let e=t.split(".")[0].replace(/-/g,"+").replace(/_/g,"/"),n=JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(e),a=>a.charCodeAt(0)))),{use:r,sub:o,acc:i,chal:s}=n;return r!==hc||typeof o!="string"||typeof i!="string"||typeof s!="string"?null:{login:o,account:i,challenge:s}}catch{return null}}function Jo(t){let e=new URLSearchParams(t);e.delete(yr);let n=e.toString();return n?`?${n}`:""}var zo="calimero.auth.login.pending",Qo="auth_state";function xr(t,e={}){try{let n=t.indexOf("#");if(n===-1)return null;let r=t.substring(n+1),o=new URLSearchParams(r),i=o.get("access_token");return i?!e.allowUnsolicited&&!Te(zo,yc(t,n))?(console.warn("[mero-js] ignoring auth callback tokens: they answer no login begun in this browser"),null):{accessToken:i,refreshToken:o.get("refresh_token")??"",applicationId:o.get("application_id")??"",contextId:o.get("context_id")??"",contextIdentity:o.get("context_identity")??"",nodeUrl:o.get("node_url")??""}:null}catch{return null}}function yc(t,e){let n=t.indexOf("?");return n===-1||n>e?null:new URLSearchParams(t.substring(n+1,e)).get(Qo)}function vr(t,e){let n=new URL(e.callbackUrl);n.searchParams.set(Qo,ct(zo,{}));let r=new URLSearchParams;return r.set("callback-url",n.toString()),e.permissions&&e.permissions.length>0&&r.set("permissions",e.permissions.join(",")),r.set("mode",e.mode),e.packageName&&(r.set("package-name",e.packageName),e.packageVersion&&r.set("package-version",e.packageVersion),e.registryUrl&&r.set("registry-url",e.registryUrl)),`${t.replace(/\/+$/,"")}/auth/login?${r.toString()}`}function Jt(t){let e=j(t.credential,"credential"),n=j(t.request,"request signature"),r=t.session===void 0?new Uint8Array([0]):f(new Uint8Array([1]),j(t.session,"session statement"));return y(f(e,r,n))}function bc(t){if(t==null)return new Uint8Array(0);if(typeof t=="string"||t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error(`a request-carried proof cannot commit to a ${t?.constructor?.name??typeof t} body: pass a string or bytes, or use a session for this call`)}function zt(t){let e=t.ttlSeconds??120,n=t.now??(()=>Math.floor(Date.now()/1e3));return async r=>{let o=n();return Jt({credential:t.credential,session:t.session,request:await Ht({method:r.method,path:r.path,body:bc(r.body),issuedAt:o,expiresAt:o+e,signerSecret:t.signerSecret})})}}var Qt=class extends Error{constructor(e,n,r,o){super(n),this.name="RpcError",this.code=e,this.data=r,this.type=o}};async function Rr(t,e,n){let r=await t.post("/jsonrpc",{jsonrpc:"2.0",id:1,method:e,params:n});if(r.error){let o=r.error;throw new Qt(o.code??-1,o.message??o.type??"RPC error",o.data,o.type)}return r.result}var ut=class{constructor(e){this.kind="node";this.canSubscribe=!0;this.httpClient=e.httpClient}async execute(e){let n=await Rr(this.httpClient,"execute",{contextId:e.contextId,method:e.method,argsJson:e.argsJson??{}});return n&&"output"in n?n.output:n}async executeWithMetadata(e){return{returns:await this.execute(e),transport:"node"}}async migrateMyEntries(e){return this.execute({contextId:e,method:"migrate_my_entries"})}async countMyPending(e){return this.execute({contextId:e,method:"count_my_pending"})}};var wc=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function Yo(t){return t.type!==void 0&&wc.has(t.type)}var Ac=new Set(["token_reuse","token_revoked"]),xc=new Set([401,403]),vc=1e4;function Xo(t){let e=t.headers.get("x-auth-error");return!e||!xc.has(t.status)?null:Ac.has(e)?e:null}var B=class{constructor(e){this.sessionId=null;this.abortController=null;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.presence=new Map;this.closed=!1;this.listeners={connect:[],event:[],error:[]};if(this.baseUrl=e.baseUrl.replace(/\/+$/,""),e.authorize)this.authorize=e.authorize;else if(e.getAuthToken){let n=e.getAuthToken;this.authorize=async()=>({Authorization:`Bearer ${await n()}`})}else throw new Error("SseClient needs either `getAuthToken` or `authorize`");this.reconnectDelayMs=e.reconnectDelayMs??3e3,this.fetchImpl=(n,r)=>e.fetch?e.fetch(n,r):globalThis.fetch(n,r)}on(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(n)||o.push(n)}}off(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r],i=o.indexOf(n);i!==-1&&o.splice(i,1)}}onAppVersionChanged(e){let n=r=>{if(r.type!=="AppVersionChanged")return;let o=r.data;e({contextId:r.contextId,fromVersion:o?.fromVersion,toVersion:o?.toVersion})};return this.on("event",n),()=>this.off("event",n)}onMigrationEvent(e){let n=r=>{Yo(r)&&e(r)};return this.on("event",n),()=>this.off("event",n)}emit(e,n){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(n)}catch{}}async connect(){if(this.abortController&&!this.closed)return;this.closed=!1;let e=new AbortController;this.abortController=e;try{let n=`${this.baseUrl}/sse`,r={...await this.authorize({method:"GET",path:de(n)}),Accept:"text/event-stream"},o=Bt(r),i=await this.fetchImpl(n,{headers:r,signal:e.signal,...o&&{redirect:"manual"}});if(o&&qt(i,n),!i.ok){let s=Xo(i),a=await i.text().catch(()=>{});throw s?new oe(s,i.status,i.statusText,n,i.headers,a):new O(i.status,i.statusText,n,i.headers,a)}if(!i.body)throw new Error("SSE response has no body");this.readStream(i.body,e).catch(s=>{if(this.superseded(e))return;let a=s instanceof Error?s:new Error(String(s));this.emit("error",a),this.scheduleReconnect()})}catch(n){if(this.superseded(e))return;let r=n instanceof Error?n:new Error(String(n));if(this.emit("error",r),r instanceof oe)return;this.scheduleReconnect()}}superseded(e){return this.closed||e.signal.aborted||this.abortController!==e}async readStream(e,n){let r=e.getReader(),o=new TextDecoder,i="";try{for(;;){let{done:s,value:a}=await r.read();if(s)break;i+=o.decode(a,{stream:!0});let c=i.split(`
2
- `);i=c.pop()??"";for(let u of c)if(u.startsWith("data:")){let d=u.slice(5).trim();d&&this.handleMessage(d)}}if(i+=o.decode(),i.startsWith("data:")){let s=i.slice(5).trim();s&&this.handleMessage(s)}}catch(s){if(this.superseded(n))return;let a=s instanceof Error?s:new Error(String(s));this.emit("error",a)}this.superseded(n)||this.scheduleReconnect()}handleMessage(e){try{let n=JSON.parse(e);if(n.type==="connect"&&n.session_id){let o=n.session_id;if(this.sessionId=o,this.presence.clear(),this.subscribedContextIds.size===0&&this.subscribedGroupIds.size===0){this.emit("connect",o);return}this.postSubscription("subscribe",{contextIds:[...this.subscribedContextIds],groupIds:[...this.subscribedGroupIds]}).then(i=>{this.closed||this.sessionId!==o||(this.emit("connect",o),i&&this.emit("error",i))});return}if(!n.result)return;let r=n.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),i=new TextDecoder().decode(o);r=JSON.parse(i)}catch{}if(n.result.contextId){n.result.type==="Ephemeral"&&this.notePresence(n.result.contextId,r),this.emit("event",{contextId:n.result.contextId,type:n.result.type,data:r});return}n.result.groupId&&this.emit("event",{groupId:n.result.groupId,type:n.result.type,data:r})}catch{}}async subscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>!this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>!this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.add(i);for(let i of n.groupIds??[])this.subscribedGroupIds.add(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("subscribe",{contextIds:r,groupIds:o})}isSubscribed(e){return this.subscribedContextIds.has(e)}presenceSeed(e){let n=Date.now();return[...this.presence.get(e)?.values()??[]].map(({data:r,at:o})=>({...r,ageMs:(typeof r.ageMs=="number"?r.ageMs:0)+(n-o)}))}notePresence(e,n){if(!this.subscribedContextIds.has(e))return;let r=n;if(!r||typeof r.author!="string")return;let o=this.presence.get(e);o||this.presence.set(e,o=new Map),r.removed?o.delete(r.author):o.set(r.author,{data:r,at:Date.now()})}async unsubscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.delete(i),this.presence.delete(i);for(let i of n.groupIds??[])this.subscribedGroupIds.delete(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("unsubscribe",{contextIds:r,groupIds:o})}async sendSubscription(e,n){let r=await this.postSubscription(e,n);r&&this.emit("error",r)}async postSubscription(e,n){let r=new AbortController,o=setTimeout(()=>r.abort(new DOMException(`SSE ${e} timed out`,"TimeoutError")),vc);try{let i={};n.contextIds&&n.contextIds.length>0&&(i.contextIds=n.contextIds),n.groupIds&&n.groupIds.length>0&&(i.groupIds=n.groupIds);let s=`${this.baseUrl}/sse/subscription`,a=JSON.stringify({id:this.sessionId,method:e,params:i}),c={...await this.authorize({method:"POST",path:de(s),body:a}),"Content-Type":"application/json"},u=Bt(c),d=await this.fetchImpl(s,{method:"POST",headers:c,body:a,signal:r.signal,...u&&{redirect:"manual"}});if(u&&qt(d,s),!d.ok){let l=Xo(d),p=await d.text().catch(()=>{});return l?new oe(l,d.status,d.statusText,`${this.baseUrl}/sse/subscription`,d.headers,p):new O(d.status,d.statusText,`${this.baseUrl}/sse/subscription`,d.headers,p)}return null}catch(i){return i instanceof Error?i:new Error(`SSE ${e} failed`)}finally{clearTimeout(o)}}forceReconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.sessionId=null,this.connect()}scheduleReconnect(){this.closed||(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.forceReconnect()},this.reconnectDelayMs))}close(){this.closed=!0,this.abortController&&(this.abortController.abort(),this.abortController=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.sessionId=null,this.subscribedContextIds.clear(),this.subscribedGroupIds.clear()}};var Yt=class Yt{constructor(e){this.ws=null;this.closed=!1;this.reconnectAttempt=0;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.listeners={connect:[],event:[],error:[]};this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.getAuthToken=e.getAuthToken}on(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(n)||o.push(n)}}off(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r],i=o.indexOf(n);i!==-1&&o.splice(i,1)}}emit(e,n){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(n)}catch{}}async connect(){if(!(this.ws&&(this.ws.readyState===0||this.ws.readyState===1))){this.closed=!1;try{let e=await this.getAuthToken();if(!e)throw new Error("No authentication token available for WebSocket connection");let n=this.baseUrl.replace(/^http/,"ws");this.ws=new WebSocket(`${n}/ws?token=${encodeURIComponent(e)}`),this.ws.onopen=()=>{this.reconnectAttempt=0,this.emit("connect"),this.resubscribeAfterReconnect()},this.ws.onmessage=r=>{this.handleMessage(r.data)},this.ws.onerror=()=>{this.emit("error",new Error("WebSocket error"))},this.ws.onclose=()=>{this.closed||this.scheduleReconnect()}}catch(e){if(this.closed)return;let n=e instanceof Error?e:new Error(String(e));this.emit("error",n),this.scheduleReconnect()}}}handleMessage(e){if(typeof e=="string")try{let n=JSON.parse(e);if(!n.result)return;let r=n.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),i=new TextDecoder().decode(o);r=JSON.parse(i)}catch{}if(n.result.contextId){this.emit("event",{contextId:n.result.contextId,type:n.result.type,data:r});return}n.result.groupId&&this.emit("event",{groupId:n.result.groupId,type:n.result.type,data:r})}catch{}}subscribe(e){let n=Array.isArray(e)?{contextIds:e}:e;for(let r of n.contextIds??[])this.subscribedContextIds.add(r);for(let r of n.groupIds??[])this.subscribedGroupIds.add(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams(n.contextIds??[],n.groupIds??[])})}unsubscribe(e){let n=Array.isArray(e)?{contextIds:e}:e;for(let r of n.contextIds??[])this.subscribedContextIds.delete(r);for(let r of n.groupIds??[])this.subscribedGroupIds.delete(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"unsubscribe",params:this.buildSubscriptionParams(n.contextIds??[],n.groupIds??[])})}resubscribeAfterReconnect(){this.subscribedContextIds.size===0&&this.subscribedGroupIds.size===0||this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams([...this.subscribedContextIds],[...this.subscribedGroupIds])})}buildSubscriptionParams(e,n){let r={};return e.length>0&&(r.contextIds=e),n.length>0&&(r.groupIds=n),r}sendMessage(e){this.ws&&this.ws.readyState===1&&this.ws.send(JSON.stringify(e))}scheduleReconnect(){if(this.closed)return;this.reconnectTimer&&clearTimeout(this.reconnectTimer);let e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),Yt.MAX_BACKOFF_MS);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e)}close(){this.closed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscribedContextIds.clear(),this.subscribedGroupIds.clear()}};Yt.MAX_BACKOFF_MS=3e4;var ie=Yt;function se(){return{encode(t){return Array.from(new TextEncoder().encode(JSON.stringify(t)))},decode(t){return JSON.parse(new TextDecoder().decode(new Uint8Array(t)))}}}var dt=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,n,r=se()){await Rr(this.httpClient,"set_ephemeral",{contextId:e,state:r.encode(n)})}subscribe(e,n,r=se()){return Xt(this.sse,e,n,r)}};function Xt(t,e,n,r=se()){let o=i=>{let s=i;if(s.type!=="Ephemeral"||s.contextId!==e)return;let a=s.data;if(!a?.author)return;let c=!!a.removed,u={author:a.author,state:c||a.state===void 0?void 0:r.decode(a.state),removed:c};a.ageMs!==void 0&&(u.ageMs=a.ageMs),a.account!==void 0&&(u.account=a.account),n(u)};if(t.on("event",o),t.isSubscribed?.(e))for(let i of t.presenceSeed?.(e)??[])o({contextId:e,type:"Ephemeral",data:i});return t.connect().catch(()=>{}),t.subscribe([e]).catch(()=>{}),()=>{t.off("event",o)}}var Rc=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function Zo(t){let e=t instanceof Error?`: ${t.message}`:"";return new Error("this runtime has no WebCrypto Ed25519, so nothing can be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it"+e)}async function Ue(t,e="secret"){let n=m(t,e,32),r=f(Rc,n),o,i;try{let s=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!0,["sign"]),a=await crypto.subtle.exportKey("jwk",s);i=y(Uint8Array.from(atob(a.x.replace(/-/g,"+").replace(/_/g,"/")),c=>c.charCodeAt(0))),o=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!1,["sign"])}catch(s){throw Zo(s)}return ti(o,i)}async function ei(t,e){if(t.type!=="private")throw new Error(`signerFromCryptoKey needs the private half of the pair, got a ${t.type} key`);if(!t.usages.includes("sign"))throw new Error("this CryptoKey cannot sign: generate it with usages ['sign', 'verify']");let n;if(typeof e=="string")m(e,"publicKey",32),n=e.trim().toLowerCase();else try{n=y(new Uint8Array(await crypto.subtle.exportKey("raw",e)))}catch(r){let o=r instanceof Error?`: ${r.message}`:"";throw new Error("could not read the public half of this key pair; pass the public key as 64 hex instead"+o)}return ti(t,n)}function ti(t,e){return{publicKey:e,async sign(n){try{return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},t,n))}catch(r){throw Zo(r)}}}}async function I(t,e,n){if(e&&t!==void 0)throw new Error(`pass either ${n} or signer, not both \u2014 they may name different keys`);if(e)return e;if(t!==void 0)return Ue(t,n);throw new Error(`${n} or signer is required`)}var Cc=new TextEncoder().encode("calimero.mdma.account-ownership-claim.v1\0"),Sc=6e4,ni=5*6e4,ri=1024,ii="mdma:enable-ha-namespace",si="mdma:enable-ha-namespace-as-account";function oi(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var Cr=(t,e)=>{if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);return t.toLowerCase()};async function ai(t,e,n,r){if(r!==void 0&&!(r.length>0&&r.length<=ri))throw new Error(`relayUrl must be a non-empty string of at most ${ri} characters`);let o=t.ttlMs??Sc;if(!(o>0&&o<=ni))throw new Error(`ttlMs must be in (0, ${ni}]`);let i=Cr(t.namespaceId,"namespaceId"),s=Cr(t.accountId,"accountId"),a=Cr(t.salt,"salt"),c=await I(t.deviceSecret,t.signer,"deviceSecret"),u=(t.now??Date.now)(),d=Array.from(crypto.getRandomValues(new Uint8Array(16)),x=>x.toString(16).padStart(2,"0")).join(""),l=new TextEncoder().encode(JSON.stringify({v:1,audience:e,group_id:i,account_id:s,salt:a,...n===void 0?{}:{subject:n},nonce:d,issued_at_ms:u,expires_at_ms:u+o,...r===void 0?{}:{relay_url:r}})),p=await c.sign(f(Cc,l));return{kind:"account",credential:t.credential,signed_payload:oi(l),signature:oi(p)}}async function kc(t){if(!t.subject)throw new Error("subject must be the cloud login email");return ai(t,ii,t.subject)}async function Sr(t){return ai(t,si,void 0,t.relayUrl)}var Ec=new TextEncoder().encode("calimero.device.cert.v1"),Ic=new TextEncoder().encode("calimero.account.genesis.v1"),Pc=new TextEncoder().encode("calimero.device.id.v1"),Oe=2,Tc=237;async function kr(t,e){if(e.length!==16)throw new Error(`nonce must be 16 bytes, got ${e.length}`);let n=m(t,"account",32),r=await E(Pc,[n,e]);return y(f(e,r.subarray(0,16)))}async function Zt(t){return E(Ec,[m(t.account,"account",32),m(t.device,"device",32),m(t.signPublicKey,"signPublicKey",32),m(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch)])}function ci(t){return f(new Uint8Array([Oe]),t.rootPublicKey,R(0),m(t.account,"account",32),m(t.device,"device",32),m(t.signPublicKey,"signPublicKey",32),m(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch),t.signature)}async function li(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=m(e.publicKey,"signer.publicKey",32),r=await F(e.publicKey),o=0,i=await Zt({account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch}),s=await e.sign(i),a=ci({rootPublicKey:n,account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch,signature:s});return y(a)}function Er(t){let e=m(t,"credential",Tc);if(e[0]!==Oe)throw new Error(`this credential has account genesis version ${e[0]}, not ${Oe} \u2014 it names a different account than its root key derives here, and core would refuse it`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint32(33,!0);if(r!==0)throw new Error(`this credential carries a ${r}-handoff root chain, which this SDK cannot verify yet \u2014 the signing root is not the genesis root, so checking it means walking the chain`);let o=(i,s)=>y(e.subarray(i,i+s));return{rootPublicKey:o(1,32),account:o(37,32),device:o(69,32),signPublicKey:o(101,32),kemPublicKey:o(133,32),keyEpoch:n.getUint32(165,!0),deviceEpoch:n.getUint32(169,!0),signature:o(173,64)}}async function en(t){let e=Er(t),n=await F(e.rootPublicKey);if(n!==e.account)throw new Error(`this credential names account ${e.account}, but its root key derives ${n} \u2014 the certificate was re-pointed at another account`);let r=m(e.device,"device",32).subarray(0,16);if(await kr(e.account,r)!==e.device)throw new Error(`this credential names device ${e.device}, which was not minted for account ${e.account}; core refuses it`);if(!await Go(e.rootPublicKey,m(e.signature,"signature",64),await Zt(e)))throw new Error(`the root key of account ${e.account} did not sign this certificate`);return e}async function tn(t){return F(y(await re(t)))}async function F(t){return y(await E(Ic,[f(new Uint8Array([Oe]),m(t,"rootPublicKey",32))]))}var Dc=new TextEncoder().encode("calimero.device.scope.v1");async function Ir(t){return E(Dc,[m(t.account,"account",32),m(t.device,"device",32),R(t.scopeEpoch),R(t.keyEpoch),...t.applications.map((e,n)=>m(e,`applications[${n}]`,32))])}async function ui(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=m(e.publicKey,"signer.publicKey",32),r=await F(y(n)),o=t.applications??[],i=t.scopeEpoch??0;if(!Number.isInteger(i)||i<0||i>4294967295)throw new Error(`scopeEpoch must be a u32, got ${i}`);let s=0,a=await Ir({account:r,device:t.device,applications:o,scopeEpoch:i,keyEpoch:s}),c=await e.sign(a);if(c.length!==64)throw new Error(`signer returned ${c.length} bytes, expected a 64-byte Ed25519 signature`);return y(f(new Uint8Array([Oe]),n,R(0),m(r,"account",32),m(t.device,"device",32),R(o.length),...o.map((u,d)=>m(u,`applications[${d}]`,32)),R(i),R(s),c))}var Pr=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"];var Uc=new TextEncoder().encode("calimero.mdma.account-link.v1\0"),Oc=new TextEncoder().encode("calimero.mdma.account-login.v1\0"),Ne=256,di=Ne/32,Tr=(Ne+di)/11;async function pi(){let t=crypto.getRandomValues(new Uint8Array(Ne/8));return bi(y(t),await Ai(t))}async function gi(t){let e=wi(t);return bi(y(await xi(e)),e.join(" "))}async function Dr(t){return m(t,"secret",32),{secret:t,publicKey:y(await re(t)),accountId:await tn(t)}}async function mi(){let t=crypto.getRandomValues(new Uint8Array(Ne/8)),e=await Ai(t);return{...await hi(t),phrase:e}}async function fi(t){return hi(await xi(wi(t)))}async function hi(t){let e=await Ue(y(t),"rootSecret");return t.fill(0),{publicKey:e.publicKey,accountId:await F(e.publicKey),signer:e}}async function Y(t){let e=typeof t=="string"?await Ue(t,"rootSecret"):t;return yi(e)}async function nn(t,e){return yi(await I(t,e,"rootSecret"))}async function yi(t){return{signer:t,publicKey:t.publicKey,accountId:await F(t.publicKey)}}async function pt(t){if(!t.nonce)throw new Error("nonce is required to sign an account link");let n=await(await I(t.rootSecret,t.signer,"rootSecret")).sign(f(Uc,new TextEncoder().encode(t.nonce)));return Ci(n)}async function rn(t){if(!t.nonce)throw new Error("nonce is required to sign an account login");let n=await(await I(t.rootSecret,t.signer,"rootSecret")).sign(f(Oc,new TextEncoder().encode(t.nonce)));return Ci(n)}async function bi(t,e){return{...await Dr(t),phrase:e}}function wi(t){let e=t.normalize("NFKD").toLowerCase().trim().split(/\s+/),n=e[0]===""?0:e.length;if(n!==Tr)throw new Error(`recovery phrase must be ${Tr} words, got ${n}`);return e}async function Ai(t){let e=Ri(t)+await vi(t),n=[];for(let r=0;r<Tr;r+=1){let o=Number.parseInt(e.slice(r*11,r*11+11),2);n.push(Pr[o])}return n.join(" ")}async function xi(t){let e="";for(let r of t){let o=Pr.indexOf(r);if(o<0)throw new Error(`"${r}" is not a word in the recovery phrase list`);e+=o.toString(2).padStart(11,"0")}let n=new Uint8Array(Ne/8);for(let r=0;r<n.length;r+=1)n[r]=Number.parseInt(e.slice(r*8,r*8+8),2);if(e.slice(Ne)!==await vi(n))throw new Error("recovery phrase checksum failed \u2014 check for a mistyped or transposed word");return n}async function vi(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return Ri(e).slice(0,di)}function Ri(t){let e="";for(let n of t)e+=n.toString(2).padStart(8,"0");return e}function Ci(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var Nc=new TextEncoder().encode("calimero.tee-attest.key-binding.v1"),on=new TextEncoder().encode("MOCK_TDX_QUOTE_V1"),_c=568;function Mc(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}function Ur(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r+=1)n|=t[r]^e[r];return n===0}function Gc(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}function Kc(t,e){if(typeof t!="string"||!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);let n=new Uint8Array(32);for(let r=0;r<32;r+=1)n[r]=Number.parseInt(t.slice(r*2,r*2+2),16);return n}async function sn(t){let e=await crypto.subtle.digest("SHA-256",Mc(Nc,new Uint8Array(32),t));return new Uint8Array(e)}function Or(t){let e=t.length>=on.length&&Ur(t.subarray(0,on.length),on),n=e?on.length:_c;if(t.length<n+64)throw new Error(`the quote is too short to carry report data (${t.length} bytes)`);return{reportData:t.slice(n,n+64),mock:e}}async function an(t){let e=crypto.getRandomValues(new Uint8Array(32)),n=`${t.relayUrl.replace(/\/+$/,"")}/admin-api/tee/attest`,r=JSON.stringify({nonce:y(e),bindNodeKey:!0,...t.verify?.includeCollateral?{includeCollateral:!0}:{}}),o={method:"POST",headers:{"Content-Type":"application/json"},body:r},i=t.fetch?await t.fetch(n,o):await globalThis.fetch(n,o);if(!i.ok){let p=await i.text().catch(()=>"");throw new Error(`the relay would not attest (HTTP ${i.status})${p?`: ${p}`:""}`)}let s=await i.json(),a=s.data??s;if(typeof a.quoteB64!="string")throw new Error("the relay returned no quote");let c=Kc(a.boundPublicKey,"boundPublicKey"),u=Gc(a.quoteB64),{reportData:d,mock:l}=Or(u);if(l){if(!t.allowMock)throw new Error("the relay answered with a MOCK quote, which proves nothing about the hardware")}else if(t.verify){if(!await t.verify({quoteB64:a.quoteB64,nonce:y(e),reportDataSuffix:y(await sn(c)),...a.collateral?{collateral:a.collateral}:{}}))throw new Error("the relay's quote did not verify: not a trusted image, or not bound to this request")}else if(t.verifyQuote)await t.verifyQuote(u);else throw new Error("a real TDX quote needs a verify (or verifyQuote) to check its signature and measurements");if(!Ur(d.subarray(0,32),e))throw new Error("the quote does not carry our nonce: it was not made for this request");if(!Ur(d.subarray(32,64),await sn(c)))throw new Error("the quote does not bind the key the relay named: refusing it");return{nodeKey:y(c),mock:l}}var $c="Noise_NK_25519_AESGCM_SHA256",Nr=32,Lc=16,Hc=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Mr=class t{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode($c),n=new Uint8Array(32);return n.set(e),new t(n)}async mixHash(e){this.h=await Bc(f(this.h,e))}async mixKey(e){let[n,r]=await ki(this.ck,e);this.ck=n,this.k=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:Si(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(n),n}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let n=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Si(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),n}split(){return ki(this.ck,new Uint8Array)}};async function Ei(t,e,n){let r=await Mr.initialize();await r.mixHash(e),await r.mixHash(t);let o=await _e(n);return await r.mixHash(o.publicKey),await r.mixKey(await gt(o.privateKey,t)),{message1:f(o.publicKey,await r.encryptAndHash(new Uint8Array)),async finish(s){if(s.length<Nr+Lc)throw new Error("Noise: message 2 is too short");let a=s.slice(0,Nr);return await r.mixHash(a),await r.mixKey(await gt(o.privateKey,a)),{payload:await r.decryptAndHash(s.slice(Nr)),split:await r.split()}}}}async function _e(t){if(!t){let r;try{r=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"])}catch(i){throw new Error(`Sealed transport needs WebCrypto with X25519, which this runtime lacks (${i?.name??"no crypto.subtle"}). Current browsers and Node have it; in React Native, install react-native-quick-crypto as the global crypto.`)}let o=new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey));return{privateKey:r.privateKey,publicKey:o}}let e=await crypto.subtle.importKey("pkcs8",f(Hc,t),{name:"X25519"},!0,["deriveBits"]),n=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:qc(n.x)}}async function gt(t,e){let n=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:n},t,256))}function Si(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}async function Bc(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}async function _r(t,e){let 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 ki(t,e){let n=await _r(t,e),r=await _r(n,new Uint8Array([1])),o=await _r(n,f(r,new Uint8Array([2])));return[r,o]}function qc(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}var Di="/sealed/v2/handshake",Ui="/sealed/v2",ft="application/vnd.calimero.sealed",Gr=2,jc=new TextEncoder().encode("calimero/sealed-http/v2"),mt=16,Fc=1+mt+8,Vc=0,Wc=1,Jc=2,zc=1+64*1024+16,Qc=1024,Yc=6e4,Xc="calimero.tee-attest.transport-key.v1",Zc=[101,204,205,304],Oi=new TextEncoder,ht=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},Me=class extends Error{constructor(n,r,o,i){super(o);this.status=n;this.code=r;this.retryAfterMs=i;this.name="SealedTransportError"}};async function Ni(t,e){let n=await crypto.subtle.digest("SHA-256",f(Oi.encode(Xc),t,e));return new Uint8Array(n)}async function _i(t,e,n={}){if(n.applicationId===void 0!=(n.applicationHash===void 0))throw new Error("applicationId and applicationHash are given together or not at all");let r=y(crypto.getRandomValues(new Uint8Array(32))),o=await t.teeAttest({nonce:r,applicationId:n.applicationId,bindTransportKey:!0,...e.includeCollateral?{includeCollateral:!0}:{}});if(!o.transportPublicKey)throw new Error("The node did not report a transport key; it predates sealed transport");let i=m(o.transportPublicKey,"transportPublicKey",32),s=n.applicationHash?m(n.applicationHash,"applicationHash",32):new Uint8Array(32),a=y(await Ni(s,i));if(!await e({quoteB64:o.quoteB64,nonce:r,reportDataSuffix:a,collateral:o.collateral}))throw new Error("The attestation did not verify, so its transport key is not trusted");return i}function fe(t){let e=t.fetch??((o,i)=>fetch(o,i)),n=`${t.baseUrl.replace(/\/+$/,"")}/admin-api/tee/attest`,r={async teeAttest(o){let i=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)});if(!i.ok)throw new Error(`The node refused to attest: HTTP ${i.status}`);let s=await i.json();if(!s.data)throw new Error("The attestation response is malformed");return s.data}};return Mi({baseUrl:t.baseUrl,transportPublicKey:()=>_i(r,t.verify,{applicationId:t.applicationId,applicationHash:t.applicationHash}),fetch:e})}function Mi(t){let e=new URL(t.baseUrl),n=e.pathname.replace(/\/+$/,""),r=`${e.origin}${n}`,o=t.fetch??((l,p)=>fetch(l,p)),i=typeof t.transportPublicKey=="function"?t.transportPublicKey:void 0,s=i?Promise.resolve().then(i):Promise.resolve(t.transportPublicKey);s.catch(()=>{});let a,c=async()=>{try{return await Pi(o,r,await Ii(s))}catch(l){if(!(l instanceof ht)||!i)throw l;return s=Promise.resolve().then(i),Pi(o,r,await Ii(s))}},u=async()=>{let l=a??d(void 0),p=await l;if(Date.now()<p.renewAt)return[p,l];let x=d(l);return[await x,x]},d=l=>{if(a===l){let p=c();a=p,p.catch(()=>{a===p&&(a=void 0)})}return a};return async(l,p)=>{let x=new Request(l,p),v=new URL(x.url);if(v.origin!==e.origin||!v.pathname.startsWith(`${n}/`))throw new Error(`Refusing to send ${v.href} outside the sealed node at ${t.baseUrl}`);let P=[];x.headers.forEach((h,w)=>P.push([w,h]));let b={method:x.method,path:v.pathname.slice(n.length)+v.search,headers:P},k=new Uint8Array(await x.arrayBuffer()),T=async h=>{let{requestId:w,header:S,envelope:U}=await tl(h,b,k),M=await o(`${r}${Ui}`,{method:"POST",headers:{"content-type":ft},body:U,signal:x.signal});if(M.headers.get("content-type")!==ft)throw await Ki(M);return rl(M,h.responseKey,S,w)},[H,z]=await u();try{return await T(H)}catch(h){if(!(h instanceof Me)||h.code!=="unknown_session")throw h;return T(await d(z))}}}async function Ii(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function Pi(t,e,n){try{return await Ti(t,e,n)}catch(r){if(!(r instanceof Me)||r.code!=="busy")throw r;return await new Promise(o=>setTimeout(o,r.retryAfterMs??1e3)),Ti(t,e,n)}}async function Ti(t,e,n){let r=await Ei(n,jc),o=await t(`${e}${Di}`,{method:"POST",headers:{"content-type":ft},body:f(new Uint8Array([Gr]),n,r.message1)});if(o.headers.get("content-type")!==ft)throw await Ki(o);let i=await il(o,Qc);return el(r,i)}async function el(t,e){if(e[0]!==Gr)throw new Error("The handshake reply is malformed");let n;try{n=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:r,split:o}=n;if(r.length!==mt+4)throw new Error("The handshake reply is malformed");let i=r.slice(0,mt),s=new DataView(r.buffer,r.byteOffset).getUint32(mt,!1),[a,c]=await Promise.all([crypto.subtle.importKey("raw",o[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",o[1],"AES-GCM",!1,["decrypt"])]);return o[0].fill(0),o[1].fill(0),{requestKey:a,responseKey:c,nextRequestId:1,renewAt:Date.now()+s*1e3-Yc,header(u){let d=new Uint8Array(Fc);return d[0]=Gr,d.set(i,1),new DataView(d.buffer).setBigUint64(1+mt,BigInt(u),!1),d}}}async function tl(t,e,n){let r=t.nextRequestId;t.nextRequestId+=1;let o=t.header(r),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:Gi(r,0),additionalData:o},t.requestKey,nl(e,n));return{requestId:r,header:o,envelope:f(o,new Uint8Array(i))}}function Gi(t,e){let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setBigUint64(0,BigInt(t),!1),r.setUint32(8,e,!1),n}function nl(t,e){let n=Oi.encode(JSON.stringify(t)),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,n.length,!1),f(r,n,e)}async function rl(t,e,n,r){if(!t.body)throw new Error("The sealed response has no body");let o=ol(t.body.getReader()),i=0,s=async()=>{let d=await o.next();if(!d)return null;let l;try{l=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Gi(r,i),additionalData:n},e,d))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return i+=1,{kind:l[0],data:l.slice(1)}},a=await s();if(!a||a.kind!==Vc)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(Zc.includes(c.status))return await o.cancel(),new Response(null,{status:c.status,headers:c.headers});let u=new ReadableStream({async pull(d){try{let l=await s();l?l.kind===Wc?d.enqueue(l.data):l.kind===Jc?(d.close(),await o.cancel()):d.error(new Error("The sealed response is malformed")):d.error(new Error("The sealed response was cut short"))}catch(l){d.error(l)}},cancel(){return o.cancel()}});return new Response(u,{status:c.status,headers:c.headers})}function ol(t){let e=new Uint8Array,n=async r=>{for(;e.length<r;){let{done:o,value:i}=await t.read();if(o)return!1;e=f(e,i)}return!0};return{async next(){if(!await n(4))return null;let r=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(r>zc)throw await t.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await n(4+r))return null;let o=e.slice(4,4+r);return e=e.slice(4+r),o},cancel:()=>t.cancel()}}async function il(t,e){if(!t.body)return new Uint8Array;let n=t.body.getReader(),r=new Uint8Array;for(;;){let{done:o,value:i}=await n.read();if(o)return r;if(r=f(r,i),r.length>e)throw await n.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function Ki(t){let e,n=`Sealed request refused: HTTP ${t.status}`;try{let i=await t.json();e=i?.error?.code,i?.error?.message&&(n=`Sealed request refused: ${i.error.message}`)}catch{}if(e==="stale_transport_key")return new ht;let r=Number(t.headers.get("retry-after")),o=Number.isFinite(r)&&r>0?Math.min(r,5)*1e3:void 0;return new Me(t.status,e,n,o)}var sl=/^[0-9a-f]{96}$/,al=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function bt(t){let e=Ge(t.allowedMrtd??[],"allowedMrtd"),n=(t.allowedMeasurements??[]).map((a,c)=>{let u=`allowedMeasurements[${c}]`;return al.map(d=>Ge([a?.[d]??""],`${u}.${d}`)[0]).join()}),r=[Ge(t.allowedRtmr0??[],"allowedRtmr0"),Ge(t.allowedRtmr1??[],"allowedRtmr1"),Ge(t.allowedRtmr2??[],"allowedRtmr2"),Ge(t.allowedRtmr3??[],"allowedRtmr3")];if(t.allowedMeasurements!==void 0&&n.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(n.length===0){if(e.length===0)throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");if(r.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 o=t.allowedTcbStatuses??["UpToDate"],i=t.now??Date.now;return Object.assign(async({quoteB64:a,nonce:c,reportDataSuffix:u,collateral:d})=>{let l=ll(a),p=d??await t.fetchCollateral?.(l);if(!p)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let x;try{x=t.dcapVerify(l,p,Math.floor(i()/1e3))}catch(k){throw new Error(`The quote did not verify: ${k?.message??String(k)}`)}if(x.status==="Revoked"||!o.includes(x.status))throw new Error(`The platform's TCB status is ${x.status}, which is not accepted`);let v=cl(x.report);if(v.tdAttributes?.length!==8||(v.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let P=[v.mrTd,v.rtMr0,v.rtMr1,v.rtMr2,v.rtMr3].map(k=>y(k));if(n.length>0&&!n.includes(P.join()))throw new Error(`The measurements (MRTD ${P[0]}, RTMR0-3 ${P.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(P[0]))throw new Error(`MRTD ${P[0]} is not an image this verifier trusts`);if([v.rtMr0,v.rtMr1,v.rtMr2,v.rtMr3].forEach((k,T)=>{let H=r[T];if(H.length>0&&!H.includes(y(k)))throw new Error(`RTMR${T} ${y(k)} is not one this verifier trusts`)}),y(v.reportData)!==`${c}${u}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function Ge(t,e){return t.map(n=>{let r=n.trim().toLowerCase();if(!sl.test(r))throw new Error(`${e} holds ${JSON.stringify(n)}, which is not a 48-byte hex measurement`);return r})}function cl(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 ll(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}var ul=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],yt="locked-read-only";function Kr(t,{profile:e,allowDebugProfile:n=!1}){if(t.length===0)throw new Error("No release given, so no image would be trusted");let r,o=t.map((i,s)=>{let a=i?.tag??`releases[${s}]`;if(i?.role!==void 0&&i.role!=="node")throw new Error(`${a} lists the measurements of a ${i.role}, not of a node image`);let c=i?.profiles?.[e];if(!c){let d=Object.keys(i?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${d})`)}if(e!==yt&&!n)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(yt)}, or pass allowDebugProfile to test`);let u=(c.allowed_tcb_statuses??["uptodate"]).map(d=>dl(d,a));return r=r===void 0?u:r.filter(d=>u.includes(d)),{mrtd:c.mrtd,rtmr0:c.rtmr0,rtmr1:c.rtmr1,rtmr2:c.rtmr2,rtmr3:c.rtmr3}});if(!r||r.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:o,allowedTcbStatuses:r}}function dl(t,e){let n=ul.find(r=>r.toLowerCase()===String(t).toLowerCase());if(!n)throw new Error(`${e} accepts TCB status ${JSON.stringify(t)}, which this verifier does not know`);return n}var $i=[{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"]}],Li=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var pl="1.2.840.10045.2.1",gl={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},ml={"P-256":32,"P-384":48},fl={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function Hi(t,e,n){if(e+2>n)throw new Error("it is truncated");let r=t[e];if((r&31)===31)throw new Error("it uses a tag this parser does not read");let o=t[e+1],i=e+2;if(o&128){let a=o&127;if(a===0||a>4||i+a>n)throw new Error("it has a length this parser does not read");o=0;for(let c=0;c<a;c+=1)o=o*256+t[i+c];i+=a}let s=i+o;if(s>n)throw new Error("it is truncated");return{tag:r,bytes:t,offset:e,start:i,end:s}}function $e(t){let e=Hi(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function G(t){let e=[];for(let n=t.start;n<t.end;){let r=Hi(t.bytes,n,t.end);e.push(r),n=r.end}return e}function N(t,e,n){if(!t||t.tag!==e)throw new Error(`${n} is not where it should be`);return t}function ae(t){return t.bytes.slice(t.start,t.end)}function cn(t){return t.bytes.slice(t.offset,t.end)}function Ke(t){let e=ae(N(t,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let n=[],r=0;for(let s of e)r=r*128+(s&127),s&128||(n.push(r),r=0);let o=n.shift();return[...o<80?[Math.floor(o/40),o%40]:[2,o-80],...n].join(".")}function hl(t){let e=new TextDecoder().decode(ae(t)),n=t.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,r=t.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,o=n??r;if(!o)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let i=Number(o[1]);n&&(i+=i<50?2e3:1900);let[s,a,c,u,d]=o.slice(2).map(Number);return Date.UTC(i,s-1,a,c,u,d)}function $r(t){try{let[e,n,r,...o]=G(N($e(t),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let i=G(N(e,48,"The signed part")),s=i[0]?.tag===160?1:0,[a,c,u,d,l,p,...x]=i.slice(s);N(a,2,"The serial number");let v=Ke(G(N(n,48,"The signature algorithm"))[0]);if(Ke(G(N(c,48,"The signature algorithm"))[0])!==v)throw new Error("it names two different signature algorithms");let b=fl[v];if(!b)throw new Error(`it is signed with ${v}, not ECDSA with SHA-256 or SHA-384`);let[k,T]=G(N(d,48,"The validity")).map(hl);if(T===void 0)throw new Error("its validity is incomplete");let[H,z]=G(N(p,48,"The public key"));N(z,3,"The public key");let[h,w]=G(N(H,48,"The key algorithm"));if(Ke(h)!==pl)throw new Error("its key is not an elliptic-curve key");let S=gl[Ke(w)];if(!S)throw new Error("its key is on a curve other than P-256 or P-384");let U=new Map,M=x.find(ee=>ee.tag===163);if(M){let[ee]=G(M);for(let te of G(N(ee,48,"The extensions"))){let ke=G(N(te,48,"An extension"));if(ke.length===3)N(ke[1],1,"An extension's critical flag");else if(ke.length!==2)throw new Error("it has a malformed extension");let ar=Ke(ke[0]);if(U.has(ar))throw new Error(`it has extension ${ar} twice`);U.set(ar,ae(N(ke[ke.length-1],4,"An extension value")))}}let Q=ae(N(r,3,"The signature"));if(Q[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:cn(e),signatureHash:b,signature:Q.slice(1),issuer:cn(N(u,48,"The issuer")),subject:cn(N(l,48,"The subject")),notBefore:k,notAfter:T,spki:cn(p),curve:S,extensions:U}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function Bi(t){return G(N($e(t),48,"The list")).map(Ke)}function yl(t,e){let n=ml[e],r=G(N($e(t),48,"The signature"));if(r.length!==2)throw new Error("The signature is not an ECDSA signature");let o=new Uint8Array(n*2);return r.forEach((i,s)=>{let a=ae(N(i,2,"The signature"));if(a.length===0||a[0]&128)throw new Error("The signature is not an ECDSA signature");for(;a.length>1&&a[0]===0;)a=a.subarray(1);if(a.length>n)throw new Error("The signature is not an ECDSA signature");o.set(a,s*n+n-a.length)}),o}async function ln(t,e,n,r,o){let i;try{i=yl(r,e)}catch{return!1}let s=await crypto.subtle.importKey("spki",t,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:n},s,i,o)}function V(t,e){let n=t.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(n)||n.length%4!==0)throw new Error(`${e} is not base64`);let r=atob(n),o=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)o[i]=r.charCodeAt(i);return o}function Lr(t,e){let n=[...t.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(n.length!==1||t.replace(n[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return V(n[0][1],e)}var bl="2.5.29.17",wl="2.5.29.37",Al="1.3.6.1.5.5.7.3.3",xl="1.3.6.1.4.1.57264.1.8",vl="1.3.6.1.4.1.57264.1.1",Rl=134,Cl=12,Sl=48,kl=new TextEncoder,Le=t=>new TextDecoder().decode(t);async function un(t,e,n,r){let{base64Signature:o,cert:i,rekorBundle:s}=Tl(e),a=s.Payload;if(r!==void 0&&r.trim()!==o.trim())throw new Error("The detached signature is not the one in the bundle");let c=V(o,"The bundle signature"),u=Lr(Le(V(i,"The bundle certificate")),"The bundle certificate"),d=$r(u),l=Li.find(T=>T.logId===a.logID.toLowerCase());if(!l)throw new Error(`The bundle names Rekor log ${a.logID}, which the Sigstore trust root does not know`);let p=kl.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await ln(V(l.publicKey,"The Rekor key"),"P-256","SHA-256",V(s.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 v=a.integratedTime*1e3;if(!Fi(v,l.validFor))throw new Error(`Rekor log ${l.baseUrl} was not in use at ${wt(v)}, when the entry says it was logged`);let P=Dl(a.body),b=y(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(P.hash!==b)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!Hr(V(P.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let k=Lr(Le(V(P.publicKey,"The logged certificate")),"The logged certificate");if(!Hr(k,u))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await ln(d.spki,"P-256","SHA-256",c,t))throw new Error("The signature over the file does not verify with the bundle's certificate");return await El(d,v),Pl(d,n),{integratedTime:a.integratedTime}}async function El(t,e){if(!ji(t,e))throw new Error(`The signing certificate was valid ${wt(t.notBefore)} to ${wt(t.notAfter)}, not at ${wt(e)} when Rekor logged it`);let n=[];for(let r of $i){let o=r.certChain.map(s=>$r(V(s,"A Fulcio certificate")));if(!await qi(t,o[0]))continue;let i=await Il(o,r.validFor,e);if(!i)return;n.push(`${r.uri} (valid from ${r.validFor.start}): ${i}`)}throw new Error(n.length>0?`The signing certificate's CA is not trusted at ${wt(e)}: ${n.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function Il(t,e,n){if(!Fi(n,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of t.entries()){if(!ji(o,n))return`its certificate ${r} was not valid then`;let i=t[r+1]??o;if(!await qi(o,i))return`its certificate ${r} is not signed by the next`}}async function qi(t,e){return Hr(t.issuer,e.subject)?ln(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function Pl(t,e){let n=t.extensions.get(bl);if(!n)throw new Error("The signing certificate names no identity");let r=G(N($e(n),Sl,"The subject alternative name")),o=r.filter(u=>u.tag===Rl).map(u=>Le(ae(u)));if(o.length!==1||r.length!==1||o[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(o.length===1?o[0]:o)}, not by ${e.identity}`);let i=t.extensions.get(xl),s=t.extensions.get(vl),a=i?Le(ae(N($e(i),Cl,"The OIDC issuer"))):s?Le(s):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(wl);if(!c||!Bi(c).includes(Al))throw new Error("The signing certificate is not for code signing")}function Tl(t){let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let n=e,r=n?.rekorBundle?.Payload;if(!(typeof n?.base64Signature=="string"&&typeof n.cert=="string"&&typeof n.rekorBundle?.SignedEntryTimestamp=="string"&&typeof r?.body=="string"&&typeof r.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(r.logID)&&Number.isSafeInteger(r.integratedTime)&&r.integratedTime>=0&&Number.isSafeInteger(r.logIndex)&&r.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return n}function Dl(t){let e;try{e=JSON.parse(Le(V(t,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let n=e?.spec?.data?.hash,r=e?.spec?.signature;if(e?.kind!=="hashedrekord"||n?.algorithm!=="sha256"||typeof n.value!="string"||typeof r?.content!="string"||typeof r.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:n.value.toLowerCase(),signature:r.content,publicKey:r.publicKey.content}}function ji(t,e){return t.notBefore<=e&&e<=t.notAfter}function Fi(t,e){return Date.parse(e.start)<=t&&(e.end===void 0||t<=Date.parse(e.end))}function wt(t){return new Date(t).toISOString()}function Hr(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Br=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"}),Ul=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],dn="https://cloud.calimero.network";async function Wi(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await un(r,e,{identity:n.identity??Br.identity,issuer:n.issuer??Br.issuer},n.signature);let o;try{o=JSON.parse(new TextDecoder().decode(r))}catch{throw new Error("The signed release is not JSON")}if(o?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(o?.role)} release, not a node one`);let i=Object.values(o.profiles??{}),s=a=>Ul.every(c=>/^[0-9a-f]{96}$/i.test(String(a?.[c])));if(typeof o.tag!="string"||i.length===0||!i.every(s))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(n.expectedVersion!==void 0&&o.tag!==n.expectedVersion)throw new Error(`The signed release is ${o.tag}, not ${n.expectedVersion}`);return o}async function pn(t,e={}){let n=await(e.fetch??fetch)(t,{headers:{accept:"application/json"}});if(!n.ok)throw new Error(`Fetching the node release from ${t} failed: HTTP ${n.status}`);let r;try{r=(await n.json())?.data}catch{throw new Error(`${t} did not answer with JSON`)}if(typeof r?.version!="string"||typeof r.publishedMrtds!="string"||typeof r.bundle!="string")throw new Error(`${t} did not answer with a signed node release`);return{version:r.version,publishedMrtds:r.publishedMrtds,bundle:r.bundle}}function Ji(t){let e=/^merotee-.+-(\d+)-(\d+)-(\d+)$/.exec(t);if(!e)throw new Error(`${JSON.stringify(t)} is not the image of a mero-tee node release`);return`${Number(e[1])}.${Number(e[2])}.${Number(e[3])}`}async function gn(t,e={}){let n=await Qi(t,e.fetch??fetch);if(n===void 0)throw new Error(`${zi(t)} was refused unsealed: the node requires sealing and is too old to name its release before a session exists. Name the release it runs yourself (createSignedReleaseSealedFetch's \`releaseVersion\`), or upgrade the node`);return n}function zi(t){return`${t.replace(/\/+$/,"")}/admin-api/tee/info`}async function Qi(t,e){let n=zi(t),r=await e(n,{headers:{accept:"application/json"}});if(r.status===403&&await r.json().then(s=>s?.error?.code).catch(()=>{})==="sealed_required")return;if(!r.ok)throw new Error(`Fetching ${n} failed: HTTP ${r.status}`);let o;try{o=(await r.json())?.data?.osImage}catch{throw new Error(`${n} did not answer with JSON`)}if(typeof o!="string")throw new Error(`${n} did not name the node's image`);return Ji(o)}function mn(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${At(e,"version")}`}async function Yi(t){let e=At(t.minReleaseVersion,"minReleaseVersion"),n=At(t.release?.version,"The release version"),r=await Wi(t.release.publishedMrtds,t.release.bundle,{expectedVersion:n,identity:t.identity,issuer:t.issuer});if(Nl(n,e)<0)throw new Error(`Release ${n} is older than the minimum trusted, ${e}`);return Kr([r],{profile:t.profile,allowDebugProfile:t.allowDebugProfile})}function fn(t){return At(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async n=>{let r=await Yi({release:await t.release(),profile:t.profile,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer});return bt({dcapVerify:t.dcapVerify,fetchCollateral:t.fetchCollateral,now:t.now,...r})(n)},{includeCollateral:!0})}function Ol(t){let{baseUrl:e,releaseSource:n,releaseVersion:r,applicationId:o,applicationHash:i,fetch:s,...a}=t;r!==void 0&&At(r,"releaseVersion");let c=s??((d,l)=>fetch(d,l));return fe({baseUrl:e,verify:fn({...a,release:async()=>{let d=r===void 0?await gn(e,{fetch:c}):await Qi(e,c)??r;return typeof n=="function"?n({baseUrl:e,version:d,fetch:c}):pn(mn(n??dn,d),{fetch:c})}}),applicationId:o,applicationHash:i,fetch:c})}var Xi=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function At(t,e){let n=typeof t=="string"?Xi.exec(t):null,r=n?.[4];if(!n||r!==void 0&&r.split(".").some(o=>o===""))throw new Error(`${e} is ${JSON.stringify(t)}, not a release version like 2.3.87`);return t}function Nl(t,e){let[n,r]=Vi(t),[o,i]=Vi(e);for(let c=0;c<3;c+=1)if(n[c]!==o[c])return n[c]<o[c]?-1:1;if(r===void 0||i===void 0)return r===i?0:r===void 0?1:-1;let s=r.split("."),a=i.split(".");for(let c=0;c<Math.max(s.length,a.length);c+=1){let[u,d]=[s[c],a[c]];if(u===void 0||d===void 0)return u===void 0?-1:1;let[l,p]=[/^\d+$/.test(u),/^\d+$/.test(d)],x=l&&p?Math.sign(Number(u)-Number(d)):l!==p?l?-1:1:u<d?-1:u>d?1:0;if(x!==0)return x}return 0}function Vi(t){let e=Xi.exec(t);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var _l=new TextEncoder().encode("calimero.warrant.v2"),Ml=new TextEncoder().encode("calimero.warrant.intent.v1"),Zi=64,es=256;async function qr(t,e){let n=new TextEncoder().encode(JSON.stringify(e));return E(Ml,[new TextEncoder().encode(t),n])}async function hn(t){let e=m(t.context,"context",32),n=m(t.authorAccount,"authorAccount",32),r=m(t.executor,"executor",32),o=m(t.executorKey,"executorKey",32),i=m(t.releaseBytecodeId,"releaseBytecodeId",32),s=jr(t.releaseVersion??""),a=ce(t.accountHeads,"accountHeads"),c=ce(t.governanceFloor,"governanceFloor"),u=await I(t.deviceSecret,t.signer,"deviceSecret"),d=m(u.publicKey,"signer.publicKey",32),l=new TextEncoder().encode(t.method),p=await qr(t.method,t.argsJson),x=C(t.nonce),v=C(t.notAfter),P=await E(_l,[e,n,d,r,o,i,s,l,p,C(a.length),...a,C(c.length),...c,x,v]),b=xt(await u.sign(P));return y(f(e,n,d,r,o,i,R(s.length),s,R(l.length),l,p,R(a.length),...a,R(c.length),...c,x,v,b))}function xt(t){if(!(t instanceof Uint8Array)||t.length!==64){let e=t instanceof Uint8Array?`${t.length} bytes`:typeof t;throw new Error(`signer returned ${e}, expected a 64-byte Ed25519 signature`)}return t}function jr(t){let e=new TextEncoder().encode(t);return Gl(e.length),e}function Gl(t){if(t>es)throw new Error(`releaseVersion is ${t} bytes, over the ${es} a node accepts`)}function ce(t,e){let n=t??[];if(n.length>Zi)throw new Error(`${e} cites ${n.length} heads, over the ${Zi} a node accepts`);return n.map((r,o)=>m(r,`${e}[${o}]`,32))}var Kl=new TextEncoder().encode("calimero.context-creation-warrant.v1"),$l=new TextEncoder().encode("calimero.context-creation.init.v1"),yn=256;async function Fr(t){let e=new TextEncoder().encode(JSON.stringify(t));return E($l,[e])}async function Ll(t){return E(Kl,[t.group,t.seed,t.authorAccount,t.deviceKey,t.executor,t.executorKey,t.applicationId,new Uint8Array([t.serviceName===null?0:1]),t.serviceName??new Uint8Array(0),new Uint8Array([t.name===null?0:1]),t.name??new Uint8Array(0),t.initHash,C(t.accountHeads.length),...t.accountHeads,C(t.governanceFloor.length),...t.governanceFloor,C(t.nonce),C(t.notAfter)])}async function bn(t){let e=m(t.group,"group",32),n=t.seed===void 0?crypto.getRandomValues(new Uint8Array(32)):m(t.seed,"seed",32),r=m(t.authorAccount,"authorAccount",32),o=m(t.executor,"executor",32),i=m(t.executorKey,"executorKey",32),s=m(t.applicationId,"applicationId",32),a=ts(t.serviceName,"serviceName"),c=ts(t.name,"name"),u=ce(t.accountHeads,"accountHeads"),d=ce(t.governanceFloor,"governanceFloor"),l=await I(t.deviceSecret,t.signer,"deviceSecret"),p=m(l.publicKey,"signer.publicKey",32),x=await Fr(t.initArgs),v=await Ll({group:e,seed:n,authorAccount:r,deviceKey:p,executor:o,executorKey:i,applicationId:s,serviceName:a,name:c,initHash:x,accountHeads:u,governanceFloor:d,nonce:t.nonce,notAfter:t.notAfter}),P=xt(await l.sign(v));return{warrant:y(f(e,n,r,p,o,i,s,ns(a),ns(c),x,R(u.length),...u,R(d.length),...d,C(t.nonce),C(t.notAfter),P)),seed:y(n)}}function rs(t){let e=t.trim();if(!/^[0-9a-fA-F]*$/.test(e)||e.length%2!==0)throw new Error("creation warrant must be an even number of hex characters");let n=new Uint8Array(e.length/2);for(let l=0;l<n.length;l+=1)n[l]=Number.parseInt(e.slice(l*2,l*2+2),16);let r=new DataView(n.buffer),o=0,i=(l,p)=>{if(o+l>n.length)throw new Error(`creation warrant ends inside ${p} (${n.length} bytes)`);let x=n.subarray(o,o+l);return o+=l,x},s=l=>r.getUint32(i(4,l).byteOffset,!0),a=l=>r.getBigUint64(i(8,l).byteOffset,!0),c=l=>{let p=i(1,l)[0];if(p===0)return null;if(p!==1)throw new Error(`${l} has option tag ${p}, expected 0 or 1`);let x=s(l);if(x>yn)throw new Error(`${l} is ${x} bytes, over the ${yn} a node accepts`);return new TextDecoder("utf-8",{fatal:!0}).decode(i(x,l))},u=l=>{let p=s(l);if(p>64)throw new Error(`${l} cites ${p} heads, over the 64 a node accepts`);return Array.from({length:p},()=>y(i(32,l)))},d={group:y(i(32,"group")),seed:y(i(32,"seed")),authorAccount:y(i(32,"authorAccount")),deviceKey:y(i(32,"deviceKey")),executor:y(i(32,"executor")),executorKey:y(i(32,"executorKey")),applicationId:y(i(32,"applicationId")),serviceName:c("serviceName"),name:c("name"),initHash:y(i(32,"initHash")),accountHeads:u("accountHeads"),governanceFloor:u("governanceFloor"),nonce:a("nonce"),notAfter:a("notAfter"),signature:y(i(64,"signature"))};if(o!==n.length)throw new Error(`creation warrant is ${n.length} bytes but its fields account for ${o}`);return d}function ts(t,e){if(t===void 0)return null;let n=new TextEncoder().encode(t);if(n.length>yn)throw new Error(`${e} is ${n.length} UTF-8 bytes, over the ${yn} a node accepts`);return n}function ns(t){return t===null?new Uint8Array([0]):f(new Uint8Array([1]),R(t.length),t)}var Hl=new TextEncoder().encode("calimero.governance-warrant.v1"),Bl=new TextEncoder().encode("calimero.governance-warrant.op.v1"),ql={group:0,root:1};async function Vr(t){return E(Bl,[new Uint8Array([Wr(t.kind)]),t.bytes])}async function jl(t){return E(Hl,[t.scope,new Uint8Array([Wr(t.kind)]),t.authorAccount,t.deviceKey,t.executor,t.executorKey,t.opHash,C(t.accountHeads.length),...t.accountHeads,C(t.governanceFloor.length),...t.governanceFloor,C(t.nonce),C(t.notAfter)])}async function vt(t){let e=m(t.scope,"scope",32),n=m(t.authorAccount,"authorAccount",32),r=m(t.executor,"executor",32),o=m(t.executorKey,"executorKey",32),i=ce(t.accountHeads,"accountHeads"),s=ce(t.governanceFloor,"governanceFloor"),a=Wr(t.op.kind),c=await I(t.deviceSecret,t.signer,"deviceSecret"),u=m(c.publicKey,"signer.publicKey",32),d=await Vr(t.op),l=await jl({scope:e,kind:t.op.kind,authorAccount:n,deviceKey:u,executor:r,executorKey:o,opHash:d,accountHeads:i,governanceFloor:s,nonce:t.nonce,notAfter:t.notAfter}),p=xt(await c.sign(l));return y(f(e,new Uint8Array([a]),n,u,r,o,d,R(i.length),...i,R(s.length),...s,C(t.nonce),C(t.notAfter),p))}function os(t){let e=t.trim();if(!/^[0-9a-fA-F]*$/.test(e)||e.length%2!==0)throw new Error("governance warrant must be an even number of hex characters");let n=new Uint8Array(e.length/2);for(let l=0;l<n.length;l+=1)n[l]=Number.parseInt(e.slice(l*2,l*2+2),16);let r=new DataView(n.buffer),o=0,i=(l,p)=>{if(o+l>n.length)throw new Error(`governance warrant ends inside ${p} (${n.length} bytes)`);let x=n.subarray(o,o+l);return o+=l,x},s=l=>r.getUint32(i(4,l).byteOffset,!0),a=l=>r.getBigUint64(i(8,l).byteOffset,!0),c=l=>{let p=s(l);if(p>64)throw new Error(`${l} cites ${p} heads, over the 64 a node accepts`);return Array.from({length:p},()=>y(i(32,l)))},u=()=>{let l=i(1,"kind")[0];if(l===0)return"group";if(l===1)return"root";throw new Error(`governance warrant has kind ${l}, expected 0 (group) or 1 (root)`)},d={scope:y(i(32,"scope")),kind:u(),authorAccount:y(i(32,"authorAccount")),deviceKey:y(i(32,"deviceKey")),executor:y(i(32,"executor")),executorKey:y(i(32,"executorKey")),opHash:y(i(32,"opHash")),accountHeads:c("accountHeads"),governanceFloor:c("governanceFloor"),nonce:a("nonce"),notAfter:a("notAfter"),signature:y(i(64,"signature"))};if(o!==n.length)throw new Error(`governance warrant is ${n.length} bytes but its fields account for ${o}`);return d}function Wr(t){let e=ql[t];if(e===void 0)throw new Error(`op kind must be 'group' or 'root', got ${String(t)}`);return e}var Fl={Admin:0,Member:1,ReadOnly:2},K={MemberAdded:1,MemberRemoved:2,MemberLeft:3,MemberRoleSet:4,MemberCapabilitySet:5,DefaultCapabilitiesSet:6,TargetApplicationSet:7,ContextDetached:9,SubgroupVisibilitySet:10,GroupMetadataSet:11,MemberMetadataSet:12,ContextMetadataSet:13,ContextCapabilityGranted:16,ContextCapabilityRevoked:17},Rt={GroupCreated:0,GroupReparented:1,GroupDeleted:2,MemberJoinedOpen:7,NamespaceCreatedV2:9},Vl=new TextEncoder().encode("calimero.namespace.id.v1"),zr=new Uint8Array(32),wn=R(0);function ss(t){let e=Fl[t];if(e===void 0)throw new Error(`role must be Admin, Member or ReadOnly, got ${String(t)}`);return new Uint8Array([e])}function D(t){return new Uint8Array([t])}function He(t,e){return{kind:"group",bytes:f(D(K.MemberAdded),m(t,"member",32),ss(e))}}function An(t){return{kind:"group",bytes:f(D(K.MemberRemoved),m(t,"member",32),zr,wn)}}function Ct(t){return{kind:"group",bytes:f(D(K.MemberLeft),m(t,"member",32),zr,wn)}}function xn(t,e){return{kind:"group",bytes:f(D(K.MemberRoleSet),m(t,"member",32),ss(e))}}var Wl=new TextEncoder().encode("calimero.subgroup.id.v1");async function Qr(t,e,n,r){return y(await E(Wl,[m(t,"admin",32),m(e,"parentId",32),new Uint8Array([n?1:0]),m(r,"salt",32)]))}function is(t,e){if(t.length===0)throw new Error(`${e} must not be empty`);let n=new TextEncoder().encode(t);return f(R(n.length),n)}function vn(t){return{kind:"group",bytes:f(D(K.TargetApplicationSet),zr,m(t.applicationId,"applicationId",32),is(t.package,"package"),is(t.version,"version"))}}function Be(t){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`capabilities must be a u32 bit mask, got ${String(t)}`);if(ge(t,_.CAN_AUTHOR_ON_BEHALF))throw new Error("capabilities may not include CAN_AUTHOR_ON_BEHALF (512): a relay never carries a change to it");return{kind:"group",bytes:f(D(K.DefaultCapabilitiesSet),R(t))}}function Yr(t){return{kind:"root",bytes:f(D(Rt.GroupCreated),m(t.groupId,"groupId",32),m(t.parentId,"parentId",32),D(t.restricted?1:0),m(t.admin,"admin",32),m(t.salt,"salt",32))}}async function qe(t){let e=t.salt??y(crypto.getRandomValues(new Uint8Array(32))),n=await Qr(t.admin,t.parentId,t.restricted,e);return{groupId:n,salt:e,op:Yr({...t,groupId:n,salt:e})}}function Rn(t,e){return{kind:"root",bytes:f(D(Rt.GroupReparented),m(t,"childGroupId",32),m(e,"newParentId",32))}}function Cn(t){return{kind:"root",bytes:f(D(Rt.GroupDeleted),m(t,"rootGroupId",32),wn,wn)}}async function Sn(t,e){return y(await E(Vl,[m(t,"founder",32),m(e,"salt",32)]))}function kn(t){let e=j(t.credential,"credential");if(e.length===0)throw new Error("credential must be the founder's AccountProof<DeviceCert>, got nothing");return{kind:"root",bytes:f(D(Rt.NamespaceCreatedV2),m(t.founder,"founder",32),e,m(t.salt,"salt",32))}}function Jr(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}function Xr(t){return t===void 0?D(0):f(D(1),Jr(t))}function Zr(t={}){let e=new TextEncoder,n=Object.entries(t).map(([r,o])=>[e.encode(r),o,r]).sort(([r],[o])=>{for(let i=0;i<Math.min(r.length,o.length);i++)if(r[i]!==o[i])return r[i]-o[i];return r.length-o.length});return f(R(n.length),...n.flatMap(([,r,o])=>[Jr(o),Jr(r)]))}function Jl(t,e){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`${e} must be a u32 bit mask, got ${String(t)}`);if(ge(t,_.CAN_AUTHOR_ON_BEHALF))throw new Error(`${e} may not include CAN_AUTHOR_ON_BEHALF (512): a relay never carries a change to it`);return t}function En(t,e){return{kind:"group",bytes:f(D(K.MemberCapabilitySet),m(t,"member",32),R(Jl(e,"capabilities")))}}function In(t){return{kind:"group",bytes:f(D(K.ContextDetached),m(t,"contextId",32))}}function Pn(t){if(t!=="open"&&t!=="restricted")throw new Error(`mode must be open or restricted, got ${String(t)}`);return{kind:"group",bytes:f(D(K.SubgroupVisibilitySet),D(t==="open"?0:1))}}function je(t={}){return{kind:"group",bytes:f(D(K.GroupMetadataSet),Xr(t.name),Zr(t.data))}}function Tn(t,e={}){return{kind:"group",bytes:f(D(K.MemberMetadataSet),m(t,"member",32),Xr(e.name),Zr(e.data))}}function Dn(t,e={}){return{kind:"group",bytes:f(D(K.ContextMetadataSet),m(t,"contextId",32),Xr(e.name),Zr(e.data))}}function as(t){if(!Number.isInteger(t)||t<1||t>255)throw new Error(`capability must be a non-zero u8, got ${String(t)}`);return D(t)}function cs(t,e,n){return{kind:"group",bytes:f(D(K.ContextCapabilityGranted),m(t,"contextId",32),m(e,"member",32),as(n))}}function ls(t,e,n){return{kind:"group",bytes:f(D(K.ContextCapabilityRevoked),m(t,"contextId",32),m(e,"member",32),as(n))}}function Un(t){return{kind:"root",bytes:f(D(Rt.MemberJoinedOpen),m(t.member,"member",32),m(t.groupId,"groupId",32),j(t.credential,"credential"))}}var On=300,he=class extends Error{constructor(n,r,o){super(`relay refused the intent (HTTP ${o}): ${n}`);this.reason=n;this.retryable=r;this.status=o;this.name="IntentRefusedError"}},zl=t=>new Promise(e=>setTimeout(e,t));function Ql(t){let e=t?.get?.("Retry-After");if(!e)return null;let n=Number.parseInt(e,10);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);return Number.isFinite(r)?Math.max(0,r-Date.now()):null}var W=class{constructor(e){this.config=e,this.baseUrl=e.relayUrl.replace(/\/+$/,"");let n=e.fetch;this.fetchImpl=n?(r,o)=>n(r,o):(r,o)=>globalThis.fetch(r,o),this.timeoutMs=e.timeoutMs??1e4,this.rateLimitRetries=e.rateLimitRetries??3}get relayUrl(){return this.baseUrl}get authorAccount(){return this.config.authorAccount}get authorProof(){return this.config.authorProof}async authorSigner(){return I(this.config.deviceSecret,this.config.signer,"deviceSecret")}async describe(e){return(await this.json("GET",`/admin-api/contexts/${g(e)}/intents`)).data}async execute(e,n,r={}){let o=await this.describe(e),i=this.checkedExecutor(o),s=y(m(o.releaseBytecodeId??"","the relay's releaseBytecodeId",32)),a=o.releaseVersion??"";jr(a);let c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??On,l=await hn({context:e,authorAccount:this.config.authorAccount,executor:i.executorAccount,executorKey:i.executorKey,releaseBytecodeId:s,releaseVersion:a,method:n,argsJson:r,nonce:u,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(d),signer:c}),p=await this.json("POST",`/admin-api/contexts/${g(e)}/intents`,{method:n,argsJson:r,warrant:l,authorProof:this.config.authorProof});return{rootHash:p.data.rootHash,returns:p.data.returns??null}}async presenceIntent(e,n){await this.jsonOnce("POST",`/admin-api/contexts/${g(e)}/presence-intents`,n)}async describeCreation(e,n={}){let r=n.author?`?author=${encodeURIComponent(n.author)}`:"";return(await this.json("GET",`/admin-api/groups/${g(e)}/context-intents${r}`)).data}async createContext(e){let n=await this.describeCreation(e.groupId,{author:this.config.authorAccount});if(!n.canCreateOnBehalf)throw new he(`the relay (${n.executorAccount}) has no standing to act for members of group ${n.groupId}; an admin must admit it as a relay or grant it CAN_AUTHOR_ON_BEHALF (checked before signing \u2014 no nonce was spent)`,!1,403);if(n.authorMayCreate===!1)throw new he(`the author (${this.config.authorAccount}) may not create contexts in group ${n.groupId}; it needs CAN_CREATE_CONTEXT or admin (checked before signing \u2014 no nonce was spent)`,!1,403);let r=this.checkedExecutor(n),o=e.initArgs??{},i=await this.authorSigner(),s=await this.config.nonces.next(),a=this.config.ttlSeconds??On,{warrant:c}=await bn({group:e.groupId,seed:e.seed,authorAccount:this.config.authorAccount,executor:r.executorAccount,executorKey:r.executorKey,applicationId:e.applicationId,serviceName:e.serviceName,name:e.name,initArgs:o,nonce:s,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(a),signer:i}),u=await this.json("POST",`/admin-api/groups/${g(e.groupId)}/context-intents`,{warrant:c,authorProof:this.config.authorProof,initArgs:o});return{contextId:u.data.contextId,groupId:u.data.groupId,memberPublicKey:u.data.memberPublicKey}}async describeGovernance(e){return(await this.json("GET",`/admin-api/groups/${g(e)}/governance-intents`)).data}async govern(e){let n=await this.describeGovernance(e.groupId);if(!n.canActOnBehalf)throw new he(`the relay (${n.executorAccount}) has no standing to act for members of group ${n.groupId}; an admin must admit it as a relay or grant it CAN_AUTHOR_ON_BEHALF (checked before signing, no nonce was spent)`,!1,403);let r=this.checkedExecutor(n),o=await this.authorSigner(),i=await this.config.nonces.next(),s=this.config.ttlSeconds??On,a=await vt({scope:e.groupId,op:e.op,authorAccount:this.config.authorAccount,executor:r.executorAccount,executorKey:r.executorKey,nonce:i,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(s),signer:o});return{groupId:(await this.postGovernance(e.groupId,e.op,a)).groupId}}async foundNamespace(e){if(!e?.executor)throw new Error("foundNamespace needs the relay's account and signing key: pass executor (checked before signing, no nonce was spent)");let n=this.checkedExecutor(e.executor),r=e.salt?y(m(e.salt,"salt",32)):y(crypto.getRandomValues(new Uint8Array(32))),o=await Sn(this.config.authorAccount,r),i=kn({founder:this.config.authorAccount,credential:this.config.authorProof,salt:r}),s=e.defaultCapabilities===void 0?void 0:Be(e.defaultCapabilities),a=e.application?vn(e.application):void 0,c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??On,l=await vt({scope:o,op:i,authorAccount:this.config.authorAccount,executor:n.executorAccount,executorKey:n.executorKey,nonce:u,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(d),signer:c}),p=await this.postGovernance(o,i,l),x={namespaceId:p.groupId,salt:r,teeEnabled:p.teeEnabled??!1,...p.teeError?{teeError:p.teeError}:{}},v=x,P=b=>b instanceof Error?b.message:String(b);if(a)try{await this.govern({groupId:x.namespaceId,op:a}),v={...v,applicationSet:!0}}catch(b){v={...v,applicationSet:!1,applicationError:P(b)}}if(s)try{await this.govern({groupId:x.namespaceId,op:s}),v={...v,defaultCapabilitiesSet:!0}}catch(b){v={...v,defaultCapabilitiesSet:!1,defaultCapabilitiesError:P(b)}}return v}async postGovernance(e,n,r){return(await this.json("POST",`/admin-api/groups/${g(e)}/governance-intents`,{warrant:r,authorProof:this.config.authorProof,op:y(n.bytes)})).data}checkedExecutor(e){let n={executorAccount:y(m(e.executorAccount??"","the relay's executorAccount",32)),executorKey:y(m(e.executorKey??"","the relay's executorKey",32))},r=this.config.executorAccount;if(r&&r.toLowerCase()!==n.executorAccount)throw new Error(`configured executorAccount ${r} is not the relay's account ${n.executorAccount}; a warrant naming it would be unspendable`);return n}async json(e,n,r){let o=250;for(let i=0;;i+=1)try{return await this.jsonOnce(e,n,r)}catch(s){if(!(s instanceof O&&s.status===429)||i>=this.rateLimitRetries)throw s;let c=Ql(s.headers);await zl(c??o),o*=2}}async jsonOnce(e,n,r){let o={Accept:"application/json"};r!==void 0&&(o["Content-Type"]="application/json");let i=new AbortController,s=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r===void 0?void 0:JSON.stringify(r),signal:i.signal})}catch(c){throw new O(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(!a.ok){let c=await a.text().catch(()=>"");if(a.status===400||a.status===403){let u=Yl(c);throw new he(u,/nonce/i.test(u),a.status)}throw new O(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(a.status!==204)return await a.json()}};function Yl(t){if(!t)return"no reason given";try{let e=JSON.parse(t);for(let n of[e.error,e.message])if(typeof n=="string"&&n)return n}catch{}return t}var ye=class{constructor(e,n=null){this.relay=e;this.observer=n;this.kind="relay"}get canSubscribe(){return this.observer!==null}get events(){return this.observer}get client(){return this.relay}async execute(e){let{returns:n}=await this.executeWithMetadata(e);return n}async executeWithMetadata(e){let n=await this.relay.execute(e.contextId,e.method,e.argsJson??{});return{returns:n.returns,transport:"relay",rootHash:n.rootHash}}async migrateMyEntries(e){return this.execute({contextId:e,method:"migrate_my_entries"})}async countMyPending(e){return this.execute({contextId:e,method:"count_my_pending"})}};var Xl=new TextEncoder().encode("calimero.auth.login.v1"),us={webOrigin:0,codeSigningId:1,cli:2};function ds(t){let e=new TextEncoder;switch(t.kind){case"webOrigin":return e.encode(t.origin);case"codeSigningId":return e.encode(t.id);case"cli":return new Uint8Array(0)}}function Zl(t){return f(Uint8Array.from([us[t.kind]]),ds(t))}function eu(t){let e=Uint8Array.from([us[t.kind]]);if(t.kind==="cli")return e;let n=ds(t);return f(e,R(n.length),n)}async function Nn(t){let e=m(t.node,"node",32),n=m(t.challenge,"challenge",32),r=m(t.sessionKey,"sessionKey",32),o=await I(t.deviceSecret,t.signer,"deviceSecret"),i=m(o.publicKey,"signer.publicKey",32),s=C(t.issuedAt),a=C(t.expiresAt),c=await E(Xl,[e,Zl(t.audience),n,r,i,s,a]),u=await o.sign(c);return y(f(e,eu(t.audience),n,r,i,s,a,u))}var tu=300;async function eo(){let t=y(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:y(await re(t)),secret:t}}async function Fe(t){let e=t.nodeUrl.replace(/\/+$/,""),n=t.timeoutMs??1e4,r=async(p,x)=>{let v=new AbortController,P=setTimeout(()=>v.abort(),n),b;try{let T={...x,signal:v.signal};b=t.fetch?await t.fetch(`${e}${p}`,T):await globalThis.fetch(`${e}${p}`,T)}catch(T){throw new O(0,T instanceof Error?T.name:"NetworkError",`${e}${p}`,new Headers,T instanceof Error?T.message:String(T))}finally{clearTimeout(P)}let k=await b.text().catch(()=>"");if(!b.ok)throw new O(b.status,b.statusText,`${e}${p}`,b.headers,k);return k?JSON.parse(k):{}},o=await r("/auth/challenge",{method:"GET",headers:{Accept:"application/json"}}),i=o.challenge??o.data?.challenge;if(!i)throw new Error("the node issued no challenge");let s=await eo(),a=Math.floor(Date.now()/1e3),c=await Nn({node:t.node,audience:t.audience,challenge:i,sessionKey:s.publicKey,issuedAt:a,expiresAt:a+(t.ttlSeconds??tu),signer:await I(t.deviceSecret,t.signer,"deviceSecret")}),u=await r("/auth/token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({auth_method:"account_proof",public_key:s.publicKey,client_name:t.clientName??e,timestamp:a,provider_data:{challenge:i,login_statement:c,account_proof:t.accountProof}})}),d=u.access_token??u.data?.access_token,l=u.refresh_token??u.data?.refresh_token;if(!d)throw new Error("the node minted no session");return{accessToken:d,refreshToken:l??"",sessionKey:s.publicKey,sessionSecret:s.secret}}var nu=3e4;function We(){let t=globalThis.location?.origin;return t?{kind:"webOrigin",origin:t}:{kind:"cli"}}function ru(t){try{let e=t.split(".");if(e.length!==3)return null;let n=e[1].replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4;)n+="=";let r=JSON.parse(atob(n));return typeof r.exp=="number"?r.exp*1e3:null}catch{return null}}var Ve=class{constructor(e){this.session=null;this.sessionExpiresAt=null;this.pending=null;this.sseClient=null;this.wsClient=null;this.config=e}get nodeKey(){return this.config.nodeKey}async accessToken(){let e=Date.now();return this.session&&this.sessionExpiresAt!==null&&this.sessionExpiresAt-nu>e?this.session.accessToken:(this.pending||(this.pending=this.loginNow().finally(()=>{this.pending=null})),(await this.pending).accessToken)}async loginNow(){let e=await Fe({nodeUrl:this.config.nodeUrl,node:this.config.nodeKey,signer:await this.config.signer(),accountProof:this.config.accountProof,audience:this.config.audience,clientName:this.config.clientName,ttlSeconds:this.config.ttlSeconds,fetch:this.config.fetch,timeoutMs:this.config.timeoutMs});return this.session=e,this.sessionExpiresAt=ru(e.accessToken),e}get events(){return this.sseClient||(this.sseClient=new B({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.sseClient}get ws(){return this.wsClient||(this.wsClient=new ie({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.wsClient}close(){this.sseClient?.close(),this.wsClient?.close()}};var ps=new TextEncoder().encode("calimero/presence/1");async function gs(t){let e=t===null?new Uint8Array([0]):f(new Uint8Array([1]),R(t.length),t);return new Uint8Array(await crypto.subtle.digest("SHA-256",e))}async function to(t){return f(ps,m(t.contextId,"contextId",32),m(t.author,"author",32),C(t.seq),C(t.sentAtMs),await gs(t.state))}var ou=2500,St=class{constructor(e){this.timers=new Map;this.lastSeq=new Map;this.refused=new Set;this.generation=new Map;this.relay=e.relay,this.events=e.events,this.heartbeatMs=e.heartbeatMs??ou,this.now=e.now??Date.now}async set(e,n,r=se()){let o=this.bump(e);this.refused.delete(e);let i=n===null?null:new Uint8Array(r.encode(n));await this.send(e,i),!(i===null||this.refused.has(e))&&this.generation.get(e)===o&&this.timers.set(e,setInterval(()=>{this.send(e,i).catch(()=>{})},this.heartbeatMs))}subscribe(e,n,r=se()){return Xt(this.events(),e,n,r)}close(){for(let e of new Set([...this.timers.keys(),...this.generation.keys()]))this.bump(e)}bump(e){this.stop(e);let n=(this.generation.get(e)??0)+1;return this.generation.set(e,n),n}stop(e){let n=this.timers.get(e);n!==void 0&&clearInterval(n),this.timers.delete(e)}nextSeq(e){let n=Math.max(this.now(),(this.lastSeq.get(e)??0)+1);return this.lastSeq.set(e,n),n}async send(e,n){if(this.refused.has(e))return;let r=await this.relay.authorSigner(),o=this.nextSeq(e),i=this.now(),s=await to({contextId:e,author:r.publicKey,seq:BigInt(o),sentAtMs:BigInt(i),state:n}),a=y(await r.sign(s));try{await this.relay.presenceIntent(e,{state:n===null?null:y(n),seq:o,sentAtMs:i,signature:a,authorProof:this.relay.authorProof})}catch(c){let u=c.status;if(u===void 0||u===0||u===429||u>=500)return;throw this.refused.add(e),this.stop(e),c}}};function ms(t,e){return new Error(`this client was constructed with the relay transport, which has no ${t}: ${e}. Construct a node client (createMeroClient({ baseUrl })) for that surface \u2014 nothing here will silently connect to a node you did not choose.`)}function fs(t){return new Error(`this relay-transport client cannot open ${t}: it was given no relay node key. A relay is an ordinary node and does serve /sse and /ws \u2014 but the login statement must be signed against the node's device signing key, learned out of band (never read from the node, and never derived from its peerId). Pass it as \`observe: { nodeKey }\`. For a cloud-hosted relay the cloud does not publish it yet \u2014 see mdma #312.`)}function iu(t,e,n){let r=e?.nodeKey;return r?new Ve({nodeUrl:e?.nodeUrl??t.relayUrl,nodeKey:r,accountProof:e?.accountProof??t.authorProof,audience:e?.audience??We(),signer:e?.signer?async()=>e.signer:()=>t.authorSigner(),clientName:e?.clientName,ttlSeconds:e?.ttlSeconds,fetch:e?.fetch??n,timeoutMs:e?.timeoutMs}):null}var be=class{constructor(e){this.relayObserver=null;this.relayAdmin=null;this.proofAuthorizer=null;this.relayUrl=null;this.proofEvents=null;this.relayFetch=void 0;this.relayPresence=null;if(e.transport==="relay"){this.transport="relay",this.nodeClient=null;let o=e.fetch;this.relayFetch=o;let i=e.relay instanceof W?e.relay:new W({...e.relay,fetch:e.relay.fetch??o});if(this.relayObserver=iu(i,e.observe,o),this.rpcTransport=new ye(i,this.relayObserver),this.relayUrl=i.relayUrl,e.proof&&(this.proofAuthorizer=pr(e.proof)),e.session){let s=e.session;this.relayAdmin=jo({baseUrl:i.relayUrl,getAuthToken:typeof s=="string"?async()=>s:s,fetch:o})}else if(this.proofAuthorizer){let s=this.proofAuthorizer;this.relayAdmin=Vt(st({fetch:(a,c)=>o?o(a,c):globalThis.fetch(a,c),baseUrl:i.relayUrl,authorizeRequest:s}),{baseUrl:i.relayUrl})}return}this.transport="node";let{transport:n,...r}=e;this.nodeClient=new Je(r),this.rpcTransport=this.nodeClient.rpc}get rpc(){return this.rpcTransport}get canSubscribe(){return this.rpcTransport.canSubscribe||this.proofAuthorizer!==null}get node(){if(!this.nodeClient)throw ms("node connection","it holds a signing key and a relay URL, not a node");return this.nodeClient}get relay(){if(!(this.rpcTransport instanceof ye))throw new Error("this client was constructed with the node transport and has no relay");return this.rpcTransport.client}get admin(){if(this.nodeClient)return this.nodeClient.admin;if(this.relayAdmin)return this.relayAdmin;throw new Error("this relay-transport client has no admin surface because it was given neither a `proof` nor a `session`. A warrant authorises one intent and is not a credential for reading. The caller-scoped reads (getContexts, listNamespaces) want one of the other two: pass `proof: { credential, deviceSecret }` \u2014 the device cert you already hold, which needs no login and no node key \u2014 or a `session` minted with `login()`. Context STATE reads work through execute/query either way.")}get auth(){return this.node.auth}get events(){if(this.nodeClient)return this.nodeClient.events;if(this.relayObserver)return this.relayObserver.events;if(this.proofAuthorizer&&this.relayUrl)return this.proofEvents??(this.proofEvents=new B({baseUrl:this.relayUrl,authorize:this.proofAuthorizer,fetch:this.relayFetch})),this.proofEvents;throw fs("SSE events")}get ws(){if(this.nodeClient)return this.nodeClient.ws;if(this.relayObserver)return this.relayObserver.ws;throw this.proofAuthorizer?new Error("this client authenticates with a request proof, which cannot open a WebSocket from a browser: `WebSocket` cannot set the X-Calimero-Proof header, and core's guard reads the proof from a header only (the ?token= query parameter is the session equivalent and has no proof counterpart). Use `client.events` \u2014 SSE is fetch-based, carries the header, and is the recommended transport anyway."):fs("WebSocket events")}get ephemeral(){return this.nodeClient?this.nodeClient.ephemeral:(this.relayPresence??(this.relayPresence=new St({relay:this.relay,events:()=>this.events})),this.relayPresence)}get cloud(){if(!this.nodeClient)throw ms("bundled cloud client","a relay client is built from a cloud connection rather than owning one \u2014 reach it through the `cloud` field that `connectCloud` returns, or construct a `CloudClient` directly");return this.nodeClient.cloud}close(){this.nodeClient?.close(),this.relayObserver?.close(),this.proofEvents?.close()}};function _n(t){return new be(t)}var oo="calimero.delegated.connection",io="calimero.delegated.credential";function so(){if(typeof sessionStorage>"u")return null;try{let t=sessionStorage.getItem(oo);return t?JSON.parse(t):null}catch{return null}}function ys(t){try{sessionStorage.setItem(oo,JSON.stringify(t))}catch{}}function bs(){try{sessionStorage.removeItem(oo)}catch{}}function ws(){let t=so();if(t){let{account:e,credential:n,deviceSecret:r}=t;return{account:e,credential:n,deviceSecret:r}}if(typeof sessionStorage>"u")return null;try{let e=sessionStorage.getItem(io);if(!e)return null;let n=JSON.parse(e);return!n.account||!n.credential||!n.deviceSecret?null:n}catch{return null}}function As(t){try{sessionStorage.setItem(io,JSON.stringify(t))}catch{}}function xs(){try{sessionStorage.removeItem(io)}catch{}}function ao(t){let e=Gn(t);return{next:async()=>{let n=0n;try{n=vs(t)}catch{n=0n}try{localStorage.setItem(e,String(n+1n))}catch{}return n}}}function Gn(t){return`calimero.nonce.${t}`}function vs(t){let e=localStorage.getItem(Gn(t));if(e!==null)return BigInt(e);let n=`${Gn(t)}.`,r=0n;for(let o=0;o<localStorage.length;o++){let i=localStorage.key(o);if(!i?.startsWith(n))continue;let s=BigInt(localStorage.getItem(i)??"0");s>r&&(r=s)}return r}function $n(t,e,n){try{vs(t)<=n&&localStorage.setItem(Gn(t),String(n+1n))}catch{}}var Rs="calimero.delegated.relay-node-key.";function X(t){return t.replace(/\/+$/,"")}function co(t,e){localStorage.setItem(Rs+X(t),e.trim().toLowerCase())}function Ln(t){try{let e=localStorage.getItem(Rs+X(t));return e&&/^[0-9a-f]{64}$/.test(e)?e:null}catch{return null}}function lo(t){try{let{hostname:e}=new URL(t);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch{return!1}}var su="locked-read-only",au="2.3.99",no;function cu(t){let e=t,n=typeof e.verify=="function"?e.verify:e.default?.verify;if(typeof n!="function")throw new TypeError("@phala/dcap-qvl loaded without a verify function");return n}var ze=class extends Error{constructor(n,r){super(`${n}: ${r instanceof Error?r.message:String(r)}`);this.step=n;this.cause=r;this.name="RelayKeyTransportError"}};async function hs(t,e){try{return await e()}catch(n){throw n instanceof ze?n:new ze(t,n)}}function lu(t){return async(e,n)=>{let r;try{r=await globalThis.fetch(e,n)}catch(o){throw t.failure=o,new ze(`reaching ${String(e)}`,o)}return r.ok||(t.failure??(t.failure=new Error(`${String(e)} answered HTTP ${r.status}`))),r}}function Cs(t,e){return Object.assign(async r=>{let o=await hs("loading the quote verifier",()=>(no??(no=import("@phala/dcap-qvl").then(i=>cu(i),i=>{throw no=void 0,i})),no));return fn({dcapVerify:o,release:()=>hs("fetching the release the relay runs",async()=>pn(mn(dn,await gn(t,{fetch:e})))),profile:su,minReleaseVersion:au})(r)},{includeCollateral:!0})}async function we(t,e={}){let n=e.fresh?null:Ln(t);if(n)return{kind:"learned",nodeKey:n};let r={failure:null},o=lu(r);try{let i=lo(t),{nodeKey:s}=await an({relayUrl:t,allowMock:i,fetch:o,...i?{}:{verify:Cs(t,o)}});return co(t,s),{kind:"learned",nodeKey:s}}catch(i){return i instanceof ze||r.failure?{kind:"unavailable",error:i}:{kind:"refused",error:i}}}async function Ss(t){let e=await we(t);return e.kind==="learned"?e.nodeKey:(console.warn("[mero-js] could not learn the relay node key from its attestation",e.error),null)}var Kn=[1e3,2e3,5e3,1e4,3e4];function uu(t,e){return new Promise(n=>{if(e?.aborted)return n();let r=setTimeout(o,t);function o(){clearTimeout(r),e?.removeEventListener("abort",o),n()}e?.addEventListener("abort",o)})}async function ks(t,e={}){let{signal:n}=e;for(let r=0;!n?.aborted;r+=1){let o=await we(t);if(o.kind==="learned")return o.nodeKey;if(o.kind==="refused")return console.warn("[mero-js] refusing the relay's attestation; its node key stays unknown",o.error),null;let i=Kn[Math.min(r,Kn.length-1)];console.warn(`[mero-js] could not reach what proves the relay's node key; retrying in ${i/1e3} s`,o.error),await uu(i,n)}return null}function du(t){try{let e=JSON.parse(atob(t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")));return typeof e.exp=="number"?e.exp*1e3:null}catch{return null}}var ro=new Map;function Es(){ro.clear()}async function pu(t){if(t.status!==403)return!1;try{return(await t.clone().json()).error?.code==="sealed_route_unguarded"}catch{return!1}}function gu(t){return t.headers.has("authorization")||new URL(t.url).pathname.startsWith("/auth/")}function mu(t){let e=(o,i)=>globalThis.fetch(o,i),n=fe({baseUrl:t,verify:Cs(t,e),fetch:e}),r=!1;return async(o,i)=>{let s=new Request(o,i);if(r&&gu(s))return e(s);let a=await n(s.clone());return await pu(a)?(r||(r=!0,console.warn(`[mero-js] ${X(t)} cannot guard logged-in calls sealed (no forward_auth); they go over its TLS until it does`)),e(s)):a}}function Ye(t){if(lo(t))return;let e=X(t),n=ro.get(e);return n||(n=mu(t),ro.set(e,n)),n}function fu(t,e){let n=null,r=null;return async()=>{let o=n?du(n):null;return n&&(o===null||o-Date.now()>3e4)?n:(r||(r=Fe({nodeUrl:t.relayUrl,fetch:Ye(t.relayUrl),node:e,deviceSecret:t.deviceSecret,accountProof:t.credential,audience:We()}).then(i=>(n=i.accessToken,n)).catch(i=>{console.warn("[mero-js] relay login failed",i),n=null}).finally(()=>{r=null})),r)}}var Mn=new Map;function Is(){Mn.clear()}function hu(t){return typeof t=="object"&&t!==null&&t.status===409}function yu(t,e){let n=t.rpc,r=X(e),o=async i=>{let s=`${r}|${i.contextId}|${i.method}`;if(Mn.get(s)!=="write")try{let{returns:a}=await t.admin.queryContext(i.contextId,{method:i.method,argsJson:i.argsJson??{}});return Mn.set(s,"read"),{returns:a,transport:"relay"}}catch(a){hu(a)&&Mn.set(s,"write")}return n.executeWithMetadata(i)};return{get kind(){return n.kind},get canSubscribe(){return n.canSubscribe},execute:async i=>(await o(i)).returns,executeWithMetadata:o,migrateMyEntries:i=>n.migrateMyEntries(i),countMyPending:i=>n.countMyPending(i)}}function bu(t){return new B({baseUrl:t,authorize:async()=>({}),fetch:(e,n)=>new Promise((r,o)=>{let i=()=>o(Object.assign(new Error("the stream was closed before the relay was attested"),{name:"AbortError"}));if(n?.signal?.aborted)return i();n?.signal?.addEventListener("abort",i,{once:!0})})})}function wu(t,e){let n=e.session?yu(t,e.relayUrl):null,r=null;return new Proxy(t,{get(o,i){if(i==="rpc"&&n)return n;if(!e.attested){if(i==="canSubscribe")return!1;if(i==="events")return r??(r=bu(e.relayUrl));if(i==="close")return()=>{r?.close(),o.close()}}let s=Reflect.get(o,i,o);return typeof s=="function"?s.bind(o):s}})}function uo(t,e){if(!t.relayUrl)return null;let n=Ln(t.relayUrl),r=_n({transport:"relay",fetch:Ye(t.relayUrl),relay:{relayUrl:t.relayUrl,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:ao(t.relayUrl)},proof:{credential:t.credential,deviceSecret:t.deviceSecret},session:n?fu({...t,relayUrl:t.relayUrl},n):void 0,observe:n?{nodeKey:n}:void 0});return wu(r,{relayUrl:t.relayUrl,session:n!==null,attested:n!==null||lo(t.relayUrl)})}var Ps="calimero.delegated.relays.";function q(t){try{let e=localStorage.getItem(Ps+t),n=e?JSON.parse(e):{};return{namespaces:n.namespaces??{},contexts:n.contexts??{}}}catch{return{namespaces:{},contexts:{}}}}function po(t,e){try{localStorage.setItem(Ps+t,JSON.stringify(e))}catch{}}function Ae(t,e,n){let r=q(t),o=X(e);n.namespaceId&&(r.namespaces[n.namespaceId]=o),n.contextId&&(r.contexts[n.contextId]=o),po(t,r)}function Ts(t,e){return q(t).contexts[e]??null}function Hn(t,e){return e.executorAccount||!t?.executorAccount||!t.relayUrl||!e.relayUrl||X(t.relayUrl)!==X(e.relayUrl)?e:{...e,executorAccount:t.executorAccount}}function Xe(t){let e=q(t.account),n=[t.relayUrl,...Object.values(e.namespaces),...Object.values(e.contexts)].filter(r=>typeof r=="string"&&r.length>0).map(X);return[...new Set(n)]}var Qe=class extends Error{constructor(n){super(`none of this account's relays answered: ${n.map(r=>`${r.relayUrl} (${r.kind})`).join(", ")}`);this.failures=n;this.name="RelaysUnavailableError",this.relays=n.map(r=>r.relayUrl)}get refused(){return this.failures.every(n=>n.kind==="refused")}};async function Ds(t,e){let n=await we(e);if(n.kind!=="learned")return console.warn("[mero-js] could not learn the relay node key from its attestation",n.error),{failure:{relayUrl:e,kind:n.kind,error:n.error}};let r=uo({...t,relayUrl:e},null);return r?{client:r}:{failure:{relayUrl:e,kind:"unavailable",error:new Error(`no client for ${e}`)}}}async function Us(t){let e=[],n=q(t.account),r=Xe(t),o=[];for(let i of r){let s=await Ds(t,i);if("failure"in s){o.push(s.failure);continue}let{client:a}=s;try{let{contexts:c}=await a.admin.getContexts();for(let u of c??[])e.push({...u,relayUrl:i}),n.contexts[u.id]=i}catch(c){o.push({relayUrl:i,kind:"unavailable",error:c}),console.warn(`[mero-js] could not list contexts on ${i}`,c)}}if(po(t.account,n),r.length>0&&o.length===r.length)throw new Qe(o);return e}async function Os(t){var s,a;let e=[],n=new Set,r=q(t.account),o=Xe(t),i=[];for(let c of o){let u=await Ds(t,c);if("failure"in u){i.push(u.failure);continue}let{client:d}=u;try{for(let l of await d.admin.listNamespaces())n.has(l.namespaceId)||(n.add(l.namespaceId),e.push({...l,relayUrl:c}),(s=r.namespaces)[a=l.namespaceId]??(s[a]=c))}catch(l){i.push({relayUrl:c,kind:"unavailable",error:l}),console.warn(`[mero-js] could not list namespaces on ${c}`,l)}}if(po(t.account,r),o.length>0&&i.length===o.length)throw new Qe(i);return e}function go(t=1){let e=BigInt(t);if(e<1n)throw new Error("nonce sequence starts at 1");return{next(){let n=e;return e+=1n,Promise.resolve(n)},advanceTo(n){return n>e&&(e=n),Promise.resolve()}}}function kt(t,e){let n=e??globalThis.localStorage;if(!n)throw new Error("no localStorage in this runtime: pass a storage implementation, or use createMemoryNonceSource for a process that owns its whole sequence");let r=()=>{let o=n.getItem(t);if(o===null||o==="")return 0n;try{let i=BigInt(o);return i>0n?i:0n}catch{return 0n}};return{next(){let o=r()+1n;return n.setItem(t,o.toString()),Promise.resolve(o)},advanceTo(o){let i=o>0n?o-1n:0n;return i>r()&&n.setItem(t,i.toString()),Promise.resolve()}}}async function Ns(t){if(!t.sessionToken&&!t.googleIdToken)throw new Error("connectCloud needs either a sessionToken or a googleIdToken");let e=await I(t.deviceSecret,t.signer,"deviceSecret"),n=new $({cloudBaseUrl:t.cloudBaseUrl,sessionToken:t.sessionToken,onSession:t.onSession,fetch:t.fetch,timeoutMs:t.timeoutMs});!t.sessionToken&&t.googleIdToken&&await n.signInWithGoogle(t.googleIdToken);let r=await n.getMyNamespaces(),o=xu(r,t.namespaceId),i=await n.getNamespaceRelays(o.namespaceId),s=mo(i);if(!s)throw new Error(vu(o,i));let a=new W({relayUrl:s.relayUrl,executorAccount:s.executorAccount,authorAccount:t.authorAccount,authorProof:t.authorProof,signer:e,nonces:t.nonces??Ru(e.publicKey),ttlSeconds:t.ttlSeconds,fetch:t.seal?fe({baseUrl:s.relayUrl,verify:t.seal,fetch:t.fetch}):t.fetch,timeoutMs:t.timeoutMs});return{cloud:n,relay:a,namespaceId:o.namespaceId,namespace:o,relayInfo:s,execute:(c,u,d)=>a.execute(c,u,d),client:new be({transport:"relay",relay:a,observe:{nodeKey:t.relayNodeKey??s.nodeKey,audience:t.observeAudience,fetch:t.fetch,timeoutMs:t.timeoutMs}})}}async function Au(t){let{root:e,authorAccount:n,...r}=t,o=await I(r.deviceSecret,r.signer,"deviceSecret"),i=await Y(e),a=await new $({cloudBaseUrl:t.cloudBaseUrl,onSession:t.onSession,fetch:t.fetch,timeoutMs:t.timeoutMs}).signInWithAccount(i.signer);return Ns({...r,deviceSecret:void 0,signer:o,sessionToken:a.sessionToken,authorAccount:n??i.accountId})}function xu(t,e){if(e){let n=t.find(r=>r.namespaceId===e);if(!n)throw new Error(`this account owns no namespace ${e}; it owns: ${t.map(r=>r.namespaceId).join(", ")||"(none)"}`);return n}if(t.length===0)throw new Error("this account owns no namespaces in the cloud: claim one first, then enable HA on it so a relay is assigned");if(t.length>1)throw new Error(`this account owns ${t.length} namespaces \u2014 pass namespaceId to say which: ${t.map(n=>n.namespaceId).join(", ")}`);return t[0]}function vu(t,e){if(e.length===0)return t.haStatus==="enabled"?`namespace ${t.namespaceId} has HA enabled but no relay has been assigned to it yet \u2014 retry shortly`:`namespace ${t.namespaceId} has no relays: enable HA on it in the cloud to have an attested node assigned`;let n=e.filter(o=>o.teeRole!==null&&o.teeRole!=="RelayTee");if(n.length===e.length)return`every node on namespace ${t.namespaceId} is a read-only TEE replica (ReadOnlyTee), which never relays delegated writes: an admin of the namespace must set its TEE admission policy with mode: 'relay' \u2014 AdminClient.setTeeAdmissionPolicy(namespaceId, { ..., mode: 'relay' }) \u2014 so fleet nodes are admitted as RelayTee`;let r=e.filter(o=>o.teeRole===null&&!o.authorshipReady);return r.length>0&&r.length+n.length===e.length?`every relay on namespace ${t.namespaceId} is waiting for the authorship grant: an admin of the namespace must grant CAN_AUTHOR_ON_BEHALF to ${r.map(o=>o.executorAccount??o.peerId).join(", ")||"the relay account"} \u2014 with AdminClient.grantAuthorship(namespaceId, account) for these relays, and AdminClient.openToDelegatedExecution(namespaceId) so relays assigned later need no further op`:`namespace ${t.namespaceId} has ${e.length} relay(s), but none is ready to relay yet (a URL, an executor account and a recent heartbeat) \u2014 retry shortly`}function Ru(t){let e=`mero-js:warrant-nonce:${t}`;try{return kt(e)}catch{return go(1)}}var Cu=new TextEncoder().encode("calimero.mdma.routing-read.v1\0");async function _s(t,e){m(e,"deviceSecret",32);let n=await ne(e),r=f(Cu,new TextEncoder().encode(t)),o=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,r));return Su(o)}async function Bn(t,e){return{"X-Calimero-Credential":e.credential,"X-Calimero-Nonce":t.nonce,"X-Calimero-Signature":await _s(t.nonce,e.deviceSecret)}}function Su(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var ku="https://cloud.calimero.network";async function Ms(t){let e=new URL(t.cloudWebUrl??ku),{callbackUrl:n,challenge:r}=await Wt(t.accountId,t.returnTo);return e.searchParams.set("link-account",t.accountId),e.searchParams.set("challenge",r),e.searchParams.set("callback-url",n),e.toString()}async function Eu(t){throw window.location.assign(await Ms(t)),new Error("redirecting to the cloud to authorise this link")}function Iu(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw De(t.search??"",null),fo(),new Error(n==="denied"?"the account link was declined at the cloud":`the cloud refused this link: ${n}`);let r=e.get("grant"),o=e.get("account");if(!r||!o)return null;let i=De(t.search??"",o),s=lt(r);if(!i||s?.account!==o)throw fo(),new Error("this account link answers a request this browser did not make - start the link again from here");return fo(),{grant:r,account:o,login:s.login,verifier:i}}function fo(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+Jo(location.search))}async function Pu(t){let e=await Y(t.root);if(e.accountId!==t.account)throw new Error(`this grant is for account ${t.account}, but the root here derives ${e.accountId} \u2014 it was minted for a different account`);return new $({cloudBaseUrl:t.cloudBaseUrl,fetch:t.fetch}).linkAccountWithGrant({grant:t.grant,verifier:t.verifier,signer:e.signer})}var Tu="enrol-device",Du="enrol-kem",Uu="callback-url",$s="state",ho="calimero.device.enrol.pending";function Ls(t){Ks(t.devicePublicKey,"devicePublicKey"),Ks(t.kemPublicKey,"kemPublicKey"),Gu(t.returnTo),Mu(t.returnTo);let e=new URL(t.walletUrl);return e.searchParams.set(Tu,t.devicePublicKey),e.searchParams.set(Du,t.kemPublicKey),e.searchParams.set(Uu,t.returnTo),e.searchParams.set($s,ct(ho,{})),e.toString()}function Ou(t){throw window.location.assign(Ls(t)),new Error("redirecting to the wallet to approve this device")}function Nu(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Te(ho,e.get($s)),Gs(),new Error(n==="denied"||n==="cancelled"?"the device was not approved at the wallet":`the wallet refused this enrolment: ${n}`);let r=e.get("credential"),o=e.get("account"),i=e.get("device");if(!r||!o||!i)return null;Gs();let s=e.get("state");return{credential:r,account:o,device:i,...s?{state:s}:{}}}function Gs(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+location.search)}async function _u(t){if(!Te(ho,t.state))throw new Error("this enrolment answers a request this app did not make - start the enrolment again from here");let e=await en(t.credential);if(e.signPublicKey!==xe(t.devicePublicKey))throw new Error(`this credential certifies device key ${e.signPublicKey}, but this app holds ${xe(t.devicePublicKey)} \u2014 it would sign with a key the certificate does not cover`);if(t.kemPublicKey!==void 0&&e.kemPublicKey!==xe(t.kemPublicKey))throw new Error(`this credential names delivery key ${e.kemPublicKey}, not the one this app asked about \u2014 group keys would be sealed to somebody else`);if(e.account!==xe(t.account))throw new Error(`the wallet reported account ${xe(t.account)}, but the credential names ${e.account}`);if(e.device!==xe(t.device))throw new Error(`the wallet reported device ${xe(t.device)}, but the credential names ${e.device}`);return{credential:t.credential,account:e.account,device:e.device,certificate:e}}function Ks(t,e){if(!/^[0-9a-f]{64}$/.test(t))throw new Error(`${e} must be 64 lowercase hex characters`)}function xe(t){return t.trim().toLowerCase()}function Hs(t,e){let n=e??(typeof window>"u"?void 0:window.location.origin);if(!n)return!1;try{return new URL(t).origin!==n}catch{return!1}}function Mu(t){Hs(t)&&console.warn(`[calimero] enrolling a device but sending the credential to ${new URL(t).origin}, which is not this page's origin. Legitimate when deliberate; worth a second look otherwise.`)}function Gu(t){let e;try{e=new URL(t)}catch{throw new Error(`returnTo must be an absolute URL, got ${t}`)}let n=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]"||e.hostname==="::1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new Error(`returnTo must be https:, or http: on localhost \u2014 got ${e.protocol}//${e.hostname}`)}function qn(t){if(!t)return null;let e=t.trim().toLowerCase(),n=e.startsWith("0x")?e.slice(2):e;return n.length>0?n:null}function $u(t,e){if(e.size===0)return!0;let n=qn(t.account);return n!==null&&e.has(n)}async function jn(t){let e=t.cloud??new $({cloudBaseUrl:t.cloudBaseUrl,routingCredential:{credential:t.credential,deviceSecret:t.deviceSecret}}),n,r;try{let p=await e.getNamespaceRouting(t.namespaceId);n=p.nodes,r=p.servable}catch(p){return{ok:!1,step:"admitters-lookup",reason:`The cloud could not be asked which nodes serve namespace ${t.namespaceId}: ${p instanceof Error?p.message:String(p)}. Nothing is known about the invitation yet \u2014 this is the lookup failing, not the invitation.`}}if(n.length===0)return{ok:!1,step:"no-nodes",reason:"The cloud lists no nodes serving this namespace, so there is no hosted node to be admitted through. The namespace has no fleet assignment \u2014 whoever invited you is running their own node, and admission has to go through a node the cloud routes to."};let o=new Set((t.admitters??[]).map(qn).filter(p=>p!==null)),i=n.filter(p=>$u(p,o));if(i.length===0)return{ok:!1,step:"not-invited",reason:`${n.length} node${n.length===1?"":"s"} serve this namespace, but your invitation names none of them. The signed admitter list is a snapshot from when the invitation was minted, so a node assigned since is healthy and will still refuse the claim. Ask for a fresh invitation.`};let s=i.filter(p=>p.canAdmit),a=s.length>0?s:i,c=s.length===0||!r,u=a.filter(p=>typeof p.relayUrl=="string"&&p.relayUrl.length>0),[d]=u;if(d===void 0)return{ok:!1,step:"no-relay-url",reason:"A node your invitation names can admit you, but the cloud knows no address for it yet, so there would be nothing to connect through afterwards. Try again shortly."};let l=u.find(p=>p.canExecute)??u.find(p=>p.fresh)??d;return{ok:!0,relayUrl:l.relayUrl,admitUrl:l.admitUrl??`${l.relayUrl.replace(/\/+$/,"")}/admin-api/namespaces/${g(t.namespaceId)}/admit`,admitterAccount:l.account,peerId:l.peerId,writable:l.canExecute,stale:!l.fresh||c}}var Fn=1440*60,bo={Admin:0,Member:1,ReadOnly:2};function Dt(t){let e=t.admitters??[];return f(yo(t.inviter_identity,"inviter_identity"),yo(t.group_id,"group_id"),C(t.expiration_timestamp),yo(t.secret_salt,"secret_salt"),new Uint8Array([t.invited_role]),R(e.length),...e.map((n,r)=>m(n,`admitters[${r}]`,32)))}async function wo(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",Dt(t)))}function Ao(t){return[...new Set(t.filter(n=>n.role==="Admin").map(n=>n.identity.toLowerCase()))].sort()}async function Vn(t){let e=await I(t.deviceSecret,t.signer,"deviceSecret"),n=m(e.publicKey,"signer.publicKey",32),r=m(t.groupId,"groupId",32);m(t.inviterAccount,"inviterAccount",32);let o=[...t.admitters??[]].map(p=>p.trim().toLowerCase());if(o.length===0){if(!t.members)throw new Error("name the admitters, or pass the group members to default them to its admins: an invitation with no admitters is claimable by broadcast");if(o=Ao(t.members),o.length===0)throw new Error("the member list names no admin, so there is nobody to default the admitters to")}o.forEach((p,x)=>m(p,`admitters[${x}]`,32));let i=t.invitedRole??bo.Member;if(![0,1,2].includes(i))throw new Error(`invitedRole must be 0 (Admin), 1 (Member) or 2 (ReadOnly), got ${i}`);let s=t.now??Math.floor(Date.now()/1e3),a=Math.min(t.validForSecs??Fn,Fn);if(!Number.isInteger(a)||a<=0)throw new Error(`validForSecs must be a positive whole number, got ${t.validForSecs}`);let c=t.nonce??crypto.getRandomValues(new Uint8Array(32));if(c.length!==32)throw new Error(`nonce must be 32 bytes, got ${c.length}`);let u={inviter_identity:Array.from(n),group_id:Array.from(r),expiration_timestamp:s+a,secret_salt:Array.from(c),invited_role:i,admitters:o},d=await e.sign(await wo(u));if(d.length!==64)throw new Error(`signer returned ${d.length} bytes, expected a 64-byte Ed25519 signature`);let l={invitation:u,inviter_signature:y(d),inviter_account:t.inviterAccount.trim().toLowerCase()};return t.admitterAddrs?.length&&(l.admitter_addrs=[...t.admitterAddrs]),t.applicationId&&(l.application_id=Array.from(m(t.applicationId,"applicationId",32))),t.appKey&&(l.app_key=Array.from(m(t.appKey,"appKey",32))),l}function yo(t,e){if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return new Uint8Array(t)}var xo=26,Lu=new TextEncoder().encode("calimero.namespace.v1"),Hu=0,Bs={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreatedV2:9,MemberJoinedViaTeeAttestation:10};function qs(t,e){if(t==null)return new Uint8Array([0]);if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return f(new Uint8Array([1]),new Uint8Array(t))}function js(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}function Wn(t){let e=t.invitation,n=t.admitter_addrs??[];return f(Dt(e),js(t.inviter_signature),t.inviter_account?f(new Uint8Array([1]),m(t.inviter_account,"inviter_account",32)):new Uint8Array([0]),R(n.length),...n.map(js),qs(t.application_id,"application_id"),qs(t.app_key,"app_key"))}async function Jn(t){let e=t.parentOpHashes??[],n=m(t.credential,"credential",t.credential.length/2),r=BigInt(t.invitation.invitation.expiration_timestamp??0)!==0n,o=t.joinedAt??BigInt(Math.floor(Date.now()/1e3)),i=r?f(new Uint8Array([Bs.MemberJoinedAt]),m(t.member,"member",32),Wn(t.invitation),C(o),n):f(new Uint8Array([Bs.MemberJoined]),m(t.member,"member",32),Wn(t.invitation),n),s=f(new Uint8Array([Hu]),i),a=await I(t.deviceSecret,t.signer,"deviceSecret"),c=m(a.publicKey,"signer.publicKey",32),u=f(new Uint8Array([xo]),m(t.namespaceId,"namespaceId",32),R(e.length),...e.map((p,x)=>m(p,`parentOpHashes[${x}]`,32)),c,C(t.nonce),s),d=await a.sign(f(Lu,u)),l=new Uint8Array([0]);return y(f(u,d,l))}function Bu(t,e){let n=e?`: ${e}`:"";switch(t){case 400:return`The node refused the join as malformed (400)${n}. The signature covers the invitation exactly as sent, so an edited or re-serialised invitation fails here \u2014 as does a namespace id that is not the invitation's own group.`;case 403:return`The node refused to carry this join (403)${n}. Either it is not in the invitation's signed admitters list \u2014 being live and listed by the cloud is not the same thing \u2014 or the invitation itself was rejected as expired or not the inviter\u2019s to issue.`;case 409:return`That node holds no device of its own, so it cannot endorse anyone (409)${n}. Another admitter from the same invitation would work.`;default:return`The join was not published (HTTP ${t})${n}.`}}function qu(t){let e=kt(`calimero.delegated.joinnonce.${t}`);return()=>e.next()}function Fs(t){return t.replace(/\/+$/,"")}async function zn(t){let{account:e,credential:n,deviceSecret:r}=t.credential,o;try{o=await Jn({namespaceId:t.namespaceId,member:e,invitation:t.invitation,credential:n,deviceSecret:r,nonce:await(t.deps?.nonce??qu(e))()})}catch(l){return{ok:!1,step:"sign",reason:`The join op could not be signed, so nothing was sent: ${l instanceof Error?l.message:String(l)}`}}let i={invitation:t.invitation,signedOp:o},s=t.admitUrl??`${Fs(t.nodeUrl)}/admin-api/namespaces/${g(t.namespaceId)}/admit`,a=t.deps?.fetch??fetch,c;try{c=await a(s,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(i)})}catch(l){return{ok:!1,step:"admit",reason:`The admitter at ${t.nodeUrl} could not be reached: ${l instanceof Error?l.message:String(l)}. The invitation is untouched \u2014 this is the node being unreachable, not a refusal.`}}let u=await c.text();if(!c.ok)return{ok:!1,step:"admit",status:c.status,reason:Bu(c.status,u)};let d=!1;try{d=(u?JSON.parse(u):{}).data?.published===!0}catch{d=!1}return{ok:!0,published:d,session:{relayUrl:Fs(t.nodeUrl),account:e,credential:n,deviceSecret:r}}}async function Qn(t){let e=t.deps?.resolve??jn,n=t.deps?.join??zn,r=null,o=t.nodeUrl,i;if(!o){let a=await e({namespaceId:t.namespaceId,admitters:t.invitation.invitation.admitters,credential:t.credential.credential,deviceSecret:t.credential.deviceSecret,cloudBaseUrl:t.cloudBaseUrl});if(a.ok===!1)return a;r=a,o=a.relayUrl,i=a.admitUrl}let s=await n({nodeUrl:o,admitUrl:i,namespaceId:t.namespaceId,invitation:t.invitation,credential:t.credential,deps:{fetch:t.deps?.fetch,nonce:t.deps?.nonce}});return s.ok===!1?s:{ok:!0,published:s.published,relay:r,session:s.session}}async function Vs(t,e,n,r){let i=await(r.bootstrap??Qn)({namespaceId:e,invitation:n,credential:{account:t.account,credential:t.credential,deviceSecret:t.deviceSecret},cloudBaseUrl:r.cloudBaseUrl});if(i.ok===!1)throw Object.assign(new Error(i.reason),{step:i.step,...i.status!==void 0?{status:i.status}:{}});return i.session.relayUrl&&Ae(t.account,i.session.relayUrl,{namespaceId:e}),r.onJoined(Hn(t,i.session)),{namespaceId:e}}function Ws(t){let e=new TextEncoder().encode(t),n=new Uint8Array(4+e.length);return new DataView(n.buffer).setUint32(0,e.length,!0),n.set(e,4),n}async function vo(t,e){let n=Ws(t),r=Ws(e),o=new Uint8Array(n.length+r.length);o.set(n,0),o.set(r,n.length);let i=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(i),s=>s.toString(16).padStart(2,"0")).join("")}function ju(t,e){let[n,r]=[t,e].map(o=>o.split(/[.-]/).map(i=>Number.parseInt(i,10)||0));for(let o=0;o<Math.max(n.length,r.length);o++)if((n[o]??0)!==(r[o]??0))return(n[o]??0)>(r[o]??0);return!1}function Ut(t){return t.filter(e=>!e.yanked&&typeof e.appVersion=="string"&&e.appVersion.length>0).reduce((e,n)=>!e||ju(n.appVersion,e.appVersion)?n:e,void 0)}async function Ot(t,e,n=globalThis.fetch){let r=`${t.replace(/\/+$/,"")}/api/v2/bundles?package=${encodeURIComponent(e)}`,o=await n(r,{headers:{Accept:"application/json"}});if(!o.ok)throw new Error(`the registry has no ${e} (HTTP ${o.status})`);let i=await o.json();return Array.isArray(i)?i:[]}async function Js(t,e,n={}){let o=(await Ot(t,e,n.fetch)).filter(c=>!c.yanked),i=[...new Set(o.map(c=>c.signerId).filter(c=>typeof c=="string"&&c.length>0))];if(i.length>1)throw new Error(`the registry lists ${e} under more than one publisher (${i.join(", ")}): refusing to guess which application it is`);let s=Ut(o);if(!s)throw new Error(`the registry lists no version of ${e}`);let a=s.signerId;if(!a)throw new Error(`the registry names no publisher for ${e} ${s.appVersion}`);return{applicationId:await vo(e,a),signerId:a,version:s.appVersion}}function Qs(t,e){return{next:async()=>Fu(t,e)}}function Fu(t,e){let n=`calimero.governance-nonce.${t}.${e}`,r=0n;try{r=BigInt(localStorage.getItem(n)??"0")}catch{}let o=[r+1n,BigInt(Date.now())].reduce((i,s)=>i>s?i:s);try{localStorage.setItem(n,String(o))}catch{}return o}function Ys(t,e){let n=q(t.account).namespaces[e]??t.relayUrl;if(!n)throw new Error("no relay is known for this namespace, so there is nowhere to send this");return n.replace(/\/+$/,"")}function Vu(t){return!t||t.length===0?{}:JSON.parse(new TextDecoder().decode(Uint8Array.from(t)))}function Xn(t,e,n,r){return new W({relayUrl:e,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:n,fetch:r??Ye(e)})}async function Nt(t,e,n={}){let r=Ys(t,e.namespaceId),o=0n,i=await Xn(t,r,{next:async()=>o},n.fetch).createContext({groupId:e.groupId??e.namespaceId,applicationId:e.applicationId,serviceName:e.serviceName,seed:e.contextSeed,initArgs:Vu(e.initializationParams),name:e.name});return $n(r,i.contextId,o),Ae(t.account,r,{namespaceId:e.namespaceId,contextId:i.contextId}),{contextId:i.contextId}}async function Re(t,e,n={}){let r=Ys(t,e.namespaceId);return Xn(t,r,Qs(r,e.group),n.fetch).govern({groupId:e.group,op:e.op})}async function Xs(t,e,n={}){let{groupId:r}=await Re(t,{namespaceId:e.namespaceId,group:e.namespaceId,op:(await qe({parentId:e.namespaceId,restricted:!0,admin:t.account})).op},n);for(let i of e.members)await Re(t,{namespaceId:e.namespaceId,group:r,op:He(i,"Member")},n);let{contextId:o}=await Nt(t,{...e,groupId:r},n);return{contextId:o,groupId:r}}async function Zn(t,e={},n={}){let o=Xe(t).map(u=>u.replace(/\/+$/,""))[0];if(!o)throw new Error("no relay is known for this account, so there is nowhere to found a namespace");let i=await Wu(t,o,n.fetch),s=BigInt(Date.now()),a=await Xn(t,o,{next:async()=>s++},n.fetch).foundNamespace({executor:i,...e.defaultCapabilities!==void 0?{defaultCapabilities:e.defaultCapabilities}:{},...e.application?{application:e.application}:{}});try{localStorage.setItem(`calimero.governance-nonce.${o}.${a.namespaceId}`,String(s))}catch{}if(Ae(t.account,o,{namespaceId:a.namespaceId}),e.application&&a.applicationSet!==!0)throw new Error(`founded ${a.namespaceId} but could not give it its application: ${a.applicationError??"unknown reason"}`);let c=a.teeEnabled?await zu(t,a.namespaceId,a.salt,o,n):{haEnabled:!1,haError:`the relay did not attest the founding, so no fleet node could be admitted for HA${a.teeError?`: ${a.teeError}`:""}`};return{namespaceId:a.namespaceId,teeEnabled:a.teeEnabled,...c}}async function Wu(t,e,n){let r=t.executorAccount&&t.relayUrl?.replace(/\/+$/,"")===e?t.executorAccount:null;if(r)return{executorAccount:r,executorKey:await zs(e)};let o=Object.entries(q(t.account).namespaces).find(([,a])=>a.replace(/\/+$/,"")===e)?.[0];if(!o)throw new Error("the executor account of this relay is not known: join a namespace on it first, or connect with the relay's executor account (the cloud shows it beside the relay)");let i=await zs(e),s=await Xn(t,e,Qs(e,o),n).describeGovernance(o);if(s.executorKey?.toLowerCase()!==i)throw new Error(`the relay's discovery names signing key ${s.executorKey}, not the relay's node key ${i}: refusing to found through it`);return{executorAccount:s.executorAccount,executorKey:i}}async function zs(t){let e=await we(t,{fresh:!0});if(e.kind==="learned")return e.nodeKey;throw new Error(e.kind==="unavailable"?"the relay's signing key could not be learned: its attestation did not answer, try again":"the relay's attestation was refused, so founding through it is not possible: it is not a signed locked-read-only release")}var er="link this account to your cloud user in the wallet so the cloud can host this namespace on its fleet",Yn={account_not_linked:er,account_linked_to_several_users:"this account is linked to more than one cloud user, so the cloud cannot tell whose plan hosts the namespace: unlink it from all but one in the wallet",ha_request_pending:"another namespace of this account is still waiting to be hosted; the cloud hosts one new namespace at a time without a cloud sign-in. Sign in to the cloud and turn off hosting for the waiting namespace, or wait until it is hosted",unknown_relay:"the cloud does not run the relay this namespace was founded on, so it cannot host it",relay_not_dialable:"the relay this namespace was founded on has not reported its address to the cloud yet; try enabling hosting again shortly"};function Ju(t){try{let e=JSON.parse(t.bodyText??""),n=e?.detail?.namespace_id??e?.namespace_id;return typeof n=="string"&&/^[0-9a-f]{64}$/i.test(n)?n.toLowerCase():null}catch{return null}}async function zu(t,e,n,r,o){try{return await new $({cloudBaseUrl:o.cloudBaseUrl,fetch:o.fetch}).enableHaAsAccount({namespaceId:e,salt:n,accountId:t.account,credential:t.credential,deviceSecret:t.deviceSecret,relayUrl:r}),{haEnabled:!0}}catch(i){if(i instanceof ve)return{haEnabled:!1,haError:er};if(i instanceof J&&Yn[i.code]){let s=i.code==="ha_request_pending"?Ju(i):null,a=Yn[i.code];return{haEnabled:!1,haError:s?`${a} (waiting: ${s})`:a}}return{haEnabled:!1,haError:i instanceof Error?i.message:String(i)}}}async function Ze(t,e,n=globalThis.fetch){let r=Ut(await Ot(t,e,n));if(!r)throw new Error(`the registry lists no version of ${e}`);return r.appVersion}var Zs="calimero.delegated.group-namespace.",Ro=new Map;function ea(t){let e={};try{e=JSON.parse(localStorage.getItem(Zs+t)??"{}")}catch{}return{...e,...Ro.get(t)}}function _t(t,e,n){Ro.set(t,{...Ro.get(t),[e]:n});try{let r=ea(t);r[e]=n,localStorage.setItem(Zs+t,JSON.stringify(r))}catch{}}function Mt(t,e){return q(t.account).namespaces[e]?e:ea(t.account)[e]}function ta(t,e){let n=Mt(t,e);if(!n)throw new Error(`the namespace of group ${e} is not known to this account: it can manage only groups in namespaces it joined or subgroups it created`);return n}async function tr(t,e,n){return Re(t,{namespaceId:ta(t,e),group:e,op:n})}async function nr(t,e,n){let r=ta(t,e);return Re(t,{namespaceId:r,group:r,op:n})}var Ce=class extends Error{constructor(n){super(`${n} is not available for an account: it needs a node`);this.method=n;this.name="NotForAccountError"}},et=class extends Error{constructor(n){super(`${n} needs a relay, and this account has none yet: join from an invitation first`);this.method=n;this.name="NoRelayError"}},tt=class extends Error{constructor(n,r){super(r==="not-hosted"?`nobody could claim an invitation to ${n} yet: the cloud lists no node holding the namespace, so an invitee with no node of their own has no relay to be admitted through.`:`nobody could claim an invitation to ${n}: the cloud routes to none of the relays or admins it would name as admitters`);this.namespaceId=n;this.reason=r;this.name="InvitationNotClaimableError"}},na={listNamespaces:async()=>[],listNamespacesForApplication:async()=>[],getContexts:async()=>({contexts:[]})},Qu=new Set(["upgradeGroup","retryGroupUpgrade","activateGroupUpgrade","abortMigration","installApplication","installDevApplication","uninstallApplication","generateContextIdentity","deleteContext","leaveContext","createContextAlias","createApplicationAlias","createDeviceAlias","deleteContextAlias","deleteApplicationAlias","deleteDeviceAlias","lookupContextAlias","lookupApplicationAlias","lookupDeviceAlias","listContextAliases","listApplicationAliases","listDeviceAliases","deleteNamespace","createGroupInvitation","joinGroup","setTeeAdmissionPolicy","getTeeAdmissionPolicy","deleteBlob","listAccountDevices","revokeAccountDevice"]);function Yu(t){if(!(t instanceof Error))return!1;let e=t.status;return(e===void 0||e===409)&&/signer [0-9a-f]+ is a direct member/i.test(t.message)}function ra(t,e={}){let{session:n,read:r,app:o}=t,i=e.govern?.group??tr,s=e.govern?.root??nr,a=e.createContext??Nt,c=e.found??Zn,u=e.latestVersion??Ze,d=e.signInvitation??Vn,l=e.join,p=e.routing;async function x(h,w){if(!l)throw new Ce("joinNamespace without a join handler");return l(h,w.invitation)}let v=()=>{if(r===null)throw new et("this call");return r};async function P(h){if(Mt(n,h))return;let w=await v().getGroupInfo(h);_t(n.account,h,w.namespaceId??h)}let b=async(h,w,S)=>(await P(w),i(h,w,S)),k=async(h,w,S)=>(await P(w),s(h,w,S));async function T(h){try{return await k(n,h,Un({member:n.account,groupId:h,credential:n.credential})),!0}catch(w){if(Yu(w))return!1;throw w}}async function H(h,w){let S=w??String(await v().getContextGroup(h)),{members:U}=await v().listGroupMembers(S);return U.some(M=>M.identity.toLowerCase()===n.account.toLowerCase())}let z={async listNamespacesForApplication(h){return(await v().listNamespaces()).filter(w=>w.targetApplicationId===h)},async getNodeIdentity(){return{accountId:n.account,deviceId:null,publicKey:"",deviceCertified:!0}},async createNamespace(h){if(!o.packageName)throw new Ce("createNamespace without a packageName");let w=o.packageVersion??await u(o.registryUrl??"https://apps.calimero.network",o.packageName),{namespaceId:S,haEnabled:U,haError:M}=await c(n,{defaultCapabilities:231,application:{applicationId:h.applicationId,package:o.packageName,version:w}});return h.name&&await b(n,S,je({name:h.name})),{namespaceId:S,haEnabled:U,...M!==void 0?{haError:M}:{}}},async createGroupInNamespace(h,w={}){let{op:S}=await qe({parentId:h,restricted:w.visibility==="restricted",admin:n.account}),{groupId:U}=await k(n,h,S);return _t(n.account,U,h),w.groupName&&await b(n,U,je({name:w.groupName})),{groupId:U}},async addGroupMembers(h,w){for(let S of w.members)await b(n,h,He(S.identity,S.role??"Member"))},async removeGroupMembers(h,w){for(let S of w.members)await b(n,h,An(S))},async setGroupMetadata(h,w){await b(n,h,je(w))},async setMemberMetadata(h,w,S){await b(n,h,Tn(w,S))},async setContextMetadata(h,w,S){await b(n,h,Dn(w,S))},async setDefaultCapabilities(h,w){await b(n,h,Be(w.defaultCapabilities))},async setSubgroupVisibility(h,w){await b(n,h,Pn(w.subgroupVisibility==="open"?"open":"restricted"))},async setMemberCapabilities(h,w,S){await b(n,h,En(w,S.capabilities))},async deleteGroup(h){return await k(n,h,Cn(h)),{isDeleted:!0}},async reparentGroup(h,w){return await k(n,h,Rn(h,w.newParentId)),{reparented:!0}},async leaveGroup(h){await b(n,h,Ct(n.account))},async leaveNamespace(h){await b(n,h,Ct(n.account))},async getContextIdentitiesOwned(h){return{identities:await H(h)?[n.account]:[]}},async joinContext(h){return await T(String(await v().getContextGroup(h))),{contextId:h,memberPublicKey:n.account}},async createContext(h){let S=(await v().getGroupInfo(h.groupId)).namespaceId??h.groupId,{contextId:U}=await a(n,{namespaceId:S,groupId:h.groupId,applicationId:h.applicationId,serviceName:h.serviceName,contextSeed:h.contextSeed,name:h.name,initializationParams:h.initializationParams});return{contextId:U,memberPublicKey:n.account,groupId:h.groupId}},async createNamespaceInvitation(h){let[{members:w},S]=await Promise.all([v().listGroupMembers(h),v().getGroupInfo(h)]),U=w.filter(Q=>Q.role==="RelayTee").map(Q=>Q.identity.toLowerCase());if(p){let Q=new Set(U.length>0?U:w.filter(te=>te.role==="Admin").map(te=>te.identity.toLowerCase())),ee=null;try{ee=(await p(h)).nodes}catch{}if(ee!==null){if(ee.length===0)throw new tt(h,"not-hosted");if(!ee.some(te=>te.account!==null&&Q.has(te.account.toLowerCase())))throw new tt(h,"no-named-node")}}return{invitation:await d({groupId:h,inviterAccount:n.account,deviceSecret:n.deviceSecret,...U.length>0?{admitters:U}:{},members:w,applicationId:S.targetApplicationId,appKey:S.appKey})}},async syncGroup(h){return{groupId:h,synced:!0}},async syncContext(){},joinNamespace:x,async updateMemberRole(h,w,S){await b(n,h,xn(w,S.role))},async joinSubgroupInheritance(h){return{groupId:h,memberPublicKey:n.account,wasInherited:await T(h)}},async detachContextFromGroup(h,w){await b(n,h,In(w))}};return r===null?new Proxy({},{get(h,w){if(typeof w=="string")return w==="getNodeIdentity"?z.getNodeIdentity:w==="joinNamespace"?x:w in na?na[w]:async()=>{throw new et(w)}}}):new Proxy(r,{get(h,w,S){return typeof w=="string"&&w in z?z[w]:typeof w=="string"&&Qu.has(w)?async()=>{throw new Ce(w)}:Reflect.get(h,w,S)}})}function oa(t,e={}){let{admin:n,app:r}=t,o=e.latestVersion??Ze;async function i(a){let{apps:c}=await n.listApplications();if(c.some(l=>l.id===a))return;if(!r.packageName)throw new Error(`application ${a} is not installed on this node, and no packageName is set to install it`);let u=r.packageVersion??await o(r.registryUrl??"https://apps.calimero.network",r.packageName),{applicationId:d}=await n.installApplication({package:r.packageName,version:u});if(d!==a)throw new Error(`installed ${r.packageName}@${u} as ${d}, not ${a}`)}let s={async createNamespace(a){return await i(a.applicationId),n.createNamespace(a)}};return new Proxy(n,{get(a,c,u){return typeof c=="string"&&c in s?s[c]:Reflect.get(a,c,u)}})}var Xu="https://manager.cloud.calimero.network";function Co(t,e){return typeof t.can_execute=="boolean"?t.can_execute:e}function So(t){return typeof t.tee_role=="string"&&t.tee_role!==""?t.tee_role:null}function mo(t){return t.find(e=>e.canExecute&&e.relayUrl!==null&&e.executorAccount!==null)??null}function Zu(t){let e=t.join;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(typeof n.state!="string")return null;let r=Array.isArray(n.refusals)?n.refusals.filter(o=>!!o&&typeof o=="object").map(o=>({peer:String(o.peer??""),reason:String(o.reason??"")})):[];return{state:n.state,attempts:typeof n.attempts=="number"?n.attempts:0,refusals:r,error:typeof n.error=="string"?n.error:null,reportedAt:typeof n.reported_at=="string"?n.reported_at:null}}function ed(t){return typeof t=="string"&&br.test(t)?t:null}var J=class extends O{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.code=n;this.name="AccountHaRefusedError"}},ve=class extends J{constructor(){super(...arguments);this.name="AccountNotLinkedError"}};ve.CODE="account_not_linked";var Et=class extends J{constructor(){super(...arguments);this.name="AccountLinkedToSeveralUsersError"}};Et.CODE="account_linked_to_several_users";var It=class extends J{constructor(){super(...arguments);this.name="HaRequestPendingError"}};It.CODE="ha_request_pending";var Pt=class extends J{constructor(){super(...arguments);this.name="UnknownRelayError"}};Pt.CODE="unknown_relay";var Tt=class extends J{constructor(){super(...arguments);this.name="RelayNotDialableError"}};Tt.CODE="relay_not_dialable";var ia={409:[ve,Et,It],422:[Pt,Tt]};function td(t){if(t)try{let e=JSON.parse(t);if(typeof e?.error=="string")return e.error;if(typeof e?.detail=="string")return e.detail;let n=e?.detail?.error;if(typeof n=="string")return n}catch{}}var nd="x-mdma-session-refresh",rd="x-mdma-session-expires",$=class{constructor(e={}){this.session=null;this.baseUrl=(e.cloudBaseUrl||Xu).replace(/\/+$/,""),this.onSession=e.onSession;let n=e.fetch;this.fetchImpl=n?(r,o)=>n(r,o):(r,o)=>globalThis.fetch(r,o),this.timeoutMs=e.timeoutMs??1e4,this.routingCredential=e.routingCredential,e.sessionToken&&(this.session={sessionToken:e.sessionToken,expiresAt:0,user:{email:""}})}getSession(){return this.session}isSignedIn(){return this.session!==null}async signInWithGoogle(e){let n=await this.request("POST","/api/auth/google",{body:{id_token:e},anonymous:!0});return this.adoptSession(n)}async signInWithAccount(e){let{signer:n,publicKey:r}=await Y(e),{nonce:o}=await this.getAccountLoginChallenge();return this.submitAccountLogin({rootPublicKey:r,nonce:o,signature:await rn({signer:n,nonce:o})})}async getAccountLoginChallenge(){let e=await this.request("GET","/api/auth/account/challenge",{anonymous:!0});return{nonce:e.nonce,expiresAtMs:e.expires_at_ms}}async submitAccountLogin(e){let n=await this.request("POST","/api/auth/account",{body:{root_public_key:e.rootPublicKey,nonce:e.nonce,signature:e.signature},anonymous:!0});return this.adoptSession(n)}async refreshSession(){let e=await this.request("POST","/api/auth/refresh");return this.adoptSession(e)}async signOut(){try{this.session&&await this.request("POST","/api/auth/logout",{parse:"none"})}finally{this.session=null,this.notifySession(null)}}async getMyNamespaces(){return(await this.request("GET","/api/cloud/me/namespaces")).map(n=>({namespaceId:String(n.namespace_id??n.group_id??""),groupId:String(n.group_id??n.namespace_id??""),haStatus:String(n.ha_status??"none"),haEnabledAt:n.ha_enabled_at??null,contexts:Array.isArray(n.contexts)?n.contexts:[],fleetReplicas:n.fleet_replicas}))}async getNamespaceRelays(e){return((await this.request("GET",`/api/cloud/me/namespaces/${g(e)}/relays`)).relays??[]).map(r=>{let o=r.relay_url??null,i=r.executor_account??null,s=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),relayUrl:o,executorAccount:i,nodeKey:r.node_key??r.node_public_key??null,status:String(r.status??""),authorshipReady:s,teeRole:So(r),canExecute:Co(r,s&&o!==null&&i!==null),lastSeenAt:r.last_seen_at??null,confirmedAt:r.confirmed_at??null,admission:typeof r.admission=="string"?r.admission:null,admissionHint:typeof r.admission_hint=="string"?r.admission_hint:null,join:Zu(r)}})}async findExecutingRelay(e){let n=await this.getNamespaceRelays(e);return mo(n)}async getNamespaceRouting(e){let n=await this.request("GET",`/api/cloud/namespaces/${g(e)}/admitters`,{anonymous:!0,headers:await this.routingProof(e)});return{namespaceId:String(n.namespace_id??e),nodes:(n.admitters??[]).map(r=>{let o=r.account??null,i=r.relay_url??null,s=r.fresh===!0,a=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),account:o,relayUrl:i,admitUrl:r.admit_url??null,status:String(r.status??""),fresh:s,canAdmit:r.can_admit===!0,authorshipReady:a,teeRole:So(r),canExecute:Co(r,a&&i!==null&&o!==null&&s)}}),servable:n.servable===!0,writable:n.writable===!0}}async getRoutingChallenge(e){let n=await this.request("GET",`/api/cloud/namespaces/${g(e)}/challenge`,{anonymous:!0});return{namespaceId:String(n.namespace_id??e),nonce:String(n.nonce??""),expiresAtMs:Number(n.expires_at_ms??0)}}async routingProof(e){if(!this.routingCredential)return;let n=await this.getRoutingChallenge(e);return Bn(n,this.routingCredential)}async getAccountRelaysChallenge(e){let n=await this.request("GET",`/api/cloud/accounts/${g(e)}/challenge`,{anonymous:!0});return{accountId:String(n.account_id??e),nonce:String(n.nonce??""),expiresAtMs:Number(n.expires_at_ms??0)}}async getAccountRelays(e){if(!this.routingCredential)throw new Error("getAccountRelays needs a routingCredential: construct the client with the device certificate and its signing secret, since this read is proven by the device, not by a session.");let n=await this.getAccountRelaysChallenge(e);return((await this.request("GET",`/api/cloud/accounts/${g(e)}/relays`,{anonymous:!0,headers:await Bn(n,this.routingCredential)})).relays??[]).map(o=>({peerId:String(o.peer_id??""),relayUrl:o.relay_url??null,fresh:o.fresh===!0,executorAccount:ed(o.executor_account),assigned:o.assigned===!0}))}async findAdmitter(e,n){let{nodes:r}=await this.getNamespaceRouting(e),o=n&&n.length>0?new Set(n.map(i=>i.toLowerCase())):null;return r.find(i=>i.canAdmit&&(o===null||i.account!==null&&o.has(i.account.toLowerCase())))??null}async getMyMachines(){return((await this.request("GET","/api/cloud/me/machines")).machines??[]).map(n=>{let r=n.relay_url??null,o=n.executor_account??null,i=(Array.isArray(n.namespaces)?n.namespaces:[]).map(s=>{let a=s;return{namespaceId:String(a.namespace_id??""),status:String(a.status??""),authorshipReady:a.authorship_ready===!0,teeRole:So(a),fresh:a.fresh===!0,confirmedAt:a.confirmed_at??null,lastSeenAt:a.last_seen_at??null}});return{peerId:String(n.peer_id??""),relayUrl:r,executorAccount:o,canExecute:Co(n,r!==null&&o!==null&&i.some(s=>s.authorshipReady)),namespaces:i}})}async claimNamespace(e,n){await this.request("POST","/api/cloud/namespaces/claim",{body:{namespace_id:e,ownership_proof:n}})}async enableNamespaceHa(e,n={}){let r=n.admitterAddrs===void 0?{}:{admitter_addrs:[...n.admitterAddrs]};return this.request("POST",`/api/cloud/namespaces/${g(e)}/enable-ha`,{body:r})}async enableFoundedNamespaceHa(e,n){return this.request("POST",`/api/cloud/me/namespaces/${g(e)}/enable-ha`,{body:{groups:[],ownership_proof:n}})}async enableHaAsAccount(e){let n=await Sr({namespaceId:e.namespaceId,accountId:e.accountId,salt:e.salt,credential:e.credential,deviceSecret:e.deviceSecret,signer:e.signer,ttlMs:e.ttlMs,relayUrl:e.relayUrl}),r=e.accountId.toLowerCase(),o=e.namespaceId.toLowerCase();try{return await this.request("POST",`/api/cloud/accounts/${g(r)}/namespaces/${g(o)}/enable-ha`,{body:{ownership_proof:n},anonymous:!0})}catch(i){if(i instanceof O&&ia[i.status]){let s=td(i.bodyText),a=ia[i.status].find(c=>c.CODE===s);if(a&&s)throw new a(s,i.status,i.statusText,i.url,i.headers,i.bodyText)}throw i}}async disableNamespaceHa(e){return this.request("POST",`/api/cloud/namespaces/${g(e)}/disable-ha`,{body:{}})}async getMyNode(){return(await this.request("GET","/api/cloud/me/node")).node??null}enableHA(e){let n=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&n.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/enable-ha?${n.toString()}`)}disableHA(e){let n=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&n.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/disable-ha?${n.toString()}`)}async linkAccount(e){let{signer:n,publicKey:r,accountId:o}=await Y(e),{nonce:i}=await this.getAccountLinkChallenge();return this.submitAccountLink({accountId:o,rootPublicKey:r,nonce:i,signature:await pt({signer:n,nonce:i})})}async getAccountLinkChallenge(){let e=await this.request("GET","/api/cloud/me/accounts/challenge");return{nonce:e.nonce,expiresAtMs:e.expires_at_ms??null}}async submitAccountLink(e){let n=await this.request("POST","/api/cloud/me/accounts",{body:{account_id:e.accountId,root_public_key:e.rootPublicKey,nonce:e.nonce,signature:e.signature}});return{accountId:String(n.account_id??e.accountId),linkedAt:n.linked_at??null,alreadyLinked:n.already_linked===!0}}static async accountLinkHandoff(e){let n=e.portalUrl.replace(/\/+$/,""),{callbackUrl:r,challenge:o}=await Wt(e.accountId,e.callbackUrl),i=new URLSearchParams({"link-account":e.accountId,challenge:o,"callback-url":r});return{url:`${n}/?${i.toString()}`,accountId:e.accountId}}static readAccountLinkCallback(e){let n=e??(typeof window>"u"?"":window.location.href);if(!n)return{};let r,o;try{({hash:r,search:o}=new URL(n))}catch{return{}}let i=new URLSearchParams(r.replace(/^#/,"")),s=i.get("grant"),a=i.get("account"),c=i.get("error"),u={};if(c&&De(o,null),s){let d=De(o,a),l=lt(s);if(!d||l?.account!==a)return{error:"unexpected_callback"};u.grant=s,u.login=l.login,u.verifier=d}return a&&(u.accountId=a),c&&(u.error=c),u}async linkAccountWithGrant(e){if(typeof e.verifier!="string"||!wr.test(e.verifier))throw new Error("no verifier for this grant - start the link again from this browser");let n=lt(e.grant);if(n?.challenge!==await Ar(e.verifier))throw new Error("this grant was not issued to this link request - start the link again from this browser");let{signer:r,publicKey:o,accountId:i}=await nn(e.rootSecret,e.signer);if(n.account!==i)throw new Error(`this grant is for account ${n.account}, but the root here derives ${i} - it was minted for a different account`);let s=await this.request("POST","/api/cloud/accounts/link",{body:{grant:e.grant,verifier:e.verifier,root_public_key:o,signature:await pt({signer:r,nonce:e.grant})},anonymous:!0});return{accountId:String(s.account_id??i),linkedAt:s.linked_at??null,alreadyLinked:s.already_linked===!0}}async getMyAccounts(){let e=await this.request("GET","/api/cloud/me/accounts");return{accounts:(e.accounts??[]).map(n=>({accountId:String(n.account_id??""),linkedAt:n.linked_at??null,hasRecoveryEnvelope:n.has_recovery_envelope===!0})),limit:e.limit??null}}adoptSession(e){return this.session={sessionToken:e.session_token,expiresAt:e.expires_at,user:e.user},this.notifySession(this.session),this.session}async notifySession(e){try{await this.onSession?.(e)}catch{}}async request(e,n,r={}){if(!r.anonymous&&!this.session)throw new Error("Not signed in to Calimero Cloud: call signInWithGoogle() or construct the client with a sessionToken");let o={...r.headers,Accept:"application/json"};r.body!==void 0&&(o["Content-Type"]="application/json"),!r.anonymous&&this.session&&(o.Authorization=`Bearer ${this.session.sessionToken}`);let i=new AbortController,s=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r.body===void 0?void 0:JSON.stringify(r.body),signal:i.signal})}catch(c){throw new O(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(this.adoptRollingRefresh(a),!a.ok){let c=await a.text().catch(()=>{});throw new O(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(!(r.parse==="none"||a.status===204))return await a.json()}adoptRollingRefresh(e){let n=e.headers.get(nd);if(!n||!this.session)return;let r=e.headers.get(rd),o=Number(r);this.session={sessionToken:n,expiresAt:Number.isFinite(o)&&o>0?o:this.session.expiresAt,user:this.session.user},this.notifySession(this.session)}};function Ku(t){let e=t&&typeof t=="object"?t.data??t:void 0;if(!e||typeof e!="object")return[];let n=e.localPeerId,r=e.externalAddrs;if(typeof n!="string"||!n||!Array.isArray(r))return[];let o=`/p2p/${n}`,i=[];for(let s of r){if(typeof s!="string")continue;let a=s.trim();if(!a.startsWith("/"))continue;let c=a.endsWith(o)?a:`${a}${o}`;i.includes(c)||i.push(c)}return i}function od(t){if(t)return typeof t=="function"?t:zt(t)}var id="mero-js:token-refresh";function sd(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function ad(t){try{let{origin:e,pathname:n}=new URL(t);return e==="null"?t:e+n.replace(/\/+$/,"")}catch{return t}}function ko(t,e){try{let n=t.split(".");if(n.length===3){let r=n[1].replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4;)r+="=";let o=JSON.parse(atob(r));if(typeof o.exp=="number")return o.exp*1e3}}catch{}return e}var Je=class{constructor(e){this.tokenData=null;this.refreshPromise=null;this.storeHoldsTokens=!1;this.tokenGeneration=0;this.onStorage=()=>{this.signedOutElsewhere()&&this.dropLocalTokens()};this.rpcClient=null;this.sseClient=null;this.wsClient=null;this.wsWarned=!1;this.config={timeoutMs:1e4,...e},this.tokenStore=e.tokenStore??null,this.nodeKey=ad(e.baseUrl),this.tokenData=this.readStoredTokens(),this.tokenStore&&(this.storeHoldsTokens=this.tokenData!==null,typeof window<"u"&&window.addEventListener("storage",this.onStorage));let n=typeof window<"u"&&"__TAURI_INTERNALS__"in window,r=od(this.config.requestProof);this.httpClient=Pe({baseUrl:this.config.baseUrl,fetch:this.config.fetch,getProof:r,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",refreshToken:async()=>(await this.performTokenRefresh()).access_token,onTokenRefresh:async o=>{this.tokenData&&(this.tokenData.access_token=o,this.persistTokens())},onAuthRevoked:async()=>{this.clearToken();try{await this.config.onAuthRevoked?.()}catch{}},timeoutMs:this.config.timeoutMs,credentials:this.config.requestCredentials??(n?"omit":void 0)}),this.authClient=Lo(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs}),this.adminClient=Vt(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs})}get auth(){return this.authClient}get admin(){return this.adminClient}get rpc(){return this.rpcClient||(this.rpcClient=new ut({httpClient:this.httpClient})),this.rpcClient}get events(){return this.sseClient||(this.sseClient=new B({baseUrl:this.config.baseUrl,fetch:this.config.fetch,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.sseClient}get ephemeral(){return this.ephemeralClient||(this.ephemeralClient=new dt({httpClient:this.httpClient,sse:this.events})),this.ephemeralClient}get cloud(){return this.cloudClient||(this.cloudClient=new $(this.config.cloud??{})),this.cloudClient}get ws(){return this.wsWarned||(this.wsWarned=!0,console.warn("[mero-js] WsClient is experimental. Use mero.events (SSE) for production.")),this.wsClient||(this.wsClient=new ie({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.wsClient}async authenticate(e){let n=e||this.config.credentials;if(!n)throw new Error("No credentials provided for authentication");try{let r={auth_method:"user_password",public_key:n.username,client_name:"mero-js-sdk",permissions:["admin"],timestamp:Math.floor(Date.now()/1e3),provider_data:{username:n.username,password:n.password}},o=await this.authClient.generateTokens(r),i=o.data.access_token;return this.tokenData={access_token:i,refresh_token:o.data.refresh_token,expires_at:ko(i,Date.now()+36e5)},this.persistTokens(),this.tokenData}catch(r){throw new Error(`Authentication failed: ${r instanceof Error?r.message:"Unknown error"}`)}}persistTokens(){!this.tokenStore||!this.tokenData||(this.tokenStore.setTokens({...this.tokenData,node_origin:this.nodeKey}),this.storeHoldsTokens=this.tokenStore.getTokens()!==null)}readStoredTokens(){let e=this.tokenStore?.getTokens();return!e||e.node_origin!==this.nodeKey?null:{access_token:e.access_token,refresh_token:e.refresh_token,expires_at:e.expires_at}}signedOutElsewhere(){return this.storeHoldsTokens&&!this.tokenStore?.getTokens()}dropLocalTokens(){this.tokenGeneration++,this.refreshPromise=null,this.tokenData=null,this.storeHoldsTokens=!1}async getValidToken(){return this.tokenData}async performTokenRefresh(){if(this.refreshPromise)return this.refreshPromise;let e=this.tokenData?.access_token,n=this.withRefreshLock(()=>this.performTokenRefreshLocked(e));this.refreshPromise=n;try{return await n}finally{this.refreshPromise===n&&(this.refreshPromise=null)}}withRefreshLock(e){if(this.tokenStore?.withLock)return this.tokenStore.withLock(e);let n=sd();return n?n.request(id,e):e()}async performTokenRefreshLocked(e){if(this.signedOutElsewhere())throw this.dropLocalTokens(),new Error("Signed out in another tab");let n=this.readStoredTokens();if(n?.refresh_token&&(this.storeHoldsTokens=!0,this.tokenData=n,e&&n.access_token!==e))return n;if(!this.tokenData?.refresh_token)throw new Error("No refresh token available");let r=this.tokenGeneration,o=this.tokenData.access_token,i=this.tokenStore?.getTokens()?.access_token===o;try{let s=await this.authClient.refreshToken({access_token:this.tokenData.access_token,refresh_token:this.tokenData.refresh_token});if(r!==this.tokenGeneration)throw new Error("Signed out during token refresh");if(i&&this.tokenStore?.getTokens()?.access_token!==o)throw this.tokenData=this.tokenStore?.getTokens()??null,this.storeHoldsTokens=this.tokenData!==null,new Error("Signed out during token refresh");let a=s.data.access_token;return this.tokenData={access_token:a,refresh_token:s.data.refresh_token,expires_at:ko(a,Date.now()+36e5)},this.persistTokens(),this.tokenData}catch(s){throw new Error(`Token refresh failed: ${s instanceof Error?s.message:"Unknown error"}`)}}clearToken(){this.dropLocalTokens(),this.tokenStore?.clear()}isAuthenticated(){return this.tokenData!==null}setTokenData(e){let n=e.expires_at||ko(e.access_token,Date.now()+36e5);this.tokenData={...e,expires_at:n},this.persistTokens()}getTokenData(){return this.tokenData}close(){typeof window<"u"&&window.removeEventListener("storage",this.onStorage),this.sseClient?.close(),this.wsClient?.close()}static parseAuthCallback(e,n){return xr(e,n)}static buildAuthLoginUrl(e,n){return vr(e,n)}};function cd(t){return new Je(t)}var Eo=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},ld="mero-tokens",Io=class{constructor(e=ld){this.key=e}getTokens(){try{if(typeof localStorage>"u")return null;let e=localStorage.getItem(this.key);if(!e)return null;let n=JSON.parse(e);return n&&n.access_token&&n.refresh_token?{access_token:n.access_token,refresh_token:n.refresh_token,expires_at:typeof n.expires_at=="number"?n.expires_at:Date.now()+36e5,...typeof n.node_origin=="string"&&{node_origin:n.node_origin}}:null}catch{return null}}setTokens(e){try{if(typeof localStorage>"u")return;localStorage.setItem(this.key,JSON.stringify(e))}catch{}}clear(){try{if(typeof localStorage>"u")return;localStorage.removeItem(this.key)}catch{}}};var ud=new TextEncoder().encode("calimero.account.owner-op.v1"),dd=new TextEncoder().encode("calimero.account.owner-op.body.v1"),pd=new TextEncoder().encode("calimero.account.genesis.v1"),gd=2,Po={transferOwnership:0,adminChanged:1,groupDelete:2,teeAdmissionPolicy:3,teeAuthoringPolicy:4,teeReleaseAdmissionPolicy:5},nt={GroupDelete:14,TransferOwnership:21,TeeAuthoringPolicySet:33,TeeAdmissionPolicySetV2:37,TeeReleaseAdmissionPolicySetV2:38,RootGuarded:42},aa={AdminChanged:3,RootGuarded:12},md={replica:0,relay:1},fd=new TextEncoder;function L(t){return new Uint8Array([t])}function ca(t){let e=fd.encode(t);return f(R(e.length),e)}function Z(t){return f(R(t.length),...t.map(ca))}function la(t){return L(t?1:0)}function ua(t){let e=md[t??"replica"];if(e===void 0)throw new Error(`mode must be replica or relay, got ${String(t)}`);return L(e)}function da(t){return{kind:"transferOwnership",plane:"group",bytes:f(L(nt.TransferOwnership),m(t,"newOwner",32))}}function pa(){return{kind:"groupDelete",plane:"group",bytes:L(nt.GroupDelete)}}function ga(t){return{kind:"adminChanged",plane:"root",bytes:f(L(aa.AdminChanged),m(t,"newAdmin",32))}}function ma(t){return{kind:"teeAuthoringPolicy",plane:"group",bytes:f(L(nt.TeeAuthoringPolicySet),Z(t))}}function fa(t){return{kind:"teeAdmissionPolicy",plane:"group",bytes:f(L(nt.TeeAdmissionPolicySetV2),Z(t.allowedMrtd),Z(t.allowedRtmr0),Z(t.allowedRtmr1),Z(t.allowedRtmr2),Z(t.allowedRtmr3),Z(t.allowedTcbStatuses),la(t.acceptMock),ua(t.mode))}}function ha(t){let e=t.minReleaseVersion===void 0?L(0):f(L(1),ca(t.minReleaseVersion));return{kind:"teeReleaseAdmissionPolicy",plane:"group",bytes:f(L(nt.TeeReleaseAdmissionPolicySetV2),Z(t.allowedProfiles),e,Z(t.allowedTcbStatuses),la(t.acceptMock),ua(t.mode))}}async function To(t){return E(dd,[t])}async function Do(t){return E(ud,[m(t.account,"account",32),m(t.namespaceId,"namespaceId",32),m(t.groupId,"groupId",32),L(ya(t.kind)),t.opDigest,C(t.counter),R(t.keyEpoch)])}function ya(t){let e=Po[t];if(e===void 0)throw new Error(`unknown owner-op kind ${String(t)}`);return e}var sa=132;async function ba(t){let e=await re(t.rootSecret),n=f(L(gd),e),r=y(await E(pd,[n])),o=t.keyEpoch??0,i=(t.chain??[]).map((d,l)=>{let p=j(d,`chain[${l}]`);if(p.length!==sa)throw new Error(`chain[${l}] must be a ${sa}-byte RootKeyHandoff, got ${p.length}`);return p});if(o>i.length)throw new Error(`keyEpoch ${o} needs ${o} handoffs in chain, got ${i.length}`);let s=await To(t.op.bytes),a=await Do({account:r,namespaceId:t.namespaceId,groupId:t.groupId,kind:t.op.kind,opDigest:s,counter:t.counter,keyEpoch:o}),c=await ne(t.rootSecret),u=new Uint8Array(await crypto.subtle.sign("Ed25519",c,a));return y(f(n,R(i.length),...i,m(r,"account",32),m(t.namespaceId,"namespaceId",32),m(t.groupId,"groupId",32),L(ya(t.op.kind)),s,C(t.counter),R(o),u))}function wa(t,e){let n=t.plane==="group"?nt.RootGuarded:aa.RootGuarded;return f(L(n),t.bytes,j(e,"rootProof"))}var Aa=[2428,2429,2528,2529],hd="localhost",yd=2e3;function xa(t){return`http://${hd}:${t}`}function va(t,e){let n=t.endsWith("/")?t:`${t}/`;return new URL(e,n).toString()}async function Ra(t,e={}){let{timeoutMs:n=yd,signal:r}=e;if(r?.aborted)return!1;let o=new AbortController,i=()=>o.abort(),s=r;s&&s.addEventListener("abort",i,{once:!0});let a=setTimeout(()=>o.abort(),n);try{let c=va(t,"admin-api/health"),u=await fetch(c,{method:"GET",signal:o.signal});if(!u.ok)return!1;try{let d=await u.json(),l=d?.data?.status!==void 0?d?.data?.status:d?.status;return l===void 0?!0:typeof l=="string"&&l.toLowerCase()==="alive"}catch{return!0}}catch{return!1}finally{clearTimeout(a),s&&s.removeEventListener("abort",i)}}async function bd(t={}){let{ports:e=Aa,timeoutMs:n,signal:r}=t;return(await Promise.all(e.map(async i=>{let s=xa(i);return await Ra(s,{timeoutMs:n,signal:r})?s:null}))).filter(i=>i!==null)}function rr(t,e){return(t<<e|t>>>32-e)>>>0}function le(t,e,n,r,o){t[e]=t[e]+t[n]>>>0,t[o]=rr(t[o]^t[e],16),t[r]=t[r]+t[o]>>>0,t[n]=rr(t[n]^t[r],12),t[e]=t[e]+t[n]>>>0,t[o]=rr(t[o]^t[e],8),t[r]=t[r]+t[o]>>>0,t[n]=rr(t[n]^t[r],7)}function Ca(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function Ea(t,e,n){let r=new Uint32Array(16);r[0]=1634760805,r[1]=857760878,r[2]=2036477234,r[3]=1797285236;for(let s=0;s<8;s+=1)r[4+s]=Ca(t,s*4);r[12]=e>>>0;for(let s=0;s<3;s+=1)r[13+s]=Ca(n,s*4);let o=r.slice();for(let s=0;s<10;s+=1)le(o,0,4,8,12),le(o,1,5,9,13),le(o,2,6,10,14),le(o,3,7,11,15),le(o,0,5,10,15),le(o,1,6,11,12),le(o,2,7,8,13),le(o,3,4,9,14);let i=new Uint8Array(64);for(let s=0;s<16;s+=1){let a=o[s]+r[s]>>>0;i[s*4]=a&255,i[s*4+1]=a>>>8&255,i[s*4+2]=a>>>16&255,i[s*4+3]=a>>>24&255}return i}function wd(t,e,n,r){let o=new Uint8Array(r.length);for(let i=0,s=e;i<r.length;i+=64,s+=1){let a=Ea(t,s,n),c=Math.min(i+64,r.length);for(let u=i;u<c;u+=1)o[u]=r[u]^a[u-i]}return o}function Uo(t){let e=0n;for(let n=t.length-1;n>=0;n-=1)e=e<<8n|BigInt(t[n]);return e}var Ad=(1n<<130n)-5n;function xd(t,e){let n=Uo(t.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,r=Uo(t.subarray(16,32)),o=0n;for(let a=0;a<e.length;a+=16){let c=e.subarray(a,Math.min(a+16,e.length)),u=Uo(c)+(1n<<BigInt(8*c.length));o=(o+u)*n%Ad}let i=o+r&(1n<<128n)-1n,s=new Uint8Array(16);for(let a=0;a<16;a+=1)s[a]=Number(i&0xffn),i>>=8n;return s}function Sa(t){return new Uint8Array((16-t%16)%16)}function ka(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function vd(t,e){let n=[t,Sa(t.length),e,Sa(e.length),ka(t.length),ka(e.length)],r=new Uint8Array(n.reduce((i,s)=>i+s.length,0)),o=0;for(let i of n)r.set(i,o),o+=i.length;return r}function Rd(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 Ia(t,e,n,r=new Uint8Array(0)){Rd(t,e);let o=Ea(t,0,e).subarray(0,32),i=wd(t,1,e,n),s=xd(o,vd(r,i)),a=new Uint8Array(i.length+16);return a.set(i),a.set(s,i.length),a}var Ta=32,Cd=1,Sd=3,kd=2,Ed=32,Id=32,Pd=12,rt=t=>new TextEncoder().encode(t),Kt=t=>new Uint8Array([t>>8&255,t&255]),Pa=f(rt("KEM"),Kt(Ta)),Gt=f(rt("HPKE"),Kt(Ta),Kt(Cd),Kt(Sd));async function Da(t,e){let n=t.length===0?new Uint8Array(32):t,r=await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",r,e))}async function Td(t,e,n){let r=new Uint8Array(n),o=new Uint8Array(0);for(let i=1,s=0;s<n;i+=1)o=await Da(t,f(o,e,new Uint8Array([i]))),r.set(o.subarray(0,Math.min(o.length,n-s)),s),s+=o.length;return r}function or(t,e,n,r){return Da(e,f(rt("HPKE-v1"),t,rt(n),r))}function Oo(t,e,n,r,o){return Td(e,f(Kt(o),rt("HPKE-v1"),t,rt(n),r),o)}async function Dd(t,e){let n=await or(Pa,new Uint8Array(0),"eae_prk",t);return Oo(Pa,n,"shared_secret",e,Ed)}async function Ud(t,e){let n=new Uint8Array(0),r=await or(Gt,n,"psk_id_hash",n),o=await or(Gt,n,"info_hash",e),i=f(new Uint8Array([kd]),r,o),s=await or(Gt,t,"secret",n);return{key:await Oo(Gt,s,"key",i,Id),nonce:await Oo(Gt,s,"base_nonce",i,Pd)}}async function Ua(t,e,n,r,o=new Uint8Array(0),i){if(t.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let s=await _e(i),a=await _e(e),c=f(await gt(s.privateKey,t),await gt(a.privateKey,t)),u=await Dd(c,f(s.publicKey,t,a.publicKey)),{key:d,nonce:l}=await Ud(u,n);return{enc:s.publicKey,ciphertext:Ia(d,l,r,o)}}var _a="mero-agent-gate/attest/v3",Ma="mero-agent-gate/provision/v2",Od=/^[a-z0-9][a-z0-9-]{0,62}$/,Nd=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,Oa=64,Na=64*1024,ue=class extends Error{constructor(n,r,o){super(n);this.status=r;this.code=o;this.name="AgentGateError"}};function Ga(t){if(!Od.test(t))throw new Error(`Agent id ${JSON.stringify(t)} must match [a-z0-9][a-z0-9-]{0,62}`)}function $t(t){return new TextEncoder().encode(t)}function Ka(t){let e=$t(t);return f(new Uint8Array([e.length]),e)}function Se(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}function ir(t,e,n){let r;try{r=Uint8Array.from(atob(t.trim()),o=>o.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(n!==void 0&&r.length!==n)throw new Error(`${e} is not ${n} bytes`);return r}async function $a(t,e,n,r){let o=new Uint8Array(32),i=f($t(_a),t,Ka(e),n??o,r??o);return new Uint8Array(await crypto.subtle.digest("SHA-256",i))}function La(t,e){return f($t(Ma),t,Ka(e))}async function _d(){let t=crypto.getRandomValues(new Uint8Array(32));return{secret:t,publicKey:await sr(t)}}async function sr(t){if(t.length!==32)throw new Error("An owner key is 32 bytes");return Se((await _e(t)).publicKey)}function Ha(t,e){return`${t.replace(/\/+$/,"")}${e}`}async function Ba(t,e,n){let r=await t(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}),o=await r.text(),i;try{i=o?JSON.parse(o):void 0}catch{}if(!r.ok){let s=i;throw new ue(`The gate answered ${r.status}${s?.error?` ${s.error}`:""}: ${s?.details??o.slice(0,200)}`,r.status,s?.error)}return i}async function No(t){let e=t.agentId??"";e&&Ga(e);let n=crypto.getRandomValues(new Uint8Array(32)),r=await Ba(t.fetch??fetch,Ha(t.gateUrl,"/attest"),{nonceB64:Se(n),...e?{agentId:e}:{}});if((r?.agentId??"")!==e)throw new Error(`Asked about agent ${JSON.stringify(e)}, the gate answered for ${JSON.stringify(r?.agentId)}`);let o=ir(r.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),i=r.signingPublicKeyB64?ir(r.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,s=r.ownerPublicKeyB64?ir(r.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!i!=!s)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let a=await $a(o,e,i,s);return await t.verifier({quoteB64:r.quoteB64,nonce:y(n),reportDataSuffix:y(a)}),{agentId:e,provisioningPublicKey:Se(o),...i?{signingPublicKey:Se(i)}:{},...s?{ownerPublicKey:Se(s)}:{}}}async function qa(t,e){let n=await sr(e);if(t.ownerPublicKey&&t.ownerPublicKey!==n)throw new ue(`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 n}function Md(t){let e=Object.keys(t);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>Oa)throw new Error(`At most ${Oa} secrets at once`);for(let n of e){if(!Nd.test(n))throw new Error(`Secret name ${JSON.stringify(n)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);if(typeof t[n]!="string")throw new Error(`Secret ${n} is not a string`);if($t(t[n]).length>Na)throw new Error(`Secret ${n} is over ${Na} bytes`)}}async function ja(t,e,n,r,o,i){if(!r.agentId)throw new Error("This quote names no agent; attest with the agent id");let s=await qa(r,o),a=ir(r.provisioningPublicKey,"provisioningPublicKey",32),c=await Ua(a,o,La(a,r.agentId),$t(JSON.stringify(i)));return Ba(t,Ha(e,n),{agentId:r.agentId,provisioningPublicKeyB64:r.provisioningPublicKey,senderPublicKeyB64:s,encappedKeyB64:Se(c.enc),ciphertextB64:Se(c.ciphertext)})}async function Gd(t){Md(t.secrets);let e=t.fetch??fetch,n=await ja(e,t.gateUrl,"/provision",t.agent,t.ownerSecret,{secrets:t.secrets}),r=await No({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e}),o=await sr(t.ownerSecret);if(r.ownerPublicKey!==o||!r.signingPublicKey)throw new ue("The gate accepted the secrets, but its quote does not name your key as owner");if(t.agent.signingPublicKey&&t.agent.signingPublicKey!==r.signingPublicKey)throw new ue("The agent's signing key changed while provisioning");return{agentId:r.agentId,provisioningPublicKey:r.provisioningPublicKey,signingPublicKey:r.signingPublicKey,ownerPublicKey:o,written:n?.written??[],claimed:n?.claimed===!0}}async function Kd(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 ja(e,t.gateUrl,"/release",t.agent,t.ownerSecret,{release:!0}),(await No({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e})).ownerPublicKey)throw new ue("The gate says it released the agent, but its quote still names an owner")}var _o=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),$d=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function Ld(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await un(r,e,{identity:n.identity??_o.identity,issuer:n.issuer??_o.issuer});let o;try{o=JSON.parse(new TextDecoder().decode(r))}catch{throw new Error("The signed agent policy is not JSON")}if(o?.role!=="agent")throw new Error(`The signed file is a ${JSON.stringify(o?.role)} policy, not an agent one`);let i=n.profile??yt;if(o.profile!==i)throw new Error(`The signed agent policy is for the ${JSON.stringify(o.profile)} profile, not ${i}`);if(n.expectedVersion!==void 0&&o.version!==n.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(o.version)}, not ${n.expectedVersion}`);return Fa(o),o}function Fa(t){for(let e of $d)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 Hd=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function Bd(t){let e=Hd.find(n=>n.toLowerCase()===t.trim().toLowerCase());if(!e)throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(t)}`);return e}var Lt=t=>t.trim().replace(/^0x/i,"");function qd(t,e){return Fa(t),bt({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:t.allowed_tcb_statuses.map(Bd),allowedMrtd:t.allowed_mrtd.map(Lt),allowedRtmr0:t.allowed_rtmr0.map(Lt),allowedRtmr1:t.allowed_rtmr1.map(Lt),allowedRtmr2:t.allowed_rtmr2.map(Lt),allowedRtmr3:t.allowed_rtmr3.map(Lt)})}export{si as ACCOUNT_HA_AUDIENCE,ii as ACCOUNT_OWNERSHIP_AUDIENCE,_a as AGENT_ATTEST_DOMAIN,Ma as AGENT_PROVISION_INFO_DOMAIN,J as AccountHaRefusedError,Et as AccountLinkedToSeveralUsersError,ve as AccountNotLinkedError,me as AdminApiClient,ue as AgentGateError,pe as AuthApiClient,oe as AuthRevokedError,_ as CAPABILITIES,xp as CAPABILITY_PRESETS,$ as CloudClient,Aa as DEFAULT_LOCAL_NODE_PORTS,dn as DEFAULT_RELEASE_MIRROR,dt as EphemeralClient,Di as HANDSHAKE_PATH,er as HA_ACCOUNT_NOT_LINKED_MESSAGE,Yn as HA_REFUSAL_MESSAGES,O as HTTPError,It as HaRequestPendingError,bo as INVITED_ROLE,he as IntentRefusedError,tt as InvitationNotClaimableError,_o as KMS_RELEASE_SIGNER,Io as LocalStorageTokenStore,Fn as MAX_INVITATION_VALIDITY_SECS,Eo as MemoryTokenStore,be as MeroClient,Je as MeroJs,Br as NODE_RELEASE_SIGNER,et as NoRelayError,Ce as NotForAccountError,Po as OWNER_OP_KIND,ps as PRESENCE_DOMAIN,yt as PRODUCTION_PROFILE,Kn as RELAY_NODE_KEY_RETRY_MS,Ie as REQUEST_PROOF_HEADER,W as RelayClient,Tt as RelayNotDialableError,Ve as RelayObserver,St as RelayPresenceClient,ye as RelayTransport,Qe as RelaysUnavailableError,ut as RpcClient,Qt as RpcError,ft as SEALED_CONTENT_TYPE,Ui as SEALED_PATH,xo as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,Me as SealedTransportError,B as SseClient,ht as StaleTransportKeyError,Pt as UnknownRelayError,it as WebHttpClient,ie as WsClient,tn as accountForRoot,F as accountForRootPublicKey,gi as accountRootFromPhrase,Dr as accountRootFromSecret,fi as accountRootSignerFromPhrase,ga as adminChangedOp,Ku as admitterAddrsFromNetworkStatus,$a as agentKeyBinding,qd as agentQuoteVerifier,vo as applicationIdForBundle,we as attemptRelayNodeKey,No as attestAgent,sn as attestKeyBinding,an as attestRelayNodeKey,Eu as beginCloudLink,Ou as beginDeviceEnrolment,Qn as bootstrapFromInvitation,vr as buildAuthLoginUrl,uo as buildDelegatedClient,Hs as callbackIsForeign,Jt as callerProof,vp as capMask,Rp as capNames,Hn as carryExecutorAccount,qa as checkOwner,hr as classifyError,xs as clearDelegatedCredential,bs as clearDelegatedSession,Ms as cloudLinkUrl,mn as cloudNodeReleaseUrl,cr as combineSignals,dc as compareSemver,Pu as completeCloudLink,_u as completeDeviceEnrolment,Ns as connectCloud,Au as connectCloudWithAccount,cs as contextCapabilityGrantedOp,ls as contextCapabilityRevokedOp,In as contextDetachedOp,Dn as contextMetadataSetOp,ra as createAccountAdmin,mi as createAccountRootSigner,jo as createAdminApiClient,Vt as createAdminApiClientFromHttpClient,fe as createAttestedSealedFetch,wp as createAuthApiClient,Lo as createAuthApiClientFromHttpClient,Hp as createBrowserAdminApiClient,yp as createBrowserAuthApiClient,Pe as createBrowserHttpClient,Nt as createDelegatedContext,Xs as createDelegatedPrivateContext,st as createHttpClient,kt as createLocalStorageNonceSource,go as createMemoryNonceSource,_n as createMeroClient,cd as createMeroJs,oa as createNodeAdmin,Bp as createNodeAdminApiClient,bp as createNodeAuthApiClient,jt as createNodeHttpClient,pr as createProofAuthorizer,zt as createProofSigner,bt as createQuoteVerifier,tc as createRetryableMethod,Mi as createSealedFetch,Ol as createSignedReleaseSealedFetch,fn as createSignedReleaseVerifier,lr as createTimeoutSignal,gr as createUniversalHttpClient,Qr as createdSubgroupId,Fr as creationInitHash,Ao as defaultAdmitters,We as defaultAudience,Be as defaultCapabilitiesSetOp,Re as delegatedGovernance,Zt as deviceCertPayload,Ls as deviceEnrolmentUrl,Ir as deviceScopePayload,bd as discoverLocalNodes,Dt as encodeGroupInvitation,Wn as encodeSignedInvitation,_i as fetchAttestedTransportKey,pn as fetchNodeRelease,gn as fetchNodeReleaseVersion,Ot as fetchRegistryBundles,Is as forgetMethodKinds,Es as forgetRelaySealing,Zn as foundDelegatedNamespace,Sn as foundedNamespaceId,pi as generateAccountRoot,_d as generateOwnerKey,eo as generateSessionKey,tr as governGroup,nr as governRoot,Vr as governanceOpHash,Yr as groupCreatedOp,pa as groupDeleteOp,Cn as groupDeletedOp,wo as groupInvitationHash,je as groupMetadataSetOp,Rn as groupReparentedOp,ge as hasCap,Mp as hexEncodeUtf8,qr as intentHash,ic as isSettled,Vs as joinAsAccount,zn as joinWithNode,se as jsonCodec,Xe as knownRelays,Ze as latestPublishedVersion,ks as learnRelayNodeKey,Us as listDelegatedContexts,Os as listDelegatedNamespaces,xa as localNodeUrl,Fe as login,$n as markContextNonceSpent,He as memberAddedOp,En as memberCapabilitySetOp,Un as memberJoinedOpenOp,Ct as memberLeftOp,Tn as memberMetadataSetOp,An as memberRemovedOp,xn as memberRoleSetOp,kr as mintDeviceId,kn as namespaceCreatedOp,Mt as namespaceOfGroup,va as nodeEndpoint,Ji as nodeReleaseVersionFromImage,qn as normaliseAccount,To as ownerOpDigest,Do as ownerOpSigningPayload,sr as ownerPublicKey,xr as parseAuthCallback,rs as parseCreationWarrant,Er as parseDeviceCredential,os as parseGovernanceWarrant,ao as persistedNonces,co as pinRelayNodeKey,to as presenceStatementBytes,Ra as probeNodeHealth,Gd as provisionAgent,La as provisionInfo,Iu as readCloudLinkCallback,ws as readDelegatedCredential,so as readDelegatedSession,Nu as readEnrolmentCallback,Ln as readPinnedRelayNodeKey,q as readRelayMap,Ho as redeemInvitation,Ts as relayForContext,Ye as relayTransportFetch,Kd as releaseAgent,_t as rememberGroupNamespace,Ae as rememberRelay,Or as reportDataOf,ot as requestBodyHash,Js as resolveApplicationIdFromRegistry,jn as resolveRelayFromInvitation,Ss as resolveRelayNodeKey,Y as resolveRoot,nn as resolveRootPair,wa as rootGuardedOpBytes,Bn as routingProofHeaders,As as saveDelegatedCredential,ys as saveDelegatedSession,Ut as selectLatestBundle,Ip as shouldRetain,Sr as signAccountHaClaim,pt as signAccountLink,rn as signAccountLogin,kc as signAccountOwnershipClaim,bn as signCreationWarrant,li as signDeviceCert,ui as signDeviceScope,vt as signGovernanceWarrant,Vn as signGroupInvitation,Nn as signLoginStatement,Jn as signMemberJoinOp,ba as signOwnerOpProof,Ht as signRequest,dr as signRequestProof,_s as signRoutingChallenge,hn as signWarrant,de as signedPath,ei as signerFromCryptoKey,Ue as signerFromSecret,gs as stateHash,qe as subgroupCreation,Pn as subgroupVisibilitySetOp,Xt as subscribePresence,vn as targetApplicationSetOp,fa as teeAdmissionPolicyOp,ma as teeAuthoringPolicyOp,ha as teeReleaseAdmissionPolicyOp,da as transferOwnershipOp,Ni as transportKeyBinding,Yi as trustSignedRelease,Kr as trustedMeasurementsFromReleases,Ga as validateAgentId,en as verifyDeviceCredential,Ld as verifySignedAgentPolicy,Wi as verifySignedNodeRelease,mr as withCap,Ft as withRetry,Cp as withoutCap};
1
+ function dr(t){let e=t.filter(Boolean);if(e.length===0)return;let n=AbortSignal;if(typeof n.any=="function")try{return n.any(e)}catch{}let r=new AbortController,o=i=>{r.abort(i.target.reason);for(let s of e)s.removeEventListener("abort",o)};for(let i of e){if(i.aborted)return AbortSignal.abort(i.reason);i.addEventListener("abort",o,{once:!0})}return r.signal}function pr(t){if(typeof AbortSignal.timeout=="function")return AbortSignal.timeout(t);let e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("Timeout","TimeoutError"))},t),e.signal}var Ko=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function R(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),e}function y(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function m(t,e,n){let r=t.trim();if(!/^[0-9a-fA-F]*$/.test(r)||r.length!==n*2)throw new Error(`${e} must be ${n*2} hex characters, got ${r.length}`);let o=new Uint8Array(n);for(let i=0;i<n;i+=1)o[i]=Number.parseInt(r.slice(i*2,i*2+2),16);return o}function j(t,e){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2!==0)throw new Error(`${e} must be an even number of hex characters`);let r=new Uint8Array(n.length/2);for(let o=0;o<r.length;o+=1)r[o]=Number.parseInt(n.slice(o*2,o*2+2),16);return r}function C(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function f(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}async function E(t,e){let n=[C(t.length),t];for(let r of e)n.push(C(r.length),r);return new Uint8Array(await crypto.subtle.digest("SHA-256",f(...n)))}async function re(t){let e=m(t,"deviceSecret",32),n=f(Ko,e);try{return await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!1,["sign"])}catch(r){let o=r instanceof Error?`: ${r.message}`:"";throw new Error("this runtime has no WebCrypto Ed25519, so a warrant cannot be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it; otherwise mint the warrant with `merod account warrant`"+o)}}async function $o(t,e,n){let r=await crypto.subtle.importKey("raw",m(t,"publicKey",32),{name:"Ed25519"},!1,["verify"]);return crypto.subtle.verify({name:"Ed25519"},r,e,n)}async function oe(t){let e=m(t,"deviceSecret",32),n=f(Ko,e),r=await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),i=(await crypto.subtle.exportKey("jwk",r)).x;return Uint8Array.from(atob(i.replace(/-/g,"+").replace(/_/g,"/")),s=>s.charCodeAt(0))}var gr=new TextEncoder().encode("calimero.auth.request.v2"),Ya=new TextEncoder().encode("calimero.auth.request.body.v1");function Lo(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}async function st(t=new Uint8Array(0)){let e=typeof t=="string"?new TextEncoder().encode(t):t;return E(Ya,[e])}async function qt(t){let e=await re(t.signerSecret),n=await st(t.body),r=C(t.issuedAt),o=C(t.expiresAt),i=new TextEncoder,s=await E(gr,[i.encode(t.method),i.encode(t.path),n,r,o]),a=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},e,s));return y(f(Lo(t.method),Lo(t.path),n,r,o,a))}var Ie=t=>new TextEncoder().encode(t),Pe="X-Calimero-Proof",Xa=300;async function mr(t){let{method:e,path:n,credential:r}=t;if(!e)throw new Error("signRequestProof needs the method the request will use");if(!n.startsWith("/"))throw new Error(`signRequestProof needs a path, got ${JSON.stringify(n)}`);let o=await st(t.body),i=Math.floor(t.now??Date.now()/1e3),s=i+(t.validForSeconds??Xa),a=await E(gr,[Ie(e),Ie(n),o,C(i),C(s)]),c=await Za(a,t);if(c.length!==64)throw new Error(`the signer returned ${c.length} bytes, not a 64-byte signature`);let u=f(R(Ie(e).length),Ie(e),R(Ie(n).length),Ie(n),o,C(i),C(s),c),d=ec(r,"credential");return y(f(d,new Uint8Array([0]),u))}async function Za(t,e){if(e.signer)return e.signer.sign(t);if(!e.deviceSecret)throw new Error("signRequestProof needs either `deviceSecret` or `signer`");let n=await re(e.deviceSecret);return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,t))}function ec(t,e){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2!==0)throw new Error(`${e} is not an even-length hex string`);return m(n,e,n.length/2)}function fr(t){if(!t.credential)throw new Error("a proof authorizer needs the `credential` from signDeviceCert");if(!t.deviceSecret&&!t.signer)throw new Error("a proof authorizer needs either `deviceSecret` or `signer`");return async({method:e,path:n,body:r})=>{let o=await mr({method:e,path:n,body:r,credential:t.credential,deviceSecret:t.deviceSecret,signer:t.signer,validForSeconds:t.validForSeconds});return{[Pe]:o}}}function pe(t){let e=new URL(t,globalThis.location?.href??"http://localhost");return e.pathname+e.search}var tc=new Set(["token_reuse","token_revoked"]);function nc(t){if(t)try{let e=JSON.parse(t),n=e?.error;if(typeof n=="string"&&n.trim()!=="")return n;let r=n?.message;if(typeof r=="string"&&r.trim()!=="")return r;let o=e?.detail;if(typeof o=="string"&&o.trim()!=="")return o}catch{}}var O=class extends Error{constructor(n,r,o,i,s){let a=nc(s)??(n===0&&s?.trim()?s.trim():void 0);super(a?`HTTP ${n} ${r}: ${a}`:`HTTP ${n} ${r}`);this.status=n;this.statusText=r;this.url=o;this.headers=i;this.bodyText=s;this.name="HTTPError";this.explanation=a}toJSON(){return{status:this.status,statusText:this.statusText,url:this.url,headers:Ho(this.headers),bodyText:this.bodyText}}},ie=class extends O{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.reason=n;this.name="AuthRevokedError";this.message=`Authentication revoked (${n}): HTTP ${r} ${o}`}},Te=class extends Error{constructor(){super(...arguments);this.name="RequestAuthError"}};function Ho(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function rc(t){let e;try{e=new URL(t,globalThis.location?.href)}catch{return t}return e.search===""&&(e.search=""),e.href}function jt(t){return Object.keys(t).some(e=>e.toLowerCase()===Pe.toLowerCase())}function Ft(t,e){if(t.type==="opaqueredirect"||t.status>=300&&t.status<400)throw new O(0,"Redirect Not Followed",e,t.headers,`the node answered with a redirect; a request carrying ${Pe} is not followed to another location`)}var at=class{constructor(e){this.transport=e;this.refreshTokenPromise=null;this.onTokenRefreshPromise=null}async get(e,n){return this.request(e,{...n,method:"GET"})}async post(e,n,r){return this.request(e,{...r,method:"POST",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async put(e,n,r){return this.request(e,{...r,method:"PUT",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async delete(e,n){return this.request(e,{...n,method:"DELETE"})}async patch(e,n,r){return this.request(e,{...r,method:"PATCH",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async head(e,n){let r=await this.makeRequest(e,{...n,method:"HEAD",parse:"response"});return{headers:Ho(r.headers),status:r.status}}async request(e,n){return this.makeRequest(e,n)}async makeRequest(e,n,r=0,o){let s=rc(this.buildUrl(e)),a=o??Date.now(),c=this.createAbortSignal(n),u=await this.buildHeaders(n?.headers),d;u instanceof Headers?(d={},u.forEach((b,k)=>{d[k]=b})):d=u;let l=n?.method||"GET";if(this.transport.authorizeRequest){let b=n?.body;if(b!==void 0&&typeof b!="string"&&!(b instanceof Uint8Array))throw new Error("this transport authorizes each request against its body, so the body must be a string or Uint8Array \u2014 a stream cannot be signed, because the signature would have to read bytes the request then cannot send.");Object.assign(d,await this.transport.authorizeRequest({method:l,path:pe(s),body:b}))}let p={method:l,headers:d},x=n?.body instanceof ReadableStream||typeof n?.body=="object"&&n?.body!==null&&"getReader"in n.body&&!(n.body instanceof Blob);(n?.body!==void 0&&!x||n?.body!==void 0&&x&&r===0)&&(p.body=n.body);let v;if(r>0&&o!==void 0){let b=n?.timeoutMs||this.transport.timeoutMs;if(b){let k=Date.now()-a,T=Math.max(0,b-k);v=this.createAbortSignal({...n,timeoutMs:T})}else v=this.createAbortSignal(n)}else v=c;if(v&&(p.signal=v),this.transport.credentials!==void 0&&(p.credentials=this.transport.credentials),n?.mode!==void 0&&(p.mode=n.mode),n?.cache!==void 0&&(p.cache=n.cache),n?.redirect!==void 0&&(p.redirect=n.redirect),n?.referrer!==void 0&&(p.referrer=n.referrer),n?.referrerPolicy!==void 0&&(p.referrerPolicy=n.referrerPolicy),n?.integrity!==void 0&&(p.integrity=n.integrity),n?.keepalive!==void 0&&(p.keepalive=n.keepalive),this.transport.getProof){let b=await this.transport.getProof({method:p.method??"GET",path:pe(s),body:p.body});b&&(d["X-Calimero-Proof"]=b)}let P=jt(d);P&&p.redirect!=="error"&&(p.redirect="manual");try{let b=await this.transport.fetch(s,p);if(P&&Ft(b,s),!b.ok){let k=await this.getBodyText(b),T=new O(b.status,b.statusText,s,b.headers,k),H=b.headers.get("x-auth-error");if((b.status===401||b.status===403)&&H&&tc.has(H)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new ie(H,b.status,b.statusText,s,b.headers,k)}let Q=n?.signal?.aborted===!0;if(b.status===401&&this.transport.refreshToken&&H==="token_expired"&&r<1&&!x&&!Q)try{let h=this.refreshTokenPromise;h||(h=this.transport.refreshToken(),this.refreshTokenPromise=h);let w=await h;if(!w||w.trim()==="")throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("Refresh token returned empty token");if(!this.transport.onTokenRefresh)throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("onTokenRefresh callback is required when refreshToken is provided. The callback must update the token storage so getAuthToken() returns the new token.");let S=this.onTokenRefreshPromise;S||(S=this.transport.onTokenRefresh(w),this.onTokenRefreshPromise=S),await S,this.refreshTokenPromise=null,this.onTokenRefreshPromise=null;let U=n?.timeoutMs||this.transport.timeoutMs;if(U&&o!==void 0){let M=Date.now()-a;if(U-M<=0)throw T}return this.makeRequest(e,n,r+1,a)}catch(h){throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,h instanceof Error&&h.message.includes("onTokenRefresh")?h:T}throw T}return this.parseResponse(b,n?.parse)}catch(b){throw b instanceof O||b instanceof Error&&b.message.includes("onTokenRefresh")?b:new O(0,"Network Error",s,new Headers,b instanceof Error?b.message:"Unknown error")}}buildUrl(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;let n=this.transport.baseUrl;return e.startsWith("/")?`${n.endsWith("/")?n.slice(0,-1):n}${e}`:`${n.endsWith("/")?n:`${n}/`}${e}`}createAbortSignal(e){let n=[];this.transport.defaultAbortSignal&&n.push(this.transport.defaultAbortSignal),e?.signal&&n.push(e.signal);let r=e?.timeoutMs||this.transport.timeoutMs;return r&&n.push(pr(r)),n.length>0?dr(n):void 0}async buildHeaders(e){let n={...this.transport.defaultHeaders};if(this.transport.getAuthToken)try{let r=await this.transport.getAuthToken();r&&r.trim()!==""&&(n.Authorization=`Bearer ${r}`)}catch(r){if(r instanceof Te)throw r}return e&&(e instanceof Headers?e.forEach((r,o)=>{n[o]=r}):Array.isArray(e)?e.forEach(([r,o])=>{n[r]=o}):Object.assign(n,e)),n}async parseResponse(e,n){switch(n){case"text":return await e.text();case"blob":return await e.blob();case"arrayBuffer":return await e.arrayBuffer();case"response":return e;default:{let r=await e.text();if(!r)return null;try{return JSON.parse(r)}catch{throw new Error(`Expected a JSON response (status ${e.status}) but body was not JSON: ${r.slice(0,200)}`)}}}}async getBodyText(e){try{let n=await e.text();return n.length>65536?n.slice(0,65536)+"...":n}catch{return""}}};function ct(t){return new at(t)}function De(t){let e={fetch:(n,r)=>t.fetch?t.fetch(n,r):globalThis.fetch(n,r),baseUrl:t.baseUrl,getAuthToken:t.getAuthToken,getProof:t.getProof,onTokenRefresh:t.onTokenRefresh,refreshToken:t.refreshToken,onAuthRevoked:t.onAuthRevoked,defaultHeaders:t.defaultHeaders,timeoutMs:t.timeoutMs,credentials:t.credentials,defaultAbortSignal:t.defaultAbortSignal};return ct(e)}function Vt(t){let e=t.fetch??globalThis.fetch;if(!e)throw new Error("No fetch implementation available. Please provide a fetch implementation (e.g., undici.fetch) or use Node.js 18+ which has native fetch support.");let r={fetch:e===globalThis.fetch?(o,i)=>globalThis.fetch(o,i):(o,i)=>e(o,i),baseUrl:t.baseUrl,getAuthToken:t.getAuthToken,getProof:t.getProof,onTokenRefresh:t.onTokenRefresh,refreshToken:t.refreshToken,onAuthRevoked:t.onAuthRevoked,defaultHeaders:t.defaultHeaders,timeoutMs:t.timeoutMs,credentials:t.credentials,defaultAbortSignal:t.defaultAbortSignal};return ct(r)}function hr(t){return typeof window<"u"?De(t):Vt(t)}function oc(t,e){if(e<=0)return!1;let r=t?.name;if(r==="TimeoutError")return!0;if(r==="AbortError")return!1;let o=t;if("status"in o&&typeof o.status=="number"){let i=o.status;return i>=500||i===429}return r==="TypeError"}function ic(t){let n=250*Math.pow(2,t-1),r=(Math.random()-.5)*.4*n;return Math.max(0,n+r)}async function Wt(t,e={}){let{attempts:n=3}=e,r;for(let o=1;o<=n;o++)try{return await t(o)}catch(i){if(r=i,!oc(r,n-o))throw r;let s=ic(o),u=r.headers?.get?.("Retry-After");if(u){let d=parseInt(u,10);if(!isNaN(d))s=Math.max(s,d*1e3);else{let l=new Date(u);if(!isNaN(l.getTime())){let p=Math.max(0,l.getTime()-Date.now());s=Math.max(s,Math.min(p,6e4))}}}await new Promise(d=>setTimeout(d,s))}throw r||new Error("Retry failed without error")}function sc(t,e={}){return async(...n)=>Wt(()=>t(...n),e)}function g(t){if(t===""||t==="."||t==="..")throw new TypeError(`invalid request path segment: ${JSON.stringify(t)}`);return encodeURIComponent(t)}var ge=class{constructor(e){this.httpClient=e}async getHealth(){let e=await this.httpClient.get("/auth/health");if(!e.data)throw new Error("Health response data is null");return e.data}async getIdentity(){let e=await this.httpClient.get("/admin/identity");if(!e.data)throw new Error("Identity response data is null");return e.data}async getProviders(){let e=await this.httpClient.get("/auth/providers");if(!e.data)throw new Error("Providers response data is null");return e.data}async getLoginPage(){return this.httpClient.get("/auth/login",{parse:"text"})}async generateTokens(e){return this.httpClient.post("/auth/token",e)}async refreshToken(e){return this.httpClient.post("/auth/refresh",e)}async generateMockTokens(e){return this.httpClient.post("/auth/mock-token",e)}async validateToken(e){try{let n=await this.validateTokenGet(e);return{valid:n.status===200,headers:n.headers,status:n.status}}catch{return{valid:!1,headers:{},status:401}}}async validateTokenGet(e){let n=await this.httpClient.head("/auth/validate",{headers:{Authorization:`Bearer ${e}`}});return{status:n.status,headers:n.headers}}async revokeTokens(e){let n=await this.httpClient.post("/admin/revoke",e);if(!n.data)throw new Error("Revoke tokens response data is null");return n.data}async listRootKeys(){let e=await this.httpClient.get("/admin/keys");if(!e.data)throw new Error("Root keys response data is null");return e.data}async createRootKey(e){let n=await this.httpClient.post("/admin/keys",e);if(!n.data)throw new Error("Create root key response data is null");return n.data}async deleteRootKey(e){return this.httpClient.delete(`/admin/keys/${g(e)}`)}async listClientKeys(){let e=await this.httpClient.get("/admin/keys/clients");if(!e.data)throw new Error("Client keys response data is null");return e.data}async generateClientKey(e){return this.httpClient.post("/admin/client-key",e)}async deleteClientKey(e,n){return this.httpClient.delete(`/admin/keys/${g(e)}/clients/${g(n)}`)}async getKeyPermissions(e){return this.httpClient.get(`/admin/keys/${g(e)}/permissions`)}async updateKeyPermissions(e,n){return this.httpClient.put(`/admin/keys/${g(e)}/permissions`,{add:n.add,remove:n.remove})}};var lt=class{async get(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async post(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async put(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async delete(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async patch(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async head(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async request(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}};function xp(t){let e=new lt;return new ge(e)}function vp(t){let e=new lt;return new ge(e)}function Rp(t){let e=new lt;return new ge(e)}function Bo(t,e){return new ge(t)}var _={CAN_CREATE_CONTEXT:1,CAN_INVITE_MEMBERS:2,CAN_JOIN_OPEN_SUBGROUPS:4,MANAGE_MEMBERS:8,MANAGE_APPLICATION:16,CAN_CREATE_SUBGROUP:32,CAN_DELETE_SUBGROUP:64,CAN_MANAGE_VISIBILITY:128,CAN_MANAGE_METADATA:256,CAN_AUTHOR_ON_BEHALF:512},Sp={NONE:0,JOIN_ONLY:_.CAN_JOIN_OPEN_SUBGROUPS,CONTRIBUTOR:_.CAN_CREATE_CONTEXT|_.CAN_INVITE_MEMBERS|_.CAN_JOIN_OPEN_SUBGROUPS,COLLABORATOR:_.CAN_CREATE_CONTEXT|_.CAN_INVITE_MEMBERS|_.CAN_JOIN_OPEN_SUBGROUPS|_.CAN_CREATE_SUBGROUP|_.CAN_DELETE_SUBGROUP|_.CAN_MANAGE_VISIBILITY};function kp(...t){let e=0;for(let n of t)if(typeof n=="number")e|=n;else if(Object.prototype.hasOwnProperty.call(_,n))e|=_[n];else throw new Error(`unknown capability: ${String(n)}`);return e>>>0}function Ep(t){return Object.keys(_).filter(e=>me(t,_[e]))}function me(t,e){let n=e>>>0;return(t&n)>>>0===n}function yr(t,e){return(t|e)>>>0}function Ip(t,e){return(t&~e)>>>0}var F=class extends Te{constructor(n,r){let o=ac(r),i=r instanceof Error?r.message:String(r);super(o==="signed-out"?`the relay ${n} refused this device's credential (${i}); sign in again`:`could not log in to the relay ${n}: ${i}`);this.name="RelayLoginError";this.cause=r,this.relayUrl=n,this.kind=o,this.loginStatus=qo(r)}};function ac(t){let e=qo(t);return e===401||e===403?"signed-out":"unavailable"}function qo(t){let e=t?.status;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var jo={invalid:!1,unauthorized:!0,forbidden:!1,"not-found":!0,conflict:!1,gone:!1,"too-large":!1,"rate-limited":!0,unavailable:!0,server:!0,unreachable:!0,unknown:!0};function Fo(t){switch(t){case 0:return"unreachable";case 400:return"invalid";case 401:return"unauthorized";case 403:return"forbidden";case 404:return"not-found";case 409:return"conflict";case 410:return"gone";case 413:return"too-large";case 429:return"rate-limited";case 503:case 504:return"unavailable"}return t>=500&&t<600?"server":t>=400&&t<500?"invalid":"unknown"}function cc(t){if(!t||typeof t!="object")return;let e=t;for(let n of[e.status,e.response?.status,e.statusCode])if(typeof n=="number"&&Number.isFinite(n))return n}function Jt(t,e="Request failed"){if(typeof t=="string")return t.trim()||e;if(!t||typeof t!="object")return e;let n=t;for(let r of[n.explanation,n.response?.data?.error,n.response?.data?.message,n.data?.message,n.error,n.message])if(typeof r=="string"&&r.trim())return r;return e}function br(t){if(t instanceof F){let r=t.loginStatus,o=t.kind==="signed-out"?"unauthorized":r?Fo(r):"unreachable";return{kind:o,status:r,retryable:jo[o],message:Jt(t)}}let e=cc(t),n;return e!==void 0?n=Fo(e):t instanceof TypeError?n="unreachable":n="unknown",{kind:n,status:e,retryable:jo[n],message:Jt(t)}}function lc(t){return t.status!=="failed"||!t.retryable}function Mp(t){return!lc(t)}var uc={invitation_expired:"expired",invitation_invalid:"invalid",invitation_already_used:"already-used",removed_from_group:"removed",reentry_blocked:"refused"};function dc(t){if(!t||typeof t!="object")return;let e=t;if(typeof e.response?.data?.code=="string")return e.response.data.code;if(typeof e.bodyText=="string")try{let n=JSON.parse(e.bodyText);return typeof n?.code=="string"?n.code:void 0}catch{return}}function pc(t){let e=t.toLowerCase();return e.includes("invitation has expired")||e.includes("invitation expired")||/\binvitation for group .+? expired at \d+/.test(e)?"expired":e.includes("malformed")||e.includes("does not match namespace_id")||e.includes("invalid invitation")||/\binvitation for group .+? is invalid:/.test(e)?"invalid":e.includes("has already used this invitation")?"already-used":/\bwas removed from group\b/.test(e)?"removed":null}var gc=new Set(["already-used","removed"]);function mc(t,e){if(t instanceof F)return{reason:t.kind==="signed-out"?"signed-out":"node-unreachable",retryable:!0};let{kind:n,status:r}=br(t),o=pc(e),i=dc(t),s=i?uc[i]:void 0;return s?{reason:s,retryable:!1}:o&&gc.has(o)?{reason:o,retryable:!1}:i==="join_refused_by_member"?{reason:"unknown",retryable:!0}:r===401?{reason:"signed-out",retryable:!0}:r===400?{reason:o??"invalid",retryable:!1}:r===410?{reason:"expired",retryable:!1}:r===403?{reason:"refused",retryable:!1}:r===409?{reason:o??"refused",retryable:!1}:n==="unavailable"?{reason:"no-one-online",retryable:!0}:n==="unreachable"?{reason:"node-unreachable",retryable:!0}:o?{reason:o,retryable:!1}:{reason:"unknown",retryable:!0}}async function Vo(t,e){let{namespaceId:n,invitation:r,teamName:o}=t,i=null;try{await e.join(n,r)}catch(d){i=d}let s=null;try{s=(await e.memberships()).includes(n)}catch{s=null}if(i===null)return{status:"joined",namespaceId:n,teamName:o};if(s===!0)return{status:"already-member",namespaceId:n,teamName:o};let a=Jt(i,"Could not join. Check the invitation."),{reason:c,retryable:u}=mc(i,a);return{status:"failed",namespaceId:n,message:a,reason:c,retryable:u}}function A(t){return t?.data}function fc(t,e){let[n,r]=Wo(t),[o,i]=Wo(e),s=n.split("."),a=o.split("."),c=Math.max(s.length,a.length);for(let p=0;p<c;p++){let x=Jo(s[p]??"0",a[p]??"0");if(x!==0)return x}if(r===void 0&&i===void 0)return 0;if(r===void 0)return 1;if(i===void 0)return-1;let u=r.split("."),d=i.split("."),l=Math.max(u.length,d.length);for(let p=0;p<l;p++){if(p>=u.length)return-1;if(p>=d.length)return 1;let x=Jo(u[p],d[p]);if(x!==0)return x}return 0}function Wo(t){let e=t.split("+",1)[0],n=e.indexOf("-");return n===-1?[e,void 0]:[e.slice(0,n),e.slice(n+1)]}function Jo(t,e){let n=/^\d+$/.test(t),r=/^\d+$/.test(e);if(n&&r){let o=Number(t)-Number(e);return o<0?-1:o>0?1:0}return n?-1:r?1:t<e?-1:t>e?1:0}async function hc(t,e,n){return Wt(async()=>{let r=await fetch(t,{signal:AbortSignal.timeout(1e4)});if(!r.ok){let o=new Error(`registry ${e} fetch failed (${r.status}) for ${n}`);throw o.status=r.status,o}return r},{attempts:3})}var fe=class{constructor(e){this.httpClient=e}async healthCheck(){return A(await this.httpClient.get("/admin-api/health"))}async readinessCheck(){return A(await this.httpClient.get("/admin-api/ready"))}async isAuthed(){return this.httpClient.get("/admin-api/is-authed")}async installApplication(e){return A(await this.httpClient.post("/admin-api/install-application",e))}async getRegistryVersions(e,n){let r=new URL("/api/v2/bundles",new URL(e).origin);r.searchParams.set("package",n);let i=await(await hc(r.toString(),"versions",n)).json();return(Array.isArray(i)?i:[]).map(s=>s.appVersion).filter(s=>typeof s=="string").sort((s,a)=>fc(a,s))}async installDevApplication(e){return A(await this.httpClient.post("/admin-api/install-dev-application",e))}async uninstallApplication(e){return A(await this.httpClient.delete(`/admin-api/applications/${g(e)}`))}async listApplications(){return A(await this.httpClient.get("/admin-api/applications"))}async getApplication(e){return A(await this.httpClient.get(`/admin-api/applications/${g(e)}`))}async listApplicationVersions(e){return A(await this.httpClient.get(`/admin-api/applications/${g(e)}/versions`))}async getApplicationAbi(e,n){let r=n?`?service_name=${encodeURIComponent(n)}`:"";return A(await this.httpClient.get(`/admin-api/applications/${g(e)}/abi${r}`))}async listPackages(){let e=await this.httpClient.get("/admin-api/packages");return e?.data??e}async listPackageVersions(e){let n=await this.httpClient.get(`/admin-api/packages/${g(e)}/versions`);return n?.data??n}async getLatestPackageVersion(e){return this.httpClient.get(`/admin-api/packages/${g(e)}/latest`)}async createContext(e){let n={...e,initializationParams:e.initializationParams??[]};return A(await this.httpClient.post("/admin-api/contexts",n))}async deleteContext(e){return A(await this.httpClient.delete(`/admin-api/contexts/${g(e)}`))}async getContexts(){return A(await this.httpClient.get("/admin-api/contexts"))}async getContext(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}`))}async getContextsForApplication(e){return A(await this.httpClient.get(`/admin-api/contexts/for-application/${g(e)}`))}async generateContextIdentity(){return A(await this.httpClient.post("/admin-api/identity/context",{}))}async getContextIdentities(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/identities`))}async getContextIdentitiesOwned(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/identities-owned`))}async joinContext(e){return A(await this.httpClient.post(`/admin-api/contexts/${g(e)}/join`,{}))}async getContextGroup(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/group`))}async getContextStorage(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/storage`))}async syncContext(e){let n=e?`/admin-api/contexts/sync/${g(e)}`:"/admin-api/contexts/sync";await this.httpClient.post(n,{})}async resyncContext(e,n={}){return await this.httpClient.post(`/admin-api/contexts/${g(e)}/resync`,n)??{contextId:e,resyncStarted:!0}}async updateContextApplication(e,n){await this.httpClient.post(`/admin-api/contexts/${g(e)}/application`,n)}async getContextsWithExecutorsForApplication(e){let n=await this.httpClient.get(`/admin-api/contexts/with-executors/for-application/${g(e)}`);return Array.isArray(n)?n:n?.contexts??n?.data??[]}async uploadBlob(e){let n=new URLSearchParams;e.hash&&n.set("hash",e.hash),e.contextId&&n.set("context_id",e.contextId);let r=n.toString(),o=r?`/admin-api/blobs?${r}`:"/admin-api/blobs",i=A(await this.httpClient.request(o,{method:"PUT",body:e.data,headers:{"Content-Type":"application/octet-stream"}}));return{blobId:i.blob_id,size:i.size}}async deleteBlob(e){let n=await this.httpClient.delete(`/admin-api/blobs/${g(e)}`);return{blobId:n.blob_id,deleted:n.deleted}}async listBlobs(){return{blobs:A(await this.httpClient.get("/admin-api/blobs")).blobs.map(n=>({blobId:n.blob_id,size:n.size}))}}blobPath(e,n){if(!n?.contextId)return`/admin-api/blobs/${g(e)}`;let r=new URLSearchParams({context_id:n.contextId});return`/admin-api/blobs/${g(e)}?${r.toString()}`}async getBlob(e,n){return this.httpClient.get(this.blobPath(e,n),{parse:"arrayBuffer"})}async getBlobInfo(e,n){let{headers:r}=await this.httpClient.head(this.blobPath(e,n)),o=Number(r["content-length"]);return{blobId:r["x-blob-id"]??e,size:Number.isFinite(o)?o:0,hash:r["x-blob-hash"],mimeType:r["x-blob-mime-type"],source:r["x-blob-source"]}}async createContextAlias(e){return A(await this.httpClient.post("/admin-api/alias/create/context",{alias:e.alias,contextId:e.contextId}))}async createApplicationAlias(e){return A(await this.httpClient.post("/admin-api/alias/create/application",{alias:e.alias,applicationId:e.applicationId}))}async lookupContextAlias(e){return A(await this.httpClient.post(`/admin-api/alias/lookup/context/${g(e)}`,{}))}async lookupApplicationAlias(e){return A(await this.httpClient.post(`/admin-api/alias/lookup/application/${g(e)}`,{}))}async deleteContextAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/context/${g(e)}`,{}))}async deleteApplicationAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/application/${g(e)}`,{}))}async listContextAliases(){return A(await this.httpClient.get("/admin-api/alias/list/context"))}async listApplicationAliases(){return A(await this.httpClient.get("/admin-api/alias/list/application"))}async createDeviceAlias(e){return A(await this.httpClient.post("/admin-api/alias/create/device",{alias:e.alias,deviceId:e.deviceId}))}async lookupDeviceAlias(e){return A(await this.httpClient.post(`/admin-api/alias/lookup/device/${g(e)}`,{}))}async deleteDeviceAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/device/${g(e)}`,{}))}async listDeviceAliases(){return A(await this.httpClient.get("/admin-api/alias/list/device"))}async listNamespaces(){return A(await this.httpClient.get("/admin-api/namespaces"))}async getNamespace(e){return A(await this.httpClient.get(`/admin-api/namespaces/${g(e)}`))}async getNodeIdentity(){return A(await this.httpClient.get("/admin-api/identity"))}async performIntent(e,n){return A(await this.httpClient.post(`/admin-api/contexts/${g(e)}/intents`,n))}async queryContext(e,n){return A(await this.httpClient.post(`/admin-api/contexts/${g(e)}/query`,n))}async getIntentRelay(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/intents`))}async listNamespacesForApplication(e){return A(await this.httpClient.get(`/admin-api/namespaces/for-application/${g(e)}`))}async createNamespace(e){return A(await this.httpClient.post("/admin-api/namespaces",e))}async deleteNamespace(e){return A(await this.httpClient.request(`/admin-api/namespaces/${g(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async createNamespaceInvitation(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/invite`,n??{}))}async admitJoin(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/admit`,n,{timeoutMs:65e3}))}async joinNamespace(e,n){let r=A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/join`,n,{timeoutMs:65e3}));return r&&r.namespaceId===void 0&&r.groupId!==void 0?{...r,namespaceId:r.groupId}:r}async redeemInvitation(e,n,r={}){let{groupName:o,teamName:i}=r;return Vo({namespaceId:e,invitation:n,teamName:i},{join:async()=>{await this.joinNamespace(e,o===void 0?{invitation:n}:{invitation:n,groupName:o})},memberships:async()=>(await this.listNamespaces()??[]).map(s=>s.namespaceId)})}async createGroupInNamespace(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/groups`,n??{}))}async listNamespaceGroups(e){return A(await this.httpClient.get(`/admin-api/namespaces/${g(e)}/groups`))}async initAccountPairing(e){return A(await this.httpClient.post("/admin-api/account/pair-init",e))}async completeAccountPairing(e){return A(await this.httpClient.post("/admin-api/account/pair-complete",e))}async relinkAccountDevice(e,n){return A(await this.httpClient.post(`/admin-api/account/devices/${g(e)}/relink`,n??{}))}async rescopeAccountDevice(e,n){return A(await this.httpClient.put(`/admin-api/account/devices/${g(e)}/scope`,n))}async signWithAccountRoot(e){return A(await this.httpClient.post("/admin-api/account/sign-with-root",e))}async labelAccountDevice(e,n){return A(await this.httpClient.put(`/admin-api/account/devices/${g(e)}/label`,n))}async listAccountDevices(){return(await this.httpClient.get("/admin-api/account/devices")).devices}async listAccountApplications(){return(await this.httpClient.get("/admin-api/account/applications")).applications}async revokeAccountDevice(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/account/revoke`,n))}async linkAccountDevice(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/account/link-device`,n))}async getGroupInfo(e){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}`))}async getDefaultCapabilities(e){return(await this.getGroupInfo(e)).defaultCapabilities}async getSubgroupVisibility(e){return(await this.getGroupInfo(e)).subgroupVisibility}async deleteGroup(e){return A(await this.httpClient.request(`/admin-api/groups/${g(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async listGroupMembers(e){let n=await this.httpClient.get(`/admin-api/groups/${g(e)}/members`);if(!Array.isArray(n?.members)){let r=String(e).replace(/[\r\n\t\s]/g,"").slice(0,64);throw new Error(`Invalid listGroupMembers response for group ${r}: missing or non-array \`members\` field`)}return n}async listGroupMemberDevices(e,n){let r=new URLSearchParams;n?.offset!==void 0&&r.set("offset",String(n.offset)),n?.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${g(e)}/member-devices`;return(await this.httpClient.get(o?`${i}?${o}`:i)).members}async listMemberDevices(e,n={}){let r=new URLSearchParams;n.offset!==void 0&&r.set("offset",String(n.offset)),n.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${g(e)}/member-devices${o?`?${o}`:""}`;return this.httpClient.get(i)}async sealToAccount(e,n,r){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/accounts/${g(n)}/seal`,r))}async listGroupContexts(e){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}/contexts`))}async addGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${g(e)}/members`,n)}async removeGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${g(e)}/members/remove`,n)}async updateMemberRole(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/members/${g(n)}/role`,r)}async getMemberCapabilities(e,n){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}/members/${g(n)}/capabilities`))}async setMemberCapabilities(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/members/${g(n)}/capabilities`,r)}async setDefaultCapabilities(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/settings/default-capabilities`,n)}async openToDelegatedExecution(e){let n=await this.getDefaultCapabilities(e);if(me(n,_.CAN_AUTHOR_ON_BEHALF))return{changed:!1,defaultCapabilities:n};let r=yr(n,_.CAN_AUTHOR_ON_BEHALF);return await this.setDefaultCapabilities(e,{defaultCapabilities:r}),{changed:!0,defaultCapabilities:r}}async grantAuthorship(e,n){let{capabilities:r}=await this.getMemberCapabilities(e,n);if(me(r,_.CAN_AUTHOR_ON_BEHALF))return{changed:!1,capabilities:r};let o=yr(r,_.CAN_AUTHOR_ON_BEHALF);return await this.setMemberCapabilities(e,n,{capabilities:o}),{changed:!0,capabilities:o}}async setSubgroupVisibility(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/settings/subgroup-visibility`,n)}async setTeeAdmissionPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/settings/tee-admission-policy`,n)}async getTeeAdmissionPolicy(e){let n=await this.httpClient.get(`/admin-api/groups/${g(e)}/settings/tee-admission-policy`);return n.data??n}async setTeeAuthoringPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/settings/tee-authoring-policy`,n)}async disableTeeAuthoringPolicy(e,n={}){let r=`/admin-api/groups/${g(e)}/settings/tee-authoring-policy`;if(n.rootProof===void 0){await this.httpClient.delete(r);return}await this.httpClient.request(r,{method:"DELETE",body:JSON.stringify({rootProof:n.rootProof}),headers:{"Content-Type":"application/json"}})}async transferOwnership(e,n){await this.httpClient.post(`/admin-api/groups/${g(e)}/transfer-ownership`,n)}async changeNamespaceAdmin(e,n){await this.httpClient.post(`/admin-api/namespaces/${g(e)}/admin`,n)}async ownerDeleteGroup(e,n={}){await this.httpClient.post(`/admin-api/groups/${g(e)}/owner-delete`,n)}async setGroupMetadata(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/metadata`,n)}async getGroupMetadata(e){return(await this.httpClient.get(`/admin-api/groups/${g(e)}/metadata`))?.data??null}async setMemberMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/members/${g(n)}/metadata`,r)}async getMemberMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${g(e)}/members/${g(n)}/metadata`))?.data??null}async setContextMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/contexts/${g(n)}/metadata`,r)}async getContextMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${g(e)}/contexts/${g(n)}/metadata`))?.data??null}async syncGroup(e){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/sync`,{}))}async upgradeGroup(e,n){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/upgrade`,n))}async getGroupUpgradeStatus(e){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}/upgrade/status`))}async getMigrationStatus(e){return this.httpClient.get(`/admin-api/groups/${g(e)}/migration-status`)}async listNamespaceRevokedDevices(e){return this.httpClient.get(`/admin-api/namespaces/${g(e)}/revoked-devices`)}async getCascadeStatus(e){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}/cascade-status`))}async activateGroupUpgrade(e,n={}){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/upgrade/activate`,n))}async retryGroupUpgrade(e){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/upgrade/retry`,{}))}async reparentGroup(e,n){let r=await this.httpClient.post(`/admin-api/groups/${g(e)}/reparent`,n);return r?.data??r}async listSubgroups(e){let n=await this.httpClient.get(`/admin-api/groups/${g(e)}/subgroups`);return n.subgroups??n.data??[]}async detachContextFromGroup(e,n){await this.httpClient.post(`/admin-api/groups/${g(e)}/contexts/${g(n)}/remove`,{})}async createGroupInvitation(e,n){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/invite`,n??{}))}async joinGroup(e){return A(await this.httpClient.post("/admin-api/groups/join",e))}async joinSubgroupInheritance(e){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/join-via-inheritance`,{}))}async getTeeInfo(){return A(await this.httpClient.get("/admin-api/tee/info"))}async teeAttest(e){return A(await this.httpClient.post("/admin-api/tee/attest",e))}async getPeersCount(){return this.httpClient.get("/admin-api/peers")}async getNetworkStatus(){return this.httpClient.get("/admin-api/network/status")}async getUsage(){return this.httpClient.get("/admin-api/usage")}async createGroup(e){return A(await this.httpClient.post("/admin-api/groups",e))}async leaveGroup(e){await this.httpClient.post(`/admin-api/groups/${g(e)}/leave`,{})}async leaveContext(e){await this.httpClient.post(`/admin-api/contexts/${g(e)}/leave`,{})}async leaveNamespace(e){await this.httpClient.post(`/admin-api/namespaces/${g(e)}/leave`,{})}async issueOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${g(e)}/issue-ownership-proof`,n)}async issueNamespaceOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${g(e)}/issue-namespace-ownership-proof`,n)}async setMemberAutoFollow(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/members/${g(n)}/auto-follow`,r)}async abortMigration(e){return this.httpClient.post(`/admin-api/groups/${g(e)}/migration/abort`,{})}};function jp(t){return Array.from(new TextEncoder().encode(t),e=>e.toString(16).padStart(2,"0")).join("")}function zp(t){return new fe(De(t))}function Qp(t){return new fe(Vt(t))}function zo(t){return new fe(hr(t))}function zt(t,e){return new fe(t)}var Qo="calimero.cloud.link.pending",wr="link_state",yc=600*1e3,Ar=/^[0-9a-f]{64}$/,bc=20,wc=32,xr=/^[0-9a-f]{64}$/,Ac="account-link-grant";function Yo(t,e){try{let n=localStorage.getItem(t),r=n?JSON.parse(n):{};return Object.fromEntries(Object.entries(r).filter(([,o])=>o&&typeof o.expiresAt=="number"&&o.expiresAt>e))}catch{return{}}}function Xo(t,e){try{localStorage.setItem(t,JSON.stringify(e))}catch{}}function ut(t,e){let n=Date.now(),r=Yo(t,n),o=y(crypto.getRandomValues(new Uint8Array(16)));return r[o]={...e,expiresAt:n+yc},Xo(t,Object.fromEntries(Object.entries(r).slice(-bc))),o}function Ue(t,e){let n=Yo(t,Date.now());if(!e||!Object.prototype.hasOwnProperty.call(n,e))return null;let r=n[e];return delete n[e],Xo(t,n),r}async function vr(t){let e=Uint8Array.from(t.match(/../g)??[],n=>parseInt(n,16));return y(new Uint8Array(await crypto.subtle.digest("SHA-256",e)))}async function Qt(t,e){if(!Ar.test(t))throw new Error("accountId must be 64 lowercase hex characters");let n=new URL(e),r=y(crypto.getRandomValues(new Uint8Array(wc))),o=await vr(r);return n.searchParams.set(wr,ut(Qo,{account:t,verifier:r})),{callbackUrl:n.toString(),challenge:o}}function Oe(t,e){let n=Ue(Qo,new URLSearchParams(t).get(wr));return!n||n.account!==e?null:typeof n.verifier=="string"&&xr.test(n.verifier)?n.verifier:null}function dt(t){try{let e=t.split(".")[0].replace(/-/g,"+").replace(/_/g,"/"),n=JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(e),a=>a.charCodeAt(0)))),{use:r,sub:o,acc:i,chal:s}=n;return r!==Ac||typeof o!="string"||typeof i!="string"||typeof s!="string"?null:{login:o,account:i,challenge:s}}catch{return null}}function Zo(t){let e=new URLSearchParams(t);e.delete(wr);let n=e.toString();return n?`?${n}`:""}var ei="calimero.auth.login.pending",ti="auth_state";function Rr(t,e={}){try{let n=t.indexOf("#");if(n===-1)return null;let r=t.substring(n+1),o=new URLSearchParams(r),i=o.get("access_token");return i?!e.allowUnsolicited&&!Ue(ei,xc(t,n))?(console.warn("[mero-js] ignoring auth callback tokens: they answer no login begun in this browser"),null):{accessToken:i,refreshToken:o.get("refresh_token")??"",applicationId:o.get("application_id")??"",contextId:o.get("context_id")??"",contextIdentity:o.get("context_identity")??"",nodeUrl:o.get("node_url")??""}:null}catch{return null}}function xc(t,e){let n=t.indexOf("?");return n===-1||n>e?null:new URLSearchParams(t.substring(n+1,e)).get(ti)}function Cr(t,e){let n=new URL(e.callbackUrl);n.searchParams.set(ti,ut(ei,{}));let r=new URLSearchParams;return r.set("callback-url",n.toString()),e.permissions&&e.permissions.length>0&&r.set("permissions",e.permissions.join(",")),r.set("mode",e.mode),e.packageName&&(r.set("package-name",e.packageName),e.packageVersion&&r.set("package-version",e.packageVersion),e.registryUrl&&r.set("registry-url",e.registryUrl)),`${t.replace(/\/+$/,"")}/auth/login?${r.toString()}`}function Yt(t){let e=j(t.credential,"credential"),n=j(t.request,"request signature"),r=t.session===void 0?new Uint8Array([0]):f(new Uint8Array([1]),j(t.session,"session statement"));return y(f(e,r,n))}function vc(t){if(t==null)return new Uint8Array(0);if(typeof t=="string"||t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error(`a request-carried proof cannot commit to a ${t?.constructor?.name??typeof t} body: pass a string or bytes, or use a session for this call`)}function Xt(t){let e=t.ttlSeconds??120,n=t.now??(()=>Math.floor(Date.now()/1e3));return async r=>{let o=n();return Yt({credential:t.credential,session:t.session,request:await qt({method:r.method,path:r.path,body:vc(r.body),issuedAt:o,expiresAt:o+e,signerSecret:t.signerSecret})})}}var Zt=class extends Error{constructor(e,n,r,o){super(n),this.name="RpcError",this.code=e,this.data=r,this.type=o}};async function Sr(t,e,n){let r=await t.post("/jsonrpc",{jsonrpc:"2.0",id:1,method:e,params:n});if(r.error){let o=r.error;throw new Zt(o.code??-1,o.message??o.type??"RPC error",o.data,o.type)}return r.result}var pt=class{constructor(e){this.kind="node";this.canSubscribe=!0;this.httpClient=e.httpClient}async execute(e){let n=await Sr(this.httpClient,"execute",{contextId:e.contextId,method:e.method,argsJson:e.argsJson??{}});return n&&"output"in n?n.output:n}async executeWithMetadata(e){return{returns:await this.execute(e),transport:"node"}}async migrateMyEntries(e){return this.execute({contextId:e,method:"migrate_my_entries"})}async countMyPending(e){return this.execute({contextId:e,method:"count_my_pending"})}};var Rc=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function ni(t){return t.type!==void 0&&Rc.has(t.type)}var Cc=new Set(["token_reuse","token_revoked"]),Sc=new Set([401,403]),kc=1e4;function ri(t){let e=t.headers.get("x-auth-error");return!e||!Sc.has(t.status)?null:Cc.has(e)?e:null}var B=class{constructor(e){this.sessionId=null;this.abortController=null;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.presence=new Map;this.closed=!1;this.listeners={connect:[],event:[],error:[]};if(this.baseUrl=e.baseUrl.replace(/\/+$/,""),e.authorize)this.authorize=e.authorize;else if(e.getAuthToken){let n=e.getAuthToken;this.authorize=async()=>({Authorization:`Bearer ${await n()}`})}else throw new Error("SseClient needs either `getAuthToken` or `authorize`");this.reconnectDelayMs=e.reconnectDelayMs??3e3,this.fetchImpl=(n,r)=>e.fetch?e.fetch(n,r):globalThis.fetch(n,r)}on(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(n)||o.push(n)}}off(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r],i=o.indexOf(n);i!==-1&&o.splice(i,1)}}onAppVersionChanged(e){let n=r=>{if(r.type!=="AppVersionChanged")return;let o=r.data;e({contextId:r.contextId,fromVersion:o?.fromVersion,toVersion:o?.toVersion})};return this.on("event",n),()=>this.off("event",n)}onMigrationEvent(e){let n=r=>{ni(r)&&e(r)};return this.on("event",n),()=>this.off("event",n)}emit(e,n){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(n)}catch{}}async connect(){if(this.abortController&&!this.closed)return;this.closed=!1;let e=new AbortController;this.abortController=e;try{let n=`${this.baseUrl}/sse`,r={...await this.authorize({method:"GET",path:pe(n)}),Accept:"text/event-stream"},o=jt(r),i=await this.fetchImpl(n,{headers:r,signal:e.signal,...o&&{redirect:"manual"}});if(o&&Ft(i,n),!i.ok){let s=ri(i),a=await i.text().catch(()=>{});throw s?new ie(s,i.status,i.statusText,n,i.headers,a):new O(i.status,i.statusText,n,i.headers,a)}if(!i.body)throw new Error("SSE response has no body");this.readStream(i.body,e).catch(s=>{if(this.superseded(e))return;let a=s instanceof Error?s:new Error(String(s));this.emit("error",a),this.scheduleReconnect()})}catch(n){if(this.superseded(e))return;let r=n instanceof Error?n:new Error(String(n));if(this.emit("error",r),r instanceof ie)return;this.scheduleReconnect()}}superseded(e){return this.closed||e.signal.aborted||this.abortController!==e}async readStream(e,n){let r=e.getReader(),o=new TextDecoder,i="";try{for(;;){let{done:s,value:a}=await r.read();if(s)break;i+=o.decode(a,{stream:!0});let c=i.split(`
2
+ `);i=c.pop()??"";for(let u of c)if(u.startsWith("data:")){let d=u.slice(5).trim();d&&this.handleMessage(d)}}if(i+=o.decode(),i.startsWith("data:")){let s=i.slice(5).trim();s&&this.handleMessage(s)}}catch(s){if(this.superseded(n))return;let a=s instanceof Error?s:new Error(String(s));this.emit("error",a)}this.superseded(n)||this.scheduleReconnect()}handleMessage(e){try{let n=JSON.parse(e);if(n.type==="connect"&&n.session_id){let o=n.session_id;if(this.sessionId=o,this.presence.clear(),this.subscribedContextIds.size===0&&this.subscribedGroupIds.size===0){this.emit("connect",o);return}this.postSubscription("subscribe",{contextIds:[...this.subscribedContextIds],groupIds:[...this.subscribedGroupIds]}).then(i=>{this.closed||this.sessionId!==o||(this.emit("connect",o),i&&this.emit("error",i))});return}if(!n.result)return;let r=n.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),i=new TextDecoder().decode(o);r=JSON.parse(i)}catch{}if(n.result.contextId){n.result.type==="Ephemeral"&&this.notePresence(n.result.contextId,r),this.emit("event",{contextId:n.result.contextId,type:n.result.type,data:r});return}n.result.groupId&&this.emit("event",{groupId:n.result.groupId,type:n.result.type,data:r})}catch{}}async subscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>!this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>!this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.add(i);for(let i of n.groupIds??[])this.subscribedGroupIds.add(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("subscribe",{contextIds:r,groupIds:o})}isSubscribed(e){return this.subscribedContextIds.has(e)}presenceSeed(e){let n=Date.now();return[...this.presence.get(e)?.values()??[]].map(({data:r,at:o})=>({...r,ageMs:(typeof r.ageMs=="number"?r.ageMs:0)+(n-o)}))}notePresence(e,n){if(!this.subscribedContextIds.has(e))return;let r=n;if(!r||typeof r.author!="string")return;let o=this.presence.get(e);o||this.presence.set(e,o=new Map),r.removed?o.delete(r.author):o.set(r.author,{data:r,at:Date.now()})}async unsubscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.delete(i),this.presence.delete(i);for(let i of n.groupIds??[])this.subscribedGroupIds.delete(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("unsubscribe",{contextIds:r,groupIds:o})}async sendSubscription(e,n){let r=await this.postSubscription(e,n);r&&this.emit("error",r)}async postSubscription(e,n){let r=new AbortController,o=setTimeout(()=>r.abort(new DOMException(`SSE ${e} timed out`,"TimeoutError")),kc);try{let i={};n.contextIds&&n.contextIds.length>0&&(i.contextIds=n.contextIds),n.groupIds&&n.groupIds.length>0&&(i.groupIds=n.groupIds);let s=`${this.baseUrl}/sse/subscription`,a=JSON.stringify({id:this.sessionId,method:e,params:i}),c={...await this.authorize({method:"POST",path:pe(s),body:a}),"Content-Type":"application/json"},u=jt(c),d=await this.fetchImpl(s,{method:"POST",headers:c,body:a,signal:r.signal,...u&&{redirect:"manual"}});if(u&&Ft(d,s),!d.ok){let l=ri(d),p=await d.text().catch(()=>{});return l?new ie(l,d.status,d.statusText,`${this.baseUrl}/sse/subscription`,d.headers,p):new O(d.status,d.statusText,`${this.baseUrl}/sse/subscription`,d.headers,p)}return null}catch(i){return i instanceof Error?i:new Error(`SSE ${e} failed`)}finally{clearTimeout(o)}}forceReconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.sessionId=null,this.connect()}scheduleReconnect(){this.closed||(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.forceReconnect()},this.reconnectDelayMs))}close(){this.closed=!0,this.abortController&&(this.abortController.abort(),this.abortController=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.sessionId=null,this.subscribedContextIds.clear(),this.subscribedGroupIds.clear()}};var en=class en{constructor(e){this.ws=null;this.closed=!1;this.reconnectAttempt=0;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.listeners={connect:[],event:[],error:[]};this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.getAuthToken=e.getAuthToken}on(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(n)||o.push(n)}}off(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r],i=o.indexOf(n);i!==-1&&o.splice(i,1)}}emit(e,n){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(n)}catch{}}async connect(){if(!(this.ws&&(this.ws.readyState===0||this.ws.readyState===1))){this.closed=!1;try{let e=await this.getAuthToken();if(!e)throw new Error("No authentication token available for WebSocket connection");let n=this.baseUrl.replace(/^http/,"ws");this.ws=new WebSocket(`${n}/ws?token=${encodeURIComponent(e)}`),this.ws.onopen=()=>{this.reconnectAttempt=0,this.emit("connect"),this.resubscribeAfterReconnect()},this.ws.onmessage=r=>{this.handleMessage(r.data)},this.ws.onerror=()=>{this.emit("error",new Error("WebSocket error"))},this.ws.onclose=()=>{this.closed||this.scheduleReconnect()}}catch(e){if(this.closed)return;let n=e instanceof Error?e:new Error(String(e));this.emit("error",n),this.scheduleReconnect()}}}handleMessage(e){if(typeof e=="string")try{let n=JSON.parse(e);if(!n.result)return;let r=n.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),i=new TextDecoder().decode(o);r=JSON.parse(i)}catch{}if(n.result.contextId){this.emit("event",{contextId:n.result.contextId,type:n.result.type,data:r});return}n.result.groupId&&this.emit("event",{groupId:n.result.groupId,type:n.result.type,data:r})}catch{}}subscribe(e){let n=Array.isArray(e)?{contextIds:e}:e;for(let r of n.contextIds??[])this.subscribedContextIds.add(r);for(let r of n.groupIds??[])this.subscribedGroupIds.add(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams(n.contextIds??[],n.groupIds??[])})}unsubscribe(e){let n=Array.isArray(e)?{contextIds:e}:e;for(let r of n.contextIds??[])this.subscribedContextIds.delete(r);for(let r of n.groupIds??[])this.subscribedGroupIds.delete(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"unsubscribe",params:this.buildSubscriptionParams(n.contextIds??[],n.groupIds??[])})}resubscribeAfterReconnect(){this.subscribedContextIds.size===0&&this.subscribedGroupIds.size===0||this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams([...this.subscribedContextIds],[...this.subscribedGroupIds])})}buildSubscriptionParams(e,n){let r={};return e.length>0&&(r.contextIds=e),n.length>0&&(r.groupIds=n),r}sendMessage(e){this.ws&&this.ws.readyState===1&&this.ws.send(JSON.stringify(e))}scheduleReconnect(){if(this.closed)return;this.reconnectTimer&&clearTimeout(this.reconnectTimer);let e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),en.MAX_BACKOFF_MS);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e)}close(){this.closed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscribedContextIds.clear(),this.subscribedGroupIds.clear()}};en.MAX_BACKOFF_MS=3e4;var se=en;function ae(){return{encode(t){return Array.from(new TextEncoder().encode(JSON.stringify(t)))},decode(t){return JSON.parse(new TextDecoder().decode(new Uint8Array(t)))}}}var gt=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,n,r=ae()){await Sr(this.httpClient,"set_ephemeral",{contextId:e,state:r.encode(n)})}subscribe(e,n,r=ae()){return tn(this.sse,e,n,r)}};function tn(t,e,n,r=ae()){let o=i=>{let s=i;if(s.type!=="Ephemeral"||s.contextId!==e)return;let a=s.data;if(!a?.author)return;let c=!!a.removed,u={author:a.author,state:c||a.state===void 0?void 0:r.decode(a.state),removed:c};a.ageMs!==void 0&&(u.ageMs=a.ageMs),a.account!==void 0&&(u.account=a.account),n(u)};if(t.on("event",o),t.isSubscribed?.(e))for(let i of t.presenceSeed?.(e)??[])o({contextId:e,type:"Ephemeral",data:i});return t.connect().catch(()=>{}),t.subscribe([e]).catch(()=>{}),()=>{t.off("event",o)}}var Ec=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function oi(t){let e=t instanceof Error?`: ${t.message}`:"";return new Error("this runtime has no WebCrypto Ed25519, so nothing can be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it"+e)}async function Ne(t,e="secret"){let n=m(t,e,32),r=f(Ec,n),o,i;try{let s=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!0,["sign"]),a=await crypto.subtle.exportKey("jwk",s);i=y(Uint8Array.from(atob(a.x.replace(/-/g,"+").replace(/_/g,"/")),c=>c.charCodeAt(0))),o=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!1,["sign"])}catch(s){throw oi(s)}return si(o,i)}async function ii(t,e){if(t.type!=="private")throw new Error(`signerFromCryptoKey needs the private half of the pair, got a ${t.type} key`);if(!t.usages.includes("sign"))throw new Error("this CryptoKey cannot sign: generate it with usages ['sign', 'verify']");let n;if(typeof e=="string")m(e,"publicKey",32),n=e.trim().toLowerCase();else try{n=y(new Uint8Array(await crypto.subtle.exportKey("raw",e)))}catch(r){let o=r instanceof Error?`: ${r.message}`:"";throw new Error("could not read the public half of this key pair; pass the public key as 64 hex instead"+o)}return si(t,n)}function si(t,e){return{publicKey:e,async sign(n){try{return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},t,n))}catch(r){throw oi(r)}}}}async function I(t,e,n){if(e&&t!==void 0)throw new Error(`pass either ${n} or signer, not both \u2014 they may name different keys`);if(e)return e;if(t!==void 0)return Ne(t,n);throw new Error(`${n} or signer is required`)}var Ic=new TextEncoder().encode("calimero.mdma.account-ownership-claim.v1\0"),Pc=6e4,ai=5*6e4,ci=1024,ui="mdma:enable-ha-namespace",di="mdma:enable-ha-namespace-as-account";function li(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var kr=(t,e)=>{if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);return t.toLowerCase()};async function pi(t,e,n,r){if(r!==void 0&&!(r.length>0&&r.length<=ci))throw new Error(`relayUrl must be a non-empty string of at most ${ci} characters`);let o=t.ttlMs??Pc;if(!(o>0&&o<=ai))throw new Error(`ttlMs must be in (0, ${ai}]`);let i=kr(t.namespaceId,"namespaceId"),s=kr(t.accountId,"accountId"),a=kr(t.salt,"salt"),c=await I(t.deviceSecret,t.signer,"deviceSecret"),u=(t.now??Date.now)(),d=Array.from(crypto.getRandomValues(new Uint8Array(16)),x=>x.toString(16).padStart(2,"0")).join(""),l=new TextEncoder().encode(JSON.stringify({v:1,audience:e,group_id:i,account_id:s,salt:a,...n===void 0?{}:{subject:n},nonce:d,issued_at_ms:u,expires_at_ms:u+o,...r===void 0?{}:{relay_url:r}})),p=await c.sign(f(Ic,l));return{kind:"account",credential:t.credential,signed_payload:li(l),signature:li(p)}}async function Tc(t){if(!t.subject)throw new Error("subject must be the cloud login email");return pi(t,ui,t.subject)}async function Er(t){return pi(t,di,void 0,t.relayUrl)}var Dc=new TextEncoder().encode("calimero.device.cert.v1"),Uc=new TextEncoder().encode("calimero.account.genesis.v1"),Oc=new TextEncoder().encode("calimero.device.id.v1"),_e=2,Nc=237;async function Ir(t,e){if(e.length!==16)throw new Error(`nonce must be 16 bytes, got ${e.length}`);let n=m(t,"account",32),r=await E(Oc,[n,e]);return y(f(e,r.subarray(0,16)))}async function nn(t){return E(Dc,[m(t.account,"account",32),m(t.device,"device",32),m(t.signPublicKey,"signPublicKey",32),m(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch)])}function gi(t){return f(new Uint8Array([_e]),t.rootPublicKey,R(0),m(t.account,"account",32),m(t.device,"device",32),m(t.signPublicKey,"signPublicKey",32),m(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch),t.signature)}async function mi(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=m(e.publicKey,"signer.publicKey",32),r=await V(e.publicKey),o=0,i=await nn({account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch}),s=await e.sign(i),a=gi({rootPublicKey:n,account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch,signature:s});return y(a)}function Pr(t){let e=m(t,"credential",Nc);if(e[0]!==_e)throw new Error(`this credential has account genesis version ${e[0]}, not ${_e} \u2014 it names a different account than its root key derives here, and core would refuse it`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint32(33,!0);if(r!==0)throw new Error(`this credential carries a ${r}-handoff root chain, which this SDK cannot verify yet \u2014 the signing root is not the genesis root, so checking it means walking the chain`);let o=(i,s)=>y(e.subarray(i,i+s));return{rootPublicKey:o(1,32),account:o(37,32),device:o(69,32),signPublicKey:o(101,32),kemPublicKey:o(133,32),keyEpoch:n.getUint32(165,!0),deviceEpoch:n.getUint32(169,!0),signature:o(173,64)}}async function rn(t){let e=Pr(t),n=await V(e.rootPublicKey);if(n!==e.account)throw new Error(`this credential names account ${e.account}, but its root key derives ${n} \u2014 the certificate was re-pointed at another account`);let r=m(e.device,"device",32).subarray(0,16);if(await Ir(e.account,r)!==e.device)throw new Error(`this credential names device ${e.device}, which was not minted for account ${e.account}; core refuses it`);if(!await $o(e.rootPublicKey,m(e.signature,"signature",64),await nn(e)))throw new Error(`the root key of account ${e.account} did not sign this certificate`);return e}async function on(t){return V(y(await oe(t)))}async function V(t){return y(await E(Uc,[f(new Uint8Array([_e]),m(t,"rootPublicKey",32))]))}var _c=new TextEncoder().encode("calimero.device.scope.v1");async function Tr(t){return E(_c,[m(t.account,"account",32),m(t.device,"device",32),R(t.scopeEpoch),R(t.keyEpoch),...t.applications.map((e,n)=>m(e,`applications[${n}]`,32))])}async function fi(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=m(e.publicKey,"signer.publicKey",32),r=await V(y(n)),o=t.applications??[],i=t.scopeEpoch??0;if(!Number.isInteger(i)||i<0||i>4294967295)throw new Error(`scopeEpoch must be a u32, got ${i}`);let s=0,a=await Tr({account:r,device:t.device,applications:o,scopeEpoch:i,keyEpoch:s}),c=await e.sign(a);if(c.length!==64)throw new Error(`signer returned ${c.length} bytes, expected a 64-byte Ed25519 signature`);return y(f(new Uint8Array([_e]),n,R(0),m(r,"account",32),m(t.device,"device",32),R(o.length),...o.map((u,d)=>m(u,`applications[${d}]`,32)),R(i),R(s),c))}var Dr=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"];var Mc=new TextEncoder().encode("calimero.mdma.account-link.v1\0"),Gc=new TextEncoder().encode("calimero.mdma.account-login.v1\0"),Me=256,hi=Me/32,Ur=(Me+hi)/11;async function yi(){let t=crypto.getRandomValues(new Uint8Array(Me/8));return Ri(y(t),await Si(t))}async function bi(t){let e=Ci(t);return Ri(y(await ki(e)),e.join(" "))}async function Or(t){return m(t,"secret",32),{secret:t,publicKey:y(await oe(t)),accountId:await on(t)}}async function wi(){let t=crypto.getRandomValues(new Uint8Array(Me/8)),e=await Si(t);return{...await xi(t),phrase:e}}async function Ai(t){return xi(await ki(Ci(t)))}async function xi(t){let e=await Ne(y(t),"rootSecret");return t.fill(0),{publicKey:e.publicKey,accountId:await V(e.publicKey),signer:e}}async function X(t){let e=typeof t=="string"?await Ne(t,"rootSecret"):t;return vi(e)}async function sn(t,e){return vi(await I(t,e,"rootSecret"))}async function vi(t){return{signer:t,publicKey:t.publicKey,accountId:await V(t.publicKey)}}async function mt(t){if(!t.nonce)throw new Error("nonce is required to sign an account link");let n=await(await I(t.rootSecret,t.signer,"rootSecret")).sign(f(Mc,new TextEncoder().encode(t.nonce)));return Pi(n)}async function an(t){if(!t.nonce)throw new Error("nonce is required to sign an account login");let n=await(await I(t.rootSecret,t.signer,"rootSecret")).sign(f(Gc,new TextEncoder().encode(t.nonce)));return Pi(n)}async function Ri(t,e){return{...await Or(t),phrase:e}}function Ci(t){let e=t.normalize("NFKD").toLowerCase().trim().split(/\s+/),n=e[0]===""?0:e.length;if(n!==Ur)throw new Error(`recovery phrase must be ${Ur} words, got ${n}`);return e}async function Si(t){let e=Ii(t)+await Ei(t),n=[];for(let r=0;r<Ur;r+=1){let o=Number.parseInt(e.slice(r*11,r*11+11),2);n.push(Dr[o])}return n.join(" ")}async function ki(t){let e="";for(let r of t){let o=Dr.indexOf(r);if(o<0)throw new Error(`"${r}" is not a word in the recovery phrase list`);e+=o.toString(2).padStart(11,"0")}let n=new Uint8Array(Me/8);for(let r=0;r<n.length;r+=1)n[r]=Number.parseInt(e.slice(r*8,r*8+8),2);if(e.slice(Me)!==await Ei(n))throw new Error("recovery phrase checksum failed \u2014 check for a mistyped or transposed word");return n}async function Ei(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return Ii(e).slice(0,hi)}function Ii(t){let e="";for(let n of t)e+=n.toString(2).padStart(8,"0");return e}function Pi(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var Kc=new TextEncoder().encode("calimero.tee-attest.key-binding.v1"),cn=new TextEncoder().encode("MOCK_TDX_QUOTE_V1"),$c=568;function Lc(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}function Nr(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r+=1)n|=t[r]^e[r];return n===0}function Hc(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}function Bc(t,e){if(typeof t!="string"||!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);let n=new Uint8Array(32);for(let r=0;r<32;r+=1)n[r]=Number.parseInt(t.slice(r*2,r*2+2),16);return n}async function ln(t){let e=await crypto.subtle.digest("SHA-256",Lc(Kc,new Uint8Array(32),t));return new Uint8Array(e)}function _r(t){let e=t.length>=cn.length&&Nr(t.subarray(0,cn.length),cn),n=e?cn.length:$c;if(t.length<n+64)throw new Error(`the quote is too short to carry report data (${t.length} bytes)`);return{reportData:t.slice(n,n+64),mock:e}}async function un(t){let e=crypto.getRandomValues(new Uint8Array(32)),n=`${t.relayUrl.replace(/\/+$/,"")}/admin-api/tee/attest`,r=JSON.stringify({nonce:y(e),bindNodeKey:!0,...t.verify?.includeCollateral?{includeCollateral:!0}:{}}),o={method:"POST",headers:{"Content-Type":"application/json"},body:r},i=t.fetch?await t.fetch(n,o):await globalThis.fetch(n,o);if(!i.ok){let p=await i.text().catch(()=>"");throw new Error(`the relay would not attest (HTTP ${i.status})${p?`: ${p}`:""}`)}let s=await i.json(),a=s.data??s;if(typeof a.quoteB64!="string")throw new Error("the relay returned no quote");let c=Bc(a.boundPublicKey,"boundPublicKey"),u=Hc(a.quoteB64),{reportData:d,mock:l}=_r(u);if(l){if(!t.allowMock)throw new Error("the relay answered with a MOCK quote, which proves nothing about the hardware")}else if(t.verify){if(!await t.verify({quoteB64:a.quoteB64,nonce:y(e),reportDataSuffix:y(await ln(c)),...a.collateral?{collateral:a.collateral}:{}}))throw new Error("the relay's quote did not verify: not a trusted image, or not bound to this request")}else if(t.verifyQuote)await t.verifyQuote(u);else throw new Error("a real TDX quote needs a verify (or verifyQuote) to check its signature and measurements");if(!Nr(d.subarray(0,32),e))throw new Error("the quote does not carry our nonce: it was not made for this request");if(!Nr(d.subarray(32,64),await ln(c)))throw new Error("the quote does not bind the key the relay named: refusing it");return{nodeKey:y(c),mock:l}}var qc="Noise_NK_25519_AESGCM_SHA256",Mr=32,jc=16,Fc=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Kr=class t{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(qc),n=new Uint8Array(32);return n.set(e),new t(n)}async mixHash(e){this.h=await Vc(f(this.h,e))}async mixKey(e){let[n,r]=await Di(this.ck,e);this.ck=n,this.k=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:Ti(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(n),n}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let n=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Ti(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),n}split(){return Di(this.ck,new Uint8Array)}};async function Ui(t,e,n){let r=await Kr.initialize();await r.mixHash(e),await r.mixHash(t);let o=await Ge(n);return await r.mixHash(o.publicKey),await r.mixKey(await ft(o.privateKey,t)),{message1:f(o.publicKey,await r.encryptAndHash(new Uint8Array)),async finish(s){if(s.length<Mr+jc)throw new Error("Noise: message 2 is too short");let a=s.slice(0,Mr);return await r.mixHash(a),await r.mixKey(await ft(o.privateKey,a)),{payload:await r.decryptAndHash(s.slice(Mr)),split:await r.split()}}}}async function Ge(t){if(!t){let r;try{r=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"])}catch(i){throw new Error(`Sealed transport needs WebCrypto with X25519, which this runtime lacks (${i?.name??"no crypto.subtle"}). Current browsers and Node have it; in React Native, install react-native-quick-crypto as the global crypto.`)}let o=new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey));return{privateKey:r.privateKey,publicKey:o}}let e=await crypto.subtle.importKey("pkcs8",f(Fc,t),{name:"X25519"},!0,["deriveBits"]),n=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Wc(n.x)}}async function ft(t,e){let n=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:n},t,256))}function Ti(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}async function Vc(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}async function Gr(t,e){let 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 Di(t,e){let n=await Gr(t,e),r=await Gr(n,new Uint8Array([1])),o=await Gr(n,f(r,new Uint8Array([2])));return[r,o]}function Wc(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}var Mi="/sealed/v2/handshake",Gi="/sealed/v2",yt="application/vnd.calimero.sealed",$r=2,Jc=new TextEncoder().encode("calimero/sealed-http/v2"),ht=16,zc=1+ht+8,Qc=0,Yc=1,Xc=2,Zc=1+64*1024+16,el=1024,tl=6e4,nl="calimero.tee-attest.transport-key.v1",rl=[101,204,205,304],Ki=new TextEncoder,bt=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},Ke=class extends Error{constructor(n,r,o,i){super(o);this.status=n;this.code=r;this.retryAfterMs=i;this.name="SealedTransportError"}};async function $i(t,e){let n=await crypto.subtle.digest("SHA-256",f(Ki.encode(nl),t,e));return new Uint8Array(n)}async function Li(t,e,n={}){if(n.applicationId===void 0!=(n.applicationHash===void 0))throw new Error("applicationId and applicationHash are given together or not at all");let r=y(crypto.getRandomValues(new Uint8Array(32))),o=await t.teeAttest({nonce:r,applicationId:n.applicationId,bindTransportKey:!0,...e.includeCollateral?{includeCollateral:!0}:{}});if(!o.transportPublicKey)throw new Error("The node did not report a transport key; it predates sealed transport");let i=m(o.transportPublicKey,"transportPublicKey",32),s=n.applicationHash?m(n.applicationHash,"applicationHash",32):new Uint8Array(32),a=y(await $i(s,i));if(!await e({quoteB64:o.quoteB64,nonce:r,reportDataSuffix:a,collateral:o.collateral}))throw new Error("The attestation did not verify, so its transport key is not trusted");return i}function he(t){let e=t.fetch??((o,i)=>fetch(o,i)),n=`${t.baseUrl.replace(/\/+$/,"")}/admin-api/tee/attest`,r={async teeAttest(o){let i=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)});if(!i.ok)throw new Error(`The node refused to attest: HTTP ${i.status}`);let s=await i.json();if(!s.data)throw new Error("The attestation response is malformed");return s.data}};return Hi({baseUrl:t.baseUrl,transportPublicKey:()=>Li(r,t.verify,{applicationId:t.applicationId,applicationHash:t.applicationHash}),fetch:e})}function Hi(t){let e=new URL(t.baseUrl),n=e.pathname.replace(/\/+$/,""),r=`${e.origin}${n}`,o=t.fetch??((l,p)=>fetch(l,p)),i=typeof t.transportPublicKey=="function"?t.transportPublicKey:void 0,s=i?Promise.resolve().then(i):Promise.resolve(t.transportPublicKey);s.catch(()=>{});let a,c=async()=>{try{return await Ni(o,r,await Oi(s))}catch(l){if(!(l instanceof bt)||!i)throw l;return s=Promise.resolve().then(i),Ni(o,r,await Oi(s))}},u=async()=>{let l=a??d(void 0),p=await l;if(Date.now()<p.renewAt)return[p,l];let x=d(l);return[await x,x]},d=l=>{if(a===l){let p=c();a=p,p.catch(()=>{a===p&&(a=void 0)})}return a};return async(l,p)=>{let x=new Request(l,p),v=new URL(x.url);if(v.origin!==e.origin||!v.pathname.startsWith(`${n}/`))throw new Error(`Refusing to send ${v.href} outside the sealed node at ${t.baseUrl}`);let P=[];x.headers.forEach((h,w)=>P.push([w,h]));let b={method:x.method,path:v.pathname.slice(n.length)+v.search,headers:P},k=new Uint8Array(await x.arrayBuffer()),T=async h=>{let{requestId:w,header:S,envelope:U}=await il(h,b,k),M=await o(`${r}${Gi}`,{method:"POST",headers:{"content-type":yt},body:U,signal:x.signal});if(M.headers.get("content-type")!==yt)throw await qi(M);return al(M,h.responseKey,S,w)},[H,Q]=await u();try{return await T(H)}catch(h){if(!(h instanceof Ke)||h.code!=="unknown_session")throw h;return T(await d(Q))}}}async function Oi(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function Ni(t,e,n){try{return await _i(t,e,n)}catch(r){if(!(r instanceof Ke)||r.code!=="busy")throw r;return await new Promise(o=>setTimeout(o,r.retryAfterMs??1e3)),_i(t,e,n)}}async function _i(t,e,n){let r=await Ui(n,Jc),o=await t(`${e}${Mi}`,{method:"POST",headers:{"content-type":yt},body:f(new Uint8Array([$r]),n,r.message1)});if(o.headers.get("content-type")!==yt)throw await qi(o);let i=await ll(o,el);return ol(r,i)}async function ol(t,e){if(e[0]!==$r)throw new Error("The handshake reply is malformed");let n;try{n=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:r,split:o}=n;if(r.length!==ht+4)throw new Error("The handshake reply is malformed");let i=r.slice(0,ht),s=new DataView(r.buffer,r.byteOffset).getUint32(ht,!1),[a,c]=await Promise.all([crypto.subtle.importKey("raw",o[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",o[1],"AES-GCM",!1,["decrypt"])]);return o[0].fill(0),o[1].fill(0),{requestKey:a,responseKey:c,nextRequestId:1,renewAt:Date.now()+s*1e3-tl,header(u){let d=new Uint8Array(zc);return d[0]=$r,d.set(i,1),new DataView(d.buffer).setBigUint64(1+ht,BigInt(u),!1),d}}}async function il(t,e,n){let r=t.nextRequestId;t.nextRequestId+=1;let o=t.header(r),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:Bi(r,0),additionalData:o},t.requestKey,sl(e,n));return{requestId:r,header:o,envelope:f(o,new Uint8Array(i))}}function Bi(t,e){let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setBigUint64(0,BigInt(t),!1),r.setUint32(8,e,!1),n}function sl(t,e){let n=Ki.encode(JSON.stringify(t)),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,n.length,!1),f(r,n,e)}async function al(t,e,n,r){if(!t.body)throw new Error("The sealed response has no body");let o=cl(t.body.getReader()),i=0,s=async()=>{let d=await o.next();if(!d)return null;let l;try{l=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Bi(r,i),additionalData:n},e,d))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return i+=1,{kind:l[0],data:l.slice(1)}},a=await s();if(!a||a.kind!==Qc)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(rl.includes(c.status))return await o.cancel(),new Response(null,{status:c.status,headers:c.headers});let u=new ReadableStream({async pull(d){try{let l=await s();l?l.kind===Yc?d.enqueue(l.data):l.kind===Xc?(d.close(),await o.cancel()):d.error(new Error("The sealed response is malformed")):d.error(new Error("The sealed response was cut short"))}catch(l){d.error(l)}},cancel(){return o.cancel()}});return new Response(u,{status:c.status,headers:c.headers})}function cl(t){let e=new Uint8Array,n=async r=>{for(;e.length<r;){let{done:o,value:i}=await t.read();if(o)return!1;e=f(e,i)}return!0};return{async next(){if(!await n(4))return null;let r=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(r>Zc)throw await t.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await n(4+r))return null;let o=e.slice(4,4+r);return e=e.slice(4+r),o},cancel:()=>t.cancel()}}async function ll(t,e){if(!t.body)return new Uint8Array;let n=t.body.getReader(),r=new Uint8Array;for(;;){let{done:o,value:i}=await n.read();if(o)return r;if(r=f(r,i),r.length>e)throw await n.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function qi(t){let e,n=`Sealed request refused: HTTP ${t.status}`;try{let i=await t.json();e=i?.error?.code,i?.error?.message&&(n=`Sealed request refused: ${i.error.message}`)}catch{}if(e==="stale_transport_key")return new bt;let r=Number(t.headers.get("retry-after")),o=Number.isFinite(r)&&r>0?Math.min(r,5)*1e3:void 0;return new Ke(t.status,e,n,o)}var ul=/^[0-9a-f]{96}$/,dl=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function At(t){let e=$e(t.allowedMrtd??[],"allowedMrtd"),n=(t.allowedMeasurements??[]).map((a,c)=>{let u=`allowedMeasurements[${c}]`;return dl.map(d=>$e([a?.[d]??""],`${u}.${d}`)[0]).join()}),r=[$e(t.allowedRtmr0??[],"allowedRtmr0"),$e(t.allowedRtmr1??[],"allowedRtmr1"),$e(t.allowedRtmr2??[],"allowedRtmr2"),$e(t.allowedRtmr3??[],"allowedRtmr3")];if(t.allowedMeasurements!==void 0&&n.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(n.length===0){if(e.length===0)throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");if(r.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 o=t.allowedTcbStatuses??["UpToDate"],i=t.now??Date.now;return Object.assign(async({quoteB64:a,nonce:c,reportDataSuffix:u,collateral:d})=>{let l=gl(a),p=d??await t.fetchCollateral?.(l);if(!p)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let x;try{x=t.dcapVerify(l,p,Math.floor(i()/1e3))}catch(k){throw new Error(`The quote did not verify: ${k?.message??String(k)}`)}if(x.status==="Revoked"||!o.includes(x.status))throw new Error(`The platform's TCB status is ${x.status}, which is not accepted`);let v=pl(x.report);if(v.tdAttributes?.length!==8||(v.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let P=[v.mrTd,v.rtMr0,v.rtMr1,v.rtMr2,v.rtMr3].map(k=>y(k));if(n.length>0&&!n.includes(P.join()))throw new Error(`The measurements (MRTD ${P[0]}, RTMR0-3 ${P.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(P[0]))throw new Error(`MRTD ${P[0]} is not an image this verifier trusts`);if([v.rtMr0,v.rtMr1,v.rtMr2,v.rtMr3].forEach((k,T)=>{let H=r[T];if(H.length>0&&!H.includes(y(k)))throw new Error(`RTMR${T} ${y(k)} is not one this verifier trusts`)}),y(v.reportData)!==`${c}${u}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function $e(t,e){return t.map(n=>{let r=n.trim().toLowerCase();if(!ul.test(r))throw new Error(`${e} holds ${JSON.stringify(n)}, which is not a 48-byte hex measurement`);return r})}function pl(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 gl(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}var ml=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],wt="locked-read-only";function Lr(t,{profile:e,allowDebugProfile:n=!1}){if(t.length===0)throw new Error("No release given, so no image would be trusted");let r,o=t.map((i,s)=>{let a=i?.tag??`releases[${s}]`;if(i?.role!==void 0&&i.role!=="node")throw new Error(`${a} lists the measurements of a ${i.role}, not of a node image`);let c=i?.profiles?.[e];if(!c){let d=Object.keys(i?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${d})`)}if(e!==wt&&!n)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(wt)}, or pass allowDebugProfile to test`);let u=(c.allowed_tcb_statuses??["uptodate"]).map(d=>fl(d,a));return r=r===void 0?u:r.filter(d=>u.includes(d)),{mrtd:c.mrtd,rtmr0:c.rtmr0,rtmr1:c.rtmr1,rtmr2:c.rtmr2,rtmr3:c.rtmr3}});if(!r||r.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:o,allowedTcbStatuses:r}}function fl(t,e){let n=ml.find(r=>r.toLowerCase()===String(t).toLowerCase());if(!n)throw new Error(`${e} accepts TCB status ${JSON.stringify(t)}, which this verifier does not know`);return n}var ji=[{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"]}],Fi=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var hl="1.2.840.10045.2.1",yl={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},bl={"P-256":32,"P-384":48},wl={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function Vi(t,e,n){if(e+2>n)throw new Error("it is truncated");let r=t[e];if((r&31)===31)throw new Error("it uses a tag this parser does not read");let o=t[e+1],i=e+2;if(o&128){let a=o&127;if(a===0||a>4||i+a>n)throw new Error("it has a length this parser does not read");o=0;for(let c=0;c<a;c+=1)o=o*256+t[i+c];i+=a}let s=i+o;if(s>n)throw new Error("it is truncated");return{tag:r,bytes:t,offset:e,start:i,end:s}}function He(t){let e=Vi(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function G(t){let e=[];for(let n=t.start;n<t.end;){let r=Vi(t.bytes,n,t.end);e.push(r),n=r.end}return e}function N(t,e,n){if(!t||t.tag!==e)throw new Error(`${n} is not where it should be`);return t}function ce(t){return t.bytes.slice(t.start,t.end)}function dn(t){return t.bytes.slice(t.offset,t.end)}function Le(t){let e=ce(N(t,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let n=[],r=0;for(let s of e)r=r*128+(s&127),s&128||(n.push(r),r=0);let o=n.shift();return[...o<80?[Math.floor(o/40),o%40]:[2,o-80],...n].join(".")}function Al(t){let e=new TextDecoder().decode(ce(t)),n=t.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,r=t.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,o=n??r;if(!o)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let i=Number(o[1]);n&&(i+=i<50?2e3:1900);let[s,a,c,u,d]=o.slice(2).map(Number);return Date.UTC(i,s-1,a,c,u,d)}function Hr(t){try{let[e,n,r,...o]=G(N(He(t),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let i=G(N(e,48,"The signed part")),s=i[0]?.tag===160?1:0,[a,c,u,d,l,p,...x]=i.slice(s);N(a,2,"The serial number");let v=Le(G(N(n,48,"The signature algorithm"))[0]);if(Le(G(N(c,48,"The signature algorithm"))[0])!==v)throw new Error("it names two different signature algorithms");let b=wl[v];if(!b)throw new Error(`it is signed with ${v}, not ECDSA with SHA-256 or SHA-384`);let[k,T]=G(N(d,48,"The validity")).map(Al);if(T===void 0)throw new Error("its validity is incomplete");let[H,Q]=G(N(p,48,"The public key"));N(Q,3,"The public key");let[h,w]=G(N(H,48,"The key algorithm"));if(Le(h)!==hl)throw new Error("its key is not an elliptic-curve key");let S=yl[Le(w)];if(!S)throw new Error("its key is on a curve other than P-256 or P-384");let U=new Map,M=x.find(te=>te.tag===163);if(M){let[te]=G(M);for(let ne of G(N(te,48,"The extensions"))){let Ee=G(N(ne,48,"An extension"));if(Ee.length===3)N(Ee[1],1,"An extension's critical flag");else if(Ee.length!==2)throw new Error("it has a malformed extension");let ur=Le(Ee[0]);if(U.has(ur))throw new Error(`it has extension ${ur} twice`);U.set(ur,ce(N(Ee[Ee.length-1],4,"An extension value")))}}let Y=ce(N(r,3,"The signature"));if(Y[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:dn(e),signatureHash:b,signature:Y.slice(1),issuer:dn(N(u,48,"The issuer")),subject:dn(N(l,48,"The subject")),notBefore:k,notAfter:T,spki:dn(p),curve:S,extensions:U}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function Wi(t){return G(N(He(t),48,"The list")).map(Le)}function xl(t,e){let n=bl[e],r=G(N(He(t),48,"The signature"));if(r.length!==2)throw new Error("The signature is not an ECDSA signature");let o=new Uint8Array(n*2);return r.forEach((i,s)=>{let a=ce(N(i,2,"The signature"));if(a.length===0||a[0]&128)throw new Error("The signature is not an ECDSA signature");for(;a.length>1&&a[0]===0;)a=a.subarray(1);if(a.length>n)throw new Error("The signature is not an ECDSA signature");o.set(a,s*n+n-a.length)}),o}async function pn(t,e,n,r,o){let i;try{i=xl(r,e)}catch{return!1}let s=await crypto.subtle.importKey("spki",t,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:n},s,i,o)}function W(t,e){let n=t.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(n)||n.length%4!==0)throw new Error(`${e} is not base64`);let r=atob(n),o=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)o[i]=r.charCodeAt(i);return o}function Br(t,e){let n=[...t.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(n.length!==1||t.replace(n[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return W(n[0][1],e)}var vl="2.5.29.17",Rl="2.5.29.37",Cl="1.3.6.1.5.5.7.3.3",Sl="1.3.6.1.4.1.57264.1.8",kl="1.3.6.1.4.1.57264.1.1",El=134,Il=12,Pl=48,Tl=new TextEncoder,Be=t=>new TextDecoder().decode(t);async function gn(t,e,n,r){let{base64Signature:o,cert:i,rekorBundle:s}=Nl(e),a=s.Payload;if(r!==void 0&&r.trim()!==o.trim())throw new Error("The detached signature is not the one in the bundle");let c=W(o,"The bundle signature"),u=Br(Be(W(i,"The bundle certificate")),"The bundle certificate"),d=Hr(u),l=Fi.find(T=>T.logId===a.logID.toLowerCase());if(!l)throw new Error(`The bundle names Rekor log ${a.logID}, which the Sigstore trust root does not know`);let p=Tl.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await pn(W(l.publicKey,"The Rekor key"),"P-256","SHA-256",W(s.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 v=a.integratedTime*1e3;if(!Qi(v,l.validFor))throw new Error(`Rekor log ${l.baseUrl} was not in use at ${xt(v)}, when the entry says it was logged`);let P=_l(a.body),b=y(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(P.hash!==b)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!qr(W(P.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let k=Br(Be(W(P.publicKey,"The logged certificate")),"The logged certificate");if(!qr(k,u))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await pn(d.spki,"P-256","SHA-256",c,t))throw new Error("The signature over the file does not verify with the bundle's certificate");return await Dl(d,v),Ol(d,n),{integratedTime:a.integratedTime}}async function Dl(t,e){if(!zi(t,e))throw new Error(`The signing certificate was valid ${xt(t.notBefore)} to ${xt(t.notAfter)}, not at ${xt(e)} when Rekor logged it`);let n=[];for(let r of ji){let o=r.certChain.map(s=>Hr(W(s,"A Fulcio certificate")));if(!await Ji(t,o[0]))continue;let i=await Ul(o,r.validFor,e);if(!i)return;n.push(`${r.uri} (valid from ${r.validFor.start}): ${i}`)}throw new Error(n.length>0?`The signing certificate's CA is not trusted at ${xt(e)}: ${n.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function Ul(t,e,n){if(!Qi(n,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of t.entries()){if(!zi(o,n))return`its certificate ${r} was not valid then`;let i=t[r+1]??o;if(!await Ji(o,i))return`its certificate ${r} is not signed by the next`}}async function Ji(t,e){return qr(t.issuer,e.subject)?pn(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function Ol(t,e){let n=t.extensions.get(vl);if(!n)throw new Error("The signing certificate names no identity");let r=G(N(He(n),Pl,"The subject alternative name")),o=r.filter(u=>u.tag===El).map(u=>Be(ce(u)));if(o.length!==1||r.length!==1||o[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(o.length===1?o[0]:o)}, not by ${e.identity}`);let i=t.extensions.get(Sl),s=t.extensions.get(kl),a=i?Be(ce(N(He(i),Il,"The OIDC issuer"))):s?Be(s):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(Rl);if(!c||!Wi(c).includes(Cl))throw new Error("The signing certificate is not for code signing")}function Nl(t){let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let n=e,r=n?.rekorBundle?.Payload;if(!(typeof n?.base64Signature=="string"&&typeof n.cert=="string"&&typeof n.rekorBundle?.SignedEntryTimestamp=="string"&&typeof r?.body=="string"&&typeof r.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(r.logID)&&Number.isSafeInteger(r.integratedTime)&&r.integratedTime>=0&&Number.isSafeInteger(r.logIndex)&&r.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return n}function _l(t){let e;try{e=JSON.parse(Be(W(t,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let n=e?.spec?.data?.hash,r=e?.spec?.signature;if(e?.kind!=="hashedrekord"||n?.algorithm!=="sha256"||typeof n.value!="string"||typeof r?.content!="string"||typeof r.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:n.value.toLowerCase(),signature:r.content,publicKey:r.publicKey.content}}function zi(t,e){return t.notBefore<=e&&e<=t.notAfter}function Qi(t,e){return Date.parse(e.start)<=t&&(e.end===void 0||t<=Date.parse(e.end))}function xt(t){return new Date(t).toISOString()}function qr(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var jr=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"}),Ml=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],mn="https://cloud.calimero.network";async function Xi(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await gn(r,e,{identity:n.identity??jr.identity,issuer:n.issuer??jr.issuer},n.signature);let o;try{o=JSON.parse(new TextDecoder().decode(r))}catch{throw new Error("The signed release is not JSON")}if(o?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(o?.role)} release, not a node one`);let i=Object.values(o.profiles??{}),s=a=>Ml.every(c=>/^[0-9a-f]{96}$/i.test(String(a?.[c])));if(typeof o.tag!="string"||i.length===0||!i.every(s))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(n.expectedVersion!==void 0&&o.tag!==n.expectedVersion)throw new Error(`The signed release is ${o.tag}, not ${n.expectedVersion}`);return o}async function fn(t,e={}){let n=await(e.fetch??fetch)(t,{headers:{accept:"application/json"}});if(!n.ok)throw new Error(`Fetching the node release from ${t} failed: HTTP ${n.status}`);let r;try{r=(await n.json())?.data}catch{throw new Error(`${t} did not answer with JSON`)}if(typeof r?.version!="string"||typeof r.publishedMrtds!="string"||typeof r.bundle!="string")throw new Error(`${t} did not answer with a signed node release`);return{version:r.version,publishedMrtds:r.publishedMrtds,bundle:r.bundle}}function Zi(t){let e=/^merotee-.+-(\d+)-(\d+)-(\d+)$/.exec(t);if(!e)throw new Error(`${JSON.stringify(t)} is not the image of a mero-tee node release`);return`${Number(e[1])}.${Number(e[2])}.${Number(e[3])}`}async function hn(t,e={}){let n=await ts(t,e.fetch??fetch);if(n===void 0)throw new Error(`${es(t)} was refused unsealed: the node requires sealing and is too old to name its release before a session exists. Name the release it runs yourself (createSignedReleaseSealedFetch's \`releaseVersion\`), or upgrade the node`);return n}function es(t){return`${t.replace(/\/+$/,"")}/admin-api/tee/info`}async function ts(t,e){let n=es(t),r=await e(n,{headers:{accept:"application/json"}});if(r.status===403&&await r.json().then(s=>s?.error?.code).catch(()=>{})==="sealed_required")return;if(!r.ok)throw new Error(`Fetching ${n} failed: HTTP ${r.status}`);let o;try{o=(await r.json())?.data?.osImage}catch{throw new Error(`${n} did not answer with JSON`)}if(typeof o!="string")throw new Error(`${n} did not name the node's image`);return Zi(o)}function yn(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${vt(e,"version")}`}async function ns(t){let e=vt(t.minReleaseVersion,"minReleaseVersion"),n=vt(t.release?.version,"The release version"),r=await Xi(t.release.publishedMrtds,t.release.bundle,{expectedVersion:n,identity:t.identity,issuer:t.issuer});if(Kl(n,e)<0)throw new Error(`Release ${n} is older than the minimum trusted, ${e}`);return Lr([r],{profile:t.profile,allowDebugProfile:t.allowDebugProfile})}function bn(t){return vt(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async n=>{let r=await ns({release:await t.release(),profile:t.profile,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer});return At({dcapVerify:t.dcapVerify,fetchCollateral:t.fetchCollateral,now:t.now,...r})(n)},{includeCollateral:!0})}function Gl(t){let{baseUrl:e,releaseSource:n,releaseVersion:r,applicationId:o,applicationHash:i,fetch:s,...a}=t;r!==void 0&&vt(r,"releaseVersion");let c=s??((d,l)=>fetch(d,l));return he({baseUrl:e,verify:bn({...a,release:async()=>{let d=r===void 0?await hn(e,{fetch:c}):await ts(e,c)??r;return typeof n=="function"?n({baseUrl:e,version:d,fetch:c}):fn(yn(n??mn,d),{fetch:c})}}),applicationId:o,applicationHash:i,fetch:c})}var rs=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function vt(t,e){let n=typeof t=="string"?rs.exec(t):null,r=n?.[4];if(!n||r!==void 0&&r.split(".").some(o=>o===""))throw new Error(`${e} is ${JSON.stringify(t)}, not a release version like 2.3.87`);return t}function Kl(t,e){let[n,r]=Yi(t),[o,i]=Yi(e);for(let c=0;c<3;c+=1)if(n[c]!==o[c])return n[c]<o[c]?-1:1;if(r===void 0||i===void 0)return r===i?0:r===void 0?1:-1;let s=r.split("."),a=i.split(".");for(let c=0;c<Math.max(s.length,a.length);c+=1){let[u,d]=[s[c],a[c]];if(u===void 0||d===void 0)return u===void 0?-1:1;let[l,p]=[/^\d+$/.test(u),/^\d+$/.test(d)],x=l&&p?Math.sign(Number(u)-Number(d)):l!==p?l?-1:1:u<d?-1:u>d?1:0;if(x!==0)return x}return 0}function Yi(t){let e=rs.exec(t);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var $l=new TextEncoder().encode("calimero.warrant.v2"),Ll=new TextEncoder().encode("calimero.warrant.intent.v1"),os=64,is=256;async function Fr(t,e){let n=new TextEncoder().encode(JSON.stringify(e));return E(Ll,[new TextEncoder().encode(t),n])}async function wn(t){let e=m(t.context,"context",32),n=m(t.authorAccount,"authorAccount",32),r=m(t.executor,"executor",32),o=m(t.executorKey,"executorKey",32),i=m(t.releaseBytecodeId,"releaseBytecodeId",32),s=Vr(t.releaseVersion??""),a=le(t.accountHeads,"accountHeads"),c=le(t.governanceFloor,"governanceFloor"),u=await I(t.deviceSecret,t.signer,"deviceSecret"),d=m(u.publicKey,"signer.publicKey",32),l=new TextEncoder().encode(t.method),p=await Fr(t.method,t.argsJson),x=C(t.nonce),v=C(t.notAfter),P=await E($l,[e,n,d,r,o,i,s,l,p,C(a.length),...a,C(c.length),...c,x,v]),b=Rt(await u.sign(P));return y(f(e,n,d,r,o,i,R(s.length),s,R(l.length),l,p,R(a.length),...a,R(c.length),...c,x,v,b))}function Rt(t){if(!(t instanceof Uint8Array)||t.length!==64){let e=t instanceof Uint8Array?`${t.length} bytes`:typeof t;throw new Error(`signer returned ${e}, expected a 64-byte Ed25519 signature`)}return t}function Vr(t){let e=new TextEncoder().encode(t);return Hl(e.length),e}function Hl(t){if(t>is)throw new Error(`releaseVersion is ${t} bytes, over the ${is} a node accepts`)}function le(t,e){let n=t??[];if(n.length>os)throw new Error(`${e} cites ${n.length} heads, over the ${os} a node accepts`);return n.map((r,o)=>m(r,`${e}[${o}]`,32))}var Bl=new TextEncoder().encode("calimero.context-creation-warrant.v1"),ql=new TextEncoder().encode("calimero.context-creation.init.v1"),An=256;async function Wr(t){let e=new TextEncoder().encode(JSON.stringify(t));return E(ql,[e])}async function jl(t){return E(Bl,[t.group,t.seed,t.authorAccount,t.deviceKey,t.executor,t.executorKey,t.applicationId,new Uint8Array([t.serviceName===null?0:1]),t.serviceName??new Uint8Array(0),new Uint8Array([t.name===null?0:1]),t.name??new Uint8Array(0),t.initHash,C(t.accountHeads.length),...t.accountHeads,C(t.governanceFloor.length),...t.governanceFloor,C(t.nonce),C(t.notAfter)])}async function xn(t){let e=m(t.group,"group",32),n=t.seed===void 0?crypto.getRandomValues(new Uint8Array(32)):m(t.seed,"seed",32),r=m(t.authorAccount,"authorAccount",32),o=m(t.executor,"executor",32),i=m(t.executorKey,"executorKey",32),s=m(t.applicationId,"applicationId",32),a=ss(t.serviceName,"serviceName"),c=ss(t.name,"name"),u=le(t.accountHeads,"accountHeads"),d=le(t.governanceFloor,"governanceFloor"),l=await I(t.deviceSecret,t.signer,"deviceSecret"),p=m(l.publicKey,"signer.publicKey",32),x=await Wr(t.initArgs),v=await jl({group:e,seed:n,authorAccount:r,deviceKey:p,executor:o,executorKey:i,applicationId:s,serviceName:a,name:c,initHash:x,accountHeads:u,governanceFloor:d,nonce:t.nonce,notAfter:t.notAfter}),P=Rt(await l.sign(v));return{warrant:y(f(e,n,r,p,o,i,s,as(a),as(c),x,R(u.length),...u,R(d.length),...d,C(t.nonce),C(t.notAfter),P)),seed:y(n)}}function cs(t){let e=t.trim();if(!/^[0-9a-fA-F]*$/.test(e)||e.length%2!==0)throw new Error("creation warrant must be an even number of hex characters");let n=new Uint8Array(e.length/2);for(let l=0;l<n.length;l+=1)n[l]=Number.parseInt(e.slice(l*2,l*2+2),16);let r=new DataView(n.buffer),o=0,i=(l,p)=>{if(o+l>n.length)throw new Error(`creation warrant ends inside ${p} (${n.length} bytes)`);let x=n.subarray(o,o+l);return o+=l,x},s=l=>r.getUint32(i(4,l).byteOffset,!0),a=l=>r.getBigUint64(i(8,l).byteOffset,!0),c=l=>{let p=i(1,l)[0];if(p===0)return null;if(p!==1)throw new Error(`${l} has option tag ${p}, expected 0 or 1`);let x=s(l);if(x>An)throw new Error(`${l} is ${x} bytes, over the ${An} a node accepts`);return new TextDecoder("utf-8",{fatal:!0}).decode(i(x,l))},u=l=>{let p=s(l);if(p>64)throw new Error(`${l} cites ${p} heads, over the 64 a node accepts`);return Array.from({length:p},()=>y(i(32,l)))},d={group:y(i(32,"group")),seed:y(i(32,"seed")),authorAccount:y(i(32,"authorAccount")),deviceKey:y(i(32,"deviceKey")),executor:y(i(32,"executor")),executorKey:y(i(32,"executorKey")),applicationId:y(i(32,"applicationId")),serviceName:c("serviceName"),name:c("name"),initHash:y(i(32,"initHash")),accountHeads:u("accountHeads"),governanceFloor:u("governanceFloor"),nonce:a("nonce"),notAfter:a("notAfter"),signature:y(i(64,"signature"))};if(o!==n.length)throw new Error(`creation warrant is ${n.length} bytes but its fields account for ${o}`);return d}function ss(t,e){if(t===void 0)return null;let n=new TextEncoder().encode(t);if(n.length>An)throw new Error(`${e} is ${n.length} UTF-8 bytes, over the ${An} a node accepts`);return n}function as(t){return t===null?new Uint8Array([0]):f(new Uint8Array([1]),R(t.length),t)}var Fl=new TextEncoder().encode("calimero.governance-warrant.v1"),Vl=new TextEncoder().encode("calimero.governance-warrant.op.v1"),Wl={group:0,root:1};async function Jr(t){return E(Vl,[new Uint8Array([zr(t.kind)]),t.bytes])}async function Jl(t){return E(Fl,[t.scope,new Uint8Array([zr(t.kind)]),t.authorAccount,t.deviceKey,t.executor,t.executorKey,t.opHash,C(t.accountHeads.length),...t.accountHeads,C(t.governanceFloor.length),...t.governanceFloor,C(t.nonce),C(t.notAfter)])}async function Ct(t){let e=m(t.scope,"scope",32),n=m(t.authorAccount,"authorAccount",32),r=m(t.executor,"executor",32),o=m(t.executorKey,"executorKey",32),i=le(t.accountHeads,"accountHeads"),s=le(t.governanceFloor,"governanceFloor"),a=zr(t.op.kind),c=await I(t.deviceSecret,t.signer,"deviceSecret"),u=m(c.publicKey,"signer.publicKey",32),d=await Jr(t.op),l=await Jl({scope:e,kind:t.op.kind,authorAccount:n,deviceKey:u,executor:r,executorKey:o,opHash:d,accountHeads:i,governanceFloor:s,nonce:t.nonce,notAfter:t.notAfter}),p=Rt(await c.sign(l));return y(f(e,new Uint8Array([a]),n,u,r,o,d,R(i.length),...i,R(s.length),...s,C(t.nonce),C(t.notAfter),p))}function ls(t){let e=t.trim();if(!/^[0-9a-fA-F]*$/.test(e)||e.length%2!==0)throw new Error("governance warrant must be an even number of hex characters");let n=new Uint8Array(e.length/2);for(let l=0;l<n.length;l+=1)n[l]=Number.parseInt(e.slice(l*2,l*2+2),16);let r=new DataView(n.buffer),o=0,i=(l,p)=>{if(o+l>n.length)throw new Error(`governance warrant ends inside ${p} (${n.length} bytes)`);let x=n.subarray(o,o+l);return o+=l,x},s=l=>r.getUint32(i(4,l).byteOffset,!0),a=l=>r.getBigUint64(i(8,l).byteOffset,!0),c=l=>{let p=s(l);if(p>64)throw new Error(`${l} cites ${p} heads, over the 64 a node accepts`);return Array.from({length:p},()=>y(i(32,l)))},u=()=>{let l=i(1,"kind")[0];if(l===0)return"group";if(l===1)return"root";throw new Error(`governance warrant has kind ${l}, expected 0 (group) or 1 (root)`)},d={scope:y(i(32,"scope")),kind:u(),authorAccount:y(i(32,"authorAccount")),deviceKey:y(i(32,"deviceKey")),executor:y(i(32,"executor")),executorKey:y(i(32,"executorKey")),opHash:y(i(32,"opHash")),accountHeads:c("accountHeads"),governanceFloor:c("governanceFloor"),nonce:a("nonce"),notAfter:a("notAfter"),signature:y(i(64,"signature"))};if(o!==n.length)throw new Error(`governance warrant is ${n.length} bytes but its fields account for ${o}`);return d}function zr(t){let e=Wl[t];if(e===void 0)throw new Error(`op kind must be 'group' or 'root', got ${String(t)}`);return e}var zl={Admin:0,Member:1,ReadOnly:2},K={MemberAdded:1,MemberRemoved:2,MemberLeft:3,MemberRoleSet:4,MemberCapabilitySet:5,DefaultCapabilitiesSet:6,TargetApplicationSet:7,ContextDetached:9,SubgroupVisibilitySet:10,GroupMetadataSet:11,MemberMetadataSet:12,ContextMetadataSet:13,ContextCapabilityGranted:16,ContextCapabilityRevoked:17},St={GroupCreated:0,GroupReparented:1,GroupDeleted:2,MemberJoinedOpen:7,NamespaceCreatedV2:9},Ql=new TextEncoder().encode("calimero.namespace.id.v1"),Yr=new Uint8Array(32),vn=R(0);function ds(t){let e=zl[t];if(e===void 0)throw new Error(`role must be Admin, Member or ReadOnly, got ${String(t)}`);return new Uint8Array([e])}function D(t){return new Uint8Array([t])}function qe(t,e){return{kind:"group",bytes:f(D(K.MemberAdded),m(t,"member",32),ds(e))}}function Rn(t){return{kind:"group",bytes:f(D(K.MemberRemoved),m(t,"member",32),Yr,vn)}}function kt(t){return{kind:"group",bytes:f(D(K.MemberLeft),m(t,"member",32),Yr,vn)}}function Cn(t,e){return{kind:"group",bytes:f(D(K.MemberRoleSet),m(t,"member",32),ds(e))}}var Yl=new TextEncoder().encode("calimero.subgroup.id.v1");async function Xr(t,e,n,r){return y(await E(Yl,[m(t,"admin",32),m(e,"parentId",32),new Uint8Array([n?1:0]),m(r,"salt",32)]))}function us(t,e){if(t.length===0)throw new Error(`${e} must not be empty`);let n=new TextEncoder().encode(t);return f(R(n.length),n)}function Sn(t){return{kind:"group",bytes:f(D(K.TargetApplicationSet),Yr,m(t.applicationId,"applicationId",32),us(t.package,"package"),us(t.version,"version"))}}function je(t){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`capabilities must be a u32 bit mask, got ${String(t)}`);if(me(t,_.CAN_AUTHOR_ON_BEHALF))throw new Error("capabilities may not include CAN_AUTHOR_ON_BEHALF (512): a relay never carries a change to it");return{kind:"group",bytes:f(D(K.DefaultCapabilitiesSet),R(t))}}function Zr(t){return{kind:"root",bytes:f(D(St.GroupCreated),m(t.groupId,"groupId",32),m(t.parentId,"parentId",32),D(t.restricted?1:0),m(t.admin,"admin",32),m(t.salt,"salt",32))}}async function Fe(t){let e=t.salt??y(crypto.getRandomValues(new Uint8Array(32))),n=await Xr(t.admin,t.parentId,t.restricted,e);return{groupId:n,salt:e,op:Zr({...t,groupId:n,salt:e})}}function kn(t,e){return{kind:"root",bytes:f(D(St.GroupReparented),m(t,"childGroupId",32),m(e,"newParentId",32))}}function En(t){return{kind:"root",bytes:f(D(St.GroupDeleted),m(t,"rootGroupId",32),vn,vn)}}async function In(t,e){return y(await E(Ql,[m(t,"founder",32),m(e,"salt",32)]))}function Pn(t){let e=j(t.credential,"credential");if(e.length===0)throw new Error("credential must be the founder's AccountProof<DeviceCert>, got nothing");return{kind:"root",bytes:f(D(St.NamespaceCreatedV2),m(t.founder,"founder",32),e,m(t.salt,"salt",32))}}function Qr(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}function eo(t){return t===void 0?D(0):f(D(1),Qr(t))}function to(t={}){let e=new TextEncoder,n=Object.entries(t).map(([r,o])=>[e.encode(r),o,r]).sort(([r],[o])=>{for(let i=0;i<Math.min(r.length,o.length);i++)if(r[i]!==o[i])return r[i]-o[i];return r.length-o.length});return f(R(n.length),...n.flatMap(([,r,o])=>[Qr(o),Qr(r)]))}function Xl(t,e){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`${e} must be a u32 bit mask, got ${String(t)}`);if(me(t,_.CAN_AUTHOR_ON_BEHALF))throw new Error(`${e} may not include CAN_AUTHOR_ON_BEHALF (512): a relay never carries a change to it`);return t}function Tn(t,e){return{kind:"group",bytes:f(D(K.MemberCapabilitySet),m(t,"member",32),R(Xl(e,"capabilities")))}}function Dn(t){return{kind:"group",bytes:f(D(K.ContextDetached),m(t,"contextId",32))}}function Un(t){if(t!=="open"&&t!=="restricted")throw new Error(`mode must be open or restricted, got ${String(t)}`);return{kind:"group",bytes:f(D(K.SubgroupVisibilitySet),D(t==="open"?0:1))}}function Ve(t={}){return{kind:"group",bytes:f(D(K.GroupMetadataSet),eo(t.name),to(t.data))}}function On(t,e={}){return{kind:"group",bytes:f(D(K.MemberMetadataSet),m(t,"member",32),eo(e.name),to(e.data))}}function Nn(t,e={}){return{kind:"group",bytes:f(D(K.ContextMetadataSet),m(t,"contextId",32),eo(e.name),to(e.data))}}function ps(t){if(!Number.isInteger(t)||t<1||t>255)throw new Error(`capability must be a non-zero u8, got ${String(t)}`);return D(t)}function gs(t,e,n){return{kind:"group",bytes:f(D(K.ContextCapabilityGranted),m(t,"contextId",32),m(e,"member",32),ps(n))}}function ms(t,e,n){return{kind:"group",bytes:f(D(K.ContextCapabilityRevoked),m(t,"contextId",32),m(e,"member",32),ps(n))}}function _n(t){return{kind:"root",bytes:f(D(St.MemberJoinedOpen),m(t.member,"member",32),m(t.groupId,"groupId",32),j(t.credential,"credential"))}}var Mn=300,ye=class extends Error{constructor(n,r,o){super(`relay refused the intent (HTTP ${o}): ${n}`);this.reason=n;this.retryable=r;this.status=o;this.name="IntentRefusedError"}},Zl=t=>new Promise(e=>setTimeout(e,t));function eu(t){let e=t?.get?.("Retry-After");if(!e)return null;let n=Number.parseInt(e,10);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);return Number.isFinite(r)?Math.max(0,r-Date.now()):null}var J=class{constructor(e){this.config=e,this.baseUrl=e.relayUrl.replace(/\/+$/,"");let n=e.fetch;this.fetchImpl=n?(r,o)=>n(r,o):(r,o)=>globalThis.fetch(r,o),this.timeoutMs=e.timeoutMs??1e4,this.rateLimitRetries=e.rateLimitRetries??3}get relayUrl(){return this.baseUrl}get authorAccount(){return this.config.authorAccount}get authorProof(){return this.config.authorProof}async authorSigner(){return I(this.config.deviceSecret,this.config.signer,"deviceSecret")}async describe(e){return(await this.json("GET",`/admin-api/contexts/${g(e)}/intents`)).data}async execute(e,n,r={}){let o=await this.describe(e),i=this.checkedExecutor(o),s=y(m(o.releaseBytecodeId??"","the relay's releaseBytecodeId",32)),a=o.releaseVersion??"";Vr(a);let c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??Mn,l=await wn({context:e,authorAccount:this.config.authorAccount,executor:i.executorAccount,executorKey:i.executorKey,releaseBytecodeId:s,releaseVersion:a,method:n,argsJson:r,nonce:u,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(d),signer:c}),p=await this.json("POST",`/admin-api/contexts/${g(e)}/intents`,{method:n,argsJson:r,warrant:l,authorProof:this.config.authorProof});return{rootHash:p.data.rootHash,returns:p.data.returns??null}}async presenceIntent(e,n){await this.jsonOnce("POST",`/admin-api/contexts/${g(e)}/presence-intents`,n)}async describeCreation(e,n={}){let r=n.author?`?author=${encodeURIComponent(n.author)}`:"";return(await this.json("GET",`/admin-api/groups/${g(e)}/context-intents${r}`)).data}async createContext(e){let n=await this.describeCreation(e.groupId,{author:this.config.authorAccount});if(!n.canCreateOnBehalf)throw new ye(`the relay (${n.executorAccount}) has no standing to act for members of group ${n.groupId}; an admin must admit it as a relay or grant it CAN_AUTHOR_ON_BEHALF (checked before signing \u2014 no nonce was spent)`,!1,403);if(n.authorMayCreate===!1)throw new ye(`the author (${this.config.authorAccount}) may not create contexts in group ${n.groupId}; it needs CAN_CREATE_CONTEXT or admin (checked before signing \u2014 no nonce was spent)`,!1,403);let r=this.checkedExecutor(n),o=e.initArgs??{},i=await this.authorSigner(),s=await this.config.nonces.next(),a=this.config.ttlSeconds??Mn,{warrant:c}=await xn({group:e.groupId,seed:e.seed,authorAccount:this.config.authorAccount,executor:r.executorAccount,executorKey:r.executorKey,applicationId:e.applicationId,serviceName:e.serviceName,name:e.name,initArgs:o,nonce:s,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(a),signer:i}),u=await this.json("POST",`/admin-api/groups/${g(e.groupId)}/context-intents`,{warrant:c,authorProof:this.config.authorProof,initArgs:o});return{contextId:u.data.contextId,groupId:u.data.groupId,memberPublicKey:u.data.memberPublicKey}}async describeGovernance(e){return(await this.json("GET",`/admin-api/groups/${g(e)}/governance-intents`)).data}async govern(e){let n=await this.describeGovernance(e.groupId);if(!n.canActOnBehalf)throw new ye(`the relay (${n.executorAccount}) has no standing to act for members of group ${n.groupId}; an admin must admit it as a relay or grant it CAN_AUTHOR_ON_BEHALF (checked before signing, no nonce was spent)`,!1,403);let r=this.checkedExecutor(n),o=await this.authorSigner(),i=await this.config.nonces.next(),s=this.config.ttlSeconds??Mn,a=await Ct({scope:e.groupId,op:e.op,authorAccount:this.config.authorAccount,executor:r.executorAccount,executorKey:r.executorKey,nonce:i,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(s),signer:o});return{groupId:(await this.postGovernance(e.groupId,e.op,a)).groupId}}async foundNamespace(e){if(!e?.executor)throw new Error("foundNamespace needs the relay's account and signing key: pass executor (checked before signing, no nonce was spent)");let n=this.checkedExecutor(e.executor),r=e.salt?y(m(e.salt,"salt",32)):y(crypto.getRandomValues(new Uint8Array(32))),o=await In(this.config.authorAccount,r),i=Pn({founder:this.config.authorAccount,credential:this.config.authorProof,salt:r}),s=e.defaultCapabilities===void 0?void 0:je(e.defaultCapabilities),a=e.application?Sn(e.application):void 0,c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??Mn,l=await Ct({scope:o,op:i,authorAccount:this.config.authorAccount,executor:n.executorAccount,executorKey:n.executorKey,nonce:u,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(d),signer:c}),p=await this.postGovernance(o,i,l),x={namespaceId:p.groupId,salt:r,teeEnabled:p.teeEnabled??!1,...p.teeError?{teeError:p.teeError}:{}},v=x,P=b=>b instanceof Error?b.message:String(b);if(a)try{await this.govern({groupId:x.namespaceId,op:a}),v={...v,applicationSet:!0}}catch(b){v={...v,applicationSet:!1,applicationError:P(b)}}if(s)try{await this.govern({groupId:x.namespaceId,op:s}),v={...v,defaultCapabilitiesSet:!0}}catch(b){v={...v,defaultCapabilitiesSet:!1,defaultCapabilitiesError:P(b)}}return v}async postGovernance(e,n,r){return(await this.json("POST",`/admin-api/groups/${g(e)}/governance-intents`,{warrant:r,authorProof:this.config.authorProof,op:y(n.bytes)})).data}checkedExecutor(e){let n={executorAccount:y(m(e.executorAccount??"","the relay's executorAccount",32)),executorKey:y(m(e.executorKey??"","the relay's executorKey",32))},r=this.config.executorAccount;if(r&&r.toLowerCase()!==n.executorAccount)throw new Error(`configured executorAccount ${r} is not the relay's account ${n.executorAccount}; a warrant naming it would be unspendable`);return n}async json(e,n,r){let o=250;for(let i=0;;i+=1)try{return await this.jsonOnce(e,n,r)}catch(s){if(!(s instanceof O&&s.status===429)||i>=this.rateLimitRetries)throw s;let c=eu(s.headers);await Zl(c??o),o*=2}}async jsonOnce(e,n,r){let o={Accept:"application/json"};r!==void 0&&(o["Content-Type"]="application/json");let i=new AbortController,s=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r===void 0?void 0:JSON.stringify(r),signal:i.signal})}catch(c){throw new O(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(!a.ok){let c=await a.text().catch(()=>"");if(a.status===400||a.status===403){let u=tu(c);throw new ye(u,/nonce/i.test(u),a.status)}throw new O(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(a.status!==204)return await a.json()}};function tu(t){if(!t)return"no reason given";try{let e=JSON.parse(t);for(let n of[e.error,e.message])if(typeof n=="string"&&n)return n}catch{}return t}var be=class{constructor(e,n=null){this.relay=e;this.observer=n;this.kind="relay"}get canSubscribe(){return this.observer!==null}get events(){return this.observer}get client(){return this.relay}async execute(e){let{returns:n}=await this.executeWithMetadata(e);return n}async executeWithMetadata(e){let n=await this.relay.execute(e.contextId,e.method,e.argsJson??{});return{returns:n.returns,transport:"relay",rootHash:n.rootHash}}async migrateMyEntries(e){return this.execute({contextId:e,method:"migrate_my_entries"})}async countMyPending(e){return this.execute({contextId:e,method:"count_my_pending"})}};var nu=new TextEncoder().encode("calimero.auth.login.v1"),fs={webOrigin:0,codeSigningId:1,cli:2};function hs(t){let e=new TextEncoder;switch(t.kind){case"webOrigin":return e.encode(t.origin);case"codeSigningId":return e.encode(t.id);case"cli":return new Uint8Array(0)}}function ru(t){return f(Uint8Array.from([fs[t.kind]]),hs(t))}function ou(t){let e=Uint8Array.from([fs[t.kind]]);if(t.kind==="cli")return e;let n=hs(t);return f(e,R(n.length),n)}async function Gn(t){let e=m(t.node,"node",32),n=m(t.challenge,"challenge",32),r=m(t.sessionKey,"sessionKey",32),o=await I(t.deviceSecret,t.signer,"deviceSecret"),i=m(o.publicKey,"signer.publicKey",32),s=C(t.issuedAt),a=C(t.expiresAt),c=await E(nu,[e,ru(t.audience),n,r,i,s,a]),u=await o.sign(c);return y(f(e,ou(t.audience),n,r,i,s,a,u))}var iu=300;async function no(){let t=y(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:y(await oe(t)),secret:t}}async function We(t){let e=t.nodeUrl.replace(/\/+$/,""),n=t.timeoutMs??1e4,r=async(p,x)=>{let v=new AbortController,P=setTimeout(()=>v.abort(),n),b;try{let T={...x,signal:v.signal};b=t.fetch?await t.fetch(`${e}${p}`,T):await globalThis.fetch(`${e}${p}`,T)}catch(T){throw new O(0,T instanceof Error?T.name:"NetworkError",`${e}${p}`,new Headers,T instanceof Error?T.message:String(T))}finally{clearTimeout(P)}let k=await b.text().catch(()=>"");if(!b.ok)throw new O(b.status,b.statusText,`${e}${p}`,b.headers,k);return k?JSON.parse(k):{}},o=await r("/auth/challenge",{method:"GET",headers:{Accept:"application/json"}}),i=o.challenge??o.data?.challenge;if(!i)throw new Error("the node issued no challenge");let s=await no(),a=Math.floor(Date.now()/1e3),c=await Gn({node:t.node,audience:t.audience,challenge:i,sessionKey:s.publicKey,issuedAt:a,expiresAt:a+(t.ttlSeconds??iu),signer:await I(t.deviceSecret,t.signer,"deviceSecret")}),u=await r("/auth/token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({auth_method:"account_proof",public_key:s.publicKey,client_name:t.clientName??e,timestamp:a,provider_data:{challenge:i,login_statement:c,account_proof:t.accountProof}})}),d=u.access_token??u.data?.access_token,l=u.refresh_token??u.data?.refresh_token;if(!d)throw new Error("the node minted no session");return{accessToken:d,refreshToken:l??"",sessionKey:s.publicKey,sessionSecret:s.secret}}var su=3e4;function ze(){let t=globalThis.location?.origin;return t?{kind:"webOrigin",origin:t}:{kind:"cli"}}function au(t){try{let e=t.split(".");if(e.length!==3)return null;let n=e[1].replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4;)n+="=";let r=JSON.parse(atob(n));return typeof r.exp=="number"?r.exp*1e3:null}catch{return null}}var Je=class{constructor(e){this.session=null;this.sessionExpiresAt=null;this.pending=null;this.sseClient=null;this.wsClient=null;this.config=e}get nodeKey(){return this.config.nodeKey}async accessToken(){let e=Date.now();return this.session&&this.sessionExpiresAt!==null&&this.sessionExpiresAt-su>e?this.session.accessToken:(this.pending||(this.pending=this.loginNow().finally(()=>{this.pending=null})),(await this.pending).accessToken)}async loginNow(){let e=await We({nodeUrl:this.config.nodeUrl,node:this.config.nodeKey,signer:await this.config.signer(),accountProof:this.config.accountProof,audience:this.config.audience,clientName:this.config.clientName,ttlSeconds:this.config.ttlSeconds,fetch:this.config.fetch,timeoutMs:this.config.timeoutMs});return this.session=e,this.sessionExpiresAt=au(e.accessToken),e}get events(){return this.sseClient||(this.sseClient=new B({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.sseClient}get ws(){return this.wsClient||(this.wsClient=new se({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.wsClient}close(){this.sseClient?.close(),this.wsClient?.close()}};var ys=new TextEncoder().encode("calimero/presence/1");async function bs(t){let e=t===null?new Uint8Array([0]):f(new Uint8Array([1]),R(t.length),t);return new Uint8Array(await crypto.subtle.digest("SHA-256",e))}async function ro(t){return f(ys,m(t.contextId,"contextId",32),m(t.author,"author",32),C(t.seq),C(t.sentAtMs),await bs(t.state))}var cu=2500,Et=class{constructor(e){this.timers=new Map;this.lastSeq=new Map;this.refused=new Set;this.generation=new Map;this.relay=e.relay,this.events=e.events,this.heartbeatMs=e.heartbeatMs??cu,this.now=e.now??Date.now}async set(e,n,r=ae()){let o=this.bump(e);this.refused.delete(e);let i=n===null?null:new Uint8Array(r.encode(n));await this.send(e,i),!(i===null||this.refused.has(e))&&this.generation.get(e)===o&&this.timers.set(e,setInterval(()=>{this.send(e,i).catch(()=>{})},this.heartbeatMs))}subscribe(e,n,r=ae()){return tn(this.events(),e,n,r)}close(){for(let e of new Set([...this.timers.keys(),...this.generation.keys()]))this.bump(e)}bump(e){this.stop(e);let n=(this.generation.get(e)??0)+1;return this.generation.set(e,n),n}stop(e){let n=this.timers.get(e);n!==void 0&&clearInterval(n),this.timers.delete(e)}nextSeq(e){let n=Math.max(this.now(),(this.lastSeq.get(e)??0)+1);return this.lastSeq.set(e,n),n}async send(e,n){if(this.refused.has(e))return;let r=await this.relay.authorSigner(),o=this.nextSeq(e),i=this.now(),s=await ro({contextId:e,author:r.publicKey,seq:BigInt(o),sentAtMs:BigInt(i),state:n}),a=y(await r.sign(s));try{await this.relay.presenceIntent(e,{state:n===null?null:y(n),seq:o,sentAtMs:i,signature:a,authorProof:this.relay.authorProof})}catch(c){let u=c.status;if(u===void 0||u===0||u===429||u>=500)return;throw this.refused.add(e),this.stop(e),c}}};function ws(t,e){return new Error(`this client was constructed with the relay transport, which has no ${t}: ${e}. Construct a node client (createMeroClient({ baseUrl })) for that surface \u2014 nothing here will silently connect to a node you did not choose.`)}function As(t){return new Error(`this relay-transport client cannot open ${t}: it was given no relay node key. A relay is an ordinary node and does serve /sse and /ws \u2014 but the login statement must be signed against the node's device signing key, learned out of band (never read from the node, and never derived from its peerId). Pass it as \`observe: { nodeKey }\`. For a cloud-hosted relay the cloud does not publish it yet \u2014 see mdma #312.`)}function lu(t,e,n){let r=e?.nodeKey;return r?new Je({nodeUrl:e?.nodeUrl??t.relayUrl,nodeKey:r,accountProof:e?.accountProof??t.authorProof,audience:e?.audience??ze(),signer:e?.signer?async()=>e.signer:()=>t.authorSigner(),clientName:e?.clientName,ttlSeconds:e?.ttlSeconds,fetch:e?.fetch??n,timeoutMs:e?.timeoutMs}):null}var we=class{constructor(e){this.relayObserver=null;this.relayAdmin=null;this.proofAuthorizer=null;this.relayUrl=null;this.proofEvents=null;this.relayFetch=void 0;this.relayPresence=null;if(e.transport==="relay"){this.transport="relay",this.nodeClient=null;let o=e.fetch;this.relayFetch=o;let i=e.relay instanceof J?e.relay:new J({...e.relay,fetch:e.relay.fetch??o});if(this.relayObserver=lu(i,e.observe,o),this.rpcTransport=new be(i,this.relayObserver),this.relayUrl=i.relayUrl,e.proof&&(this.proofAuthorizer=fr(e.proof)),e.session){let s=e.session;this.relayAdmin=zo({baseUrl:i.relayUrl,getAuthToken:typeof s=="string"?async()=>s:s,fetch:o})}else if(this.proofAuthorizer){let s=this.proofAuthorizer;this.relayAdmin=zt(ct({fetch:(a,c)=>o?o(a,c):globalThis.fetch(a,c),baseUrl:i.relayUrl,authorizeRequest:s}),{baseUrl:i.relayUrl})}return}this.transport="node";let{transport:n,...r}=e;this.nodeClient=new Qe(r),this.rpcTransport=this.nodeClient.rpc}get rpc(){return this.rpcTransport}get canSubscribe(){return this.rpcTransport.canSubscribe||this.proofAuthorizer!==null}get node(){if(!this.nodeClient)throw ws("node connection","it holds a signing key and a relay URL, not a node");return this.nodeClient}get relay(){if(!(this.rpcTransport instanceof be))throw new Error("this client was constructed with the node transport and has no relay");return this.rpcTransport.client}get admin(){if(this.nodeClient)return this.nodeClient.admin;if(this.relayAdmin)return this.relayAdmin;throw new Error("this relay-transport client has no admin surface because it was given neither a `proof` nor a `session`. A warrant authorises one intent and is not a credential for reading. The caller-scoped reads (getContexts, listNamespaces) want one of the other two: pass `proof: { credential, deviceSecret }` \u2014 the device cert you already hold, which needs no login and no node key \u2014 or a `session` minted with `login()`. Context STATE reads work through execute/query either way.")}get auth(){return this.node.auth}get events(){if(this.nodeClient)return this.nodeClient.events;if(this.relayObserver)return this.relayObserver.events;if(this.proofAuthorizer&&this.relayUrl)return this.proofEvents??(this.proofEvents=new B({baseUrl:this.relayUrl,authorize:this.proofAuthorizer,fetch:this.relayFetch})),this.proofEvents;throw As("SSE events")}get ws(){if(this.nodeClient)return this.nodeClient.ws;if(this.relayObserver)return this.relayObserver.ws;throw this.proofAuthorizer?new Error("this client authenticates with a request proof, which cannot open a WebSocket from a browser: `WebSocket` cannot set the X-Calimero-Proof header, and core's guard reads the proof from a header only (the ?token= query parameter is the session equivalent and has no proof counterpart). Use `client.events` \u2014 SSE is fetch-based, carries the header, and is the recommended transport anyway."):As("WebSocket events")}get ephemeral(){return this.nodeClient?this.nodeClient.ephemeral:(this.relayPresence??(this.relayPresence=new Et({relay:this.relay,events:()=>this.events})),this.relayPresence)}get cloud(){if(!this.nodeClient)throw ws("bundled cloud client","a relay client is built from a cloud connection rather than owning one \u2014 reach it through the `cloud` field that `connectCloud` returns, or construct a `CloudClient` directly");return this.nodeClient.cloud}close(){this.nodeClient?.close(),this.relayObserver?.close(),this.proofEvents?.close()}};function Kn(t){return new we(t)}var so="calimero.delegated.connection",ao="calimero.delegated.credential";function co(){if(typeof sessionStorage>"u")return null;try{let t=sessionStorage.getItem(so);return t?JSON.parse(t):null}catch{return null}}function vs(t){try{sessionStorage.setItem(so,JSON.stringify(t))}catch{}}function Rs(){try{sessionStorage.removeItem(so)}catch{}}function Cs(){let t=co();if(t){let{account:e,credential:n,deviceSecret:r}=t;return{account:e,credential:n,deviceSecret:r}}if(typeof sessionStorage>"u")return null;try{let e=sessionStorage.getItem(ao);if(!e)return null;let n=JSON.parse(e);return!n.account||!n.credential||!n.deviceSecret?null:n}catch{return null}}function Ss(t){try{sessionStorage.setItem(ao,JSON.stringify(t))}catch{}}function ks(){try{sessionStorage.removeItem(ao)}catch{}}function lo(t){let e=Ln(t);return{next:async()=>{let n=0n;try{n=Es(t)}catch{n=0n}try{localStorage.setItem(e,String(n+1n))}catch{}return n}}}function Ln(t){return`calimero.nonce.${t}`}function Es(t){let e=localStorage.getItem(Ln(t));if(e!==null)return BigInt(e);let n=`${Ln(t)}.`,r=0n;for(let o=0;o<localStorage.length;o++){let i=localStorage.key(o);if(!i?.startsWith(n))continue;let s=BigInt(localStorage.getItem(i)??"0");s>r&&(r=s)}return r}function Bn(t,e,n){try{Es(t)<=n&&localStorage.setItem(Ln(t),String(n+1n))}catch{}}var Is="calimero.delegated.relay-node-key.";function Z(t){return t.replace(/\/+$/,"")}function uo(t,e){localStorage.setItem(Is+Z(t),e.trim().toLowerCase())}function qn(t){try{let e=localStorage.getItem(Is+Z(t));return e&&/^[0-9a-f]{64}$/.test(e)?e:null}catch{return null}}function po(t){try{let{hostname:e}=new URL(t);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch{return!1}}var uu="locked-read-only",du="2.3.99",oo;function pu(t){let e=t,n=typeof e.verify=="function"?e.verify:e.default?.verify;if(typeof n!="function")throw new TypeError("@phala/dcap-qvl loaded without a verify function");return n}var Ye=class extends Error{constructor(n,r){super(`${n}: ${r instanceof Error?r.message:String(r)}`);this.step=n;this.cause=r;this.name="RelayKeyTransportError"}};async function xs(t,e){try{return await e()}catch(n){throw n instanceof Ye?n:new Ye(t,n)}}function gu(t){return async(e,n)=>{let r;try{r=await globalThis.fetch(e,n)}catch(o){throw t.failure=o,new Ye(`reaching ${String(e)}`,o)}return r.ok||(t.failure??(t.failure=new Error(`${String(e)} answered HTTP ${r.status}`))),r}}function Ps(t,e){return Object.assign(async r=>{let o=await xs("loading the quote verifier",()=>(oo??(oo=import("@phala/dcap-qvl").then(i=>pu(i),i=>{throw oo=void 0,i})),oo));return bn({dcapVerify:o,release:()=>xs("fetching the release the relay runs",async()=>fn(yn(mn,await hn(t,{fetch:e})))),profile:uu,minReleaseVersion:du})(r)},{includeCollateral:!0})}async function Ae(t,e={}){let n=e.fresh?null:qn(t);if(n)return{kind:"learned",nodeKey:n};let r={failure:null},o=gu(r);try{let i=po(t),{nodeKey:s}=await un({relayUrl:t,allowMock:i,fetch:o,...i?{}:{verify:Ps(t,o)}});return uo(t,s),{kind:"learned",nodeKey:s}}catch(i){return i instanceof Ye||r.failure?{kind:"unavailable",error:i}:{kind:"refused",error:i}}}async function Ts(t){let e=await Ae(t);return e.kind==="learned"?e.nodeKey:(console.warn("[mero-js] could not learn the relay node key from its attestation",e.error),null)}var Hn=[1e3,2e3,5e3,1e4,3e4];function mu(t,e){return new Promise(n=>{if(e?.aborted)return n();let r=setTimeout(o,t);function o(){clearTimeout(r),e?.removeEventListener("abort",o),n()}e?.addEventListener("abort",o)})}async function Ds(t,e={}){let{signal:n}=e;for(let r=0;!n?.aborted;r+=1){let o=await Ae(t);if(o.kind==="learned")return o.nodeKey;if(o.kind==="refused")return console.warn("[mero-js] refusing the relay's attestation; its node key stays unknown",o.error),null;let i=Hn[Math.min(r,Hn.length-1)];console.warn(`[mero-js] could not reach what proves the relay's node key; retrying in ${i/1e3} s`,o.error),await mu(i,n)}return null}function fu(t){try{let e=JSON.parse(atob(t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")));return typeof e.exp=="number"?e.exp*1e3:null}catch{return null}}var io=new Map;function Us(){io.clear()}async function hu(t){if(t.status!==403)return!1;try{return(await t.clone().json()).error?.code==="sealed_route_unguarded"}catch{return!1}}function yu(t){return t.headers.has("authorization")||new URL(t.url).pathname.startsWith("/auth/")}function bu(t){let e=(o,i)=>globalThis.fetch(o,i),n=he({baseUrl:t,verify:Ps(t,e),fetch:e}),r=!1;return async(o,i)=>{let s=new Request(o,i);if(r&&yu(s))return e(s);let a=await n(s.clone());return await hu(a)?(r||(r=!0,console.warn(`[mero-js] ${Z(t)} cannot guard logged-in calls sealed (no forward_auth); they go over its TLS until it does`)),e(s)):a}}function Ze(t){if(po(t))return;let e=Z(t),n=io.get(e);return n||(n=bu(t),io.set(e,n)),n}function wu(t,e){let n=null,r=null;return async()=>{let o=n?fu(n):null;return n&&(o===null||o-Date.now()>3e4)?n:(r||(r=We({nodeUrl:t.relayUrl,fetch:Ze(t.relayUrl),node:e,deviceSecret:t.deviceSecret,accountProof:t.credential,audience:ze()}).then(i=>(n=i.accessToken,n)).catch(i=>{throw n=null,new F(t.relayUrl,i)}).finally(()=>{r=null})),r)}}var $n=new Map;function Os(){$n.clear()}function Au(t){return typeof t=="object"&&t!==null&&t.status===409}function xu(t,e){let n=t.rpc,r=Z(e),o=async i=>{let s=`${r}|${i.contextId}|${i.method}`;if($n.get(s)!=="write")try{let{returns:a}=await t.admin.queryContext(i.contextId,{method:i.method,argsJson:i.argsJson??{}});return $n.set(s,"read"),{returns:a,transport:"relay"}}catch(a){Au(a)&&$n.set(s,"write")}return n.executeWithMetadata(i)};return{get kind(){return n.kind},get canSubscribe(){return n.canSubscribe},execute:async i=>(await o(i)).returns,executeWithMetadata:o,migrateMyEntries:i=>n.migrateMyEntries(i),countMyPending:i=>n.countMyPending(i)}}function vu(t){return new B({baseUrl:t,authorize:async()=>({}),fetch:(e,n)=>new Promise((r,o)=>{let i=()=>o(Object.assign(new Error("the stream was closed before the relay was attested"),{name:"AbortError"}));if(n?.signal?.aborted)return i();n?.signal?.addEventListener("abort",i,{once:!0})})})}function Ru(t,e){let n=e.session?xu(t,e.relayUrl):null,r=null;return new Proxy(t,{get(o,i){if(i==="rpc"&&n)return n;if(!e.attested){if(i==="canSubscribe")return!1;if(i==="events")return r??(r=vu(e.relayUrl));if(i==="close")return()=>{r?.close(),o.close()}}let s=Reflect.get(o,i,o);return typeof s=="function"?s.bind(o):s}})}function go(t,e){if(!t.relayUrl)return null;let n=qn(t.relayUrl),r=Kn({transport:"relay",fetch:Ze(t.relayUrl),relay:{relayUrl:t.relayUrl,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:lo(t.relayUrl)},proof:{credential:t.credential,deviceSecret:t.deviceSecret},session:n?wu({...t,relayUrl:t.relayUrl},n):void 0,observe:n?{nodeKey:n}:void 0});return Ru(r,{relayUrl:t.relayUrl,session:n!==null,attested:n!==null||po(t.relayUrl)})}var Ns="calimero.delegated.relays.";function q(t){try{let e=localStorage.getItem(Ns+t),n=e?JSON.parse(e):{};return{namespaces:n.namespaces??{},contexts:n.contexts??{}}}catch{return{namespaces:{},contexts:{}}}}function mo(t,e){try{localStorage.setItem(Ns+t,JSON.stringify(e))}catch{}}function xe(t,e,n){let r=q(t),o=Z(e);n.namespaceId&&(r.namespaces[n.namespaceId]=o),n.contextId&&(r.contexts[n.contextId]=o),mo(t,r)}function _s(t,e){return q(t).contexts[e]??null}function jn(t,e){return e.executorAccount||!t?.executorAccount||!t.relayUrl||!e.relayUrl||Z(t.relayUrl)!==Z(e.relayUrl)?e:{...e,executorAccount:t.executorAccount}}function et(t){let e=q(t.account),n=[t.relayUrl,...Object.values(e.namespaces),...Object.values(e.contexts)].filter(r=>typeof r=="string"&&r.length>0).map(Z);return[...new Set(n)]}var Xe=class extends Error{constructor(n){super(`none of this account's relays answered: ${n.map(r=>`${r.relayUrl} (${r.kind})`).join(", ")}`);this.failures=n;this.name="RelaysUnavailableError",this.relays=n.map(r=>r.relayUrl)}get refused(){return this.failures.every(n=>n.kind==="refused")}};async function Ms(t,e){let n=await Ae(e);if(n.kind!=="learned")return console.warn("[mero-js] could not learn the relay node key from its attestation",n.error),{failure:{relayUrl:e,kind:n.kind,error:n.error}};let r=go({...t,relayUrl:e},null);return r?{client:r}:{failure:{relayUrl:e,kind:"unavailable",error:new Error(`no client for ${e}`)}}}async function Gs(t){let e=[],n=q(t.account),r=et(t),o=[];for(let i of r){let s=await Ms(t,i);if("failure"in s){o.push(s.failure);continue}let{client:a}=s;try{let{contexts:c}=await a.admin.getContexts();for(let u of c??[])e.push({...u,relayUrl:i}),n.contexts[u.id]=i}catch(c){o.push({relayUrl:i,kind:"unavailable",error:c}),console.warn(`[mero-js] could not list contexts on ${i}`,c)}}if(mo(t.account,n),r.length>0&&o.length===r.length)throw new Xe(o);return e}async function Ks(t){var s,a;let e=[],n=new Set,r=q(t.account),o=et(t),i=[];for(let c of o){let u=await Ms(t,c);if("failure"in u){i.push(u.failure);continue}let{client:d}=u;try{for(let l of await d.admin.listNamespaces())n.has(l.namespaceId)||(n.add(l.namespaceId),e.push({...l,relayUrl:c}),(s=r.namespaces)[a=l.namespaceId]??(s[a]=c))}catch(l){i.push({relayUrl:c,kind:"unavailable",error:l}),console.warn(`[mero-js] could not list namespaces on ${c}`,l)}}if(mo(t.account,r),o.length>0&&i.length===o.length)throw new Xe(i);return e}function fo(t=1){let e=BigInt(t);if(e<1n)throw new Error("nonce sequence starts at 1");return{next(){let n=e;return e+=1n,Promise.resolve(n)},advanceTo(n){return n>e&&(e=n),Promise.resolve()}}}function It(t,e){let n=e??globalThis.localStorage;if(!n)throw new Error("no localStorage in this runtime: pass a storage implementation, or use createMemoryNonceSource for a process that owns its whole sequence");let r=()=>{let o=n.getItem(t);if(o===null||o==="")return 0n;try{let i=BigInt(o);return i>0n?i:0n}catch{return 0n}};return{next(){let o=r()+1n;return n.setItem(t,o.toString()),Promise.resolve(o)},advanceTo(o){let i=o>0n?o-1n:0n;return i>r()&&n.setItem(t,i.toString()),Promise.resolve()}}}async function $s(t){if(!t.sessionToken&&!t.googleIdToken)throw new Error("connectCloud needs either a sessionToken or a googleIdToken");let e=await I(t.deviceSecret,t.signer,"deviceSecret"),n=new $({cloudBaseUrl:t.cloudBaseUrl,sessionToken:t.sessionToken,onSession:t.onSession,fetch:t.fetch,timeoutMs:t.timeoutMs});!t.sessionToken&&t.googleIdToken&&await n.signInWithGoogle(t.googleIdToken);let r=await n.getMyNamespaces(),o=Su(r,t.namespaceId),i=await n.getNamespaceRelays(o.namespaceId),s=ho(i);if(!s)throw new Error(ku(o,i));let a=new J({relayUrl:s.relayUrl,executorAccount:s.executorAccount,authorAccount:t.authorAccount,authorProof:t.authorProof,signer:e,nonces:t.nonces??Eu(e.publicKey),ttlSeconds:t.ttlSeconds,fetch:t.seal?he({baseUrl:s.relayUrl,verify:t.seal,fetch:t.fetch}):t.fetch,timeoutMs:t.timeoutMs});return{cloud:n,relay:a,namespaceId:o.namespaceId,namespace:o,relayInfo:s,execute:(c,u,d)=>a.execute(c,u,d),client:new we({transport:"relay",relay:a,observe:{nodeKey:t.relayNodeKey??s.nodeKey,audience:t.observeAudience,fetch:t.fetch,timeoutMs:t.timeoutMs}})}}async function Cu(t){let{root:e,authorAccount:n,...r}=t,o=await I(r.deviceSecret,r.signer,"deviceSecret"),i=await X(e),a=await new $({cloudBaseUrl:t.cloudBaseUrl,onSession:t.onSession,fetch:t.fetch,timeoutMs:t.timeoutMs}).signInWithAccount(i.signer);return $s({...r,deviceSecret:void 0,signer:o,sessionToken:a.sessionToken,authorAccount:n??i.accountId})}function Su(t,e){if(e){let n=t.find(r=>r.namespaceId===e);if(!n)throw new Error(`this account owns no namespace ${e}; it owns: ${t.map(r=>r.namespaceId).join(", ")||"(none)"}`);return n}if(t.length===0)throw new Error("this account owns no namespaces in the cloud: claim one first, then enable HA on it so a relay is assigned");if(t.length>1)throw new Error(`this account owns ${t.length} namespaces \u2014 pass namespaceId to say which: ${t.map(n=>n.namespaceId).join(", ")}`);return t[0]}function ku(t,e){if(e.length===0)return t.haStatus==="enabled"?`namespace ${t.namespaceId} has HA enabled but no relay has been assigned to it yet \u2014 retry shortly`:`namespace ${t.namespaceId} has no relays: enable HA on it in the cloud to have an attested node assigned`;let n=e.filter(o=>o.teeRole!==null&&o.teeRole!=="RelayTee");if(n.length===e.length)return`every node on namespace ${t.namespaceId} is a read-only TEE replica (ReadOnlyTee), which never relays delegated writes: an admin of the namespace must set its TEE admission policy with mode: 'relay' \u2014 AdminClient.setTeeAdmissionPolicy(namespaceId, { ..., mode: 'relay' }) \u2014 so fleet nodes are admitted as RelayTee`;let r=e.filter(o=>o.teeRole===null&&!o.authorshipReady);return r.length>0&&r.length+n.length===e.length?`every relay on namespace ${t.namespaceId} is waiting for the authorship grant: an admin of the namespace must grant CAN_AUTHOR_ON_BEHALF to ${r.map(o=>o.executorAccount??o.peerId).join(", ")||"the relay account"} \u2014 with AdminClient.grantAuthorship(namespaceId, account) for these relays, and AdminClient.openToDelegatedExecution(namespaceId) so relays assigned later need no further op`:`namespace ${t.namespaceId} has ${e.length} relay(s), but none is ready to relay yet (a URL, an executor account and a recent heartbeat) \u2014 retry shortly`}function Eu(t){let e=`mero-js:warrant-nonce:${t}`;try{return It(e)}catch{return fo(1)}}var Iu=new TextEncoder().encode("calimero.mdma.routing-read.v1\0");async function Ls(t,e){m(e,"deviceSecret",32);let n=await re(e),r=f(Iu,new TextEncoder().encode(t)),o=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,r));return Pu(o)}async function Fn(t,e){return{"X-Calimero-Credential":e.credential,"X-Calimero-Nonce":t.nonce,"X-Calimero-Signature":await Ls(t.nonce,e.deviceSecret)}}function Pu(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var Tu="https://cloud.calimero.network";async function Hs(t){let e=new URL(t.cloudWebUrl??Tu),{callbackUrl:n,challenge:r}=await Qt(t.accountId,t.returnTo);return e.searchParams.set("link-account",t.accountId),e.searchParams.set("challenge",r),e.searchParams.set("callback-url",n),e.toString()}async function Du(t){throw window.location.assign(await Hs(t)),new Error("redirecting to the cloud to authorise this link")}function Uu(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Oe(t.search??"",null),yo(),new Error(n==="denied"?"the account link was declined at the cloud":`the cloud refused this link: ${n}`);let r=e.get("grant"),o=e.get("account");if(!r||!o)return null;let i=Oe(t.search??"",o),s=dt(r);if(!i||s?.account!==o)throw yo(),new Error("this account link answers a request this browser did not make - start the link again from here");return yo(),{grant:r,account:o,login:s.login,verifier:i}}function yo(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+Zo(location.search))}async function Ou(t){let e=await X(t.root);if(e.accountId!==t.account)throw new Error(`this grant is for account ${t.account}, but the root here derives ${e.accountId} \u2014 it was minted for a different account`);return new $({cloudBaseUrl:t.cloudBaseUrl,fetch:t.fetch}).linkAccountWithGrant({grant:t.grant,verifier:t.verifier,signer:e.signer})}var Nu="enrol-device",_u="enrol-kem",Mu="callback-url",js="state",bo="calimero.device.enrol.pending";function Fs(t){qs(t.devicePublicKey,"devicePublicKey"),qs(t.kemPublicKey,"kemPublicKey"),Hu(t.returnTo),Lu(t.returnTo);let e=new URL(t.walletUrl);return e.searchParams.set(Nu,t.devicePublicKey),e.searchParams.set(_u,t.kemPublicKey),e.searchParams.set(Mu,t.returnTo),e.searchParams.set(js,ut(bo,{})),e.toString()}function Gu(t){throw window.location.assign(Fs(t)),new Error("redirecting to the wallet to approve this device")}function Ku(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Ue(bo,e.get(js)),Bs(),new Error(n==="denied"||n==="cancelled"?"the device was not approved at the wallet":`the wallet refused this enrolment: ${n}`);let r=e.get("credential"),o=e.get("account"),i=e.get("device");if(!r||!o||!i)return null;Bs();let s=e.get("state");return{credential:r,account:o,device:i,...s?{state:s}:{}}}function Bs(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+location.search)}async function $u(t){if(!Ue(bo,t.state))throw new Error("this enrolment answers a request this app did not make - start the enrolment again from here");let e=await rn(t.credential);if(e.signPublicKey!==ve(t.devicePublicKey))throw new Error(`this credential certifies device key ${e.signPublicKey}, but this app holds ${ve(t.devicePublicKey)} \u2014 it would sign with a key the certificate does not cover`);if(t.kemPublicKey!==void 0&&e.kemPublicKey!==ve(t.kemPublicKey))throw new Error(`this credential names delivery key ${e.kemPublicKey}, not the one this app asked about \u2014 group keys would be sealed to somebody else`);if(e.account!==ve(t.account))throw new Error(`the wallet reported account ${ve(t.account)}, but the credential names ${e.account}`);if(e.device!==ve(t.device))throw new Error(`the wallet reported device ${ve(t.device)}, but the credential names ${e.device}`);return{credential:t.credential,account:e.account,device:e.device,certificate:e}}function qs(t,e){if(!/^[0-9a-f]{64}$/.test(t))throw new Error(`${e} must be 64 lowercase hex characters`)}function ve(t){return t.trim().toLowerCase()}function Vs(t,e){let n=e??(typeof window>"u"?void 0:window.location.origin);if(!n)return!1;try{return new URL(t).origin!==n}catch{return!1}}function Lu(t){Vs(t)&&console.warn(`[calimero] enrolling a device but sending the credential to ${new URL(t).origin}, which is not this page's origin. Legitimate when deliberate; worth a second look otherwise.`)}function Hu(t){let e;try{e=new URL(t)}catch{throw new Error(`returnTo must be an absolute URL, got ${t}`)}let n=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]"||e.hostname==="::1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new Error(`returnTo must be https:, or http: on localhost \u2014 got ${e.protocol}//${e.hostname}`)}function Vn(t){if(!t)return null;let e=t.trim().toLowerCase(),n=e.startsWith("0x")?e.slice(2):e;return n.length>0?n:null}function qu(t,e){if(e.size===0)return!0;let n=Vn(t.account);return n!==null&&e.has(n)}async function Wn(t){let e=t.cloud??new $({cloudBaseUrl:t.cloudBaseUrl,routingCredential:{credential:t.credential,deviceSecret:t.deviceSecret}}),n,r;try{let p=await e.getNamespaceRouting(t.namespaceId);n=p.nodes,r=p.servable}catch(p){return{ok:!1,step:"admitters-lookup",reason:`The cloud could not be asked which nodes serve namespace ${t.namespaceId}: ${p instanceof Error?p.message:String(p)}. Nothing is known about the invitation yet \u2014 this is the lookup failing, not the invitation.`}}if(n.length===0)return{ok:!1,step:"no-nodes",reason:"The cloud lists no nodes serving this namespace, so there is no hosted node to be admitted through. The namespace has no fleet assignment \u2014 whoever invited you is running their own node, and admission has to go through a node the cloud routes to."};let o=new Set((t.admitters??[]).map(Vn).filter(p=>p!==null)),i=n.filter(p=>qu(p,o));if(i.length===0)return{ok:!1,step:"not-invited",reason:`${n.length} node${n.length===1?"":"s"} serve this namespace, but your invitation names none of them. The signed admitter list is a snapshot from when the invitation was minted, so a node assigned since is healthy and will still refuse the claim. Ask for a fresh invitation.`};let s=i.filter(p=>p.canAdmit),a=s.length>0?s:i,c=s.length===0||!r,u=a.filter(p=>typeof p.relayUrl=="string"&&p.relayUrl.length>0),[d]=u;if(d===void 0)return{ok:!1,step:"no-relay-url",reason:"A node your invitation names can admit you, but the cloud knows no address for it yet, so there would be nothing to connect through afterwards. Try again shortly."};let l=u.find(p=>p.canExecute)??u.find(p=>p.fresh)??d;return{ok:!0,relayUrl:l.relayUrl,admitUrl:l.admitUrl??`${l.relayUrl.replace(/\/+$/,"")}/admin-api/namespaces/${g(t.namespaceId)}/admit`,admitterAccount:l.account,peerId:l.peerId,writable:l.canExecute,stale:!l.fresh||c}}var Jn=1440*60,Ao={Admin:0,Member:1,ReadOnly:2};function Ot(t){let e=t.admitters??[];return f(wo(t.inviter_identity,"inviter_identity"),wo(t.group_id,"group_id"),C(t.expiration_timestamp),wo(t.secret_salt,"secret_salt"),new Uint8Array([t.invited_role]),R(e.length),...e.map((n,r)=>m(n,`admitters[${r}]`,32)))}async function xo(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",Ot(t)))}function vo(t){return[...new Set(t.filter(n=>n.role==="Admin").map(n=>n.identity.toLowerCase()))].sort()}async function zn(t){let e=await I(t.deviceSecret,t.signer,"deviceSecret"),n=m(e.publicKey,"signer.publicKey",32),r=m(t.groupId,"groupId",32);m(t.inviterAccount,"inviterAccount",32);let o=[...t.admitters??[]].map(p=>p.trim().toLowerCase());if(o.length===0){if(!t.members)throw new Error("name the admitters, or pass the group members to default them to its admins: an invitation with no admitters is claimable by broadcast");if(o=vo(t.members),o.length===0)throw new Error("the member list names no admin, so there is nobody to default the admitters to")}o.forEach((p,x)=>m(p,`admitters[${x}]`,32));let i=t.invitedRole??Ao.Member;if(![0,1,2].includes(i))throw new Error(`invitedRole must be 0 (Admin), 1 (Member) or 2 (ReadOnly), got ${i}`);let s=t.now??Math.floor(Date.now()/1e3),a=Math.min(t.validForSecs??Jn,Jn);if(!Number.isInteger(a)||a<=0)throw new Error(`validForSecs must be a positive whole number, got ${t.validForSecs}`);let c=t.nonce??crypto.getRandomValues(new Uint8Array(32));if(c.length!==32)throw new Error(`nonce must be 32 bytes, got ${c.length}`);let u={inviter_identity:Array.from(n),group_id:Array.from(r),expiration_timestamp:s+a,secret_salt:Array.from(c),invited_role:i,admitters:o},d=await e.sign(await xo(u));if(d.length!==64)throw new Error(`signer returned ${d.length} bytes, expected a 64-byte Ed25519 signature`);let l={invitation:u,inviter_signature:y(d),inviter_account:t.inviterAccount.trim().toLowerCase()};return t.admitterAddrs?.length&&(l.admitter_addrs=[...t.admitterAddrs]),t.applicationId&&(l.application_id=Array.from(m(t.applicationId,"applicationId",32))),t.appKey&&(l.app_key=Array.from(m(t.appKey,"appKey",32))),l}function wo(t,e){if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return new Uint8Array(t)}var Ro=26,ju=new TextEncoder().encode("calimero.namespace.v1"),Fu=0,Ws={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreatedV2:9,MemberJoinedViaTeeAttestation:10};function Js(t,e){if(t==null)return new Uint8Array([0]);if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return f(new Uint8Array([1]),new Uint8Array(t))}function zs(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}function Qn(t){let e=t.invitation,n=t.admitter_addrs??[];return f(Ot(e),zs(t.inviter_signature),t.inviter_account?f(new Uint8Array([1]),m(t.inviter_account,"inviter_account",32)):new Uint8Array([0]),R(n.length),...n.map(zs),Js(t.application_id,"application_id"),Js(t.app_key,"app_key"))}async function Yn(t){let e=t.parentOpHashes??[],n=m(t.credential,"credential",t.credential.length/2),r=BigInt(t.invitation.invitation.expiration_timestamp??0)!==0n,o=t.joinedAt??BigInt(Math.floor(Date.now()/1e3)),i=r?f(new Uint8Array([Ws.MemberJoinedAt]),m(t.member,"member",32),Qn(t.invitation),C(o),n):f(new Uint8Array([Ws.MemberJoined]),m(t.member,"member",32),Qn(t.invitation),n),s=f(new Uint8Array([Fu]),i),a=await I(t.deviceSecret,t.signer,"deviceSecret"),c=m(a.publicKey,"signer.publicKey",32),u=f(new Uint8Array([Ro]),m(t.namespaceId,"namespaceId",32),R(e.length),...e.map((p,x)=>m(p,`parentOpHashes[${x}]`,32)),c,C(t.nonce),s),d=await a.sign(f(ju,u)),l=new Uint8Array([0]);return y(f(u,d,l))}function Vu(t,e){let n=e?`: ${e}`:"";switch(t){case 400:return`The node refused the join as malformed (400)${n}. The signature covers the invitation exactly as sent, so an edited or re-serialised invitation fails here \u2014 as does a namespace id that is not the invitation's own group.`;case 403:return`The node refused to carry this join (403)${n}. Either it is not in the invitation's signed admitters list \u2014 being live and listed by the cloud is not the same thing \u2014 or the invitation itself was rejected as expired or not the inviter\u2019s to issue.`;case 409:return`That node holds no device of its own, so it cannot endorse anyone (409)${n}. Another admitter from the same invitation would work.`;default:return`The join was not published (HTTP ${t})${n}.`}}function Wu(t){let e=It(`calimero.delegated.joinnonce.${t}`);return()=>e.next()}function Qs(t){return t.replace(/\/+$/,"")}async function Xn(t){let{account:e,credential:n,deviceSecret:r}=t.credential,o;try{o=await Yn({namespaceId:t.namespaceId,member:e,invitation:t.invitation,credential:n,deviceSecret:r,nonce:await(t.deps?.nonce??Wu(e))()})}catch(l){return{ok:!1,step:"sign",reason:`The join op could not be signed, so nothing was sent: ${l instanceof Error?l.message:String(l)}`}}let i={invitation:t.invitation,signedOp:o},s=t.admitUrl??`${Qs(t.nodeUrl)}/admin-api/namespaces/${g(t.namespaceId)}/admit`,a=t.deps?.fetch??fetch,c;try{c=await a(s,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(i)})}catch(l){return{ok:!1,step:"admit",reason:`The admitter at ${t.nodeUrl} could not be reached: ${l instanceof Error?l.message:String(l)}. The invitation is untouched \u2014 this is the node being unreachable, not a refusal.`}}let u=await c.text();if(!c.ok)return{ok:!1,step:"admit",status:c.status,reason:Vu(c.status,u)};let d=!1;try{d=(u?JSON.parse(u):{}).data?.published===!0}catch{d=!1}return{ok:!0,published:d,session:{relayUrl:Qs(t.nodeUrl),account:e,credential:n,deviceSecret:r}}}async function Zn(t){let e=t.deps?.resolve??Wn,n=t.deps?.join??Xn,r=null,o=t.nodeUrl,i;if(!o){let a=await e({namespaceId:t.namespaceId,admitters:t.invitation.invitation.admitters,credential:t.credential.credential,deviceSecret:t.credential.deviceSecret,cloudBaseUrl:t.cloudBaseUrl});if(a.ok===!1)return a;r=a,o=a.relayUrl,i=a.admitUrl}let s=await n({nodeUrl:o,admitUrl:i,namespaceId:t.namespaceId,invitation:t.invitation,credential:t.credential,deps:{fetch:t.deps?.fetch,nonce:t.deps?.nonce}});return s.ok===!1?s:{ok:!0,published:s.published,relay:r,session:s.session}}async function Ys(t,e,n,r){let i=await(r.bootstrap??Zn)({namespaceId:e,invitation:n,credential:{account:t.account,credential:t.credential,deviceSecret:t.deviceSecret},cloudBaseUrl:r.cloudBaseUrl});if(i.ok===!1)throw Object.assign(new Error(i.reason),{step:i.step,...i.status!==void 0?{status:i.status}:{}});return i.session.relayUrl&&xe(t.account,i.session.relayUrl,{namespaceId:e}),r.onJoined(jn(t,i.session)),{namespaceId:e}}function Xs(t){let e=new TextEncoder().encode(t),n=new Uint8Array(4+e.length);return new DataView(n.buffer).setUint32(0,e.length,!0),n.set(e,4),n}async function Co(t,e){let n=Xs(t),r=Xs(e),o=new Uint8Array(n.length+r.length);o.set(n,0),o.set(r,n.length);let i=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(i),s=>s.toString(16).padStart(2,"0")).join("")}function Ju(t,e){let[n,r]=[t,e].map(o=>o.split(/[.-]/).map(i=>Number.parseInt(i,10)||0));for(let o=0;o<Math.max(n.length,r.length);o++)if((n[o]??0)!==(r[o]??0))return(n[o]??0)>(r[o]??0);return!1}function Nt(t){return t.filter(e=>!e.yanked&&typeof e.appVersion=="string"&&e.appVersion.length>0).reduce((e,n)=>!e||Ju(n.appVersion,e.appVersion)?n:e,void 0)}async function _t(t,e,n=globalThis.fetch){let r=`${t.replace(/\/+$/,"")}/api/v2/bundles?package=${encodeURIComponent(e)}`,o=await n(r,{headers:{Accept:"application/json"}});if(!o.ok)throw new Error(`the registry has no ${e} (HTTP ${o.status})`);let i=await o.json();return Array.isArray(i)?i:[]}async function Zs(t,e,n={}){let o=(await _t(t,e,n.fetch)).filter(c=>!c.yanked),i=[...new Set(o.map(c=>c.signerId).filter(c=>typeof c=="string"&&c.length>0))];if(i.length>1)throw new Error(`the registry lists ${e} under more than one publisher (${i.join(", ")}): refusing to guess which application it is`);let s=Nt(o);if(!s)throw new Error(`the registry lists no version of ${e}`);let a=s.signerId;if(!a)throw new Error(`the registry names no publisher for ${e} ${s.appVersion}`);return{applicationId:await Co(e,a),signerId:a,version:s.appVersion}}function ta(t,e){return{next:async()=>zu(t,e)}}function zu(t,e){let n=`calimero.governance-nonce.${t}.${e}`,r=0n;try{r=BigInt(localStorage.getItem(n)??"0")}catch{}let o=[r+1n,BigInt(Date.now())].reduce((i,s)=>i>s?i:s);try{localStorage.setItem(n,String(o))}catch{}return o}function na(t,e){let n=q(t.account).namespaces[e]??t.relayUrl;if(!n)throw new Error("no relay is known for this namespace, so there is nowhere to send this");return n.replace(/\/+$/,"")}function Qu(t){return!t||t.length===0?{}:JSON.parse(new TextDecoder().decode(Uint8Array.from(t)))}function tr(t,e,n,r){return new J({relayUrl:e,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:n,fetch:r??Ze(e)})}async function Mt(t,e,n={}){let r=na(t,e.namespaceId),o=0n,i=await tr(t,r,{next:async()=>o},n.fetch).createContext({groupId:e.groupId??e.namespaceId,applicationId:e.applicationId,serviceName:e.serviceName,seed:e.contextSeed,initArgs:Qu(e.initializationParams),name:e.name});return Bn(r,i.contextId,o),xe(t.account,r,{namespaceId:e.namespaceId,contextId:i.contextId}),{contextId:i.contextId}}async function Ce(t,e,n={}){let r=na(t,e.namespaceId);return tr(t,r,ta(r,e.group),n.fetch).govern({groupId:e.group,op:e.op})}async function ra(t,e,n={}){let{groupId:r}=await Ce(t,{namespaceId:e.namespaceId,group:e.namespaceId,op:(await Fe({parentId:e.namespaceId,restricted:!0,admin:t.account})).op},n);for(let i of e.members)await Ce(t,{namespaceId:e.namespaceId,group:r,op:qe(i,"Member")},n);let{contextId:o}=await Mt(t,{...e,groupId:r},n);return{contextId:o,groupId:r}}async function nr(t,e={},n={}){let o=et(t).map(u=>u.replace(/\/+$/,""))[0];if(!o)throw new Error("no relay is known for this account, so there is nowhere to found a namespace");let i=await Yu(t,o,n.fetch),s=BigInt(Date.now()),a=await tr(t,o,{next:async()=>s++},n.fetch).foundNamespace({executor:i,...e.defaultCapabilities!==void 0?{defaultCapabilities:e.defaultCapabilities}:{},...e.application?{application:e.application}:{}});try{localStorage.setItem(`calimero.governance-nonce.${o}.${a.namespaceId}`,String(s))}catch{}if(xe(t.account,o,{namespaceId:a.namespaceId}),e.application&&a.applicationSet!==!0)throw new Error(`founded ${a.namespaceId} but could not give it its application: ${a.applicationError??"unknown reason"}`);let c=a.teeEnabled?await Zu(t,a.namespaceId,a.salt,o,n):{haEnabled:!1,haError:`the relay did not attest the founding, so no fleet node could be admitted for HA${a.teeError?`: ${a.teeError}`:""}`};return{namespaceId:a.namespaceId,teeEnabled:a.teeEnabled,...c}}async function Yu(t,e,n){let r=t.executorAccount&&t.relayUrl?.replace(/\/+$/,"")===e?t.executorAccount:null;if(r)return{executorAccount:r,executorKey:await ea(e)};let o=Object.entries(q(t.account).namespaces).find(([,a])=>a.replace(/\/+$/,"")===e)?.[0];if(!o)throw new Error("the executor account of this relay is not known: join a namespace on it first, or connect with the relay's executor account (the cloud shows it beside the relay)");let i=await ea(e),s=await tr(t,e,ta(e,o),n).describeGovernance(o);if(s.executorKey?.toLowerCase()!==i)throw new Error(`the relay's discovery names signing key ${s.executorKey}, not the relay's node key ${i}: refusing to found through it`);return{executorAccount:s.executorAccount,executorKey:i}}async function ea(t){let e=await Ae(t,{fresh:!0});if(e.kind==="learned")return e.nodeKey;throw new Error(e.kind==="unavailable"?"the relay's signing key could not be learned: its attestation did not answer, try again":"the relay's attestation was refused, so founding through it is not possible: it is not a signed locked-read-only release")}var rr="link this account to your cloud user in the wallet so the cloud can host this namespace on its fleet",er={account_not_linked:rr,account_linked_to_several_users:"this account is linked to more than one cloud user, so the cloud cannot tell whose plan hosts the namespace: unlink it from all but one in the wallet",ha_request_pending:"another namespace of this account is still waiting to be hosted; the cloud hosts one new namespace at a time without a cloud sign-in. Sign in to the cloud and turn off hosting for the waiting namespace, or wait until it is hosted",unknown_relay:"the cloud does not run the relay this namespace was founded on, so it cannot host it",relay_not_dialable:"the relay this namespace was founded on has not reported its address to the cloud yet; try enabling hosting again shortly"};function Xu(t){try{let e=JSON.parse(t.bodyText??""),n=e?.detail?.namespace_id??e?.namespace_id;return typeof n=="string"&&/^[0-9a-f]{64}$/i.test(n)?n.toLowerCase():null}catch{return null}}async function Zu(t,e,n,r,o){try{return await new $({cloudBaseUrl:o.cloudBaseUrl,fetch:o.fetch}).enableHaAsAccount({namespaceId:e,salt:n,accountId:t.account,credential:t.credential,deviceSecret:t.deviceSecret,relayUrl:r}),{haEnabled:!0}}catch(i){if(i instanceof Re)return{haEnabled:!1,haError:rr};if(i instanceof z&&er[i.code]){let s=i.code==="ha_request_pending"?Xu(i):null,a=er[i.code];return{haEnabled:!1,haError:s?`${a} (waiting: ${s})`:a}}return{haEnabled:!1,haError:i instanceof Error?i.message:String(i)}}}async function tt(t,e,n=globalThis.fetch){let r=Nt(await _t(t,e,n));if(!r)throw new Error(`the registry lists no version of ${e}`);return r.appVersion}var oa="calimero.delegated.group-namespace.",So=new Map;function ia(t){let e={};try{e=JSON.parse(localStorage.getItem(oa+t)??"{}")}catch{}return{...e,...So.get(t)}}function Gt(t,e,n){So.set(t,{...So.get(t),[e]:n});try{let r=ia(t);r[e]=n,localStorage.setItem(oa+t,JSON.stringify(r))}catch{}}function Kt(t,e){return q(t.account).namespaces[e]?e:ia(t.account)[e]}function sa(t,e){let n=Kt(t,e);if(!n)throw new Error(`the namespace of group ${e} is not known to this account: it can manage only groups in namespaces it joined or subgroups it created`);return n}async function or(t,e,n){return Ce(t,{namespaceId:sa(t,e),group:e,op:n})}async function ir(t,e,n){let r=sa(t,e);return Ce(t,{namespaceId:r,group:r,op:n})}var Se=class extends Error{constructor(n){super(`${n} is not available for an account: it needs a node`);this.method=n;this.name="NotForAccountError"}},nt=class extends Error{constructor(n){super(`${n} needs a relay, and this account has none yet: join from an invitation first`);this.method=n;this.name="NoRelayError"}},rt=class extends Error{constructor(n,r){super(r==="not-hosted"?`nobody could claim an invitation to ${n} yet: the cloud lists no node holding the namespace, so an invitee with no node of their own has no relay to be admitted through.`:`nobody could claim an invitation to ${n}: the cloud routes to none of the relays or admins it would name as admitters`);this.namespaceId=n;this.reason=r;this.name="InvitationNotClaimableError"}},aa={listNamespaces:async()=>[],listNamespacesForApplication:async()=>[],getContexts:async()=>({contexts:[]})},ed=new Set(["upgradeGroup","retryGroupUpgrade","activateGroupUpgrade","abortMigration","installApplication","installDevApplication","uninstallApplication","generateContextIdentity","deleteContext","leaveContext","createContextAlias","createApplicationAlias","createDeviceAlias","deleteContextAlias","deleteApplicationAlias","deleteDeviceAlias","lookupContextAlias","lookupApplicationAlias","lookupDeviceAlias","listContextAliases","listApplicationAliases","listDeviceAliases","deleteNamespace","createGroupInvitation","joinGroup","setTeeAdmissionPolicy","getTeeAdmissionPolicy","deleteBlob","listAccountDevices","revokeAccountDevice"]);function td(t){if(!(t instanceof Error))return!1;let e=t.status;return(e===void 0||e===409)&&/signer [0-9a-f]+ is a direct member/i.test(t.message)}function ca(t,e={}){let{session:n,read:r,app:o}=t,i=e.govern?.group??or,s=e.govern?.root??ir,a=e.createContext??Mt,c=e.found??nr,u=e.latestVersion??tt,d=e.signInvitation??zn,l=e.join,p=e.routing;async function x(h,w){if(!l)throw new Se("joinNamespace without a join handler");return l(h,w.invitation)}let v=()=>{if(r===null)throw new nt("this call");return r};async function P(h){if(Kt(n,h))return;let w=await v().getGroupInfo(h);Gt(n.account,h,w.namespaceId??h)}let b=async(h,w,S)=>(await P(w),i(h,w,S)),k=async(h,w,S)=>(await P(w),s(h,w,S));async function T(h){try{return await k(n,h,_n({member:n.account,groupId:h,credential:n.credential})),!0}catch(w){if(td(w))return!1;throw w}}async function H(h,w){let S=w??String(await v().getContextGroup(h)),{members:U}=await v().listGroupMembers(S);return U.some(M=>M.identity.toLowerCase()===n.account.toLowerCase())}let Q={async listNamespacesForApplication(h){return(await v().listNamespaces()).filter(w=>w.targetApplicationId===h)},async getNodeIdentity(){return{accountId:n.account,deviceId:null,publicKey:"",deviceCertified:!0}},async createNamespace(h){if(!o.packageName)throw new Se("createNamespace without a packageName");let w=o.packageVersion??await u(o.registryUrl??"https://apps.calimero.network",o.packageName),{namespaceId:S,haEnabled:U,haError:M}=await c(n,{defaultCapabilities:231,application:{applicationId:h.applicationId,package:o.packageName,version:w}});return h.name&&await b(n,S,Ve({name:h.name})),{namespaceId:S,haEnabled:U,...M!==void 0?{haError:M}:{}}},async createGroupInNamespace(h,w={}){let{op:S}=await Fe({parentId:h,restricted:w.visibility==="restricted",admin:n.account}),{groupId:U}=await k(n,h,S);return Gt(n.account,U,h),w.groupName&&await b(n,U,Ve({name:w.groupName})),{groupId:U}},async addGroupMembers(h,w){for(let S of w.members)await b(n,h,qe(S.identity,S.role??"Member"))},async removeGroupMembers(h,w){for(let S of w.members)await b(n,h,Rn(S))},async setGroupMetadata(h,w){await b(n,h,Ve(w))},async setMemberMetadata(h,w,S){await b(n,h,On(w,S))},async setContextMetadata(h,w,S){await b(n,h,Nn(w,S))},async setDefaultCapabilities(h,w){await b(n,h,je(w.defaultCapabilities))},async setSubgroupVisibility(h,w){await b(n,h,Un(w.subgroupVisibility==="open"?"open":"restricted"))},async setMemberCapabilities(h,w,S){await b(n,h,Tn(w,S.capabilities))},async deleteGroup(h){return await k(n,h,En(h)),{isDeleted:!0}},async reparentGroup(h,w){return await k(n,h,kn(h,w.newParentId)),{reparented:!0}},async leaveGroup(h){await b(n,h,kt(n.account))},async leaveNamespace(h){await b(n,h,kt(n.account))},async getContextIdentitiesOwned(h){return{identities:await H(h)?[n.account]:[]}},async joinContext(h){return await T(String(await v().getContextGroup(h))),{contextId:h,memberPublicKey:n.account}},async createContext(h){let S=(await v().getGroupInfo(h.groupId)).namespaceId??h.groupId,{contextId:U}=await a(n,{namespaceId:S,groupId:h.groupId,applicationId:h.applicationId,serviceName:h.serviceName,contextSeed:h.contextSeed,name:h.name,initializationParams:h.initializationParams});return{contextId:U,memberPublicKey:n.account,groupId:h.groupId}},async createNamespaceInvitation(h){let[{members:w},S]=await Promise.all([v().listGroupMembers(h),v().getGroupInfo(h)]),U=w.filter(Y=>Y.role==="RelayTee").map(Y=>Y.identity.toLowerCase());if(p){let Y=new Set(U.length>0?U:w.filter(ne=>ne.role==="Admin").map(ne=>ne.identity.toLowerCase())),te=null;try{te=(await p(h)).nodes}catch{}if(te!==null){if(te.length===0)throw new rt(h,"not-hosted");if(!te.some(ne=>ne.account!==null&&Y.has(ne.account.toLowerCase())))throw new rt(h,"no-named-node")}}return{invitation:await d({groupId:h,inviterAccount:n.account,deviceSecret:n.deviceSecret,...U.length>0?{admitters:U}:{},members:w,applicationId:S.targetApplicationId,appKey:S.appKey})}},async syncGroup(h){return{groupId:h,synced:!0}},async syncContext(){},joinNamespace:x,async updateMemberRole(h,w,S){await b(n,h,Cn(w,S.role))},async joinSubgroupInheritance(h){return{groupId:h,memberPublicKey:n.account,wasInherited:await T(h)}},async detachContextFromGroup(h,w){await b(n,h,Dn(w))}};return r===null?new Proxy({},{get(h,w){if(typeof w=="string")return w==="getNodeIdentity"?Q.getNodeIdentity:w==="joinNamespace"?x:w in aa?aa[w]:async()=>{throw new nt(w)}}}):new Proxy(r,{get(h,w,S){return typeof w=="string"&&w in Q?Q[w]:typeof w=="string"&&ed.has(w)?async()=>{throw new Se(w)}:Reflect.get(h,w,S)}})}function la(t,e={}){let{admin:n,app:r}=t,o=e.latestVersion??tt;async function i(a){let{apps:c}=await n.listApplications();if(c.some(l=>l.id===a))return;if(!r.packageName)throw new Error(`application ${a} is not installed on this node, and no packageName is set to install it`);let u=r.packageVersion??await o(r.registryUrl??"https://apps.calimero.network",r.packageName),{applicationId:d}=await n.installApplication({package:r.packageName,version:u});if(d!==a)throw new Error(`installed ${r.packageName}@${u} as ${d}, not ${a}`)}let s={async createNamespace(a){return await i(a.applicationId),n.createNamespace(a)}};return new Proxy(n,{get(a,c,u){return typeof c=="string"&&c in s?s[c]:Reflect.get(a,c,u)}})}var nd="https://manager.cloud.calimero.network";function ko(t,e){return typeof t.can_execute=="boolean"?t.can_execute:e}function Eo(t){return typeof t.tee_role=="string"&&t.tee_role!==""?t.tee_role:null}function ho(t){return t.find(e=>e.canExecute&&e.relayUrl!==null&&e.executorAccount!==null)??null}function rd(t){let e=t.join;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(typeof n.state!="string")return null;let r=Array.isArray(n.refusals)?n.refusals.filter(o=>!!o&&typeof o=="object").map(o=>({peer:String(o.peer??""),reason:String(o.reason??"")})):[];return{state:n.state,attempts:typeof n.attempts=="number"?n.attempts:0,refusals:r,error:typeof n.error=="string"?n.error:null,reportedAt:typeof n.reported_at=="string"?n.reported_at:null}}function od(t){return typeof t=="string"&&Ar.test(t)?t:null}var z=class extends O{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.code=n;this.name="AccountHaRefusedError"}},Re=class extends z{constructor(){super(...arguments);this.name="AccountNotLinkedError"}};Re.CODE="account_not_linked";var Pt=class extends z{constructor(){super(...arguments);this.name="AccountLinkedToSeveralUsersError"}};Pt.CODE="account_linked_to_several_users";var Tt=class extends z{constructor(){super(...arguments);this.name="HaRequestPendingError"}};Tt.CODE="ha_request_pending";var Dt=class extends z{constructor(){super(...arguments);this.name="UnknownRelayError"}};Dt.CODE="unknown_relay";var Ut=class extends z{constructor(){super(...arguments);this.name="RelayNotDialableError"}};Ut.CODE="relay_not_dialable";var ua={409:[Re,Pt,Tt],422:[Dt,Ut]};function id(t){if(t)try{let e=JSON.parse(t);if(typeof e?.error=="string")return e.error;if(typeof e?.detail=="string")return e.detail;let n=e?.detail?.error;if(typeof n=="string")return n}catch{}}var sd="x-mdma-session-refresh",ad="x-mdma-session-expires",$=class{constructor(e={}){this.session=null;this.baseUrl=(e.cloudBaseUrl||nd).replace(/\/+$/,""),this.onSession=e.onSession;let n=e.fetch;this.fetchImpl=n?(r,o)=>n(r,o):(r,o)=>globalThis.fetch(r,o),this.timeoutMs=e.timeoutMs??1e4,this.routingCredential=e.routingCredential,e.sessionToken&&(this.session={sessionToken:e.sessionToken,expiresAt:0,user:{email:""}})}getSession(){return this.session}isSignedIn(){return this.session!==null}async signInWithGoogle(e){let n=await this.request("POST","/api/auth/google",{body:{id_token:e},anonymous:!0});return this.adoptSession(n)}async signInWithAccount(e){let{signer:n,publicKey:r}=await X(e),{nonce:o}=await this.getAccountLoginChallenge();return this.submitAccountLogin({rootPublicKey:r,nonce:o,signature:await an({signer:n,nonce:o})})}async getAccountLoginChallenge(){let e=await this.request("GET","/api/auth/account/challenge",{anonymous:!0});return{nonce:e.nonce,expiresAtMs:e.expires_at_ms}}async submitAccountLogin(e){let n=await this.request("POST","/api/auth/account",{body:{root_public_key:e.rootPublicKey,nonce:e.nonce,signature:e.signature},anonymous:!0});return this.adoptSession(n)}async refreshSession(){let e=await this.request("POST","/api/auth/refresh");return this.adoptSession(e)}async signOut(){try{this.session&&await this.request("POST","/api/auth/logout",{parse:"none"})}finally{this.session=null,this.notifySession(null)}}async getMyNamespaces(){return(await this.request("GET","/api/cloud/me/namespaces")).map(n=>({namespaceId:String(n.namespace_id??n.group_id??""),groupId:String(n.group_id??n.namespace_id??""),haStatus:String(n.ha_status??"none"),haEnabledAt:n.ha_enabled_at??null,contexts:Array.isArray(n.contexts)?n.contexts:[],fleetReplicas:n.fleet_replicas}))}async getNamespaceRelays(e){return((await this.request("GET",`/api/cloud/me/namespaces/${g(e)}/relays`)).relays??[]).map(r=>{let o=r.relay_url??null,i=r.executor_account??null,s=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),relayUrl:o,executorAccount:i,nodeKey:r.node_key??r.node_public_key??null,status:String(r.status??""),authorshipReady:s,teeRole:Eo(r),canExecute:ko(r,s&&o!==null&&i!==null),lastSeenAt:r.last_seen_at??null,confirmedAt:r.confirmed_at??null,admission:typeof r.admission=="string"?r.admission:null,admissionHint:typeof r.admission_hint=="string"?r.admission_hint:null,join:rd(r)}})}async findExecutingRelay(e){let n=await this.getNamespaceRelays(e);return ho(n)}async getNamespaceRouting(e){let n=await this.request("GET",`/api/cloud/namespaces/${g(e)}/admitters`,{anonymous:!0,headers:await this.routingProof(e)});return{namespaceId:String(n.namespace_id??e),nodes:(n.admitters??[]).map(r=>{let o=r.account??null,i=r.relay_url??null,s=r.fresh===!0,a=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),account:o,relayUrl:i,admitUrl:r.admit_url??null,status:String(r.status??""),fresh:s,canAdmit:r.can_admit===!0,authorshipReady:a,teeRole:Eo(r),canExecute:ko(r,a&&i!==null&&o!==null&&s)}}),servable:n.servable===!0,writable:n.writable===!0}}async getRoutingChallenge(e){let n=await this.request("GET",`/api/cloud/namespaces/${g(e)}/challenge`,{anonymous:!0});return{namespaceId:String(n.namespace_id??e),nonce:String(n.nonce??""),expiresAtMs:Number(n.expires_at_ms??0)}}async routingProof(e){if(!this.routingCredential)return;let n=await this.getRoutingChallenge(e);return Fn(n,this.routingCredential)}async getAccountRelaysChallenge(e){let n=await this.request("GET",`/api/cloud/accounts/${g(e)}/challenge`,{anonymous:!0});return{accountId:String(n.account_id??e),nonce:String(n.nonce??""),expiresAtMs:Number(n.expires_at_ms??0)}}async getAccountRelays(e){if(!this.routingCredential)throw new Error("getAccountRelays needs a routingCredential: construct the client with the device certificate and its signing secret, since this read is proven by the device, not by a session.");let n=await this.getAccountRelaysChallenge(e);return((await this.request("GET",`/api/cloud/accounts/${g(e)}/relays`,{anonymous:!0,headers:await Fn(n,this.routingCredential)})).relays??[]).map(o=>({peerId:String(o.peer_id??""),relayUrl:o.relay_url??null,fresh:o.fresh===!0,executorAccount:od(o.executor_account),assigned:o.assigned===!0}))}async findAdmitter(e,n){let{nodes:r}=await this.getNamespaceRouting(e),o=n&&n.length>0?new Set(n.map(i=>i.toLowerCase())):null;return r.find(i=>i.canAdmit&&(o===null||i.account!==null&&o.has(i.account.toLowerCase())))??null}async getMyMachines(){return((await this.request("GET","/api/cloud/me/machines")).machines??[]).map(n=>{let r=n.relay_url??null,o=n.executor_account??null,i=(Array.isArray(n.namespaces)?n.namespaces:[]).map(s=>{let a=s;return{namespaceId:String(a.namespace_id??""),status:String(a.status??""),authorshipReady:a.authorship_ready===!0,teeRole:Eo(a),fresh:a.fresh===!0,confirmedAt:a.confirmed_at??null,lastSeenAt:a.last_seen_at??null}});return{peerId:String(n.peer_id??""),relayUrl:r,executorAccount:o,canExecute:ko(n,r!==null&&o!==null&&i.some(s=>s.authorshipReady)),namespaces:i}})}async claimNamespace(e,n){await this.request("POST","/api/cloud/namespaces/claim",{body:{namespace_id:e,ownership_proof:n}})}async enableNamespaceHa(e,n={}){let r=n.admitterAddrs===void 0?{}:{admitter_addrs:[...n.admitterAddrs]};return this.request("POST",`/api/cloud/namespaces/${g(e)}/enable-ha`,{body:r})}async enableFoundedNamespaceHa(e,n){return this.request("POST",`/api/cloud/me/namespaces/${g(e)}/enable-ha`,{body:{groups:[],ownership_proof:n}})}async enableHaAsAccount(e){let n=await Er({namespaceId:e.namespaceId,accountId:e.accountId,salt:e.salt,credential:e.credential,deviceSecret:e.deviceSecret,signer:e.signer,ttlMs:e.ttlMs,relayUrl:e.relayUrl}),r=e.accountId.toLowerCase(),o=e.namespaceId.toLowerCase();try{return await this.request("POST",`/api/cloud/accounts/${g(r)}/namespaces/${g(o)}/enable-ha`,{body:{ownership_proof:n},anonymous:!0})}catch(i){if(i instanceof O&&ua[i.status]){let s=id(i.bodyText),a=ua[i.status].find(c=>c.CODE===s);if(a&&s)throw new a(s,i.status,i.statusText,i.url,i.headers,i.bodyText)}throw i}}async disableNamespaceHa(e){return this.request("POST",`/api/cloud/namespaces/${g(e)}/disable-ha`,{body:{}})}async getMyNode(){return(await this.request("GET","/api/cloud/me/node")).node??null}enableHA(e){let n=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&n.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/enable-ha?${n.toString()}`)}disableHA(e){let n=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&n.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/disable-ha?${n.toString()}`)}async linkAccount(e){let{signer:n,publicKey:r,accountId:o}=await X(e),{nonce:i}=await this.getAccountLinkChallenge();return this.submitAccountLink({accountId:o,rootPublicKey:r,nonce:i,signature:await mt({signer:n,nonce:i})})}async getAccountLinkChallenge(){let e=await this.request("GET","/api/cloud/me/accounts/challenge");return{nonce:e.nonce,expiresAtMs:e.expires_at_ms??null}}async submitAccountLink(e){let n=await this.request("POST","/api/cloud/me/accounts",{body:{account_id:e.accountId,root_public_key:e.rootPublicKey,nonce:e.nonce,signature:e.signature}});return{accountId:String(n.account_id??e.accountId),linkedAt:n.linked_at??null,alreadyLinked:n.already_linked===!0}}static async accountLinkHandoff(e){let n=e.portalUrl.replace(/\/+$/,""),{callbackUrl:r,challenge:o}=await Qt(e.accountId,e.callbackUrl),i=new URLSearchParams({"link-account":e.accountId,challenge:o,"callback-url":r});return{url:`${n}/?${i.toString()}`,accountId:e.accountId}}static readAccountLinkCallback(e){let n=e??(typeof window>"u"?"":window.location.href);if(!n)return{};let r,o;try{({hash:r,search:o}=new URL(n))}catch{return{}}let i=new URLSearchParams(r.replace(/^#/,"")),s=i.get("grant"),a=i.get("account"),c=i.get("error"),u={};if(c&&Oe(o,null),s){let d=Oe(o,a),l=dt(s);if(!d||l?.account!==a)return{error:"unexpected_callback"};u.grant=s,u.login=l.login,u.verifier=d}return a&&(u.accountId=a),c&&(u.error=c),u}async linkAccountWithGrant(e){if(typeof e.verifier!="string"||!xr.test(e.verifier))throw new Error("no verifier for this grant - start the link again from this browser");let n=dt(e.grant);if(n?.challenge!==await vr(e.verifier))throw new Error("this grant was not issued to this link request - start the link again from this browser");let{signer:r,publicKey:o,accountId:i}=await sn(e.rootSecret,e.signer);if(n.account!==i)throw new Error(`this grant is for account ${n.account}, but the root here derives ${i} - it was minted for a different account`);let s=await this.request("POST","/api/cloud/accounts/link",{body:{grant:e.grant,verifier:e.verifier,root_public_key:o,signature:await mt({signer:r,nonce:e.grant})},anonymous:!0});return{accountId:String(s.account_id??i),linkedAt:s.linked_at??null,alreadyLinked:s.already_linked===!0}}async getMyAccounts(){let e=await this.request("GET","/api/cloud/me/accounts");return{accounts:(e.accounts??[]).map(n=>({accountId:String(n.account_id??""),linkedAt:n.linked_at??null,hasRecoveryEnvelope:n.has_recovery_envelope===!0})),limit:e.limit??null}}adoptSession(e){return this.session={sessionToken:e.session_token,expiresAt:e.expires_at,user:e.user},this.notifySession(this.session),this.session}async notifySession(e){try{await this.onSession?.(e)}catch{}}async request(e,n,r={}){if(!r.anonymous&&!this.session)throw new Error("Not signed in to Calimero Cloud: call signInWithGoogle() or construct the client with a sessionToken");let o={...r.headers,Accept:"application/json"};r.body!==void 0&&(o["Content-Type"]="application/json"),!r.anonymous&&this.session&&(o.Authorization=`Bearer ${this.session.sessionToken}`);let i=new AbortController,s=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r.body===void 0?void 0:JSON.stringify(r.body),signal:i.signal})}catch(c){throw new O(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(this.adoptRollingRefresh(a),!a.ok){let c=await a.text().catch(()=>{});throw new O(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(!(r.parse==="none"||a.status===204))return await a.json()}adoptRollingRefresh(e){let n=e.headers.get(sd);if(!n||!this.session)return;let r=e.headers.get(ad),o=Number(r);this.session={sessionToken:n,expiresAt:Number.isFinite(o)&&o>0?o:this.session.expiresAt,user:this.session.user},this.notifySession(this.session)}};function Bu(t){let e=t&&typeof t=="object"?t.data??t:void 0;if(!e||typeof e!="object")return[];let n=e.localPeerId,r=e.externalAddrs;if(typeof n!="string"||!n||!Array.isArray(r))return[];let o=`/p2p/${n}`,i=[];for(let s of r){if(typeof s!="string")continue;let a=s.trim();if(!a.startsWith("/"))continue;let c=a.endsWith(o)?a:`${a}${o}`;i.includes(c)||i.push(c)}return i}function cd(t){if(t)return typeof t=="function"?t:Xt(t)}var ld="mero-js:token-refresh";function ud(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function dd(t){try{let{origin:e,pathname:n}=new URL(t);return e==="null"?t:e+n.replace(/\/+$/,"")}catch{return t}}function Io(t,e){try{let n=t.split(".");if(n.length===3){let r=n[1].replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4;)r+="=";let o=JSON.parse(atob(r));if(typeof o.exp=="number")return o.exp*1e3}}catch{}return e}var Qe=class{constructor(e){this.tokenData=null;this.refreshPromise=null;this.storeHoldsTokens=!1;this.tokenGeneration=0;this.onStorage=()=>{this.signedOutElsewhere()&&this.dropLocalTokens()};this.rpcClient=null;this.sseClient=null;this.wsClient=null;this.wsWarned=!1;this.config={timeoutMs:1e4,...e},this.tokenStore=e.tokenStore??null,this.nodeKey=dd(e.baseUrl),this.tokenData=this.readStoredTokens(),this.tokenStore&&(this.storeHoldsTokens=this.tokenData!==null,typeof window<"u"&&window.addEventListener("storage",this.onStorage));let n=typeof window<"u"&&"__TAURI_INTERNALS__"in window,r=cd(this.config.requestProof);this.httpClient=De({baseUrl:this.config.baseUrl,fetch:this.config.fetch,getProof:r,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",refreshToken:async()=>(await this.performTokenRefresh()).access_token,onTokenRefresh:async o=>{this.tokenData&&(this.tokenData.access_token=o,this.persistTokens())},onAuthRevoked:async()=>{this.clearToken();try{await this.config.onAuthRevoked?.()}catch{}},timeoutMs:this.config.timeoutMs,credentials:this.config.requestCredentials??(n?"omit":void 0)}),this.authClient=Bo(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs}),this.adminClient=zt(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs})}get auth(){return this.authClient}get admin(){return this.adminClient}get rpc(){return this.rpcClient||(this.rpcClient=new pt({httpClient:this.httpClient})),this.rpcClient}get events(){return this.sseClient||(this.sseClient=new B({baseUrl:this.config.baseUrl,fetch:this.config.fetch,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.sseClient}get ephemeral(){return this.ephemeralClient||(this.ephemeralClient=new gt({httpClient:this.httpClient,sse:this.events})),this.ephemeralClient}get cloud(){return this.cloudClient||(this.cloudClient=new $(this.config.cloud??{})),this.cloudClient}get ws(){return this.wsWarned||(this.wsWarned=!0,console.warn("[mero-js] WsClient is experimental. Use mero.events (SSE) for production.")),this.wsClient||(this.wsClient=new se({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.wsClient}async authenticate(e){let n=e||this.config.credentials;if(!n)throw new Error("No credentials provided for authentication");try{let r={auth_method:"user_password",public_key:n.username,client_name:"mero-js-sdk",permissions:["admin"],timestamp:Math.floor(Date.now()/1e3),provider_data:{username:n.username,password:n.password}},o=await this.authClient.generateTokens(r),i=o.data.access_token;return this.tokenData={access_token:i,refresh_token:o.data.refresh_token,expires_at:Io(i,Date.now()+36e5)},this.persistTokens(),this.tokenData}catch(r){throw new Error(`Authentication failed: ${r instanceof Error?r.message:"Unknown error"}`)}}persistTokens(){!this.tokenStore||!this.tokenData||(this.tokenStore.setTokens({...this.tokenData,node_origin:this.nodeKey}),this.storeHoldsTokens=this.tokenStore.getTokens()!==null)}readStoredTokens(){let e=this.tokenStore?.getTokens();return!e||e.node_origin!==this.nodeKey?null:{access_token:e.access_token,refresh_token:e.refresh_token,expires_at:e.expires_at}}signedOutElsewhere(){return this.storeHoldsTokens&&!this.tokenStore?.getTokens()}dropLocalTokens(){this.tokenGeneration++,this.refreshPromise=null,this.tokenData=null,this.storeHoldsTokens=!1}async getValidToken(){return this.tokenData}async performTokenRefresh(){if(this.refreshPromise)return this.refreshPromise;let e=this.tokenData?.access_token,n=this.withRefreshLock(()=>this.performTokenRefreshLocked(e));this.refreshPromise=n;try{return await n}finally{this.refreshPromise===n&&(this.refreshPromise=null)}}withRefreshLock(e){if(this.tokenStore?.withLock)return this.tokenStore.withLock(e);let n=ud();return n?n.request(ld,e):e()}async performTokenRefreshLocked(e){if(this.signedOutElsewhere())throw this.dropLocalTokens(),new Error("Signed out in another tab");let n=this.readStoredTokens();if(n?.refresh_token&&(this.storeHoldsTokens=!0,this.tokenData=n,e&&n.access_token!==e))return n;if(!this.tokenData?.refresh_token)throw new Error("No refresh token available");let r=this.tokenGeneration,o=this.tokenData.access_token,i=this.tokenStore?.getTokens()?.access_token===o;try{let s=await this.authClient.refreshToken({access_token:this.tokenData.access_token,refresh_token:this.tokenData.refresh_token});if(r!==this.tokenGeneration)throw new Error("Signed out during token refresh");if(i&&this.tokenStore?.getTokens()?.access_token!==o)throw this.tokenData=this.tokenStore?.getTokens()??null,this.storeHoldsTokens=this.tokenData!==null,new Error("Signed out during token refresh");let a=s.data.access_token;return this.tokenData={access_token:a,refresh_token:s.data.refresh_token,expires_at:Io(a,Date.now()+36e5)},this.persistTokens(),this.tokenData}catch(s){throw new Error(`Token refresh failed: ${s instanceof Error?s.message:"Unknown error"}`)}}clearToken(){this.dropLocalTokens(),this.tokenStore?.clear()}isAuthenticated(){return this.tokenData!==null}setTokenData(e){let n=e.expires_at||Io(e.access_token,Date.now()+36e5);this.tokenData={...e,expires_at:n},this.persistTokens()}getTokenData(){return this.tokenData}close(){typeof window<"u"&&window.removeEventListener("storage",this.onStorage),this.sseClient?.close(),this.wsClient?.close()}static parseAuthCallback(e,n){return Rr(e,n)}static buildAuthLoginUrl(e,n){return Cr(e,n)}};function pd(t){return new Qe(t)}var Po=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},gd="mero-tokens",To=class{constructor(e=gd){this.key=e}getTokens(){try{if(typeof localStorage>"u")return null;let e=localStorage.getItem(this.key);if(!e)return null;let n=JSON.parse(e);return n&&n.access_token&&n.refresh_token?{access_token:n.access_token,refresh_token:n.refresh_token,expires_at:typeof n.expires_at=="number"?n.expires_at:Date.now()+36e5,...typeof n.node_origin=="string"&&{node_origin:n.node_origin}}:null}catch{return null}}setTokens(e){try{if(typeof localStorage>"u")return;localStorage.setItem(this.key,JSON.stringify(e))}catch{}}clear(){try{if(typeof localStorage>"u")return;localStorage.removeItem(this.key)}catch{}}};var md=new TextEncoder().encode("calimero.account.owner-op.v1"),fd=new TextEncoder().encode("calimero.account.owner-op.body.v1"),hd=new TextEncoder().encode("calimero.account.genesis.v1"),yd=2,Do={transferOwnership:0,adminChanged:1,groupDelete:2,teeAdmissionPolicy:3,teeAuthoringPolicy:4,teeReleaseAdmissionPolicy:5},ot={GroupDelete:14,TransferOwnership:21,TeeAuthoringPolicySet:33,TeeAdmissionPolicySetV2:37,TeeReleaseAdmissionPolicySetV2:38,RootGuarded:42},pa={AdminChanged:3,RootGuarded:12},bd={replica:0,relay:1},wd=new TextEncoder;function L(t){return new Uint8Array([t])}function ga(t){let e=wd.encode(t);return f(R(e.length),e)}function ee(t){return f(R(t.length),...t.map(ga))}function ma(t){return L(t?1:0)}function fa(t){let e=bd[t??"replica"];if(e===void 0)throw new Error(`mode must be replica or relay, got ${String(t)}`);return L(e)}function ha(t){return{kind:"transferOwnership",plane:"group",bytes:f(L(ot.TransferOwnership),m(t,"newOwner",32))}}function ya(){return{kind:"groupDelete",plane:"group",bytes:L(ot.GroupDelete)}}function ba(t){return{kind:"adminChanged",plane:"root",bytes:f(L(pa.AdminChanged),m(t,"newAdmin",32))}}function wa(t){return{kind:"teeAuthoringPolicy",plane:"group",bytes:f(L(ot.TeeAuthoringPolicySet),ee(t))}}function Aa(t){return{kind:"teeAdmissionPolicy",plane:"group",bytes:f(L(ot.TeeAdmissionPolicySetV2),ee(t.allowedMrtd),ee(t.allowedRtmr0),ee(t.allowedRtmr1),ee(t.allowedRtmr2),ee(t.allowedRtmr3),ee(t.allowedTcbStatuses),ma(t.acceptMock),fa(t.mode))}}function xa(t){let e=t.minReleaseVersion===void 0?L(0):f(L(1),ga(t.minReleaseVersion));return{kind:"teeReleaseAdmissionPolicy",plane:"group",bytes:f(L(ot.TeeReleaseAdmissionPolicySetV2),ee(t.allowedProfiles),e,ee(t.allowedTcbStatuses),ma(t.acceptMock),fa(t.mode))}}async function Uo(t){return E(fd,[t])}async function Oo(t){return E(md,[m(t.account,"account",32),m(t.namespaceId,"namespaceId",32),m(t.groupId,"groupId",32),L(va(t.kind)),t.opDigest,C(t.counter),R(t.keyEpoch)])}function va(t){let e=Do[t];if(e===void 0)throw new Error(`unknown owner-op kind ${String(t)}`);return e}var da=132;async function Ra(t){let e=await oe(t.rootSecret),n=f(L(yd),e),r=y(await E(hd,[n])),o=t.keyEpoch??0,i=(t.chain??[]).map((d,l)=>{let p=j(d,`chain[${l}]`);if(p.length!==da)throw new Error(`chain[${l}] must be a ${da}-byte RootKeyHandoff, got ${p.length}`);return p});if(o>i.length)throw new Error(`keyEpoch ${o} needs ${o} handoffs in chain, got ${i.length}`);let s=await Uo(t.op.bytes),a=await Oo({account:r,namespaceId:t.namespaceId,groupId:t.groupId,kind:t.op.kind,opDigest:s,counter:t.counter,keyEpoch:o}),c=await re(t.rootSecret),u=new Uint8Array(await crypto.subtle.sign("Ed25519",c,a));return y(f(n,R(i.length),...i,m(r,"account",32),m(t.namespaceId,"namespaceId",32),m(t.groupId,"groupId",32),L(va(t.op.kind)),s,C(t.counter),R(o),u))}function Ca(t,e){let n=t.plane==="group"?ot.RootGuarded:pa.RootGuarded;return f(L(n),t.bytes,j(e,"rootProof"))}var Sa=[2428,2429,2528,2529],Ad="localhost",xd=2e3;function ka(t){return`http://${Ad}:${t}`}function Ea(t,e){let n=t.endsWith("/")?t:`${t}/`;return new URL(e,n).toString()}async function Ia(t,e={}){let{timeoutMs:n=xd,signal:r}=e;if(r?.aborted)return!1;let o=new AbortController,i=()=>o.abort(),s=r;s&&s.addEventListener("abort",i,{once:!0});let a=setTimeout(()=>o.abort(),n);try{let c=Ea(t,"admin-api/health"),u=await fetch(c,{method:"GET",signal:o.signal});if(!u.ok)return!1;try{let d=await u.json(),l=d?.data?.status!==void 0?d?.data?.status:d?.status;return l===void 0?!0:typeof l=="string"&&l.toLowerCase()==="alive"}catch{return!0}}catch{return!1}finally{clearTimeout(a),s&&s.removeEventListener("abort",i)}}async function vd(t={}){let{ports:e=Sa,timeoutMs:n,signal:r}=t;return(await Promise.all(e.map(async i=>{let s=ka(i);return await Ia(s,{timeoutMs:n,signal:r})?s:null}))).filter(i=>i!==null)}function sr(t,e){return(t<<e|t>>>32-e)>>>0}function ue(t,e,n,r,o){t[e]=t[e]+t[n]>>>0,t[o]=sr(t[o]^t[e],16),t[r]=t[r]+t[o]>>>0,t[n]=sr(t[n]^t[r],12),t[e]=t[e]+t[n]>>>0,t[o]=sr(t[o]^t[e],8),t[r]=t[r]+t[o]>>>0,t[n]=sr(t[n]^t[r],7)}function Pa(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function Ua(t,e,n){let r=new Uint32Array(16);r[0]=1634760805,r[1]=857760878,r[2]=2036477234,r[3]=1797285236;for(let s=0;s<8;s+=1)r[4+s]=Pa(t,s*4);r[12]=e>>>0;for(let s=0;s<3;s+=1)r[13+s]=Pa(n,s*4);let o=r.slice();for(let s=0;s<10;s+=1)ue(o,0,4,8,12),ue(o,1,5,9,13),ue(o,2,6,10,14),ue(o,3,7,11,15),ue(o,0,5,10,15),ue(o,1,6,11,12),ue(o,2,7,8,13),ue(o,3,4,9,14);let i=new Uint8Array(64);for(let s=0;s<16;s+=1){let a=o[s]+r[s]>>>0;i[s*4]=a&255,i[s*4+1]=a>>>8&255,i[s*4+2]=a>>>16&255,i[s*4+3]=a>>>24&255}return i}function Rd(t,e,n,r){let o=new Uint8Array(r.length);for(let i=0,s=e;i<r.length;i+=64,s+=1){let a=Ua(t,s,n),c=Math.min(i+64,r.length);for(let u=i;u<c;u+=1)o[u]=r[u]^a[u-i]}return o}function No(t){let e=0n;for(let n=t.length-1;n>=0;n-=1)e=e<<8n|BigInt(t[n]);return e}var Cd=(1n<<130n)-5n;function Sd(t,e){let n=No(t.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,r=No(t.subarray(16,32)),o=0n;for(let a=0;a<e.length;a+=16){let c=e.subarray(a,Math.min(a+16,e.length)),u=No(c)+(1n<<BigInt(8*c.length));o=(o+u)*n%Cd}let i=o+r&(1n<<128n)-1n,s=new Uint8Array(16);for(let a=0;a<16;a+=1)s[a]=Number(i&0xffn),i>>=8n;return s}function Ta(t){return new Uint8Array((16-t%16)%16)}function Da(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function kd(t,e){let n=[t,Ta(t.length),e,Ta(e.length),Da(t.length),Da(e.length)],r=new Uint8Array(n.reduce((i,s)=>i+s.length,0)),o=0;for(let i of n)r.set(i,o),o+=i.length;return r}function Ed(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 Oa(t,e,n,r=new Uint8Array(0)){Ed(t,e);let o=Ua(t,0,e).subarray(0,32),i=Rd(t,1,e,n),s=Sd(o,kd(r,i)),a=new Uint8Array(i.length+16);return a.set(i),a.set(s,i.length),a}var _a=32,Id=1,Pd=3,Td=2,Dd=32,Ud=32,Od=12,it=t=>new TextEncoder().encode(t),Lt=t=>new Uint8Array([t>>8&255,t&255]),Na=f(it("KEM"),Lt(_a)),$t=f(it("HPKE"),Lt(_a),Lt(Id),Lt(Pd));async function Ma(t,e){let n=t.length===0?new Uint8Array(32):t,r=await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",r,e))}async function Nd(t,e,n){let r=new Uint8Array(n),o=new Uint8Array(0);for(let i=1,s=0;s<n;i+=1)o=await Ma(t,f(o,e,new Uint8Array([i]))),r.set(o.subarray(0,Math.min(o.length,n-s)),s),s+=o.length;return r}function ar(t,e,n,r){return Ma(e,f(it("HPKE-v1"),t,it(n),r))}function _o(t,e,n,r,o){return Nd(e,f(Lt(o),it("HPKE-v1"),t,it(n),r),o)}async function _d(t,e){let n=await ar(Na,new Uint8Array(0),"eae_prk",t);return _o(Na,n,"shared_secret",e,Dd)}async function Md(t,e){let n=new Uint8Array(0),r=await ar($t,n,"psk_id_hash",n),o=await ar($t,n,"info_hash",e),i=f(new Uint8Array([Td]),r,o),s=await ar($t,t,"secret",n);return{key:await _o($t,s,"key",i,Ud),nonce:await _o($t,s,"base_nonce",i,Od)}}async function Ga(t,e,n,r,o=new Uint8Array(0),i){if(t.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let s=await Ge(i),a=await Ge(e),c=f(await ft(s.privateKey,t),await ft(a.privateKey,t)),u=await _d(c,f(s.publicKey,t,a.publicKey)),{key:d,nonce:l}=await Md(u,n);return{enc:s.publicKey,ciphertext:Oa(d,l,r,o)}}var La="mero-agent-gate/attest/v3",Ha="mero-agent-gate/provision/v2",Gd=/^[a-z0-9][a-z0-9-]{0,62}$/,Kd=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,Ka=64,$a=64*1024,de=class extends Error{constructor(n,r,o){super(n);this.status=r;this.code=o;this.name="AgentGateError"}};function Ba(t){if(!Gd.test(t))throw new Error(`Agent id ${JSON.stringify(t)} must match [a-z0-9][a-z0-9-]{0,62}`)}function Ht(t){return new TextEncoder().encode(t)}function qa(t){let e=Ht(t);return f(new Uint8Array([e.length]),e)}function ke(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}function cr(t,e,n){let r;try{r=Uint8Array.from(atob(t.trim()),o=>o.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(n!==void 0&&r.length!==n)throw new Error(`${e} is not ${n} bytes`);return r}async function ja(t,e,n,r){let o=new Uint8Array(32),i=f(Ht(La),t,qa(e),n??o,r??o);return new Uint8Array(await crypto.subtle.digest("SHA-256",i))}function Fa(t,e){return f(Ht(Ha),t,qa(e))}async function $d(){let t=crypto.getRandomValues(new Uint8Array(32));return{secret:t,publicKey:await lr(t)}}async function lr(t){if(t.length!==32)throw new Error("An owner key is 32 bytes");return ke((await Ge(t)).publicKey)}function Va(t,e){return`${t.replace(/\/+$/,"")}${e}`}async function Wa(t,e,n){let r=await t(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}),o=await r.text(),i;try{i=o?JSON.parse(o):void 0}catch{}if(!r.ok){let s=i;throw new de(`The gate answered ${r.status}${s?.error?` ${s.error}`:""}: ${s?.details??o.slice(0,200)}`,r.status,s?.error)}return i}async function Mo(t){let e=t.agentId??"";e&&Ba(e);let n=crypto.getRandomValues(new Uint8Array(32)),r=await Wa(t.fetch??fetch,Va(t.gateUrl,"/attest"),{nonceB64:ke(n),...e?{agentId:e}:{}});if((r?.agentId??"")!==e)throw new Error(`Asked about agent ${JSON.stringify(e)}, the gate answered for ${JSON.stringify(r?.agentId)}`);let o=cr(r.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),i=r.signingPublicKeyB64?cr(r.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,s=r.ownerPublicKeyB64?cr(r.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!i!=!s)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let a=await ja(o,e,i,s);return await t.verifier({quoteB64:r.quoteB64,nonce:y(n),reportDataSuffix:y(a)}),{agentId:e,provisioningPublicKey:ke(o),...i?{signingPublicKey:ke(i)}:{},...s?{ownerPublicKey:ke(s)}:{}}}async function Ja(t,e){let n=await lr(e);if(t.ownerPublicKey&&t.ownerPublicKey!==n)throw new de(`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 n}function Ld(t){let e=Object.keys(t);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>Ka)throw new Error(`At most ${Ka} secrets at once`);for(let n of e){if(!Kd.test(n))throw new Error(`Secret name ${JSON.stringify(n)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);if(typeof t[n]!="string")throw new Error(`Secret ${n} is not a string`);if(Ht(t[n]).length>$a)throw new Error(`Secret ${n} is over ${$a} bytes`)}}async function za(t,e,n,r,o,i){if(!r.agentId)throw new Error("This quote names no agent; attest with the agent id");let s=await Ja(r,o),a=cr(r.provisioningPublicKey,"provisioningPublicKey",32),c=await Ga(a,o,Fa(a,r.agentId),Ht(JSON.stringify(i)));return Wa(t,Va(e,n),{agentId:r.agentId,provisioningPublicKeyB64:r.provisioningPublicKey,senderPublicKeyB64:s,encappedKeyB64:ke(c.enc),ciphertextB64:ke(c.ciphertext)})}async function Hd(t){Ld(t.secrets);let e=t.fetch??fetch,n=await za(e,t.gateUrl,"/provision",t.agent,t.ownerSecret,{secrets:t.secrets}),r=await Mo({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e}),o=await lr(t.ownerSecret);if(r.ownerPublicKey!==o||!r.signingPublicKey)throw new de("The gate accepted the secrets, but its quote does not name your key as owner");if(t.agent.signingPublicKey&&t.agent.signingPublicKey!==r.signingPublicKey)throw new de("The agent's signing key changed while provisioning");return{agentId:r.agentId,provisioningPublicKey:r.provisioningPublicKey,signingPublicKey:r.signingPublicKey,ownerPublicKey:o,written:n?.written??[],claimed:n?.claimed===!0}}async function Bd(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 za(e,t.gateUrl,"/release",t.agent,t.ownerSecret,{release:!0}),(await Mo({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e})).ownerPublicKey)throw new de("The gate says it released the agent, but its quote still names an owner")}var Go=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),qd=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function jd(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await gn(r,e,{identity:n.identity??Go.identity,issuer:n.issuer??Go.issuer});let o;try{o=JSON.parse(new TextDecoder().decode(r))}catch{throw new Error("The signed agent policy is not JSON")}if(o?.role!=="agent")throw new Error(`The signed file is a ${JSON.stringify(o?.role)} policy, not an agent one`);let i=n.profile??wt;if(o.profile!==i)throw new Error(`The signed agent policy is for the ${JSON.stringify(o.profile)} profile, not ${i}`);if(n.expectedVersion!==void 0&&o.version!==n.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(o.version)}, not ${n.expectedVersion}`);return Qa(o),o}function Qa(t){for(let e of qd)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 Fd=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function Vd(t){let e=Fd.find(n=>n.toLowerCase()===t.trim().toLowerCase());if(!e)throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(t)}`);return e}var Bt=t=>t.trim().replace(/^0x/i,"");function Wd(t,e){return Qa(t),At({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:t.allowed_tcb_statuses.map(Vd),allowedMrtd:t.allowed_mrtd.map(Bt),allowedRtmr0:t.allowed_rtmr0.map(Bt),allowedRtmr1:t.allowed_rtmr1.map(Bt),allowedRtmr2:t.allowed_rtmr2.map(Bt),allowedRtmr3:t.allowed_rtmr3.map(Bt)})}export{di as ACCOUNT_HA_AUDIENCE,ui as ACCOUNT_OWNERSHIP_AUDIENCE,La as AGENT_ATTEST_DOMAIN,Ha as AGENT_PROVISION_INFO_DOMAIN,z as AccountHaRefusedError,Pt as AccountLinkedToSeveralUsersError,Re as AccountNotLinkedError,fe as AdminApiClient,de as AgentGateError,ge as AuthApiClient,ie as AuthRevokedError,_ as CAPABILITIES,Sp as CAPABILITY_PRESETS,$ as CloudClient,Sa as DEFAULT_LOCAL_NODE_PORTS,mn as DEFAULT_RELEASE_MIRROR,gt as EphemeralClient,Mi as HANDSHAKE_PATH,rr as HA_ACCOUNT_NOT_LINKED_MESSAGE,er as HA_REFUSAL_MESSAGES,O as HTTPError,Tt as HaRequestPendingError,Ao as INVITED_ROLE,ye as IntentRefusedError,rt as InvitationNotClaimableError,Go as KMS_RELEASE_SIGNER,To as LocalStorageTokenStore,Jn as MAX_INVITATION_VALIDITY_SECS,Po as MemoryTokenStore,we as MeroClient,Qe as MeroJs,jr as NODE_RELEASE_SIGNER,nt as NoRelayError,Se as NotForAccountError,Do as OWNER_OP_KIND,ys as PRESENCE_DOMAIN,wt as PRODUCTION_PROFILE,Hn as RELAY_NODE_KEY_RETRY_MS,Pe as REQUEST_PROOF_HEADER,J as RelayClient,F as RelayLoginError,Ut as RelayNotDialableError,Je as RelayObserver,Et as RelayPresenceClient,be as RelayTransport,Xe as RelaysUnavailableError,Te as RequestAuthError,pt as RpcClient,Zt as RpcError,yt as SEALED_CONTENT_TYPE,Gi as SEALED_PATH,Ro as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,Ke as SealedTransportError,B as SseClient,bt as StaleTransportKeyError,Dt as UnknownRelayError,at as WebHttpClient,se as WsClient,on as accountForRoot,V as accountForRootPublicKey,bi as accountRootFromPhrase,Or as accountRootFromSecret,Ai as accountRootSignerFromPhrase,ba as adminChangedOp,Bu as admitterAddrsFromNetworkStatus,ja as agentKeyBinding,Wd as agentQuoteVerifier,Co as applicationIdForBundle,Ae as attemptRelayNodeKey,Mo as attestAgent,ln as attestKeyBinding,un as attestRelayNodeKey,Du as beginCloudLink,Gu as beginDeviceEnrolment,Zn as bootstrapFromInvitation,Cr as buildAuthLoginUrl,go as buildDelegatedClient,Vs as callbackIsForeign,Yt as callerProof,kp as capMask,Ep as capNames,jn as carryExecutorAccount,Ja as checkOwner,br as classifyError,ks as clearDelegatedCredential,Rs as clearDelegatedSession,Hs as cloudLinkUrl,yn as cloudNodeReleaseUrl,dr as combineSignals,fc as compareSemver,Ou as completeCloudLink,$u as completeDeviceEnrolment,$s as connectCloud,Cu as connectCloudWithAccount,gs as contextCapabilityGrantedOp,ms as contextCapabilityRevokedOp,Dn as contextDetachedOp,Nn as contextMetadataSetOp,ca as createAccountAdmin,wi as createAccountRootSigner,zo as createAdminApiClient,zt as createAdminApiClientFromHttpClient,he as createAttestedSealedFetch,Rp as createAuthApiClient,Bo as createAuthApiClientFromHttpClient,zp as createBrowserAdminApiClient,xp as createBrowserAuthApiClient,De as createBrowserHttpClient,Mt as createDelegatedContext,ra as createDelegatedPrivateContext,ct as createHttpClient,It as createLocalStorageNonceSource,fo as createMemoryNonceSource,Kn as createMeroClient,pd as createMeroJs,la as createNodeAdmin,Qp as createNodeAdminApiClient,vp as createNodeAuthApiClient,Vt as createNodeHttpClient,fr as createProofAuthorizer,Xt as createProofSigner,At as createQuoteVerifier,sc as createRetryableMethod,Hi as createSealedFetch,Gl as createSignedReleaseSealedFetch,bn as createSignedReleaseVerifier,pr as createTimeoutSignal,hr as createUniversalHttpClient,Xr as createdSubgroupId,Wr as creationInitHash,vo as defaultAdmitters,ze as defaultAudience,je as defaultCapabilitiesSetOp,Ce as delegatedGovernance,nn as deviceCertPayload,Fs as deviceEnrolmentUrl,Tr as deviceScopePayload,vd as discoverLocalNodes,Ot as encodeGroupInvitation,Qn as encodeSignedInvitation,Li as fetchAttestedTransportKey,fn as fetchNodeRelease,hn as fetchNodeReleaseVersion,_t as fetchRegistryBundles,Os as forgetMethodKinds,Us as forgetRelaySealing,nr as foundDelegatedNamespace,In as foundedNamespaceId,yi as generateAccountRoot,$d as generateOwnerKey,no as generateSessionKey,or as governGroup,ir as governRoot,Jr as governanceOpHash,Zr as groupCreatedOp,ya as groupDeleteOp,En as groupDeletedOp,xo as groupInvitationHash,Ve as groupMetadataSetOp,kn as groupReparentedOp,me as hasCap,jp as hexEncodeUtf8,Fr as intentHash,lc as isSettled,Ys as joinAsAccount,Xn as joinWithNode,ae as jsonCodec,et as knownRelays,tt as latestPublishedVersion,Ds as learnRelayNodeKey,Gs as listDelegatedContexts,Ks as listDelegatedNamespaces,ka as localNodeUrl,We as login,Bn as markContextNonceSpent,qe as memberAddedOp,Tn as memberCapabilitySetOp,_n as memberJoinedOpenOp,kt as memberLeftOp,On as memberMetadataSetOp,Rn as memberRemovedOp,Cn as memberRoleSetOp,Ir as mintDeviceId,Pn as namespaceCreatedOp,Kt as namespaceOfGroup,Ea as nodeEndpoint,Zi as nodeReleaseVersionFromImage,Vn as normaliseAccount,Uo as ownerOpDigest,Oo as ownerOpSigningPayload,lr as ownerPublicKey,Rr as parseAuthCallback,cs as parseCreationWarrant,Pr as parseDeviceCredential,ls as parseGovernanceWarrant,lo as persistedNonces,uo as pinRelayNodeKey,ro as presenceStatementBytes,Ia as probeNodeHealth,Hd as provisionAgent,Fa as provisionInfo,Uu as readCloudLinkCallback,Cs as readDelegatedCredential,co as readDelegatedSession,Ku as readEnrolmentCallback,qn as readPinnedRelayNodeKey,q as readRelayMap,Vo as redeemInvitation,_s as relayForContext,Ze as relayTransportFetch,Bd as releaseAgent,Gt as rememberGroupNamespace,xe as rememberRelay,_r as reportDataOf,st as requestBodyHash,Zs as resolveApplicationIdFromRegistry,Wn as resolveRelayFromInvitation,Ts as resolveRelayNodeKey,X as resolveRoot,sn as resolveRootPair,Ca as rootGuardedOpBytes,Fn as routingProofHeaders,Ss as saveDelegatedCredential,vs as saveDelegatedSession,Nt as selectLatestBundle,Mp as shouldRetain,Er as signAccountHaClaim,mt as signAccountLink,an as signAccountLogin,Tc as signAccountOwnershipClaim,xn as signCreationWarrant,mi as signDeviceCert,fi as signDeviceScope,Ct as signGovernanceWarrant,zn as signGroupInvitation,Gn as signLoginStatement,Yn as signMemberJoinOp,Ra as signOwnerOpProof,qt as signRequest,mr as signRequestProof,Ls as signRoutingChallenge,wn as signWarrant,pe as signedPath,ii as signerFromCryptoKey,Ne as signerFromSecret,bs as stateHash,Fe as subgroupCreation,Un as subgroupVisibilitySetOp,tn as subscribePresence,Sn as targetApplicationSetOp,Aa as teeAdmissionPolicyOp,wa as teeAuthoringPolicyOp,xa as teeReleaseAdmissionPolicyOp,ha as transferOwnershipOp,$i as transportKeyBinding,ns as trustSignedRelease,Lr as trustedMeasurementsFromReleases,Ba as validateAgentId,rn as verifyDeviceCredential,jd as verifySignedAgentPolicy,Xi as verifySignedNodeRelease,yr as withCap,Wt as withRetry,Ip as withoutCap};
3
3
  //# sourceMappingURL=index.browser.mjs.map