@calimero-network/mero-js 25.3.0 → 25.3.1

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 or(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 ir(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 _a=new Set(["token_reuse","token_revoked"]);function Ma(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 D=class extends Error{constructor(n,r,o,i,s){let a=Ma(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:Po(this.headers),bodyText:this.bodyText}}},re=class extends D{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 Po(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function Ka(t){try{return new URL(t).pathname}catch{let e=t.indexOf("?");return e===-1?t:t.slice(0,e)}}var et=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:Po(r.headers),status:r.status}}async request(e,n){return this.makeRequest(e,n)}async makeRequest(e,n,r=0,o){let s=this.buildUrl(e),a=o??Date.now(),c=this.createAbortSignal(n),u=await this.buildHeaders(n?.headers),d;u instanceof Headers?(d={},u.forEach((A,C)=>{d[C]=A})):d=u;let l=n?.method||"GET";if(this.transport.authorizeRequest){let A=n?.body;if(A!==void 0&&typeof A!="string"&&!(A 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:new URL(s).pathname,body:A}))}let m={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)&&(m.body=n.body);let v;if(r>0&&o!==void 0){let A=n?.timeoutMs||this.transport.timeoutMs;if(A){let C=Date.now()-a,P=Math.max(0,A-C);v=this.createAbortSignal({...n,timeoutMs:P})}else v=this.createAbortSignal(n)}else v=c;if(v&&(m.signal=v),this.transport.credentials!==void 0&&(m.credentials=this.transport.credentials),n?.mode!==void 0&&(m.mode=n.mode),n?.cache!==void 0&&(m.cache=n.cache),n?.redirect!==void 0&&(m.redirect=n.redirect),n?.referrer!==void 0&&(m.referrer=n.referrer),n?.referrerPolicy!==void 0&&(m.referrerPolicy=n.referrerPolicy),n?.integrity!==void 0&&(m.integrity=n.integrity),n?.keepalive!==void 0&&(m.keepalive=n.keepalive),this.transport.getProof){let A=await this.transport.getProof({method:m.method??"GET",path:Ka(s),body:m.body});A&&(d["X-Calimero-Proof"]=A)}try{let A=await this.transport.fetch(s,m);if(!A.ok){let C=await this.getBodyText(A),P=new D(A.status,A.statusText,s,A.headers,C),T=A.headers.get("x-auth-error");if((A.status===401||A.status===403)&&T&&_a.has(T)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new re(T,A.status,A.statusText,s,A.headers,C)}let j=n?.signal?.aborted===!0;if(A.status===401&&this.transport.refreshToken&&T==="token_expired"&&r<1&&!x&&!j)try{let M=this.refreshTokenPromise;M||(M=this.transport.refreshToken(),this.refreshTokenPromise=M);let h=await M;if(!h||h.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 b=this.onTokenRefreshPromise;b||(b=this.transport.onTokenRefresh(h),this.onTokenRefreshPromise=b),await b,this.refreshTokenPromise=null,this.onTokenRefreshPromise=null;let E=n?.timeoutMs||this.transport.timeoutMs;if(E&&o!==void 0){let O=Date.now()-a;if(E-O<=0)throw P}return this.makeRequest(e,n,r+1,a)}catch(M){throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,M instanceof Error&&M.message.includes("onTokenRefresh")?M:P}throw P}return this.parseResponse(A,n?.parse)}catch(A){throw A instanceof D||A instanceof Error&&A.message.includes("onTokenRefresh")?A:new D(0,"Network Error",s,new Headers,A instanceof Error?A.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(ir(r)),n.length>0?or(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 tt(t){return new et(t)}function Ee(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 tt(e)}function Ot(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 tt(r)}function sr(t){return typeof window<"u"?Ee(t):Ot(t)}function Ga(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 $a(t){let n=250*Math.pow(2,t-1),r=(Math.random()-.5)*.4*n;return Math.max(0,n+r)}async function _t(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,!Ga(r,n-o))throw r;let s=$a(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 m=Math.max(0,l.getTime()-Date.now());s=Math.max(s,Math.min(m,6e4))}}}await new Promise(d=>setTimeout(d,s))}throw r||new Error("Retry failed without error")}function La(t,e={}){return async(...n)=>_t(()=>t(...n),e)}function p(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/${p(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/${p(e)}/clients/${p(n)}`)}async getKeyPermissions(e){return this.httpClient.get(`/admin/keys/${p(e)}/permissions`)}async updateKeyPermissions(e,n){return this.httpClient.put(`/admin/keys/${p(e)}/permissions`,{add:n.add,remove:n.remove})}};var nt=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 zd(t){let e=new nt;return new pe(e)}function Qd(t){let e=new nt;return new pe(e)}function Yd(t){let e=new nt;return new pe(e)}function To(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},Zd={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 ep(...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 tp(t){return Object.keys(_).filter(e=>ge(t,_[e]))}function ge(t,e){let n=e>>>0;return(t&n)>>>0===n}function ar(t,e){return(t|e)>>>0}function np(t,e){return(t&~e)>>>0}var Ha={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 Ba(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 qa(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 cr(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 lr(t){let e=qa(t),n;return e!==void 0?n=Ba(e):t instanceof TypeError?n="unreachable":n="unknown",{kind:n,status:e,retryable:Ha[n],message:cr(t)}}function ja(t){return t.status!=="failed"||!t.retryable}function sp(t){return!ja(t)}function Fa(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":null}function Va(t,e){let{kind:n,status:r}=lr(t),o=Fa(e);return 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 Do(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=cr(i,"Could not join. Check the invitation."),{reason:c,retryable:u}=Va(i,a);return{status:"failed",namespaceId:n,message:a,reason:c,retryable:u}}var Mt=class extends Error{constructor(n,r){super(`this node does not serve warrant-nonce discovery (404 on ${n}); it predates the route, so a client must fall back to its own nonce counter`);this.path=n;this.cause=r;this.name="WarrantNonceRouteUnavailableError"}};function ur(t,e,n){let r=e[n];if(r==null)return;let o=new RegExp(`"${n}"\\s*:\\s*(\\d+)`).exec(t);if(o)return BigInt(o[1]);if(typeof r=="string"&&/^\d+$/.test(r))return BigInt(r);throw new Error(`warrant-nonce response field \`${n}\` is not a u64: ${JSON.stringify(r)}`)}function No(t){let n=JSON.parse(t)?.data;if(!n||typeof n!="object")throw new Error(`warrant-nonce response had no \`data\`: ${t.slice(0,200)}`);let r={contextId:String(n.contextId??""),authorDeviceKey:String(n.authorDeviceKey??""),seen:n.seen===!0,highWaterNonce:ur(t,n,"highWaterNonce"),windowWidth:ur(t,n,"windowWidth")??0n},o=ur(t,n,"nextNonce");return o===void 0?{...r,kind:"exhausted",seen:!0,highWaterNonce:r.highWaterNonce??0xffffffffffffffffn}:{...r,kind:"open",nextNonce:o}}function w(t){return t?.data}function Wa(t,e){let[n,r]=Uo(t),[o,i]=Uo(e),s=n.split("."),a=o.split("."),c=Math.max(s.length,a.length);for(let m=0;m<c;m++){let x=Oo(s[m]??"0",a[m]??"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 m=0;m<l;m++){if(m>=u.length)return-1;if(m>=d.length)return 1;let x=Oo(u[m],d[m]);if(x!==0)return x}return 0}function Uo(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 Oo(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 Ja(t,e,n){return _t(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 w(await this.httpClient.get("/admin-api/health"))}async readinessCheck(){return w(await this.httpClient.get("/admin-api/ready"))}async isAuthed(){return this.httpClient.get("/admin-api/is-authed")}async installApplication(e){return w(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 Ja(r.toString(),"versions",n)).json();return(Array.isArray(i)?i:[]).map(s=>s.appVersion).filter(s=>typeof s=="string").sort((s,a)=>Wa(a,s))}async installDevApplication(e){return w(await this.httpClient.post("/admin-api/install-dev-application",e))}async uninstallApplication(e){return w(await this.httpClient.delete(`/admin-api/applications/${p(e)}`))}async listApplications(){return w(await this.httpClient.get("/admin-api/applications"))}async getApplication(e){return w(await this.httpClient.get(`/admin-api/applications/${p(e)}`))}async listApplicationVersions(e){return w(await this.httpClient.get(`/admin-api/applications/${p(e)}/versions`))}async getApplicationAbi(e,n){let r=n?`?service_name=${encodeURIComponent(n)}`:"";return w(await this.httpClient.get(`/admin-api/applications/${p(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/${p(e)}/versions`);return n?.data??n}async getLatestPackageVersion(e){return this.httpClient.get(`/admin-api/packages/${p(e)}/latest`)}async createContext(e){let n={...e,initializationParams:e.initializationParams??[]};return w(await this.httpClient.post("/admin-api/contexts",n))}async deleteContext(e){return w(await this.httpClient.delete(`/admin-api/contexts/${p(e)}`))}async getContexts(){return w(await this.httpClient.get("/admin-api/contexts"))}async getContext(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}`))}async getContextsForApplication(e){return w(await this.httpClient.get(`/admin-api/contexts/for-application/${p(e)}`))}async generateContextIdentity(){return w(await this.httpClient.post("/admin-api/identity/context",{}))}async getContextIdentities(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}/identities`))}async getContextIdentitiesOwned(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}/identities-owned`))}async joinContext(e){return w(await this.httpClient.post(`/admin-api/contexts/${p(e)}/join`,{}))}async getContextGroup(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}/group`))}async getContextStorage(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}/storage`))}async syncContext(e){let n=e?`/admin-api/contexts/sync/${p(e)}`:"/admin-api/contexts/sync";await this.httpClient.post(n,{})}async resyncContext(e,n={}){return await this.httpClient.post(`/admin-api/contexts/${p(e)}/resync`,n)??{contextId:e,resyncStarted:!0}}async inviteSpecializedNode(e){return w(await this.httpClient.post("/admin-api/contexts/invite-specialized-node",e))}async updateContextApplication(e,n){await this.httpClient.post(`/admin-api/contexts/${p(e)}/application`,n)}async getContextsWithExecutorsForApplication(e){let n=await this.httpClient.get(`/admin-api/contexts/with-executors/for-application/${p(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=w(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/${p(e)}`);return{blobId:n.blob_id,deleted:n.deleted}}async listBlobs(){return{blobs:w(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/${p(e)}`;let r=new URLSearchParams({context_id:n.contextId});return`/admin-api/blobs/${p(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 w(await this.httpClient.post("/admin-api/alias/create/context",{alias:e.alias,contextId:e.contextId}))}async createApplicationAlias(e){return w(await this.httpClient.post("/admin-api/alias/create/application",{alias:e.alias,applicationId:e.applicationId}))}async lookupContextAlias(e){return w(await this.httpClient.post(`/admin-api/alias/lookup/context/${p(e)}`,{}))}async lookupApplicationAlias(e){return w(await this.httpClient.post(`/admin-api/alias/lookup/application/${p(e)}`,{}))}async deleteContextAlias(e){return w(await this.httpClient.post(`/admin-api/alias/delete/context/${p(e)}`,{}))}async deleteApplicationAlias(e){return w(await this.httpClient.post(`/admin-api/alias/delete/application/${p(e)}`,{}))}async listContextAliases(){return w(await this.httpClient.get("/admin-api/alias/list/context"))}async listApplicationAliases(){return w(await this.httpClient.get("/admin-api/alias/list/application"))}async createDeviceAlias(e){return w(await this.httpClient.post("/admin-api/alias/create/device",{alias:e.alias,deviceId:e.deviceId}))}async lookupDeviceAlias(e){return w(await this.httpClient.post(`/admin-api/alias/lookup/device/${p(e)}`,{}))}async deleteDeviceAlias(e){return w(await this.httpClient.post(`/admin-api/alias/delete/device/${p(e)}`,{}))}async listDeviceAliases(){return w(await this.httpClient.get("/admin-api/alias/list/device"))}async listNamespaces(){return w(await this.httpClient.get("/admin-api/namespaces"))}async getNamespace(e){return w(await this.httpClient.get(`/admin-api/namespaces/${p(e)}`))}async getNodeIdentity(){return w(await this.httpClient.get("/admin-api/identity"))}async getNamespaceIdentity(e){let n=await this.getNodeIdentity();return{namespaceId:e,publicKey:n.publicKey,account:n.accountId}}async performIntent(e,n){return w(await this.httpClient.post(`/admin-api/contexts/${p(e)}/intents`,n))}async queryContext(e,n){return w(await this.httpClient.post(`/admin-api/contexts/${p(e)}/query`,n))}async getIntentRelay(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}/intents`))}async listNamespacesForApplication(e){return w(await this.httpClient.get(`/admin-api/namespaces/for-application/${p(e)}`))}async createNamespace(e){return w(await this.httpClient.post("/admin-api/namespaces",e))}async deleteNamespace(e){return w(await this.httpClient.request(`/admin-api/namespaces/${p(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async createNamespaceInvitation(e,n){return w(await this.httpClient.post(`/admin-api/namespaces/${p(e)}/invite`,n??{}))}async admitJoin(e,n){return w(await this.httpClient.post(`/admin-api/namespaces/${p(e)}/admit`,n,{timeoutMs:65e3}))}async joinNamespace(e,n){let r=w(await this.httpClient.post(`/admin-api/namespaces/${p(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 Do({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 w(await this.httpClient.post(`/admin-api/namespaces/${p(e)}/groups`,n??{}))}async listNamespaceGroups(e){return w(await this.httpClient.get(`/admin-api/namespaces/${p(e)}/groups`))}async initAccountPairing(e){return w(await this.httpClient.post("/admin-api/account/pair-init",e))}async completeAccountPairing(e){return w(await this.httpClient.post("/admin-api/account/pair-complete",e))}async relinkAccountDevice(e,n){return w(await this.httpClient.post(`/admin-api/account/devices/${p(e)}/relink`,n??{}))}async rescopeAccountDevice(e,n){return w(await this.httpClient.put(`/admin-api/account/devices/${p(e)}/scope`,n))}async signWithAccountRoot(e){return w(await this.httpClient.post("/admin-api/account/sign-with-root",e))}async labelAccountDevice(e,n){return w(await this.httpClient.put(`/admin-api/account/devices/${p(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 w(await this.httpClient.post(`/admin-api/namespaces/${p(e)}/account/revoke`,n))}async linkAccountDevice(e,n){return w(await this.httpClient.post(`/admin-api/namespaces/${p(e)}/account/link-device`,n))}async getGroupInfo(e){return w(await this.httpClient.get(`/admin-api/groups/${p(e)}`))}async getDefaultCapabilities(e){return(await this.getGroupInfo(e)).defaultCapabilities}async getSubgroupVisibility(e){return(await this.getGroupInfo(e)).subgroupVisibility}async deleteGroup(e){return w(await this.httpClient.request(`/admin-api/groups/${p(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async listGroupMembers(e){let n=await this.httpClient.get(`/admin-api/groups/${p(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/${p(e)}/member-devices`;return(await this.httpClient.get(o?`${i}?${o}`:i)).members}async getWarrantNonce(e,n){let r=`/admin-api/contexts/${p(e)}/warrant-nonce/${p(n)}`,o;try{o=await this.httpClient.get(r,{parse:"text"})}catch(i){throw i instanceof D&&i.status===404?new Mt(r,i):i}return No(o)}async getWarrantNonceAsAuthor(e,n){let r=`/admin-api/contexts/${p(e)}/warrant-nonce`,o;try{o=await this.httpClient.post(r,{authorProof:n},{parse:"text"})}catch(i){throw i instanceof D&&i.status===404?new Mt(r,i):i}return No(o)}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/${p(e)}/member-devices${o?`?${o}`:""}`;return this.httpClient.get(i)}async sealToAccount(e,n,r){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/accounts/${p(n)}/seal`,r))}async listGroupContexts(e){return w(await this.httpClient.get(`/admin-api/groups/${p(e)}/contexts`))}async addGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${p(e)}/members`,n)}async removeGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${p(e)}/members/remove`,n)}async updateMemberRole(e,n,r){await this.httpClient.put(`/admin-api/groups/${p(e)}/members/${p(n)}/role`,r)}async getMemberCapabilities(e,n){return w(await this.httpClient.get(`/admin-api/groups/${p(e)}/members/${p(n)}/capabilities`))}async setMemberCapabilities(e,n,r){await this.httpClient.put(`/admin-api/groups/${p(e)}/members/${p(n)}/capabilities`,r)}async setDefaultCapabilities(e,n){await this.httpClient.put(`/admin-api/groups/${p(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=ar(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=ar(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/${p(e)}/settings/subgroup-visibility`,n)}async setTeeAdmissionPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${p(e)}/settings/tee-admission-policy`,n)}async getTeeAdmissionPolicy(e){let n=await this.httpClient.get(`/admin-api/groups/${p(e)}/settings/tee-admission-policy`);return n.data??n}async setTeeAuthoringPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${p(e)}/settings/tee-authoring-policy`,n)}async disableTeeAuthoringPolicy(e,n={}){let r=`/admin-api/groups/${p(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/${p(e)}/transfer-ownership`,n)}async changeNamespaceAdmin(e,n){await this.httpClient.post(`/admin-api/namespaces/${p(e)}/admin`,n)}async ownerDeleteGroup(e,n={}){await this.httpClient.post(`/admin-api/groups/${p(e)}/owner-delete`,n)}async setGroupMetadata(e,n){await this.httpClient.put(`/admin-api/groups/${p(e)}/metadata`,n)}async getGroupMetadata(e){return(await this.httpClient.get(`/admin-api/groups/${p(e)}/metadata`))?.data??null}async setMemberMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${p(e)}/members/${p(n)}/metadata`,r)}async getMemberMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${p(e)}/members/${p(n)}/metadata`))?.data??null}async setContextMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${p(e)}/contexts/${p(n)}/metadata`,r)}async getContextMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${p(e)}/contexts/${p(n)}/metadata`))?.data??null}async syncGroup(e){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/sync`,{}))}async upgradeGroup(e,n){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/upgrade`,n))}async getGroupUpgradeStatus(e){return w(await this.httpClient.get(`/admin-api/groups/${p(e)}/upgrade/status`))}async getMigrationStatus(e){return this.httpClient.get(`/admin-api/groups/${p(e)}/migration-status`)}async listNamespaceRevokedDevices(e){return this.httpClient.get(`/admin-api/namespaces/${p(e)}/revoked-devices`)}async getCascadeStatus(e){return w(await this.httpClient.get(`/admin-api/groups/${p(e)}/cascade-status`))}async retryGroupUpgrade(e){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/upgrade/retry`,{}))}async reparentGroup(e,n){let r=await this.httpClient.post(`/admin-api/groups/${p(e)}/reparent`,n);return r?.data??r}async listSubgroups(e){let n=await this.httpClient.get(`/admin-api/groups/${p(e)}/subgroups`);return n.subgroups??n.data??[]}async detachContextFromGroup(e,n){await this.httpClient.post(`/admin-api/groups/${p(e)}/contexts/${p(n)}/remove`,{})}async createGroupInvitation(e,n){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/invite`,n??{}))}async joinGroup(e){return w(await this.httpClient.post("/admin-api/groups/join",e))}async joinSubgroupInheritance(e){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/join-via-inheritance`,{}))}async getTeeInfo(){return w(await this.httpClient.get("/admin-api/tee/info"))}async teeAttest(e){return w(await this.httpClient.post("/admin-api/tee/attest",e))}async teeVerifyQuote(e){return w(await this.httpClient.post("/admin-api/tee/verify-quote",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 w(await this.httpClient.post("/admin-api/groups",e))}async leaveGroup(e){await this.httpClient.post(`/admin-api/groups/${p(e)}/leave`,{})}async leaveContext(e){await this.httpClient.post(`/admin-api/contexts/${p(e)}/leave`,{})}async leaveNamespace(e){await this.httpClient.post(`/admin-api/namespaces/${p(e)}/leave`,{})}async issueOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${p(e)}/issue-ownership-proof`,n)}async issueNamespaceOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${p(e)}/issue-namespace-ownership-proof`,n)}async setMemberAutoFollow(e,n,r){await this.httpClient.put(`/admin-api/groups/${p(e)}/members/${p(n)}/auto-follow`,r)}async abortMigration(e){return this.httpClient.post(`/admin-api/groups/${p(e)}/migration/abort`,{})}};function mp(t){return Array.from(new TextEncoder().encode(t),e=>e.toString(16).padStart(2,"0")).join("")}function wp(t){return new me(Ee(t))}function Ap(t){return new me(Ot(t))}function _o(t){return new me(sr(t))}function Kt(t,e){return new me(t)}function dr(t){try{let e=t.indexOf("#");if(e===-1)return null;let n=t.substring(e+1),r=new URLSearchParams(n),o=r.get("access_token");return o?{accessToken:o,refreshToken:r.get("refresh_token")??"",applicationId:r.get("application_id")??"",contextId:r.get("context_id")??"",contextIdentity:r.get("context_identity")??"",nodeUrl:r.get("node_url")??""}:null}catch{return null}}function pr(t,e){let n=new URLSearchParams;return n.set("callback-url",e.callbackUrl),e.permissions&&e.permissions.length>0&&n.set("permissions",e.permissions.join(",")),n.set("mode",e.mode),e.packageName&&(n.set("package-name",e.packageName),e.packageVersion&&n.set("package-version",e.packageVersion),e.registryUrl&&n.set("registry-url",e.registryUrl)),`${t.replace(/\/+$/,"")}/auth/login?${n.toString()}`}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 g(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 F(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 S(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 k(t,e){let n=[S(t.length),t];for(let r of e)n.push(S(r.length),r);return new Uint8Array(await crypto.subtle.digest("SHA-256",f(...n)))}async function oe(t){let e=g(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 Ko(t,e,n){let r=await crypto.subtle.importKey("raw",g(t,"publicKey",32),{name:"Ed25519"},!1,["verify"]);return crypto.subtle.verify({name:"Ed25519"},r,e,n)}async function ie(t){let e=g(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 za=new TextEncoder().encode("calimero.auth.request.v1"),Qa=new TextEncoder().encode("calimero.auth.request.body.v1");function Go(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}async function gr(t=new Uint8Array(0)){let e=typeof t=="string"?new TextEncoder().encode(t):t;return k(Qa,[e])}async function Gt(t){let e=await oe(t.signerSecret),n=await gr(t.body),r=S(t.issuedAt),o=S(t.expiresAt),i=new TextEncoder,s=await k(za,[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(Go(t.method),Go(t.path),n,r,o,a))}function $t(t){let e=F(t.credential,"credential"),n=F(t.request,"request signature"),r=t.session===void 0?new Uint8Array([0]):f(new Uint8Array([1]),F(t.session,"session statement"));return y(f(e,r,n))}function Ya(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 Lt(t){let e=t.ttlSeconds??120,n=t.now??(()=>Math.floor(Date.now()/1e3));return async r=>{let o=n();return $t({credential:t.credential,session:t.session,request:await Gt({method:r.method,path:r.path,body:Ya(r.body),issuedAt:o,expiresAt:o+e,signerSecret:t.signerSecret})})}}var Ht=class extends Error{constructor(e,n,r,o){super(n),this.name="RpcError",this.code=e,this.data=r,this.type=o}};async function mr(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 Ht(o.code??-1,o.message??o.type??"RPC error",o.data,o.type)}return r.result}var rt=class{constructor(e){this.kind="node";this.canSubscribe=!0;this.httpClient=e.httpClient}async execute(e){let n=await mr(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 Xa=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function $o(t){return t.type!==void 0&&Xa.has(t.type)}var Za=new Set(["token_reuse","token_revoked"]),ec=new Set([401,403]),tc=1e4;function Lo(t){let e=t.headers.get("x-auth-error");return!e||!ec.has(t.status)?null:Za.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=>{$o(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)){this.closed=!1,this.abortController=new AbortController;try{let e=`${this.baseUrl}/sse`,n=await this.fetchImpl(e,{headers:{...await this.authorize({method:"GET",path:new URL(e).pathname}),Accept:"text/event-stream"},signal:this.abortController.signal});if(!n.ok){let r=Lo(n),o=await n.text().catch(()=>{});throw r?new re(r,n.status,n.statusText,e,n.headers,o):new D(n.status,n.statusText,e,n.headers,o)}if(!n.body)throw new Error("SSE response has no body");this.readStream(n.body).catch(r=>{if(this.closed)return;let o=r instanceof Error?r:new Error(String(r));this.emit("error",o),this.scheduleReconnect()})}catch(e){if(this.closed)return;let n=e instanceof Error?e:new Error(String(e));if(this.emit("error",n),n instanceof re)return;this.scheduleReconnect()}}}async readStream(e){let n=e.getReader(),r=new TextDecoder,o="";try{for(;;){let{done:i,value:s}=await n.read();if(i)break;o+=r.decode(s,{stream:!0});let a=o.split(`
2
- `);o=a.pop()??"";for(let c of a)if(c.startsWith("data:")){let u=c.slice(5).trim();u&&this.handleMessage(u)}}if(o+=r.decode(),o.startsWith("data:")){let i=o.slice(5).trim();i&&this.handleMessage(i)}}catch(i){if(this.closed)return;let s=i instanceof Error?i:new Error(String(i));this.emit("error",s)}this.closed||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")),tc);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.fetchImpl(s,{method:"POST",headers:{...await this.authorize({method:"POST",path:new URL(s).pathname,body:a}),"Content-Type":"application/json"},body:a,signal:r.signal});if(!c.ok){let u=Lo(c),d=await c.text().catch(()=>{});return u?new re(u,c.status,c.statusText,`${this.baseUrl}/sse/subscription`,c.headers,d):new D(c.status,c.statusText,`${this.baseUrl}/sse/subscription`,c.headers,d)}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 Bt=class Bt{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),Bt.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()}};Bt.MAX_BACKOFF_MS=3e4;var se=Bt;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 ot=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,n,r=ae()){await mr(this.httpClient,"set_ephemeral",{contextId:e,state:r.encode(n)})}subscribe(e,n,r=ae()){return qt(this.sse,e,n,r)}};function qt(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 nc=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function Ho(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 ke(t,e="secret"){let n=g(t,e,32),r=f(nc,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 Ho(s)}return qo(o,i)}async function Bo(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")g(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 qo(t,n)}function qo(t,e){return{publicKey:e,async sign(n){try{return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},t,n))}catch(r){throw Ho(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 ke(t,n);throw new Error(`${n} or signer is required`)}var rc=new TextEncoder().encode("calimero.mdma.account-ownership-claim.v1\0"),oc=6e4,jo=5*6e4,Fo=1024,Wo="mdma:enable-ha-namespace",Jo="mdma:enable-ha-namespace-as-account";function Vo(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var fr=(t,e)=>{if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);return t.toLowerCase()};async function zo(t,e,n,r){if(r!==void 0&&!(r.length>0&&r.length<=Fo))throw new Error(`relayUrl must be a non-empty string of at most ${Fo} characters`);let o=t.ttlMs??oc;if(!(o>0&&o<=jo))throw new Error(`ttlMs must be in (0, ${jo}]`);let i=fr(t.namespaceId,"namespaceId"),s=fr(t.accountId,"accountId"),a=fr(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}})),m=await c.sign(f(rc,l));return{kind:"account",credential:t.credential,signed_payload:Vo(l),signature:Vo(m)}}async function ic(t){if(!t.subject)throw new Error("subject must be the cloud login email");return zo(t,Wo,t.subject)}async function hr(t){return zo(t,Jo,void 0,t.relayUrl)}var sc=new TextEncoder().encode("calimero.device.cert.v1"),ac=new TextEncoder().encode("calimero.account.genesis.v1"),cc=new TextEncoder().encode("calimero.device.id.v1"),Ie=2,lc=237;async function yr(t,e){if(e.length!==16)throw new Error(`nonce must be 16 bytes, got ${e.length}`);let n=g(t,"account",32),r=await k(cc,[n,e]);return y(f(e,r.subarray(0,16)))}async function jt(t){return k(sc,[g(t.account,"account",32),g(t.device,"device",32),g(t.signPublicKey,"signPublicKey",32),g(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch)])}function Qo(t){return f(new Uint8Array([Ie]),t.rootPublicKey,R(0),g(t.account,"account",32),g(t.device,"device",32),g(t.signPublicKey,"signPublicKey",32),g(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch),t.signature)}async function Yo(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=g(e.publicKey,"signer.publicKey",32),r=await V(e.publicKey),o=0,i=await jt({account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch}),s=await e.sign(i),a=Qo({rootPublicKey:n,account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch,signature:s});return y(a)}function br(t){let e=g(t,"credential",lc);if(e[0]!==Ie)throw new Error(`this credential has account genesis version ${e[0]}, not ${Ie} \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 Ft(t){let e=br(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=g(e.device,"device",32).subarray(0,16);if(await yr(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 Ko(e.rootPublicKey,g(e.signature,"signature",64),await jt(e)))throw new Error(`the root key of account ${e.account} did not sign this certificate`);return e}async function Vt(t){return V(y(await ie(t)))}async function V(t){return y(await k(ac,[f(new Uint8Array([Ie]),g(t,"rootPublicKey",32))]))}var uc=new TextEncoder().encode("calimero.device.scope.v1");async function wr(t){return k(uc,[g(t.account,"account",32),g(t.device,"device",32),R(t.scopeEpoch),R(t.keyEpoch),...t.applications.map((e,n)=>g(e,`applications[${n}]`,32))])}async function Xo(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=g(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 wr({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([Ie]),n,R(0),g(r,"account",32),g(t.device,"device",32),R(o.length),...o.map((u,d)=>g(u,`applications[${d}]`,32)),R(i),R(s),c))}var Ar=["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 dc=new TextEncoder().encode("calimero.mdma.account-link.v1\0"),pc=new TextEncoder().encode("calimero.mdma.account-login.v1\0"),Pe=256,Zo=Pe/32,xr=(Pe+Zo)/11;async function ei(){let t=crypto.getRandomValues(new Uint8Array(Pe/8));return si(y(t),await ci(t))}async function ti(t){let e=ai(t);return si(y(await li(e)),e.join(" "))}async function vr(t){return g(t,"secret",32),{secret:t,publicKey:y(await ie(t)),accountId:await Vt(t)}}async function ni(){let t=crypto.getRandomValues(new Uint8Array(Pe/8)),e=await ci(t);return{...await oi(t),phrase:e}}async function ri(t){return oi(await li(ai(t)))}async function oi(t){let e=await ke(y(t),"rootSecret");return t.fill(0),{publicKey:e.publicKey,accountId:await V(e.publicKey),signer:e}}async function Q(t){let e=typeof t=="string"?await ke(t,"rootSecret"):t;return ii(e)}async function Wt(t,e){return ii(await I(t,e,"rootSecret"))}async function ii(t){return{signer:t,publicKey:t.publicKey,accountId:await V(t.publicKey)}}async function it(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(dc,new TextEncoder().encode(t.nonce)));return pi(n)}async function Jt(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(pc,new TextEncoder().encode(t.nonce)));return pi(n)}async function si(t,e){return{...await vr(t),phrase:e}}function ai(t){let e=t.normalize("NFKD").toLowerCase().trim().split(/\s+/),n=e[0]===""?0:e.length;if(n!==xr)throw new Error(`recovery phrase must be ${xr} words, got ${n}`);return e}async function ci(t){let e=di(t)+await ui(t),n=[];for(let r=0;r<xr;r+=1){let o=Number.parseInt(e.slice(r*11,r*11+11),2);n.push(Ar[o])}return n.join(" ")}async function li(t){let e="";for(let r of t){let o=Ar.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(Pe/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(Pe)!==await ui(n))throw new Error("recovery phrase checksum failed \u2014 check for a mistyped or transposed word");return n}async function ui(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return di(e).slice(0,Zo)}function di(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 gc=new TextEncoder().encode("calimero.tee-attest.key-binding.v1"),zt=new TextEncoder().encode("MOCK_TDX_QUOTE_V1"),mc=568;function fc(...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 Rr(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 yc(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 Qt(t){let e=await crypto.subtle.digest("SHA-256",fc(gc,new Uint8Array(32),t));return new Uint8Array(e)}function Cr(t){let e=t.length>=zt.length&&Rr(t.subarray(0,zt.length),zt),n=e?zt.length:mc;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 Yt(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 m=await i.text().catch(()=>"");throw new Error(`the relay would not attest (HTTP ${i.status})${m?`: ${m}`:""}`)}let s=await i.json(),a=s.data??s;if(typeof a.quoteB64!="string")throw new Error("the relay returned no quote");let c=yc(a.boundPublicKey,"boundPublicKey"),u=hc(a.quoteB64),{reportData:d,mock:l}=Cr(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 Qt(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(!Rr(d.subarray(0,32),e))throw new Error("the quote does not carry our nonce: it was not made for this request");if(!Rr(d.subarray(32,64),await Qt(c)))throw new Error("the quote does not bind the key the relay named: refusing it");return{nodeKey:y(c),mock:l}}var bc="Noise_NK_25519_AESGCM_SHA256",Sr=32,wc=16,Ac=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(bc),n=new Uint8Array(32);return n.set(e),new t(n)}async mixHash(e){this.h=await xc(f(this.h,e))}async mixKey(e){let[n,r]=await mi(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:gi(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:gi(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),n}split(){return mi(this.ck,new Uint8Array)}};async function fi(t,e,n){let r=await kr.initialize();await r.mixHash(e),await r.mixHash(t);let o=await Te(n);return await r.mixHash(o.publicKey),await r.mixKey(await st(o.privateKey,t)),{message1:f(o.publicKey,await r.encryptAndHash(new Uint8Array)),async finish(s){if(s.length<Sr+wc)throw new Error("Noise: message 2 is too short");let a=s.slice(0,Sr);return await r.mixHash(a),await r.mixKey(await st(o.privateKey,a)),{payload:await r.decryptAndHash(s.slice(Sr)),split:await r.split()}}}}async function Te(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(Ac,t),{name:"X25519"},!0,["deriveBits"]),n=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:vc(n.x)}}async function st(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 gi(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}async function xc(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}async function Er(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 mi(t,e){let n=await Er(t,e),r=await Er(n,new Uint8Array([1])),o=await Er(n,f(r,new Uint8Array([2])));return[r,o]}function vc(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 wi="/sealed/v2/handshake",Ai="/sealed/v2",ct="application/vnd.calimero.sealed",Ir=2,Rc=new TextEncoder().encode("calimero/sealed-http/v2"),at=16,Cc=1+at+8,Sc=0,Ec=1,kc=2,Ic=1+64*1024+16,Pc=1024,Tc=6e4,Dc="calimero.tee-attest.transport-key.v1",Nc=[101,204,205,304],xi=new TextEncoder,lt=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},De=class extends Error{constructor(n,r,o,i){super(o);this.status=n;this.code=r;this.retryAfterMs=i;this.name="SealedTransportError"}};async function vi(t,e){let n=await crypto.subtle.digest("SHA-256",f(xi.encode(Dc),t,e));return new Uint8Array(n)}async function Ri(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=g(o.transportPublicKey,"transportPublicKey",32),s=n.applicationHash?g(n.applicationHash,"applicationHash",32):new Uint8Array(32),a=y(await vi(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 Ci({baseUrl:t.baseUrl,transportPublicKey:()=>Ri(r,t.verify,{applicationId:t.applicationId,applicationHash:t.applicationHash}),fetch:e})}function Ci(t){let e=new URL(t.baseUrl),n=e.pathname.replace(/\/+$/,""),r=`${e.origin}${n}`,o=t.fetch??((l,m)=>fetch(l,m)),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 yi(o,r,await hi(s))}catch(l){if(!(l instanceof lt)||!i)throw l;return s=Promise.resolve().then(i),yi(o,r,await hi(s))}},u=async()=>{let l=a??d(void 0),m=await l;if(Date.now()<m.renewAt)return[m,l];let x=d(l);return[await x,x]},d=l=>{if(a===l){let m=c();a=m,m.catch(()=>{a===m&&(a=void 0)})}return a};return async(l,m)=>{let x=new Request(l,m),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 A=[];x.headers.forEach((h,b)=>A.push([b,h]));let C={method:x.method,path:v.pathname.slice(n.length)+v.search,headers:A},P=new Uint8Array(await x.arrayBuffer()),T=async h=>{let{requestId:b,header:E,envelope:O}=await Oc(h,C,P),H=await o(`${r}${Ai}`,{method:"POST",headers:{"content-type":ct},body:O,signal:x.signal});if(H.headers.get("content-type")!==ct)throw await Ei(H);return Mc(H,h.responseKey,E,b)},[j,M]=await u();try{return await T(j)}catch(h){if(!(h instanceof De)||h.code!=="unknown_session")throw h;return T(await d(M))}}}async function hi(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function yi(t,e,n){try{return await bi(t,e,n)}catch(r){if(!(r instanceof De)||r.code!=="busy")throw r;return await new Promise(o=>setTimeout(o,r.retryAfterMs??1e3)),bi(t,e,n)}}async function bi(t,e,n){let r=await fi(n,Rc),o=await t(`${e}${wi}`,{method:"POST",headers:{"content-type":ct},body:f(new Uint8Array([Ir]),n,r.message1)});if(o.headers.get("content-type")!==ct)throw await Ei(o);let i=await Gc(o,Pc);return Uc(r,i)}async function Uc(t,e){if(e[0]!==Ir)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!==at+4)throw new Error("The handshake reply is malformed");let i=r.slice(0,at),s=new DataView(r.buffer,r.byteOffset).getUint32(at,!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-Tc,header(u){let d=new Uint8Array(Cc);return d[0]=Ir,d.set(i,1),new DataView(d.buffer).setBigUint64(1+at,BigInt(u),!1),d}}}async function Oc(t,e,n){let r=t.nextRequestId;t.nextRequestId+=1;let o=t.header(r),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:Si(r,0),additionalData:o},t.requestKey,_c(e,n));return{requestId:r,header:o,envelope:f(o,new Uint8Array(i))}}function Si(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 _c(t,e){let n=xi.encode(JSON.stringify(t)),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,n.length,!1),f(r,n,e)}async function Mc(t,e,n,r){if(!t.body)throw new Error("The sealed response has no body");let o=Kc(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:Si(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!==Sc)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(Nc.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===Ec?d.enqueue(l.data):l.kind===kc?(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 Kc(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>Ic)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 Gc(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 Ei(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 lt;let r=Number(t.headers.get("retry-after")),o=Number.isFinite(r)&&r>0?Math.min(r,5)*1e3:void 0;return new De(t.status,e,n,o)}var $c=/^[0-9a-f]{96}$/,Lc=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function dt(t){let e=Ne(t.allowedMrtd??[],"allowedMrtd"),n=(t.allowedMeasurements??[]).map((a,c)=>{let u=`allowedMeasurements[${c}]`;return Lc.map(d=>Ne([a?.[d]??""],`${u}.${d}`)[0]).join()}),r=[Ne(t.allowedRtmr0??[],"allowedRtmr0"),Ne(t.allowedRtmr1??[],"allowedRtmr1"),Ne(t.allowedRtmr2??[],"allowedRtmr2"),Ne(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=Bc(a),m=d??await t.fetchCollateral?.(l);if(!m)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,m,Math.floor(i()/1e3))}catch(P){throw new Error(`The quote did not verify: ${P?.message??String(P)}`)}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=Hc(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 A=[v.mrTd,v.rtMr0,v.rtMr1,v.rtMr2,v.rtMr3].map(P=>y(P));if(n.length>0&&!n.includes(A.join()))throw new Error(`The measurements (MRTD ${A[0]}, RTMR0-3 ${A.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(A[0]))throw new Error(`MRTD ${A[0]} is not an image this verifier trusts`);if([v.rtMr0,v.rtMr1,v.rtMr2,v.rtMr3].forEach((P,T)=>{let j=r[T];if(j.length>0&&!j.includes(y(P)))throw new Error(`RTMR${T} ${y(P)} 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 Ne(t,e){return t.map(n=>{let r=n.trim().toLowerCase();if(!$c.test(r))throw new Error(`${e} holds ${JSON.stringify(n)}, which is not a 48-byte hex measurement`);return r})}function Hc(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 Bc(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 qc=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],ut="locked-read-only";function Pr(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!==ut&&!n)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(ut)}, or pass allowDebugProfile to test`);let u=(c.allowed_tcb_statuses??["uptodate"]).map(d=>jc(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 jc(t,e){let n=qc.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 ki=[{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"]}],Ii=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var Fc="1.2.840.10045.2.1",Vc={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},Wc={"P-256":32,"P-384":48},Jc={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function Pi(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 Oe(t){let e=Pi(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function K(t){let e=[];for(let n=t.start;n<t.end;){let r=Pi(t.bytes,n,t.end);e.push(r),n=r.end}return e}function U(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 Xt(t){return t.bytes.slice(t.offset,t.end)}function Ue(t){let e=ce(U(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 zc(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 Tr(t){try{let[e,n,r,...o]=K(U(Oe(t),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let i=K(U(e,48,"The signed part")),s=i[0]?.tag===160?1:0,[a,c,u,d,l,m,...x]=i.slice(s);U(a,2,"The serial number");let v=Ue(K(U(n,48,"The signature algorithm"))[0]);if(Ue(K(U(c,48,"The signature algorithm"))[0])!==v)throw new Error("it names two different signature algorithms");let C=Jc[v];if(!C)throw new Error(`it is signed with ${v}, not ECDSA with SHA-256 or SHA-384`);let[P,T]=K(U(d,48,"The validity")).map(zc);if(T===void 0)throw new Error("its validity is incomplete");let[j,M]=K(U(m,48,"The public key"));U(M,3,"The public key");let[h,b]=K(U(j,48,"The key algorithm"));if(Ue(h)!==Fc)throw new Error("its key is not an elliptic-curve key");let E=Vc[Ue(b)];if(!E)throw new Error("its key is on a curve other than P-256 or P-384");let O=new Map,H=x.find(te=>te.tag===163);if(H){let[te]=K(H);for(let ne of K(U(te,48,"The extensions"))){let Se=K(U(ne,48,"An extension"));if(Se.length===3)U(Se[1],1,"An extension's critical flag");else if(Se.length!==2)throw new Error("it has a malformed extension");let rr=Ue(Se[0]);if(O.has(rr))throw new Error(`it has extension ${rr} twice`);O.set(rr,ce(U(Se[Se.length-1],4,"An extension value")))}}let ee=ce(U(r,3,"The signature"));if(ee[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:Xt(e),signatureHash:C,signature:ee.slice(1),issuer:Xt(U(u,48,"The issuer")),subject:Xt(U(l,48,"The subject")),notBefore:P,notAfter:T,spki:Xt(m),curve:E,extensions:O}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function Ti(t){return K(U(Oe(t),48,"The list")).map(Ue)}function Qc(t,e){let n=Wc[e],r=K(U(Oe(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(U(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 Zt(t,e,n,r,o){let i;try{i=Qc(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 Dr(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 Yc="2.5.29.17",Xc="2.5.29.37",Zc="1.3.6.1.5.5.7.3.3",el="1.3.6.1.4.1.57264.1.8",tl="1.3.6.1.4.1.57264.1.1",nl=134,rl=12,ol=48,il=new TextEncoder,_e=t=>new TextDecoder().decode(t);async function en(t,e,n,r){let{base64Signature:o,cert:i,rekorBundle:s}=ll(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=Dr(_e(W(i,"The bundle certificate")),"The bundle certificate"),d=Tr(u),l=Ii.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 m=il.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await Zt(W(l.publicKey,"The Rekor key"),"P-256","SHA-256",W(s.SignedEntryTimestamp,"The signed entry timestamp"),m))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(!Ui(v,l.validFor))throw new Error(`Rekor log ${l.baseUrl} was not in use at ${pt(v)}, when the entry says it was logged`);let A=ul(a.body),C=y(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(A.hash!==C)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!Nr(W(A.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let P=Dr(_e(W(A.publicKey,"The logged certificate")),"The logged certificate");if(!Nr(P,u))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await Zt(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 sl(d,v),cl(d,n),{integratedTime:a.integratedTime}}async function sl(t,e){if(!Ni(t,e))throw new Error(`The signing certificate was valid ${pt(t.notBefore)} to ${pt(t.notAfter)}, not at ${pt(e)} when Rekor logged it`);let n=[];for(let r of ki){let o=r.certChain.map(s=>Tr(W(s,"A Fulcio certificate")));if(!await Di(t,o[0]))continue;let i=await al(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 ${pt(e)}: ${n.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function al(t,e,n){if(!Ui(n,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of t.entries()){if(!Ni(o,n))return`its certificate ${r} was not valid then`;let i=t[r+1]??o;if(!await Di(o,i))return`its certificate ${r} is not signed by the next`}}async function Di(t,e){return Nr(t.issuer,e.subject)?Zt(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function cl(t,e){let n=t.extensions.get(Yc);if(!n)throw new Error("The signing certificate names no identity");let r=K(U(Oe(n),ol,"The subject alternative name")),o=r.filter(u=>u.tag===nl).map(u=>_e(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(el),s=t.extensions.get(tl),a=i?_e(ce(U(Oe(i),rl,"The OIDC issuer"))):s?_e(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(Xc);if(!c||!Ti(c).includes(Zc))throw new Error("The signing certificate is not for code signing")}function ll(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 ul(t){let e;try{e=JSON.parse(_e(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 Ni(t,e){return t.notBefore<=e&&e<=t.notAfter}function Ui(t,e){return Date.parse(e.start)<=t&&(e.end===void 0||t<=Date.parse(e.end))}function pt(t){return new Date(t).toISOString()}function Nr(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Ur=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"}),dl=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],tn="https://cloud.calimero.network";async function _i(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await en(r,e,{identity:n.identity??Ur.identity,issuer:n.issuer??Ur.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=>dl.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 nn(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 Mi(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 rn(t,e={}){let n=await Gi(t,e.fetch??fetch);if(n===void 0)throw new Error(`${Ki(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 Ki(t){return`${t.replace(/\/+$/,"")}/admin-api/tee/info`}async function Gi(t,e){let n=Ki(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 Mi(o)}function on(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${gt(e,"version")}`}async function $i(t){let e=gt(t.minReleaseVersion,"minReleaseVersion"),n=gt(t.release?.version,"The release version"),r=await _i(t.release.publishedMrtds,t.release.bundle,{expectedVersion:n,identity:t.identity,issuer:t.issuer});if(gl(n,e)<0)throw new Error(`Release ${n} is older than the minimum trusted, ${e}`);return Pr([r],{profile:t.profile,allowDebugProfile:t.allowDebugProfile})}function sn(t){return gt(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async n=>{let r=await $i({release:await t.release(),profile:t.profile,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer});return dt({dcapVerify:t.dcapVerify,fetchCollateral:t.fetchCollateral,now:t.now,...r})(n)},{includeCollateral:!0})}function pl(t){let{baseUrl:e,releaseSource:n,releaseVersion:r,applicationId:o,applicationHash:i,fetch:s,...a}=t;r!==void 0&&gt(r,"releaseVersion");let c=s??((d,l)=>fetch(d,l));return fe({baseUrl:e,verify:sn({...a,release:async()=>{let d=r===void 0?await rn(e,{fetch:c}):await Gi(e,c)??r;return typeof n=="function"?n({baseUrl:e,version:d,fetch:c}):nn(on(n??tn,d),{fetch:c})}}),applicationId:o,applicationHash:i,fetch:c})}var Li=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function gt(t,e){let n=typeof t=="string"?Li.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 gl(t,e){let[n,r]=Oi(t),[o,i]=Oi(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,m]=[/^\d+$/.test(u),/^\d+$/.test(d)],x=l&&m?Math.sign(Number(u)-Number(d)):l!==m?l?-1:1:u<d?-1:u>d?1:0;if(x!==0)return x}return 0}function Oi(t){let e=Li.exec(t);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var ml=new TextEncoder().encode("calimero.warrant.v2"),fl=new TextEncoder().encode("calimero.warrant.intent.v1"),Hi=64,Bi=256;async function Or(t,e){let n=new TextEncoder().encode(JSON.stringify(e));return k(fl,[new TextEncoder().encode(t),n])}async function an(t){let e=g(t.context,"context",32),n=g(t.authorAccount,"authorAccount",32),r=g(t.executor,"executor",32),o=g(t.executorKey,"executorKey",32),i=g(t.releaseBytecodeId,"releaseBytecodeId",32),s=_r(t.releaseVersion??""),a=le(t.accountHeads,"accountHeads"),c=le(t.governanceFloor,"governanceFloor"),u=await I(t.deviceSecret,t.signer,"deviceSecret"),d=g(u.publicKey,"signer.publicKey",32),l=new TextEncoder().encode(t.method),m=await Or(t.method,t.argsJson),x=S(t.nonce),v=S(t.notAfter),A=await k(ml,[e,n,d,r,o,i,s,l,m,S(a.length),...a,S(c.length),...c,x,v]),C=mt(await u.sign(A));return y(f(e,n,d,r,o,i,R(s.length),s,R(l.length),l,m,R(a.length),...a,R(c.length),...c,x,v,C))}function mt(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 _r(t){let e=new TextEncoder().encode(t);return hl(e.length),e}function hl(t){if(t>Bi)throw new Error(`releaseVersion is ${t} bytes, over the ${Bi} a node accepts`)}function le(t,e){let n=t??[];if(n.length>Hi)throw new Error(`${e} cites ${n.length} heads, over the ${Hi} a node accepts`);return n.map((r,o)=>g(r,`${e}[${o}]`,32))}var yl=new TextEncoder().encode("calimero.context-creation-warrant.v1"),bl=new TextEncoder().encode("calimero.context-creation.init.v1"),cn=256;async function Mr(t){let e=new TextEncoder().encode(JSON.stringify(t));return k(bl,[e])}async function wl(t){return k(yl,[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,S(t.accountHeads.length),...t.accountHeads,S(t.governanceFloor.length),...t.governanceFloor,S(t.nonce),S(t.notAfter)])}async function ln(t){let e=g(t.group,"group",32),n=t.seed===void 0?crypto.getRandomValues(new Uint8Array(32)):g(t.seed,"seed",32),r=g(t.authorAccount,"authorAccount",32),o=g(t.executor,"executor",32),i=g(t.executorKey,"executorKey",32),s=g(t.applicationId,"applicationId",32),a=qi(t.serviceName,"serviceName"),c=qi(t.name,"name"),u=le(t.accountHeads,"accountHeads"),d=le(t.governanceFloor,"governanceFloor"),l=await I(t.deviceSecret,t.signer,"deviceSecret"),m=g(l.publicKey,"signer.publicKey",32),x=await Mr(t.initArgs),v=await wl({group:e,seed:n,authorAccount:r,deviceKey:m,executor:o,executorKey:i,applicationId:s,serviceName:a,name:c,initHash:x,accountHeads:u,governanceFloor:d,nonce:t.nonce,notAfter:t.notAfter}),A=mt(await l.sign(v));return{warrant:y(f(e,n,r,m,o,i,s,ji(a),ji(c),x,R(u.length),...u,R(d.length),...d,S(t.nonce),S(t.notAfter),A)),seed:y(n)}}function Fi(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,m)=>{if(o+l>n.length)throw new Error(`creation warrant ends inside ${m} (${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 m=i(1,l)[0];if(m===0)return null;if(m!==1)throw new Error(`${l} has option tag ${m}, expected 0 or 1`);let x=s(l);if(x>cn)throw new Error(`${l} is ${x} bytes, over the ${cn} a node accepts`);return new TextDecoder("utf-8",{fatal:!0}).decode(i(x,l))},u=l=>{let m=s(l);if(m>64)throw new Error(`${l} cites ${m} heads, over the 64 a node accepts`);return Array.from({length:m},()=>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 qi(t,e){if(t===void 0)return null;let n=new TextEncoder().encode(t);if(n.length>cn)throw new Error(`${e} is ${n.length} UTF-8 bytes, over the ${cn} a node accepts`);return n}function ji(t){return t===null?new Uint8Array([0]):f(new Uint8Array([1]),R(t.length),t)}var Al=new TextEncoder().encode("calimero.governance-warrant.v1"),xl=new TextEncoder().encode("calimero.governance-warrant.op.v1"),vl={group:0,root:1};async function Kr(t){return k(xl,[new Uint8Array([Gr(t.kind)]),t.bytes])}async function Rl(t){return k(Al,[t.scope,new Uint8Array([Gr(t.kind)]),t.authorAccount,t.deviceKey,t.executor,t.executorKey,t.opHash,S(t.accountHeads.length),...t.accountHeads,S(t.governanceFloor.length),...t.governanceFloor,S(t.nonce),S(t.notAfter)])}async function ft(t){let e=g(t.scope,"scope",32),n=g(t.authorAccount,"authorAccount",32),r=g(t.executor,"executor",32),o=g(t.executorKey,"executorKey",32),i=le(t.accountHeads,"accountHeads"),s=le(t.governanceFloor,"governanceFloor"),a=Gr(t.op.kind),c=await I(t.deviceSecret,t.signer,"deviceSecret"),u=g(c.publicKey,"signer.publicKey",32),d=await Kr(t.op),l=await Rl({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}),m=mt(await c.sign(l));return y(f(e,new Uint8Array([a]),n,u,r,o,d,R(i.length),...i,R(s.length),...s,S(t.nonce),S(t.notAfter),m))}function Vi(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,m)=>{if(o+l>n.length)throw new Error(`governance warrant ends inside ${m} (${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 m=s(l);if(m>64)throw new Error(`${l} cites ${m} heads, over the 64 a node accepts`);return Array.from({length:m},()=>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 Gr(t){let e=vl[t];if(e===void 0)throw new Error(`op kind must be 'group' or 'root', got ${String(t)}`);return e}var Cl={Admin:0,Member:1,ReadOnly:2},G={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},ht={GroupCreated:0,GroupReparented:1,GroupDeleted:2,MemberJoinedOpen:7,NamespaceCreatedV2:9},Sl=new TextEncoder().encode("calimero.namespace.id.v1"),Lr=new Uint8Array(32),un=R(0);function Ji(t){let e=Cl[t];if(e===void 0)throw new Error(`role must be Admin, Member or ReadOnly, got ${String(t)}`);return new Uint8Array([e])}function N(t){return new Uint8Array([t])}function Me(t,e){return{kind:"group",bytes:f(N(G.MemberAdded),g(t,"member",32),Ji(e))}}function dn(t){return{kind:"group",bytes:f(N(G.MemberRemoved),g(t,"member",32),Lr,un)}}function yt(t){return{kind:"group",bytes:f(N(G.MemberLeft),g(t,"member",32),Lr,un)}}function pn(t,e){return{kind:"group",bytes:f(N(G.MemberRoleSet),g(t,"member",32),Ji(e))}}var El=new TextEncoder().encode("calimero.subgroup.id.v1");async function Hr(t,e,n,r){return y(await k(El,[g(t,"admin",32),g(e,"parentId",32),new Uint8Array([n?1:0]),g(r,"salt",32)]))}function Wi(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 gn(t){return{kind:"group",bytes:f(N(G.TargetApplicationSet),Lr,g(t.applicationId,"applicationId",32),Wi(t.package,"package"),Wi(t.version,"version"))}}function Ke(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(N(G.DefaultCapabilitiesSet),R(t))}}function Br(t){return{kind:"root",bytes:f(N(ht.GroupCreated),g(t.groupId,"groupId",32),g(t.parentId,"parentId",32),N(t.restricted?1:0),g(t.admin,"admin",32),g(t.salt,"salt",32))}}async function Ge(t){let e=t.salt??y(crypto.getRandomValues(new Uint8Array(32))),n=await Hr(t.admin,t.parentId,t.restricted,e);return{groupId:n,salt:e,op:Br({...t,groupId:n,salt:e})}}function mn(t,e){return{kind:"root",bytes:f(N(ht.GroupReparented),g(t,"childGroupId",32),g(e,"newParentId",32))}}function fn(t){return{kind:"root",bytes:f(N(ht.GroupDeleted),g(t,"rootGroupId",32),un,un)}}async function hn(t,e){return y(await k(Sl,[g(t,"founder",32),g(e,"salt",32)]))}function yn(t){let e=F(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(N(ht.NamespaceCreatedV2),g(t.founder,"founder",32),e,g(t.salt,"salt",32))}}function $r(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}function qr(t){return t===void 0?N(0):f(N(1),$r(t))}function jr(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])=>[$r(o),$r(r)]))}function kl(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 bn(t,e){return{kind:"group",bytes:f(N(G.MemberCapabilitySet),g(t,"member",32),R(kl(e,"capabilities")))}}function wn(t){return{kind:"group",bytes:f(N(G.ContextDetached),g(t,"contextId",32))}}function An(t){if(t!=="open"&&t!=="restricted")throw new Error(`mode must be open or restricted, got ${String(t)}`);return{kind:"group",bytes:f(N(G.SubgroupVisibilitySet),N(t==="open"?0:1))}}function $e(t={}){return{kind:"group",bytes:f(N(G.GroupMetadataSet),qr(t.name),jr(t.data))}}function xn(t,e={}){return{kind:"group",bytes:f(N(G.MemberMetadataSet),g(t,"member",32),qr(e.name),jr(e.data))}}function vn(t,e={}){return{kind:"group",bytes:f(N(G.ContextMetadataSet),g(t,"contextId",32),qr(e.name),jr(e.data))}}function zi(t){if(!Number.isInteger(t)||t<1||t>255)throw new Error(`capability must be a non-zero u8, got ${String(t)}`);return N(t)}function Qi(t,e,n){return{kind:"group",bytes:f(N(G.ContextCapabilityGranted),g(t,"contextId",32),g(e,"member",32),zi(n))}}function Yi(t,e,n){return{kind:"group",bytes:f(N(G.ContextCapabilityRevoked),g(t,"contextId",32),g(e,"member",32),zi(n))}}function Rn(t){return{kind:"root",bytes:f(N(ht.MemberJoinedOpen),g(t.member,"member",32),g(t.groupId,"groupId",32),F(t.credential,"credential"))}}var Cn=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"}},Il=t=>new Promise(e=>setTimeout(e,t));function Pl(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/${p(e)}/intents`)).data}async execute(e,n,r={}){let o=await this.describe(e),i=this.checkedExecutor(o),s=y(g(o.releaseBytecodeId??"","the relay's releaseBytecodeId",32)),a=o.releaseVersion??"";_r(a);let c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??Cn,l=await an({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}),m=await this.json("POST",`/admin-api/contexts/${p(e)}/intents`,{method:n,argsJson:r,warrant:l,authorProof:this.config.authorProof});return{rootHash:m.data.rootHash,returns:m.data.returns??null}}async presenceIntent(e,n){await this.jsonOnce("POST",`/admin-api/contexts/${p(e)}/presence-intents`,n)}async describeCreation(e,n={}){let r=n.author?`?author=${encodeURIComponent(n.author)}`:"";return(await this.json("GET",`/admin-api/groups/${p(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??Cn,{warrant:c}=await ln({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/${p(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/${p(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??Cn,a=await ft({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(g(e.salt,"salt",32)):y(crypto.getRandomValues(new Uint8Array(32))),o=await hn(this.config.authorAccount,r),i=yn({founder:this.config.authorAccount,credential:this.config.authorProof,salt:r}),s=e.defaultCapabilities===void 0?void 0:Ke(e.defaultCapabilities),a=e.application?gn(e.application):void 0,c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??Cn,l=await ft({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}),m=await this.postGovernance(o,i,l),x={namespaceId:m.groupId,salt:r,teeEnabled:m.teeEnabled??!1,...m.teeError?{teeError:m.teeError}:{}},v=x,A=C=>C instanceof Error?C.message:String(C);if(a)try{await this.govern({groupId:x.namespaceId,op:a}),v={...v,applicationSet:!0}}catch(C){v={...v,applicationSet:!1,applicationError:A(C)}}if(s)try{await this.govern({groupId:x.namespaceId,op:s}),v={...v,defaultCapabilitiesSet:!0}}catch(C){v={...v,defaultCapabilitiesSet:!1,defaultCapabilitiesError:A(C)}}return v}async postGovernance(e,n,r){return(await this.json("POST",`/admin-api/groups/${p(e)}/governance-intents`,{warrant:r,authorProof:this.config.authorProof,op:y(n.bytes)})).data}checkedExecutor(e){let n={executorAccount:y(g(e.executorAccount??"","the relay's executorAccount",32)),executorKey:y(g(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 D&&s.status===429)||i>=this.rateLimitRetries)throw s;let c=Pl(s.headers);await Il(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 D(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=Tl(c);throw new he(u,/nonce/i.test(u),a.status)}throw new D(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(a.status!==204)return await a.json()}};function Tl(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 Dl=new TextEncoder().encode("calimero.auth.login.v1"),Xi={webOrigin:0,codeSigningId:1,cli:2};function Zi(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 Nl(t){return f(Uint8Array.from([Xi[t.kind]]),Zi(t))}function Ul(t){let e=Uint8Array.from([Xi[t.kind]]);if(t.kind==="cli")return e;let n=Zi(t);return f(e,R(n.length),n)}async function Sn(t){let e=g(t.node,"node",32),n=g(t.challenge,"challenge",32),r=g(t.sessionKey,"sessionKey",32),o=await I(t.deviceSecret,t.signer,"deviceSecret"),i=g(o.publicKey,"signer.publicKey",32),s=S(t.issuedAt),a=S(t.expiresAt),c=await k(Dl,[e,Nl(t.audience),n,r,i,s,a]),u=await o.sign(c);return y(f(e,Ul(t.audience),n,r,i,s,a,u))}var Ol=300;async function Fr(){let t=y(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:y(await ie(t)),secret:t}}async function Le(t){let e=t.nodeUrl.replace(/\/+$/,""),n=t.timeoutMs??1e4,r=async(m,x)=>{let v=new AbortController,A=setTimeout(()=>v.abort(),n),C;try{let T={...x,signal:v.signal};C=t.fetch?await t.fetch(`${e}${m}`,T):await globalThis.fetch(`${e}${m}`,T)}catch(T){throw new D(0,T instanceof Error?T.name:"NetworkError",`${e}${m}`,new Headers,T instanceof Error?T.message:String(T))}finally{clearTimeout(A)}let P=await C.text().catch(()=>"");if(!C.ok)throw new D(C.status,C.statusText,`${e}${m}`,C.headers,P);return P?JSON.parse(P):{}},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 Fr(),a=Math.floor(Date.now()/1e3),c=await Sn({node:t.node,audience:t.audience,challenge:i,sessionKey:s.publicKey,issuedAt:a,expiresAt:a+(t.ttlSeconds??Ol),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 _l=3e4;function Be(){let t=globalThis.location?.origin;return t?{kind:"webOrigin",origin:t}:{kind:"cli"}}function Ml(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 He=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-_l>e?this.session.accessToken:(this.pending||(this.pending=this.loginNow().finally(()=>{this.pending=null})),(await this.pending).accessToken)}async loginNow(){let e=await Le({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=Ml(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 Y=t=>new TextEncoder().encode(t),Kl=Y("calimero.auth.request.v1"),Gl=Y("calimero.auth.request.body.v1"),Vr="X-Calimero-Proof",$l=300;async function Wr(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)}`);if(n.includes("?"))throw new Error(`the path must carry no query string, got ${JSON.stringify(n)} \u2014 a query is excluded from the signature on purpose, because a proxy may rewrite one. Anything that must be bound belongs in the body.`);let o=t.body===void 0?new Uint8Array:typeof t.body=="string"?Y(t.body):t.body,i=await k(Gl,[o]),s=Math.floor(t.now??Date.now()/1e3),a=s+(t.validForSeconds??$l),c=await k(Kl,[Y(e),Y(n),i,S(s),S(a)]),u=await Ll(c,t);if(u.length!==64)throw new Error(`the signer returned ${u.length} bytes, not a 64-byte signature`);let d=f(R(Y(e).length),Y(e),R(Y(n).length),Y(n),i,S(s),S(a),u),l=Hl(r,"credential");return y(f(l,new Uint8Array([0]),d))}async function Ll(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 oe(e.deviceSecret);return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,t))}function Hl(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 g(n,e,n.length/2)}function Jr(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 Wr({method:e,path:n,body:r,credential:t.credential,deviceSecret:t.deviceSecret,signer:t.signer,validForSeconds:t.validForSeconds});return{[Vr]:o}}}function Bl(t){return new URL(t).pathname}var es=new TextEncoder().encode("calimero/presence/1");async function ts(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 zr(t){return f(es,g(t.contextId,"contextId",32),g(t.author,"author",32),S(t.seq),S(t.sentAtMs),await ts(t.state))}var ql=2500,bt=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??ql,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 qt(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 zr({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 ns(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 rs(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 jl(t,e,n){let r=e?.nodeKey;return r?new He({nodeUrl:e?.nodeUrl??t.relayUrl,nodeKey:r,accountProof:e?.accountProof??t.authorProof,audience:e?.audience??Be(),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 J?e.relay:new J({...e.relay,fetch:e.relay.fetch??o});if(this.relayObserver=jl(i,e.observe,o),this.rpcTransport=new ye(i,this.relayObserver),this.relayUrl=i.relayUrl,e.proof&&(this.proofAuthorizer=Jr(e.proof)),e.session){let s=e.session;this.relayAdmin=_o({baseUrl:i.relayUrl,getAuthToken:typeof s=="string"?async()=>s:s,fetch:o})}else if(this.proofAuthorizer){let s=this.proofAuthorizer;this.relayAdmin=Kt(tt({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 ns("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 rs("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."):rs("WebSocket events")}get ephemeral(){return this.nodeClient?this.nodeClient.ephemeral:(this.relayPresence??(this.relayPresence=new bt({relay:this.relay,events:()=>this.events})),this.relayPresence)}get cloud(){if(!this.nodeClient)throw ns("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 En(t){return new be(t)}var Xr="calimero.delegated.connection",Zr="calimero.delegated.credential";function eo(){if(typeof sessionStorage>"u")return null;try{let t=sessionStorage.getItem(Xr);return t?JSON.parse(t):null}catch{return null}}function is(t){try{sessionStorage.setItem(Xr,JSON.stringify(t))}catch{}}function ss(){try{sessionStorage.removeItem(Xr)}catch{}}function as(){let t=eo();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(Zr);if(!e)return null;let n=JSON.parse(e);return!n.account||!n.credential||!n.deviceSecret?null:n}catch{return null}}function cs(t){try{sessionStorage.setItem(Zr,JSON.stringify(t))}catch{}}function ls(){try{sessionStorage.removeItem(Zr)}catch{}}function to(t){let e=In(t);return{next:async()=>{let n=0n;try{n=us(t)}catch{n=0n}try{localStorage.setItem(e,String(n+1n))}catch{}return n}}}function In(t){return`calimero.nonce.${t}`}function us(t){let e=localStorage.getItem(In(t));if(e!==null)return BigInt(e);let n=`${In(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 Tn(t,e,n){try{us(t)<=n&&localStorage.setItem(In(t),String(n+1n))}catch{}}var ds="calimero.delegated.relay-node-key.";function X(t){return t.replace(/\/+$/,"")}function no(t,e){localStorage.setItem(ds+X(t),e.trim().toLowerCase())}function Dn(t){try{let e=localStorage.getItem(ds+X(t));return e&&/^[0-9a-f]{64}$/.test(e)?e:null}catch{return null}}function ro(t){try{let{hostname:e}=new URL(t);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch{return!1}}var Fl="locked-read-only",Vl="2.3.99",Qr;function Wl(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 je=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 os(t,e){try{return await e()}catch(n){throw n instanceof je?n:new je(t,n)}}function Jl(t){return async(e,n)=>{let r;try{r=await globalThis.fetch(e,n)}catch(o){throw t.failure=o,new je(`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 os("loading the quote verifier",()=>(Qr??(Qr=import("@phala/dcap-qvl").then(i=>Wl(i),i=>{throw Qr=void 0,i})),Qr));return sn({dcapVerify:o,release:()=>os("fetching the release the relay runs",async()=>nn(on(tn,await rn(t,{fetch:e})))),profile:Fl,minReleaseVersion:Vl})(r)},{includeCollateral:!0})}async function Fe(t,e={}){let n=e.fresh?null:Dn(t);if(n)return{kind:"learned",nodeKey:n};let r={failure:null},o=Jl(r);try{let i=ro(t),{nodeKey:s}=await Yt({relayUrl:t,allowMock:i,fetch:o,...i?{}:{verify:ps(t,o)}});return no(t,s),{kind:"learned",nodeKey:s}}catch(i){return i instanceof je||r.failure?{kind:"unavailable",error:i}:{kind:"refused",error:i}}}async function Nn(t){let e=await Fe(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 Pn=[1e3,2e3,5e3,1e4,3e4];function zl(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 gs(t,e={}){let{signal:n}=e;for(let r=0;!n?.aborted;r+=1){let o=await Fe(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=Pn[Math.min(r,Pn.length-1)];console.warn(`[mero-js] could not reach what proves the relay's node key; retrying in ${i/1e3} s`,o.error),await zl(i,n)}return null}function Ql(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 Yr=new Map;function ms(){Yr.clear()}async function Yl(t){if(t.status!==403)return!1;try{return(await t.clone().json()).error?.code==="sealed_route_unguarded"}catch{return!1}}function Xl(t){return t.headers.has("authorization")||new URL(t.url).pathname.startsWith("/auth/")}function Zl(t){let e=(o,i)=>globalThis.fetch(o,i),n=fe({baseUrl:t,verify:ps(t,e),fetch:e}),r=!1;return async(o,i)=>{let s=new Request(o,i);if(r&&Xl(s))return e(s);let a=await n(s.clone());return await Yl(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 Ve(t){if(ro(t))return;let e=X(t),n=Yr.get(e);return n||(n=Zl(t),Yr.set(e,n)),n}function eu(t,e){let n=null,r=null;return async()=>{let o=n?Ql(n):null;return n&&(o===null||o-Date.now()>3e4)?n:(r||(r=Le({nodeUrl:t.relayUrl,fetch:Ve(t.relayUrl),node:e,deviceSecret:t.deviceSecret,accountProof:t.credential,audience:Be()}).then(i=>(n=i.accessToken,n)).catch(i=>{console.warn("[mero-js] relay login failed",i),n=null}).finally(()=>{r=null})),r)}}var kn=new Map;function fs(){kn.clear()}function tu(t){return typeof t=="object"&&t!==null&&t.status===409}function nu(t,e){let n=t.rpc,r=X(e),o=async i=>{let s=`${r}|${i.contextId}|${i.method}`;if(kn.get(s)!=="write")try{let{returns:a}=await t.admin.queryContext(i.contextId,{method:i.method,argsJson:i.argsJson??{}});return kn.set(s,"read"),{returns:a,transport:"relay"}}catch(a){tu(a)&&kn.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 ru(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 ou(t,e){let n=e.session?nu(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=ru(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 Un(t,e){if(!t.relayUrl)return null;let n=Dn(t.relayUrl),r=En({transport:"relay",fetch:Ve(t.relayUrl),relay:{relayUrl:t.relayUrl,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:to(t.relayUrl)},proof:{credential:t.credential,deviceSecret:t.deviceSecret},session:n?eu({...t,relayUrl:t.relayUrl},n):void 0,observe:n?{nodeKey:n}:void 0});return ou(r,{relayUrl:t.relayUrl,session:n!==null,attested:n!==null||ro(t.relayUrl)})}var hs="calimero.delegated.relays.";function q(t){try{let e=localStorage.getItem(hs+t),n=e?JSON.parse(e):{};return{namespaces:n.namespaces??{},contexts:n.contexts??{}}}catch{return{namespaces:{},contexts:{}}}}function oo(t,e){try{localStorage.setItem(hs+t,JSON.stringify(e))}catch{}}function we(t,e,n){let r=q(t),o=X(e);n.namespaceId&&(r.namespaces[n.namespaceId]=o),n.contextId&&(r.contexts[n.contextId]=o),oo(t,r)}function ys(t,e){return q(t).contexts[e]??null}function On(t,e){return e.executorAccount||!t?.executorAccount||!t.relayUrl||!e.relayUrl||X(t.relayUrl)!==X(e.relayUrl)?e:{...e,executorAccount:t.executorAccount}}function We(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)]}async function bs(t){let e=[],n=q(t.account);for(let r of We(t))try{if(!await Nn(r))continue;let o=Un({...t,relayUrl:r},null);if(!o)continue;let{contexts:i}=await o.admin.getContexts();for(let s of i??[])e.push({...s,relayUrl:r}),n.contexts[s.id]=r}catch(o){console.warn(`[mero-js] could not list contexts on ${r}`,o)}return oo(t.account,n),e}async function ws(t){var o,i;let e=[],n=new Set,r=q(t.account);for(let s of We(t))try{if(!await Nn(s))continue;let a=Un({...t,relayUrl:s},null);if(!a)continue;for(let c of await a.admin.listNamespaces())n.has(c.namespaceId)||(n.add(c.namespaceId),e.push({...c,relayUrl:s}),(o=r.namespaces)[i=c.namespaceId]??(o[i]=s))}catch(a){console.warn(`[mero-js] could not list namespaces on ${s}`,a)}return oo(t.account,r),e}function Mn(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 wt(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()}}}function iu(t){return{getWarrantNonce:(e,n)=>t.client.getWarrantNonceAsAuthor(e,t.authorProof)}}var _n=class extends Error{constructor(n,r){super(`author device ${r} has spent every nonce in context ${n}; it must re-key to write again`);this.contextId=n;this.authorDeviceKey=r;this.name="WarrantNonceExhaustedError"}};function su(t){let e=Array.isArray(t.lookups)?t.lookups:[t.lookups];if(e.length===0)throw new Error("a recovering nonce source needs at least one node to ask");let n=t.local??Mn(1),r=t.onLookupFailure??"throw",o=null,i=null,s=async()=>{let a=await Promise.allSettled(e.map(d=>d.getWarrantNonce(t.contextId,t.authorDeviceKey))),c=null,u=!1;for(let d of a){if(d.status!=="fulfilled")continue;let l=d.value;if(l.kind==="exhausted"){u=!0;continue}(c===null||l.nextNonce>c)&&(c=l.nextNonce)}if(c===null&&u)throw new _n(t.contextId,t.authorDeviceKey);if(c===null){let d=a.find(m=>m.status==="rejected"),l=d&&d.status==="rejected"?d.reason:void 0;if(r==="local"){o=0n;return}throw l instanceof Error?l:new Error(`no node could answer where the warrant-nonce sequence stands: ${String(l)}`)}o=c,await n.advanceTo?.(c)};return{async next(){o===null&&(i??(i=s().finally(()=>{i=null})),await i);let a=await n.next(),c=o!==null&&o>a?o:a;return o=c+1n,c},async advanceTo(a){(o===null||a>o)&&(o=a),await n.advanceTo?.(a)}}}async function As(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=cu(r,t.namespaceId),i=await n.getNamespaceRelays(o.namespaceId),s=io(i);if(!s)throw new Error(lu(o,i));let a=new J({relayUrl:s.relayUrl,executorAccount:s.executorAccount,authorAccount:t.authorAccount,authorProof:t.authorProof,signer:e,nonces:t.nonces??uu(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 Q(e),a=await new $({cloudBaseUrl:t.cloudBaseUrl,onSession:t.onSession,fetch:t.fetch,timeoutMs:t.timeoutMs}).signInWithAccount(i.signer);return As({...r,deviceSecret:void 0,signer:o,sessionToken:a.sessionToken,authorAccount:n??i.accountId})}function cu(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 lu(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 uu(t){let e=`mero-js:warrant-nonce:${t}`;try{return wt(e)}catch{return Mn(1)}}var du=new TextEncoder().encode("calimero.mdma.routing-read.v1\0");async function xs(t,e){g(e,"deviceSecret",32);let n=await oe(e),r=f(du,new TextEncoder().encode(t)),o=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,r));return pu(o)}async function Kn(t,e){return{"X-Calimero-Credential":e.credential,"X-Calimero-Nonce":t.nonce,"X-Calimero-Signature":await xs(t.nonce,e.deviceSecret)}}function pu(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var vs="calimero.cloud.link.pending",so="link_state";var ao=/^[0-9a-f]{64}$/;function Rs(t){try{let e=localStorage.getItem(vs),n=e?JSON.parse(e):{};return Object.fromEntries(Object.entries(n).filter(([,r])=>r&&typeof r.expiresAt=="number"&&r.expiresAt>t))}catch{return{}}}function Cs(t){try{localStorage.setItem(vs,JSON.stringify(t))}catch{}}function Gn(t,e){if(!ao.test(t))throw new Error("accountId must be 64 lowercase hex characters");let n=new URL(e),r=Date.now(),o=Rs(r),i=crypto.getRandomValues(new Uint8Array(16)),s=Array.from(i,a=>a.toString(16).padStart(2,"0")).join("");return o[s]={account:t,expiresAt:r+6e5},Cs(Object.fromEntries(Object.entries(o).slice(-20))),n.searchParams.set(so,s),n.toString()}function Je(t){let e=new URLSearchParams(t).get(so),n=Rs(Date.now());if(!e||!Object.prototype.hasOwnProperty.call(n,e))return null;let r=n[e];return delete n[e],Cs(n),r}function Ss(t){let e=new URLSearchParams(t);e.delete(so);let n=e.toString();return n?`?${n}`:""}var gu="https://cloud.calimero.network";function Es(t){let e=new URL(t.cloudWebUrl??gu);return e.searchParams.set("link-account",t.accountId),e.searchParams.set("callback-url",Gn(t.accountId,t.returnTo)),e.toString()}function mu(t){throw window.location.assign(Es(t)),new Error("redirecting to the cloud to authorise this link")}function fu(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Je(t.search??""),co(),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;if(Je(t.search??"")?.account!==o)throw co(),new Error("this account link answers a request this browser did not make - start the link again from here");return co(),{grant:r,account:o}}function co(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+Ss(location.search))}async function hu(t){let e=await Q(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,signer:e.signer})}var yu="enrol-device",bu="enrol-kem",wu="callback-url",Au="state";function Ps(t){Is(t.devicePublicKey,"devicePublicKey"),Is(t.kemPublicKey,"kemPublicKey"),Su(t.returnTo),Cu(t.returnTo);let e=new URL(t.walletUrl);return e.searchParams.set(yu,t.devicePublicKey),e.searchParams.set(bu,t.kemPublicKey),e.searchParams.set(wu,t.returnTo),t.state&&e.searchParams.set(Au,t.state),e.toString()}function xu(t){throw window.location.assign(Ps(t)),new Error("redirecting to the wallet to approve this device")}function vu(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw ks(),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;ks();let s=e.get("state");return{credential:r,account:o,device:i,...s?{state:s}:{}}}function ks(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+location.search)}async function Ru(t){if(t.expectState!==void 0&&t.expectState!==t.state)throw new Error("this enrolment answers a request this app did not make \u2014 the state it carries is not the one sent");let e=await Ft(t.credential);if(e.signPublicKey!==Ae(t.devicePublicKey))throw new Error(`this credential certifies device key ${e.signPublicKey}, but this app holds ${Ae(t.devicePublicKey)} \u2014 it would sign with a key the certificate does not cover`);if(t.kemPublicKey!==void 0&&e.kemPublicKey!==Ae(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!==Ae(t.account))throw new Error(`the wallet reported account ${Ae(t.account)}, but the credential names ${e.account}`);if(e.device!==Ae(t.device))throw new Error(`the wallet reported device ${Ae(t.device)}, but the credential names ${e.device}`);return{credential:t.credential,account:e.account,device:e.device,certificate:e}}function Is(t,e){if(!/^[0-9a-f]{64}$/.test(t))throw new Error(`${e} must be 64 lowercase hex characters`)}function Ae(t){return t.trim().toLowerCase()}function Ts(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 Cu(t){Ts(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 Su(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 $n(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 ku(t,e){if(e.size===0)return!0;let n=$n(t.account);return n!==null&&e.has(n)}async function Ln(t){let e=t.cloud??new $({cloudBaseUrl:t.cloudBaseUrl,routingCredential:{credential:t.credential,deviceSecret:t.deviceSecret}}),n,r;try{let m=await e.getNamespaceRouting(t.namespaceId);n=m.nodes,r=m.servable}catch(m){return{ok:!1,step:"admitters-lookup",reason:`The cloud could not be asked which nodes serve namespace ${t.namespaceId}: ${m instanceof Error?m.message:String(m)}. 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($n).filter(m=>m!==null)),i=n.filter(m=>ku(m,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(m=>m.canAdmit),a=s.length>0?s:i,c=s.length===0||!r,u=a.filter(m=>typeof m.relayUrl=="string"&&m.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(m=>m.canExecute)??u.find(m=>m.fresh)??d;return{ok:!0,relayUrl:l.relayUrl,admitUrl:l.admitUrl??`${l.relayUrl.replace(/\/+$/,"")}/admin-api/namespaces/${p(t.namespaceId)}/admit`,admitterAccount:l.account,peerId:l.peerId,writable:l.canExecute,stale:!l.fresh||c}}var Hn=1440*60,uo={Admin:0,Member:1,ReadOnly:2};function Ct(t){let e=t.admitters??[];return f(lo(t.inviter_identity,"inviter_identity"),lo(t.group_id,"group_id"),S(t.expiration_timestamp),lo(t.secret_salt,"secret_salt"),new Uint8Array([t.invited_role]),R(e.length),...e.map((n,r)=>g(n,`admitters[${r}]`,32)))}async function po(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",Ct(t)))}function go(t){return[...new Set(t.filter(n=>n.role==="Admin").map(n=>n.identity.toLowerCase()))].sort()}async function Bn(t){let e=await I(t.deviceSecret,t.signer,"deviceSecret"),n=g(e.publicKey,"signer.publicKey",32),r=g(t.groupId,"groupId",32);g(t.inviterAccount,"inviterAccount",32);let o=[...t.admitters??[]].map(m=>m.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=go(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((m,x)=>g(m,`admitters[${x}]`,32));let i=t.invitedRole??uo.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??Hn,Hn);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 po(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(g(t.applicationId,"applicationId",32))),t.appKey&&(l.app_key=Array.from(g(t.appKey,"appKey",32))),l}function lo(t,e){if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return new Uint8Array(t)}var mo=25,Iu=new TextEncoder().encode("calimero.namespace.v1"),Pu=0,Ds={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreatedV2:9,MemberJoinedViaTeeAttestation:10};function Ns(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 Us(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(Ct(e),Us(t.inviter_signature),t.inviter_account?f(new Uint8Array([1]),g(t.inviter_account,"inviter_account",32)):new Uint8Array([0]),R(n.length),...n.map(Us),Ns(t.application_id,"application_id"),Ns(t.app_key,"app_key"))}async function jn(t){let e=t.parentOpHashes??[],n=g(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([Ds.MemberJoinedAt]),g(t.member,"member",32),qn(t.invitation),S(o),n):f(new Uint8Array([Ds.MemberJoined]),g(t.member,"member",32),qn(t.invitation),n),s=f(new Uint8Array([Pu]),i),a=await I(t.deviceSecret,t.signer,"deviceSecret"),c=g(a.publicKey,"signer.publicKey",32),u=f(new Uint8Array([mo]),g(t.namespaceId,"namespaceId",32),R(e.length),...e.map((m,x)=>g(m,`parentOpHashes[${x}]`,32)),c,S(t.nonce),s),d=await a.sign(f(Iu,u)),l=new Uint8Array([0]);return y(f(u,d,l))}function Tu(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 Du(t){let e=wt(`calimero.delegated.joinnonce.${t}`);return()=>e.next()}function Os(t){return t.replace(/\/+$/,"")}async function Fn(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??Du(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??`${Os(t.nodeUrl)}/admin-api/namespaces/${p(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:Tu(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:Os(t.nodeUrl),account:e,credential:n,deviceSecret:r}}}async function Vn(t){let e=t.deps?.resolve??Ln,n=t.deps?.join??Fn,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 _s(t,e,n,r){let i=await(r.bootstrap??Vn)({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&&we(t.account,i.session.relayUrl,{namespaceId:e}),r.onJoined(On(t,i.session)),{namespaceId:e}}function Ms(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 fo(t,e){let n=Ms(t),r=Ms(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 Nu(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 St(t){return t.filter(e=>!e.yanked&&typeof e.appVersion=="string"&&e.appVersion.length>0).reduce((e,n)=>!e||Nu(n.appVersion,e.appVersion)?n:e,void 0)}async function Et(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 Ks(t,e,n={}){let o=(await Et(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=St(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 fo(e,a),signerId:a,version:s.appVersion}}function $s(t,e){return{next:async()=>Uu(t,e)}}function Uu(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 Ls(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 Ou(t){return!t||t.length===0?{}:JSON.parse(new TextDecoder().decode(Uint8Array.from(t)))}function Jn(t,e,n,r){return new J({relayUrl:e,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:n,fetch:r??Ve(e)})}async function kt(t,e,n={}){let r=Ls(t,e.namespaceId),o=0n,i=await Jn(t,r,{next:async()=>o},n.fetch).createContext({groupId:e.groupId??e.namespaceId,applicationId:e.applicationId,serviceName:e.serviceName,seed:e.contextSeed,initArgs:Ou(e.initializationParams),name:e.name});return Tn(r,i.contextId,o),we(t.account,r,{namespaceId:e.namespaceId,contextId:i.contextId}),{contextId:i.contextId}}async function ve(t,e,n={}){let r=Ls(t,e.namespaceId);return Jn(t,r,$s(r,e.group),n.fetch).govern({groupId:e.group,op:e.op})}async function Hs(t,e,n={}){let{groupId:r}=await ve(t,{namespaceId:e.namespaceId,group:e.namespaceId,op:(await Ge({parentId:e.namespaceId,restricted:!0,admin:t.account})).op},n);for(let i of e.members)await ve(t,{namespaceId:e.namespaceId,group:r,op:Me(i,"Member")},n);let{contextId:o}=await kt(t,{...e,groupId:r},n);return{contextId:o,groupId:r}}async function zn(t,e={},n={}){let o=We(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 _u(t,o,n.fetch),s=BigInt(Date.now()),a=await Jn(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(we(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 Ku(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 _u(t,e,n){let r=t.executorAccount&&t.relayUrl?.replace(/\/+$/,"")===e?t.executorAccount:null;if(r)return{executorAccount:r,executorKey:await Gs(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 Gs(e),s=await Jn(t,e,$s(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 Gs(t){let e=await Fe(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 Qn="link this account to your cloud user in the wallet so the cloud can host this namespace on its fleet",Wn={account_not_linked:Qn,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 Mu(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 Ku(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 xe)return{haEnabled:!1,haError:Qn};if(i instanceof z&&Wn[i.code]){let s=i.code==="ha_request_pending"?Mu(i):null,a=Wn[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=St(await Et(t,e,n));if(!r)throw new Error(`the registry lists no version of ${e}`);return r.appVersion}var Bs="calimero.delegated.group-namespace.",ho=new Map;function qs(t){let e={};try{e=JSON.parse(localStorage.getItem(Bs+t)??"{}")}catch{}return{...e,...ho.get(t)}}function It(t,e,n){ho.set(t,{...ho.get(t),[e]:n});try{let r=qs(t);r[e]=n,localStorage.setItem(Bs+t,JSON.stringify(r))}catch{}}function Pt(t,e){return q(t.account).namespaces[e]?e:qs(t.account)[e]}function js(t,e){let n=Pt(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 Yn(t,e,n){return ve(t,{namespaceId:js(t,e),group:e,op:n})}async function Xn(t,e,n){let r=js(t,e);return ve(t,{namespaceId:r,group:r,op:n})}var Re=class extends Error{constructor(n){super(`${n} is not available for an account: it needs a node`);this.method=n;this.name="NotForAccountError"}},Qe=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"}},Ye=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"}},Fs={listNamespaces:async()=>[],listNamespacesForApplication:async()=>[],getContexts:async()=>({contexts:[]})},Gu=new Set(["upgradeGroup","retryGroupUpgrade","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 $u(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 Vs(t,e={}){let{session:n,read:r,app:o}=t,i=e.govern?.group??Yn,s=e.govern?.root??Xn,a=e.createContext??kt,c=e.found??zn,u=e.latestVersion??ze,d=e.signInvitation??Bn,l=e.join,m=e.routing;async function x(h,b){if(!l)throw new Re("joinNamespace without a join handler");return l(h,b.invitation)}let v=()=>{if(r===null)throw new Qe("this call");return r};async function A(h){if(Pt(n,h))return;let b=await v().getGroupInfo(h);It(n.account,h,b.namespaceId??h)}let C=async(h,b,E)=>(await A(b),i(h,b,E)),P=async(h,b,E)=>(await A(b),s(h,b,E));async function T(h){try{return await P(n,h,Rn({member:n.account,groupId:h,credential:n.credential})),!0}catch(b){if($u(b))return!1;throw b}}async function j(h,b){let E=b??String(await v().getContextGroup(h)),{members:O}=await v().listGroupMembers(E);return O.some(H=>H.identity.toLowerCase()===n.account.toLowerCase())}let M={async listNamespacesForApplication(h){return(await v().listNamespaces()).filter(b=>b.targetApplicationId===h)},async getNodeIdentity(){return{accountId:n.account,deviceId:null,publicKey:"",deviceCertified:!0}},async createNamespace(h){if(!o.packageName)throw new Re("createNamespace without a packageName");let b=o.packageVersion??await u(o.registryUrl??"https://apps.calimero.network",o.packageName),{namespaceId:E,haEnabled:O,haError:H}=await c(n,{defaultCapabilities:231,application:{applicationId:h.applicationId,package:o.packageName,version:b}});return h.name&&await C(n,E,$e({name:h.name})),{namespaceId:E,haEnabled:O,...H!==void 0?{haError:H}:{}}},async createGroupInNamespace(h,b={}){let{op:E}=await Ge({parentId:h,restricted:b.visibility==="restricted",admin:n.account}),{groupId:O}=await P(n,h,E);return It(n.account,O,h),b.groupName&&await C(n,O,$e({name:b.groupName})),{groupId:O}},async addGroupMembers(h,b){for(let E of b.members)await C(n,h,Me(E.identity,E.role??"Member"))},async removeGroupMembers(h,b){for(let E of b.members)await C(n,h,dn(E))},async setGroupMetadata(h,b){await C(n,h,$e(b))},async setMemberMetadata(h,b,E){await C(n,h,xn(b,E))},async setContextMetadata(h,b,E){await C(n,h,vn(b,E))},async setDefaultCapabilities(h,b){await C(n,h,Ke(b.defaultCapabilities))},async setSubgroupVisibility(h,b){await C(n,h,An(b.subgroupVisibility==="open"?"open":"restricted"))},async setMemberCapabilities(h,b,E){await C(n,h,bn(b,E.capabilities))},async deleteGroup(h){return await P(n,h,fn(h)),{isDeleted:!0}},async reparentGroup(h,b){return await P(n,h,mn(h,b.newParentId)),{reparented:!0}},async leaveGroup(h){await C(n,h,yt(n.account))},async leaveNamespace(h){await C(n,h,yt(n.account))},async getContextIdentitiesOwned(h){return{identities:await j(h)?[n.account]:[]}},async joinContext(h){return await T(String(await v().getContextGroup(h))),{contextId:h,memberPublicKey:n.account}},async createContext(h){let E=(await v().getGroupInfo(h.groupId)).namespaceId??h.groupId,{contextId:O}=await a(n,{namespaceId:E,groupId:h.groupId,applicationId:h.applicationId,serviceName:h.serviceName,contextSeed:h.contextSeed,name:h.name,initializationParams:h.initializationParams});return{contextId:O,memberPublicKey:n.account,groupId:h.groupId}},async createNamespaceInvitation(h){let[{members:b},E]=await Promise.all([v().listGroupMembers(h),v().getGroupInfo(h)]),O=b.filter(ee=>ee.role==="RelayTee").map(ee=>ee.identity.toLowerCase());if(m){let ee=new Set(O.length>0?O:b.filter(ne=>ne.role==="Admin").map(ne=>ne.identity.toLowerCase())),te=null;try{te=(await m(h)).nodes}catch{}if(te!==null){if(te.length===0)throw new Ye(h,"not-hosted");if(!te.some(ne=>ne.account!==null&&ee.has(ne.account.toLowerCase())))throw new Ye(h,"no-named-node")}}return{invitation:await d({groupId:h,inviterAccount:n.account,deviceSecret:n.deviceSecret,...O.length>0?{admitters:O}:{},members:b,applicationId:E.targetApplicationId,appKey:E.appKey})}},async syncGroup(h){return{groupId:h,synced:!0}},async syncContext(){},joinNamespace:x,async updateMemberRole(h,b,E){await C(n,h,pn(b,E.role))},async joinSubgroupInheritance(h){return{groupId:h,memberPublicKey:n.account,wasInherited:await T(h)}},async detachContextFromGroup(h,b){await C(n,h,wn(b))}};return r===null?new Proxy({},{get(h,b){if(typeof b=="string")return b==="getNodeIdentity"?M.getNodeIdentity:b==="joinNamespace"?x:b in Fs?Fs[b]:async()=>{throw new Qe(b)}}}):new Proxy(r,{get(h,b,E){return typeof b=="string"&&b in M?M[b]:typeof b=="string"&&Gu.has(b)?async()=>{throw new Re(b)}:Reflect.get(h,b,E)}})}function Ws(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 Lu="https://manager.cloud.calimero.network";function yo(t,e){return typeof t.can_execute=="boolean"?t.can_execute:e}function bo(t){return typeof t.tee_role=="string"&&t.tee_role!==""?t.tee_role:null}function io(t){return t.find(e=>e.canExecute&&e.relayUrl!==null&&e.executorAccount!==null)??null}function Hu(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 Bu(t){return typeof t=="string"&&ao.test(t)?t:null}var z=class extends D{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.code=n;this.name="AccountHaRefusedError"}},xe=class extends z{constructor(){super(...arguments);this.name="AccountNotLinkedError"}};xe.CODE="account_not_linked";var At=class extends z{constructor(){super(...arguments);this.name="AccountLinkedToSeveralUsersError"}};At.CODE="account_linked_to_several_users";var xt=class extends z{constructor(){super(...arguments);this.name="HaRequestPendingError"}};xt.CODE="ha_request_pending";var vt=class extends z{constructor(){super(...arguments);this.name="UnknownRelayError"}};vt.CODE="unknown_relay";var Rt=class extends z{constructor(){super(...arguments);this.name="RelayNotDialableError"}};Rt.CODE="relay_not_dialable";var Js={409:[xe,At,xt],422:[vt,Rt]};function qu(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 ju="x-mdma-session-refresh",Fu="x-mdma-session-expires",$=class{constructor(e={}){this.session=null;this.baseUrl=(e.cloudBaseUrl||Lu).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 Q(e),{nonce:o}=await this.getAccountLoginChallenge();return this.submitAccountLogin({rootPublicKey:r,nonce:o,signature:await Jt({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/${p(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:bo(r),canExecute:yo(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:Hu(r)}})}async findExecutingRelay(e){let n=await this.getNamespaceRelays(e);return io(n)}async getNamespaceRouting(e){let n=await this.request("GET",`/api/cloud/namespaces/${p(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:bo(r),canExecute:yo(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/${p(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 Kn(n,this.routingCredential)}async getAccountRelaysChallenge(e){let n=await this.request("GET",`/api/cloud/accounts/${p(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/${p(e)}/relays`,{anonymous:!0,headers:await Kn(n,this.routingCredential)})).relays??[]).map(o=>({peerId:String(o.peer_id??""),relayUrl:o.relay_url??null,fresh:o.fresh===!0,executorAccount:Bu(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:bo(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:yo(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/${p(e)}/enable-ha`,{body:r})}async enableFoundedNamespaceHa(e,n){return this.request("POST",`/api/cloud/me/namespaces/${p(e)}/enable-ha`,{body:{groups:[],ownership_proof:n}})}async enableHaAsAccount(e){let n=await hr({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/${p(r)}/namespaces/${p(o)}/enable-ha`,{body:{ownership_proof:n},anonymous:!0})}catch(i){if(i instanceof D&&Js[i.status]){let s=qu(i.bodyText),a=Js[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/${p(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 Q(e),{nonce:i}=await this.getAccountLinkChallenge();return this.submitAccountLink({accountId:o,rootPublicKey:r,nonce:i,signature:await it({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 accountLinkHandoff(e){let n=e.portalUrl.replace(/\/+$/,""),r=new URLSearchParams({"link-account":e.accountId,"callback-url":Gn(e.accountId,e.callbackUrl)});return{url:`${n}/?${r.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={};return c&&Je(o),s&&Je(o)?.account!==a?{error:"unexpected_callback"}:(s&&(u.grant=s),a&&(u.accountId=a),c&&(u.error=c),u)}async linkAccountWithGrant(e){let{signer:n,publicKey:r,accountId:o}=await Wt(e.rootSecret,e.signer),i=await this.request("POST","/api/cloud/accounts/link",{body:{grant:e.grant,root_public_key:r,signature:await it({signer:n,nonce:e.grant})},anonymous:!0});return{accountId:String(i.account_id??o),linkedAt:i.linked_at??null,alreadyLinked:i.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 D(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 D(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(ju);if(!n||!this.session)return;let r=e.headers.get(Fu),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 Eu(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 Vu(t){if(t)return typeof t=="function"?t:Lt(t)}var Wu="mero-js:token-refresh";function Ju(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function zu(t){try{let{origin:e,pathname:n}=new URL(t);return e==="null"?t:e+n.replace(/\/+$/,"")}catch{return t}}function wo(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=zu(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=Vu(this.config.requestProof);this.httpClient=Ee({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=To(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs}),this.adminClient=Kt(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 rt({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 ot({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:wo(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=Ju();return n?n.request(Wu,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:wo(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||wo(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){return dr(e)}static buildAuthLoginUrl(e,n){return pr(e,n)}};function Qu(t){return new qe(t)}var Ao=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},Yu="mero-tokens",xo=class{constructor(e=Yu){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 Xu=new TextEncoder().encode("calimero.account.owner-op.v1"),Zu=new TextEncoder().encode("calimero.account.owner-op.body.v1"),ed=new TextEncoder().encode("calimero.account.genesis.v1"),td=2,vo={transferOwnership:0,adminChanged:1,groupDelete:2,teeAdmissionPolicy:3,teeAuthoringPolicy:4,teeReleaseAdmissionPolicy:5},Xe={GroupDelete:14,TransferOwnership:21,TeeAuthoringPolicySet:33,TeeAdmissionPolicySetV2:37,TeeReleaseAdmissionPolicySetV2:38,RootGuarded:42},Qs={AdminChanged:3,RootGuarded:12},nd={replica:0,relay:1},rd=new TextEncoder;function L(t){return new Uint8Array([t])}function Ys(t){let e=rd.encode(t);return f(R(e.length),e)}function Z(t){return f(R(t.length),...t.map(Ys))}function Xs(t){return L(t?1:0)}function Zs(t){let e=nd[t??"replica"];if(e===void 0)throw new Error(`mode must be replica or relay, got ${String(t)}`);return L(e)}function ea(t){return{kind:"transferOwnership",plane:"group",bytes:f(L(Xe.TransferOwnership),g(t,"newOwner",32))}}function ta(){return{kind:"groupDelete",plane:"group",bytes:L(Xe.GroupDelete)}}function na(t){return{kind:"adminChanged",plane:"root",bytes:f(L(Qs.AdminChanged),g(t,"newAdmin",32))}}function ra(t){return{kind:"teeAuthoringPolicy",plane:"group",bytes:f(L(Xe.TeeAuthoringPolicySet),Z(t))}}function oa(t){return{kind:"teeAdmissionPolicy",plane:"group",bytes:f(L(Xe.TeeAdmissionPolicySetV2),Z(t.allowedMrtd),Z(t.allowedRtmr0),Z(t.allowedRtmr1),Z(t.allowedRtmr2),Z(t.allowedRtmr3),Z(t.allowedTcbStatuses),Xs(t.acceptMock),Zs(t.mode))}}function ia(t){let e=t.minReleaseVersion===void 0?L(0):f(L(1),Ys(t.minReleaseVersion));return{kind:"teeReleaseAdmissionPolicy",plane:"group",bytes:f(L(Xe.TeeReleaseAdmissionPolicySetV2),Z(t.allowedProfiles),e,Z(t.allowedTcbStatuses),Xs(t.acceptMock),Zs(t.mode))}}async function Ro(t){return k(Zu,[t])}async function Co(t){return k(Xu,[g(t.account,"account",32),g(t.namespaceId,"namespaceId",32),g(t.groupId,"groupId",32),L(sa(t.kind)),t.opDigest,S(t.counter),R(t.keyEpoch)])}function sa(t){let e=vo[t];if(e===void 0)throw new Error(`unknown owner-op kind ${String(t)}`);return e}var zs=132;async function aa(t){let e=await ie(t.rootSecret),n=f(L(td),e),r=y(await k(ed,[n])),o=t.keyEpoch??0,i=(t.chain??[]).map((d,l)=>{let m=F(d,`chain[${l}]`);if(m.length!==zs)throw new Error(`chain[${l}] must be a ${zs}-byte RootKeyHandoff, got ${m.length}`);return m});if(o>i.length)throw new Error(`keyEpoch ${o} needs ${o} handoffs in chain, got ${i.length}`);let s=await Ro(t.op.bytes),a=await Co({account:r,namespaceId:t.namespaceId,groupId:t.groupId,kind:t.op.kind,opDigest:s,counter:t.counter,keyEpoch:o}),c=await oe(t.rootSecret),u=new Uint8Array(await crypto.subtle.sign("Ed25519",c,a));return y(f(n,R(i.length),...i,g(r,"account",32),g(t.namespaceId,"namespaceId",32),g(t.groupId,"groupId",32),L(sa(t.op.kind)),s,S(t.counter),R(o),u))}function ca(t,e){let n=t.plane==="group"?Xe.RootGuarded:Qs.RootGuarded;return f(L(n),t.bytes,F(e,"rootProof"))}var la=[2428,2429,2528,2529],od="localhost",id=2e3;function ua(t){return`http://${od}:${t}`}function da(t,e){let n=t.endsWith("/")?t:`${t}/`;return new URL(e,n).toString()}async function pa(t,e={}){let{timeoutMs:n=id,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=da(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 sd(t={}){let{ports:e=la,timeoutMs:n,signal:r}=t;return(await Promise.all(e.map(async i=>{let s=ua(i);return await pa(s,{timeoutMs:n,signal:r})?s:null}))).filter(i=>i!==null)}function Zn(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]=Zn(t[o]^t[e],16),t[r]=t[r]+t[o]>>>0,t[n]=Zn(t[n]^t[r],12),t[e]=t[e]+t[n]>>>0,t[o]=Zn(t[o]^t[e],8),t[r]=t[r]+t[o]>>>0,t[n]=Zn(t[n]^t[r],7)}function ga(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function ha(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]=ga(t,s*4);r[12]=e>>>0;for(let s=0;s<3;s+=1)r[13+s]=ga(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 ad(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=ha(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 So(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 ld(t,e){let n=So(t.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,r=So(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=So(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 ma(t){return new Uint8Array((16-t%16)%16)}function fa(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function ud(t,e){let n=[t,ma(t.length),e,ma(e.length),fa(t.length),fa(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 dd(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 ya(t,e,n,r=new Uint8Array(0)){dd(t,e);let o=ha(t,0,e).subarray(0,32),i=ad(t,1,e,n),s=ld(o,ud(r,i)),a=new Uint8Array(i.length+16);return a.set(i),a.set(s,i.length),a}var wa=32,pd=1,gd=3,md=2,fd=32,hd=32,yd=12,Ze=t=>new TextEncoder().encode(t),Dt=t=>new Uint8Array([t>>8&255,t&255]),ba=f(Ze("KEM"),Dt(wa)),Tt=f(Ze("HPKE"),Dt(wa),Dt(pd),Dt(gd));async function Aa(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 bd(t,e,n){let r=new Uint8Array(n),o=new Uint8Array(0);for(let i=1,s=0;s<n;i+=1)o=await Aa(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 er(t,e,n,r){return Aa(e,f(Ze("HPKE-v1"),t,Ze(n),r))}function Eo(t,e,n,r,o){return bd(e,f(Dt(o),Ze("HPKE-v1"),t,Ze(n),r),o)}async function wd(t,e){let n=await er(ba,new Uint8Array(0),"eae_prk",t);return Eo(ba,n,"shared_secret",e,fd)}async function Ad(t,e){let n=new Uint8Array(0),r=await er(Tt,n,"psk_id_hash",n),o=await er(Tt,n,"info_hash",e),i=f(new Uint8Array([md]),r,o),s=await er(Tt,t,"secret",n);return{key:await Eo(Tt,s,"key",i,hd),nonce:await Eo(Tt,s,"base_nonce",i,yd)}}async function xa(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 Te(i),a=await Te(e),c=f(await st(s.privateKey,t),await st(a.privateKey,t)),u=await wd(c,f(s.publicKey,t,a.publicKey)),{key:d,nonce:l}=await Ad(u,n);return{enc:s.publicKey,ciphertext:ya(d,l,r,o)}}var Ca="mero-agent-gate/attest/v3",Sa="mero-agent-gate/provision/v2",xd=/^[a-z0-9][a-z0-9-]{0,62}$/,vd=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,va=64,Ra=64*1024,de=class extends Error{constructor(n,r,o){super(n);this.status=r;this.code=o;this.name="AgentGateError"}};function Ea(t){if(!xd.test(t))throw new Error(`Agent id ${JSON.stringify(t)} must match [a-z0-9][a-z0-9-]{0,62}`)}function Nt(t){return new TextEncoder().encode(t)}function ka(t){let e=Nt(t);return f(new Uint8Array([e.length]),e)}function Ce(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}function tr(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 Ia(t,e,n,r){let o=new Uint8Array(32),i=f(Nt(Ca),t,ka(e),n??o,r??o);return new Uint8Array(await crypto.subtle.digest("SHA-256",i))}function Pa(t,e){return f(Nt(Sa),t,ka(e))}async function Rd(){let t=crypto.getRandomValues(new Uint8Array(32));return{secret:t,publicKey:await nr(t)}}async function nr(t){if(t.length!==32)throw new Error("An owner key is 32 bytes");return Ce((await Te(t)).publicKey)}function Ta(t,e){return`${t.replace(/\/+$/,"")}${e}`}async function Da(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 ko(t){let e=t.agentId??"";e&&Ea(e);let n=crypto.getRandomValues(new Uint8Array(32)),r=await Da(t.fetch??fetch,Ta(t.gateUrl,"/attest"),{nonceB64:Ce(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=tr(r.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),i=r.signingPublicKeyB64?tr(r.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,s=r.ownerPublicKeyB64?tr(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 Ia(o,e,i,s);return await t.verifier({quoteB64:r.quoteB64,nonce:y(n),reportDataSuffix:y(a)}),{agentId:e,provisioningPublicKey:Ce(o),...i?{signingPublicKey:Ce(i)}:{},...s?{ownerPublicKey:Ce(s)}:{}}}async function Na(t,e){let n=await nr(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 Cd(t){let e=Object.keys(t);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>va)throw new Error(`At most ${va} secrets at once`);for(let n of e){if(!vd.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(Nt(t[n]).length>Ra)throw new Error(`Secret ${n} is over ${Ra} bytes`)}}async function Ua(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 Na(r,o),a=tr(r.provisioningPublicKey,"provisioningPublicKey",32),c=await xa(a,o,Pa(a,r.agentId),Nt(JSON.stringify(i)));return Da(t,Ta(e,n),{agentId:r.agentId,provisioningPublicKeyB64:r.provisioningPublicKey,senderPublicKeyB64:s,encappedKeyB64:Ce(c.enc),ciphertextB64:Ce(c.ciphertext)})}async function Sd(t){Cd(t.secrets);let e=t.fetch??fetch,n=await Ua(e,t.gateUrl,"/provision",t.agent,t.ownerSecret,{secrets:t.secrets}),r=await ko({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e}),o=await nr(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 Ed(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 Ua(e,t.gateUrl,"/release",t.agent,t.ownerSecret,{release:!0}),(await ko({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 Io=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),kd=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function Id(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await en(r,e,{identity:n.identity??Io.identity,issuer:n.issuer??Io.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??ut;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 Oa(o),o}function Oa(t){for(let e of kd)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 Pd=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function Td(t){let e=Pd.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 Ut=t=>t.trim().replace(/^0x/i,"");function Dd(t,e){return Oa(t),dt({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:t.allowed_tcb_statuses.map(Td),allowedMrtd:t.allowed_mrtd.map(Ut),allowedRtmr0:t.allowed_rtmr0.map(Ut),allowedRtmr1:t.allowed_rtmr1.map(Ut),allowedRtmr2:t.allowed_rtmr2.map(Ut),allowedRtmr3:t.allowed_rtmr3.map(Ut)})}export{Jo as ACCOUNT_HA_AUDIENCE,Wo as ACCOUNT_OWNERSHIP_AUDIENCE,Ca as AGENT_ATTEST_DOMAIN,Sa as AGENT_PROVISION_INFO_DOMAIN,z as AccountHaRefusedError,At as AccountLinkedToSeveralUsersError,xe as AccountNotLinkedError,me as AdminApiClient,de as AgentGateError,pe as AuthApiClient,re as AuthRevokedError,_ as CAPABILITIES,Zd as CAPABILITY_PRESETS,$ as CloudClient,la as DEFAULT_LOCAL_NODE_PORTS,tn as DEFAULT_RELEASE_MIRROR,ot as EphemeralClient,wi as HANDSHAKE_PATH,Qn as HA_ACCOUNT_NOT_LINKED_MESSAGE,Wn as HA_REFUSAL_MESSAGES,D as HTTPError,xt as HaRequestPendingError,uo as INVITED_ROLE,he as IntentRefusedError,Ye as InvitationNotClaimableError,Io as KMS_RELEASE_SIGNER,xo as LocalStorageTokenStore,Hn as MAX_INVITATION_VALIDITY_SECS,Ao as MemoryTokenStore,be as MeroClient,qe as MeroJs,Ur as NODE_RELEASE_SIGNER,Qe as NoRelayError,Re as NotForAccountError,vo as OWNER_OP_KIND,es as PRESENCE_DOMAIN,ut as PRODUCTION_PROFILE,Pn as RELAY_NODE_KEY_RETRY_MS,Vr as REQUEST_PROOF_HEADER,J as RelayClient,Rt as RelayNotDialableError,He as RelayObserver,bt as RelayPresenceClient,ye as RelayTransport,rt as RpcClient,Ht as RpcError,ct as SEALED_CONTENT_TYPE,Ai as SEALED_PATH,mo as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,De as SealedTransportError,B as SseClient,lt as StaleTransportKeyError,vt as UnknownRelayError,_n as WarrantNonceExhaustedError,Mt as WarrantNonceRouteUnavailableError,et as WebHttpClient,se as WsClient,Vt as accountForRoot,V as accountForRootPublicKey,ti as accountRootFromPhrase,vr as accountRootFromSecret,ri as accountRootSignerFromPhrase,na as adminChangedOp,Eu as admitterAddrsFromNetworkStatus,Ia as agentKeyBinding,Dd as agentQuoteVerifier,fo as applicationIdForBundle,Fe as attemptRelayNodeKey,ko as attestAgent,Qt as attestKeyBinding,Yt as attestRelayNodeKey,iu as authorNonceLookup,mu as beginCloudLink,xu as beginDeviceEnrolment,Vn as bootstrapFromInvitation,pr as buildAuthLoginUrl,Un as buildDelegatedClient,Ts as callbackIsForeign,$t as callerProof,ep as capMask,tp as capNames,On as carryExecutorAccount,Na as checkOwner,lr as classifyError,ls as clearDelegatedCredential,ss as clearDelegatedSession,Es as cloudLinkUrl,on as cloudNodeReleaseUrl,or as combineSignals,Wa as compareSemver,hu as completeCloudLink,Ru as completeDeviceEnrolment,As as connectCloud,au as connectCloudWithAccount,Qi as contextCapabilityGrantedOp,Yi as contextCapabilityRevokedOp,wn as contextDetachedOp,vn as contextMetadataSetOp,Vs as createAccountAdmin,ni as createAccountRootSigner,_o as createAdminApiClient,Kt as createAdminApiClientFromHttpClient,fe as createAttestedSealedFetch,Yd as createAuthApiClient,To as createAuthApiClientFromHttpClient,wp as createBrowserAdminApiClient,zd as createBrowserAuthApiClient,Ee as createBrowserHttpClient,kt as createDelegatedContext,Hs as createDelegatedPrivateContext,tt as createHttpClient,wt as createLocalStorageNonceSource,Mn as createMemoryNonceSource,En as createMeroClient,Qu as createMeroJs,Ws as createNodeAdmin,Ap as createNodeAdminApiClient,Qd as createNodeAuthApiClient,Ot as createNodeHttpClient,Jr as createProofAuthorizer,Lt as createProofSigner,dt as createQuoteVerifier,su as createRecoveringNonceSource,La as createRetryableMethod,Ci as createSealedFetch,pl as createSignedReleaseSealedFetch,sn as createSignedReleaseVerifier,ir as createTimeoutSignal,sr as createUniversalHttpClient,Hr as createdSubgroupId,Mr as creationInitHash,go as defaultAdmitters,Be as defaultAudience,Ke as defaultCapabilitiesSetOp,ve as delegatedGovernance,jt as deviceCertPayload,Ps as deviceEnrolmentUrl,wr as deviceScopePayload,sd as discoverLocalNodes,Ct as encodeGroupInvitation,qn as encodeSignedInvitation,Ri as fetchAttestedTransportKey,nn as fetchNodeRelease,rn as fetchNodeReleaseVersion,Et as fetchRegistryBundles,fs as forgetMethodKinds,ms as forgetRelaySealing,zn as foundDelegatedNamespace,hn as foundedNamespaceId,ei as generateAccountRoot,Rd as generateOwnerKey,Fr as generateSessionKey,Yn as governGroup,Xn as governRoot,Kr as governanceOpHash,Br as groupCreatedOp,ta as groupDeleteOp,fn as groupDeletedOp,po as groupInvitationHash,$e as groupMetadataSetOp,mn as groupReparentedOp,ge as hasCap,mp as hexEncodeUtf8,Or as intentHash,ja as isSettled,_s as joinAsAccount,Fn as joinWithNode,ae as jsonCodec,We as knownRelays,ze as latestPublishedVersion,gs as learnRelayNodeKey,bs as listDelegatedContexts,ws as listDelegatedNamespaces,ua as localNodeUrl,Le as login,Tn as markContextNonceSpent,Me as memberAddedOp,bn as memberCapabilitySetOp,Rn as memberJoinedOpenOp,yt as memberLeftOp,xn as memberMetadataSetOp,dn as memberRemovedOp,pn as memberRoleSetOp,yr as mintDeviceId,yn as namespaceCreatedOp,Pt as namespaceOfGroup,da as nodeEndpoint,Mi as nodeReleaseVersionFromImage,$n as normaliseAccount,Ro as ownerOpDigest,Co as ownerOpSigningPayload,nr as ownerPublicKey,dr as parseAuthCallback,Fi as parseCreationWarrant,br as parseDeviceCredential,Vi as parseGovernanceWarrant,No as parseWarrantNonce,to as persistedNonces,no as pinRelayNodeKey,zr as presenceStatementBytes,pa as probeNodeHealth,Sd as provisionAgent,Pa as provisionInfo,fu as readCloudLinkCallback,as as readDelegatedCredential,eo as readDelegatedSession,vu as readEnrolmentCallback,Dn as readPinnedRelayNodeKey,q as readRelayMap,Do as redeemInvitation,ys as relayForContext,Ve as relayTransportFetch,Ed as releaseAgent,It as rememberGroupNamespace,we as rememberRelay,Cr as reportDataOf,gr as requestBodyHash,Ks as resolveApplicationIdFromRegistry,Ln as resolveRelayFromInvitation,Nn as resolveRelayNodeKey,Q as resolveRoot,Wt as resolveRootPair,ca as rootGuardedOpBytes,Kn as routingProofHeaders,cs as saveDelegatedCredential,is as saveDelegatedSession,St as selectLatestBundle,sp as shouldRetain,hr as signAccountHaClaim,it as signAccountLink,Jt as signAccountLogin,ic as signAccountOwnershipClaim,ln as signCreationWarrant,Yo as signDeviceCert,Xo as signDeviceScope,ft as signGovernanceWarrant,Bn as signGroupInvitation,Sn as signLoginStatement,jn as signMemberJoinOp,aa as signOwnerOpProof,Gt as signRequest,Wr as signRequestProof,xs as signRoutingChallenge,an as signWarrant,Bl as signedPath,Bo as signerFromCryptoKey,ke as signerFromSecret,ts as stateHash,Ge as subgroupCreation,An as subgroupVisibilitySetOp,qt as subscribePresence,gn as targetApplicationSetOp,oa as teeAdmissionPolicyOp,ra as teeAuthoringPolicyOp,ia as teeReleaseAdmissionPolicyOp,ea as transferOwnershipOp,vi as transportKeyBinding,$i as trustSignedRelease,Pr as trustedMeasurementsFromReleases,Ea as validateAgentId,Ft as verifyDeviceCredential,Id as verifySignedAgentPolicy,_i as verifySignedNodeRelease,ar as withCap,_t as withRetry,np as withoutCap};
1
+ function lr(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 ur(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 Uo=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 k(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(Uo,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 Oo(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(Uo,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 dr=new TextEncoder().encode("calimero.auth.request.v2"),$a=new TextEncoder().encode("calimero.auth.request.body.v1");function _o(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}async function nt(t=new Uint8Array(0)){let e=typeof t=="string"?new TextEncoder().encode(t):t;return k($a,[e])}async function Kt(t){let e=await ne(t.signerSecret),n=await nt(t.body),r=C(t.issuedAt),o=C(t.expiresAt),i=new TextEncoder,s=await k(dr,[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(_o(t.method),_o(t.path),n,r,o,a))}var Ee=t=>new TextEncoder().encode(t),ke="X-Calimero-Proof",La=300;async function pr(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 nt(t.body),i=Math.floor(t.now??Date.now()/1e3),s=i+(t.validForSeconds??La),a=await k(dr,[Ee(e),Ee(n),o,C(i),C(s)]),c=await Ha(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=Ba(r,"credential");return y(f(d,new Uint8Array([0]),u))}async function Ha(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 Ba(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 gr(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 pr({method:e,path:n,body:r,credential:t.credential,deviceSecret:t.deviceSecret,signer:t.signer,validForSeconds:t.validForSeconds});return{[ke]: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 ja(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 D=class extends Error{constructor(n,r,o,i,s){let a=ja(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:Mo(this.headers),bodyText:this.bodyText}}},oe=class extends D{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 Mo(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function Fa(t){let e;try{e=new URL(t,globalThis.location?.href)}catch{return t}return e.search===""&&(e.search=""),e.href}function Gt(t){return Object.keys(t).some(e=>e.toLowerCase()===ke.toLowerCase())}function $t(t,e){if(t.type==="opaqueredirect"||t.status>=300&&t.status<400)throw new D(0,"Redirect Not Followed",e,t.headers,`the node answered with a redirect; a request carrying ${ke} is not followed to another location`)}var rt=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:Mo(r.headers),status:r.status}}async request(e,n){return this.makeRequest(e,n)}async makeRequest(e,n,r=0,o){let s=Fa(this.buildUrl(e)),a=o??Date.now(),c=this.createAbortSignal(n),u=await this.buildHeaders(n?.headers),d;u instanceof Headers?(d={},u.forEach((w,E)=>{d[E]=w})):d=u;let l=n?.method||"GET";if(this.transport.authorizeRequest){let w=n?.body;if(w!==void 0&&typeof w!="string"&&!(w 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:w}))}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 w=n?.timeoutMs||this.transport.timeoutMs;if(w){let E=Date.now()-a,T=Math.max(0,w-E);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 w=await this.transport.getProof({method:p.method??"GET",path:de(s),body:p.body});w&&(d["X-Calimero-Proof"]=w)}let P=Gt(d);P&&p.redirect!=="error"&&(p.redirect="manual");try{let w=await this.transport.fetch(s,p);if(P&&$t(w,s),!w.ok){let E=await this.getBodyText(w),T=new D(w.status,w.statusText,s,w.headers,E),H=w.headers.get("x-auth-error");if((w.status===401||w.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,w.status,w.statusText,s,w.headers,E)}let z=n?.signal?.aborted===!0;if(w.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 b=await h;if(!b||b.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(b),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(w,n?.parse)}catch(w){throw w instanceof D||w instanceof Error&&w.message.includes("onTokenRefresh")?w:new D(0,"Network Error",s,new Headers,w instanceof Error?w.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(ur(r)),n.length>0?lr(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 ot(t){return new rt(t)}function Ie(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 ot(e)}function Lt(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 ot(r)}function mr(t){return typeof window<"u"?Ie(t):Lt(t)}function Va(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 Wa(t){let n=250*Math.pow(2,t-1),r=(Math.random()-.5)*.4*n;return Math.max(0,n+r)}async function Ht(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,!Va(r,n-o))throw r;let s=Wa(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 Ja(t,e={}){return async(...n)=>Ht(()=>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 it=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 ip(t){let e=new it;return new pe(e)}function sp(t){let e=new it;return new pe(e)}function ap(t){let e=new it;return new pe(e)}function Ko(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},lp={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 up(...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 dp(t){return Object.keys(_).filter(e=>ge(t,_[e]))}function ge(t,e){let n=e>>>0;return(t&n)>>>0===n}function fr(t,e){return(t|e)>>>0}function pp(t,e){return(t&~e)>>>0}var za={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 Qa(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 Ya(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 hr(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 yr(t){let e=Ya(t),n;return e!==void 0?n=Qa(e):t instanceof TypeError?n="unreachable":n="unknown",{kind:n,status:e,retryable:za[n],message:hr(t)}}function Xa(t){return t.status!=="failed"||!t.retryable}function hp(t){return!Xa(t)}function Za(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":null}function ec(t,e){let{kind:n,status:r}=yr(t),o=Za(e);return 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 Go(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=hr(i,"Could not join. Check the invitation."),{reason:c,retryable:u}=ec(i,a);return{status:"failed",namespaceId:n,message:a,reason:c,retryable:u}}var Bt=class extends Error{constructor(n,r){super(`this node does not serve warrant-nonce discovery (404 on ${n}); it predates the route, so a client must fall back to its own nonce counter`);this.path=n;this.cause=r;this.name="WarrantNonceRouteUnavailableError"}};function wr(t,e,n){let r=e[n];if(r==null)return;let o=new RegExp(`"${n}"\\s*:\\s*(\\d+)`).exec(t);if(o)return BigInt(o[1]);if(typeof r=="string"&&/^\d+$/.test(r))return BigInt(r);throw new Error(`warrant-nonce response field \`${n}\` is not a u64: ${JSON.stringify(r)}`)}function $o(t){let n=JSON.parse(t)?.data;if(!n||typeof n!="object")throw new Error(`warrant-nonce response had no \`data\`: ${t.slice(0,200)}`);let r={contextId:String(n.contextId??""),authorDeviceKey:String(n.authorDeviceKey??""),seen:n.seen===!0,highWaterNonce:wr(t,n,"highWaterNonce"),windowWidth:wr(t,n,"windowWidth")??0n},o=wr(t,n,"nextNonce");return o===void 0?{...r,kind:"exhausted",seen:!0,highWaterNonce:r.highWaterNonce??0xffffffffffffffffn}:{...r,kind:"open",nextNonce:o}}function A(t){return t?.data}function tc(t,e){let[n,r]=Lo(t),[o,i]=Lo(e),s=n.split("."),a=o.split("."),c=Math.max(s.length,a.length);for(let p=0;p<c;p++){let x=Ho(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=Ho(u[p],d[p]);if(x!==0)return x}return 0}function Lo(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 Ho(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 nc(t,e,n){return Ht(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 nc(r.toString(),"versions",n)).json();return(Array.isArray(i)?i:[]).map(s=>s.appVersion).filter(s=>typeof s=="string").sort((s,a)=>tc(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 inviteSpecializedNode(e){return A(await this.httpClient.post("/admin-api/contexts/invite-specialized-node",e))}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 getNamespaceIdentity(e){let n=await this.getNodeIdentity();return{namespaceId:e,publicKey:n.publicKey,account:n.accountId}}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 Go({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 getWarrantNonce(e,n){let r=`/admin-api/contexts/${g(e)}/warrant-nonce/${g(n)}`,o;try{o=await this.httpClient.get(r,{parse:"text"})}catch(i){throw i instanceof D&&i.status===404?new Bt(r,i):i}return $o(o)}async getWarrantNonceAsAuthor(e,n){let r=`/admin-api/contexts/${g(e)}/warrant-nonce`,o;try{o=await this.httpClient.post(r,{authorProof:n},{parse:"text"})}catch(i){throw i instanceof D&&i.status===404?new Bt(r,i):i}return $o(o)}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=fr(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=fr(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 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 teeVerifyQuote(e){return A(await this.httpClient.post("/admin-api/tee/verify-quote",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 Cp(t){return Array.from(new TextEncoder().encode(t),e=>e.toString(16).padStart(2,"0")).join("")}function Pp(t){return new me(Ie(t))}function Tp(t){return new me(Lt(t))}function Bo(t){return new me(mr(t))}function qt(t,e){return new me(t)}function br(t){try{let e=t.indexOf("#");if(e===-1)return null;let n=t.substring(e+1),r=new URLSearchParams(n),o=r.get("access_token");return o?{accessToken:o,refreshToken:r.get("refresh_token")??"",applicationId:r.get("application_id")??"",contextId:r.get("context_id")??"",contextIdentity:r.get("context_identity")??"",nodeUrl:r.get("node_url")??""}:null}catch{return null}}function Ar(t,e){let n=new URLSearchParams;return n.set("callback-url",e.callbackUrl),e.permissions&&e.permissions.length>0&&n.set("permissions",e.permissions.join(",")),n.set("mode",e.mode),e.packageName&&(n.set("package-name",e.packageName),e.packageVersion&&n.set("package-version",e.packageVersion),e.registryUrl&&n.set("registry-url",e.registryUrl)),`${t.replace(/\/+$/,"")}/auth/login?${n.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 rc(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 Ft(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 Kt({method:r.method,path:r.path,body:rc(r.body),issuedAt:o,expiresAt:o+e,signerSecret:t.signerSecret})})}}var Vt=class extends Error{constructor(e,n,r,o){super(n),this.name="RpcError",this.code=e,this.data=r,this.type=o}};async function xr(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 Vt(o.code??-1,o.message??o.type??"RPC error",o.data,o.type)}return r.result}var st=class{constructor(e){this.kind="node";this.canSubscribe=!0;this.httpClient=e.httpClient}async execute(e){let n=await xr(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 oc=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function qo(t){return t.type!==void 0&&oc.has(t.type)}var ic=new Set(["token_reuse","token_revoked"]),sc=new Set([401,403]),ac=1e4;function jo(t){let e=t.headers.get("x-auth-error");return!e||!sc.has(t.status)?null:ic.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=>{qo(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)){this.closed=!1,this.abortController=new AbortController;try{let e=`${this.baseUrl}/sse`,n={...await this.authorize({method:"GET",path:de(e)}),Accept:"text/event-stream"},r=Gt(n),o=await this.fetchImpl(e,{headers:n,signal:this.abortController.signal,...r&&{redirect:"manual"}});if(r&&$t(o,e),!o.ok){let i=jo(o),s=await o.text().catch(()=>{});throw i?new oe(i,o.status,o.statusText,e,o.headers,s):new D(o.status,o.statusText,e,o.headers,s)}if(!o.body)throw new Error("SSE response has no body");this.readStream(o.body).catch(i=>{if(this.closed)return;let s=i instanceof Error?i:new Error(String(i));this.emit("error",s),this.scheduleReconnect()})}catch(e){if(this.closed)return;let n=e instanceof Error?e:new Error(String(e));if(this.emit("error",n),n instanceof oe)return;this.scheduleReconnect()}}}async readStream(e){let n=e.getReader(),r=new TextDecoder,o="";try{for(;;){let{done:i,value:s}=await n.read();if(i)break;o+=r.decode(s,{stream:!0});let a=o.split(`
2
+ `);o=a.pop()??"";for(let c of a)if(c.startsWith("data:")){let u=c.slice(5).trim();u&&this.handleMessage(u)}}if(o+=r.decode(),o.startsWith("data:")){let i=o.slice(5).trim();i&&this.handleMessage(i)}}catch(i){if(this.closed)return;let s=i instanceof Error?i:new Error(String(i));this.emit("error",s)}this.closed||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")),ac);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=Gt(c),d=await this.fetchImpl(s,{method:"POST",headers:c,body:a,signal:r.signal,...u&&{redirect:"manual"}});if(u&&$t(d,s),!d.ok){let l=jo(d),p=await d.text().catch(()=>{});return l?new oe(l,d.status,d.statusText,`${this.baseUrl}/sse/subscription`,d.headers,p):new D(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 Wt=class Wt{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),Wt.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()}};Wt.MAX_BACKOFF_MS=3e4;var ie=Wt;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 at=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,n,r=se()){await xr(this.httpClient,"set_ephemeral",{contextId:e,state:r.encode(n)})}subscribe(e,n,r=se()){return Jt(this.sse,e,n,r)}};function Jt(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 cc=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function Fo(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 Pe(t,e="secret"){let n=m(t,e,32),r=f(cc,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 Fo(s)}return Wo(o,i)}async function Vo(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 Wo(t,n)}function Wo(t,e){return{publicKey:e,async sign(n){try{return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},t,n))}catch(r){throw Fo(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 Pe(t,n);throw new Error(`${n} or signer is required`)}var lc=new TextEncoder().encode("calimero.mdma.account-ownership-claim.v1\0"),uc=6e4,Jo=5*6e4,zo=1024,Yo="mdma:enable-ha-namespace",Xo="mdma:enable-ha-namespace-as-account";function Qo(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var vr=(t,e)=>{if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);return t.toLowerCase()};async function Zo(t,e,n,r){if(r!==void 0&&!(r.length>0&&r.length<=zo))throw new Error(`relayUrl must be a non-empty string of at most ${zo} characters`);let o=t.ttlMs??uc;if(!(o>0&&o<=Jo))throw new Error(`ttlMs must be in (0, ${Jo}]`);let i=vr(t.namespaceId,"namespaceId"),s=vr(t.accountId,"accountId"),a=vr(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(lc,l));return{kind:"account",credential:t.credential,signed_payload:Qo(l),signature:Qo(p)}}async function dc(t){if(!t.subject)throw new Error("subject must be the cloud login email");return Zo(t,Yo,t.subject)}async function Rr(t){return Zo(t,Xo,void 0,t.relayUrl)}var pc=new TextEncoder().encode("calimero.device.cert.v1"),gc=new TextEncoder().encode("calimero.account.genesis.v1"),mc=new TextEncoder().encode("calimero.device.id.v1"),Te=2,fc=237;async function Cr(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 k(mc,[n,e]);return y(f(e,r.subarray(0,16)))}async function zt(t){return k(pc,[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 ei(t){return f(new Uint8Array([Te]),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 ti(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=ei({rootPublicKey:n,account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch,signature:s});return y(a)}function Sr(t){let e=m(t,"credential",fc);if(e[0]!==Te)throw new Error(`this credential has account genesis version ${e[0]}, not ${Te} \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 Qt(t){let e=Sr(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 Cr(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 Oo(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 Yt(t){return F(y(await re(t)))}async function F(t){return y(await k(gc,[f(new Uint8Array([Te]),m(t,"rootPublicKey",32))]))}var hc=new TextEncoder().encode("calimero.device.scope.v1");async function Er(t){return k(hc,[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 ni(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 Er({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([Te]),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 kr=["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 yc=new TextEncoder().encode("calimero.mdma.account-link.v1\0"),wc=new TextEncoder().encode("calimero.mdma.account-login.v1\0"),De=256,ri=De/32,Ir=(De+ri)/11;async function oi(){let t=crypto.getRandomValues(new Uint8Array(De/8));return ui(y(t),await pi(t))}async function ii(t){let e=di(t);return ui(y(await gi(e)),e.join(" "))}async function Pr(t){return m(t,"secret",32),{secret:t,publicKey:y(await re(t)),accountId:await Yt(t)}}async function si(){let t=crypto.getRandomValues(new Uint8Array(De/8)),e=await pi(t);return{...await ci(t),phrase:e}}async function ai(t){return ci(await gi(di(t)))}async function ci(t){let e=await Pe(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 Pe(t,"rootSecret"):t;return li(e)}async function Xt(t,e){return li(await I(t,e,"rootSecret"))}async function li(t){return{signer:t,publicKey:t.publicKey,accountId:await F(t.publicKey)}}async function ct(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(yc,new TextEncoder().encode(t.nonce)));return hi(n)}async function Zt(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(wc,new TextEncoder().encode(t.nonce)));return hi(n)}async function ui(t,e){return{...await Pr(t),phrase:e}}function di(t){let e=t.normalize("NFKD").toLowerCase().trim().split(/\s+/),n=e[0]===""?0:e.length;if(n!==Ir)throw new Error(`recovery phrase must be ${Ir} words, got ${n}`);return e}async function pi(t){let e=fi(t)+await mi(t),n=[];for(let r=0;r<Ir;r+=1){let o=Number.parseInt(e.slice(r*11,r*11+11),2);n.push(kr[o])}return n.join(" ")}async function gi(t){let e="";for(let r of t){let o=kr.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(De/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(De)!==await mi(n))throw new Error("recovery phrase checksum failed \u2014 check for a mistyped or transposed word");return n}async function mi(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return fi(e).slice(0,ri)}function fi(t){let e="";for(let n of t)e+=n.toString(2).padStart(8,"0");return e}function hi(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var bc=new TextEncoder().encode("calimero.tee-attest.key-binding.v1"),en=new TextEncoder().encode("MOCK_TDX_QUOTE_V1"),Ac=568;function xc(...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 Tr(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 vc(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 Rc(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 tn(t){let e=await crypto.subtle.digest("SHA-256",xc(bc,new Uint8Array(32),t));return new Uint8Array(e)}function Dr(t){let e=t.length>=en.length&&Tr(t.subarray(0,en.length),en),n=e?en.length:Ac;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 nn(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=Rc(a.boundPublicKey,"boundPublicKey"),u=vc(a.quoteB64),{reportData:d,mock:l}=Dr(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 tn(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(!Tr(d.subarray(0,32),e))throw new Error("the quote does not carry our nonce: it was not made for this request");if(!Tr(d.subarray(32,64),await tn(c)))throw new Error("the quote does not bind the key the relay named: refusing it");return{nodeKey:y(c),mock:l}}var Cc="Noise_NK_25519_AESGCM_SHA256",Nr=32,Sc=16,Ec=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Or=class t{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(Cc),n=new Uint8Array(32);return n.set(e),new t(n)}async mixHash(e){this.h=await kc(f(this.h,e))}async mixKey(e){let[n,r]=await wi(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:yi(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:yi(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),n}split(){return wi(this.ck,new Uint8Array)}};async function bi(t,e,n){let r=await Or.initialize();await r.mixHash(e),await r.mixHash(t);let o=await Ne(n);return await r.mixHash(o.publicKey),await r.mixKey(await lt(o.privateKey,t)),{message1:f(o.publicKey,await r.encryptAndHash(new Uint8Array)),async finish(s){if(s.length<Nr+Sc)throw new Error("Noise: message 2 is too short");let a=s.slice(0,Nr);return await r.mixHash(a),await r.mixKey(await lt(o.privateKey,a)),{payload:await r.decryptAndHash(s.slice(Nr)),split:await r.split()}}}}async function Ne(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(Ec,t),{name:"X25519"},!0,["deriveBits"]),n=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Ic(n.x)}}async function lt(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 yi(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}async function kc(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}async function Ur(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 wi(t,e){let n=await Ur(t,e),r=await Ur(n,new Uint8Array([1])),o=await Ur(n,f(r,new Uint8Array([2])));return[r,o]}function Ic(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 Ri="/sealed/v2/handshake",Ci="/sealed/v2",dt="application/vnd.calimero.sealed",_r=2,Pc=new TextEncoder().encode("calimero/sealed-http/v2"),ut=16,Tc=1+ut+8,Dc=0,Nc=1,Uc=2,Oc=1+64*1024+16,_c=1024,Mc=6e4,Kc="calimero.tee-attest.transport-key.v1",Gc=[101,204,205,304],Si=new TextEncoder,pt=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},Ue=class extends Error{constructor(n,r,o,i){super(o);this.status=n;this.code=r;this.retryAfterMs=i;this.name="SealedTransportError"}};async function Ei(t,e){let n=await crypto.subtle.digest("SHA-256",f(Si.encode(Kc),t,e));return new Uint8Array(n)}async function ki(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 Ei(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 Ii({baseUrl:t.baseUrl,transportPublicKey:()=>ki(r,t.verify,{applicationId:t.applicationId,applicationHash:t.applicationHash}),fetch:e})}function Ii(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 xi(o,r,await Ai(s))}catch(l){if(!(l instanceof pt)||!i)throw l;return s=Promise.resolve().then(i),xi(o,r,await Ai(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,b)=>P.push([b,h]));let w={method:x.method,path:v.pathname.slice(n.length)+v.search,headers:P},E=new Uint8Array(await x.arrayBuffer()),T=async h=>{let{requestId:b,header:S,envelope:U}=await Lc(h,w,E),M=await o(`${r}${Ci}`,{method:"POST",headers:{"content-type":dt},body:U,signal:x.signal});if(M.headers.get("content-type")!==dt)throw await Ti(M);return Bc(M,h.responseKey,S,b)},[H,z]=await u();try{return await T(H)}catch(h){if(!(h instanceof Ue)||h.code!=="unknown_session")throw h;return T(await d(z))}}}async function Ai(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function xi(t,e,n){try{return await vi(t,e,n)}catch(r){if(!(r instanceof Ue)||r.code!=="busy")throw r;return await new Promise(o=>setTimeout(o,r.retryAfterMs??1e3)),vi(t,e,n)}}async function vi(t,e,n){let r=await bi(n,Pc),o=await t(`${e}${Ri}`,{method:"POST",headers:{"content-type":dt},body:f(new Uint8Array([_r]),n,r.message1)});if(o.headers.get("content-type")!==dt)throw await Ti(o);let i=await jc(o,_c);return $c(r,i)}async function $c(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!==ut+4)throw new Error("The handshake reply is malformed");let i=r.slice(0,ut),s=new DataView(r.buffer,r.byteOffset).getUint32(ut,!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-Mc,header(u){let d=new Uint8Array(Tc);return d[0]=_r,d.set(i,1),new DataView(d.buffer).setBigUint64(1+ut,BigInt(u),!1),d}}}async function Lc(t,e,n){let r=t.nextRequestId;t.nextRequestId+=1;let o=t.header(r),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:Pi(r,0),additionalData:o},t.requestKey,Hc(e,n));return{requestId:r,header:o,envelope:f(o,new Uint8Array(i))}}function Pi(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 Hc(t,e){let n=Si.encode(JSON.stringify(t)),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,n.length,!1),f(r,n,e)}async function Bc(t,e,n,r){if(!t.body)throw new Error("The sealed response has no body");let o=qc(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:Pi(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!==Dc)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(Gc.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===Nc?d.enqueue(l.data):l.kind===Uc?(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 qc(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>Oc)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 jc(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 Ti(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 pt;let r=Number(t.headers.get("retry-after")),o=Number.isFinite(r)&&r>0?Math.min(r,5)*1e3:void 0;return new Ue(t.status,e,n,o)}var Fc=/^[0-9a-f]{96}$/,Vc=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function mt(t){let e=Oe(t.allowedMrtd??[],"allowedMrtd"),n=(t.allowedMeasurements??[]).map((a,c)=>{let u=`allowedMeasurements[${c}]`;return Vc.map(d=>Oe([a?.[d]??""],`${u}.${d}`)[0]).join()}),r=[Oe(t.allowedRtmr0??[],"allowedRtmr0"),Oe(t.allowedRtmr1??[],"allowedRtmr1"),Oe(t.allowedRtmr2??[],"allowedRtmr2"),Oe(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=Jc(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(E){throw new Error(`The quote did not verify: ${E?.message??String(E)}`)}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=Wc(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(E=>y(E));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((E,T)=>{let H=r[T];if(H.length>0&&!H.includes(y(E)))throw new Error(`RTMR${T} ${y(E)} 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 Oe(t,e){return t.map(n=>{let r=n.trim().toLowerCase();if(!Fc.test(r))throw new Error(`${e} holds ${JSON.stringify(n)}, which is not a 48-byte hex measurement`);return r})}function Wc(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 Jc(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 zc=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],gt="locked-read-only";function Mr(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!==gt&&!n)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(gt)}, or pass allowDebugProfile to test`);let u=(c.allowed_tcb_statuses??["uptodate"]).map(d=>Qc(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 Qc(t,e){let n=zc.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 Di=[{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"]}],Ni=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var Yc="1.2.840.10045.2.1",Xc={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},Zc={"P-256":32,"P-384":48},el={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function Ui(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 Me(t){let e=Ui(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function K(t){let e=[];for(let n=t.start;n<t.end;){let r=Ui(t.bytes,n,t.end);e.push(r),n=r.end}return e}function O(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 rn(t){return t.bytes.slice(t.offset,t.end)}function _e(t){let e=ae(O(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 tl(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 Kr(t){try{let[e,n,r,...o]=K(O(Me(t),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let i=K(O(e,48,"The signed part")),s=i[0]?.tag===160?1:0,[a,c,u,d,l,p,...x]=i.slice(s);O(a,2,"The serial number");let v=_e(K(O(n,48,"The signature algorithm"))[0]);if(_e(K(O(c,48,"The signature algorithm"))[0])!==v)throw new Error("it names two different signature algorithms");let w=el[v];if(!w)throw new Error(`it is signed with ${v}, not ECDSA with SHA-256 or SHA-384`);let[E,T]=K(O(d,48,"The validity")).map(tl);if(T===void 0)throw new Error("its validity is incomplete");let[H,z]=K(O(p,48,"The public key"));O(z,3,"The public key");let[h,b]=K(O(H,48,"The key algorithm"));if(_e(h)!==Yc)throw new Error("its key is not an elliptic-curve key");let S=Xc[_e(b)];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]=K(M);for(let te of K(O(ee,48,"The extensions"))){let Se=K(O(te,48,"An extension"));if(Se.length===3)O(Se[1],1,"An extension's critical flag");else if(Se.length!==2)throw new Error("it has a malformed extension");let cr=_e(Se[0]);if(U.has(cr))throw new Error(`it has extension ${cr} twice`);U.set(cr,ae(O(Se[Se.length-1],4,"An extension value")))}}let Q=ae(O(r,3,"The signature"));if(Q[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:rn(e),signatureHash:w,signature:Q.slice(1),issuer:rn(O(u,48,"The issuer")),subject:rn(O(l,48,"The subject")),notBefore:E,notAfter:T,spki:rn(p),curve:S,extensions:U}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function Oi(t){return K(O(Me(t),48,"The list")).map(_e)}function nl(t,e){let n=Zc[e],r=K(O(Me(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(O(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 on(t,e,n,r,o){let i;try{i=nl(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 Gr(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 rl="2.5.29.17",ol="2.5.29.37",il="1.3.6.1.5.5.7.3.3",sl="1.3.6.1.4.1.57264.1.8",al="1.3.6.1.4.1.57264.1.1",cl=134,ll=12,ul=48,dl=new TextEncoder,Ke=t=>new TextDecoder().decode(t);async function sn(t,e,n,r){let{base64Signature:o,cert:i,rekorBundle:s}=fl(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=Gr(Ke(V(i,"The bundle certificate")),"The bundle certificate"),d=Kr(u),l=Ni.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=dl.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await on(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(!Ki(v,l.validFor))throw new Error(`Rekor log ${l.baseUrl} was not in use at ${ft(v)}, when the entry says it was logged`);let P=hl(a.body),w=y(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(P.hash!==w)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!$r(V(P.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let E=Gr(Ke(V(P.publicKey,"The logged certificate")),"The logged certificate");if(!$r(E,u))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await on(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 pl(d,v),ml(d,n),{integratedTime:a.integratedTime}}async function pl(t,e){if(!Mi(t,e))throw new Error(`The signing certificate was valid ${ft(t.notBefore)} to ${ft(t.notAfter)}, not at ${ft(e)} when Rekor logged it`);let n=[];for(let r of Di){let o=r.certChain.map(s=>Kr(V(s,"A Fulcio certificate")));if(!await _i(t,o[0]))continue;let i=await gl(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 ${ft(e)}: ${n.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function gl(t,e,n){if(!Ki(n,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of t.entries()){if(!Mi(o,n))return`its certificate ${r} was not valid then`;let i=t[r+1]??o;if(!await _i(o,i))return`its certificate ${r} is not signed by the next`}}async function _i(t,e){return $r(t.issuer,e.subject)?on(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function ml(t,e){let n=t.extensions.get(rl);if(!n)throw new Error("The signing certificate names no identity");let r=K(O(Me(n),ul,"The subject alternative name")),o=r.filter(u=>u.tag===cl).map(u=>Ke(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(sl),s=t.extensions.get(al),a=i?Ke(ae(O(Me(i),ll,"The OIDC issuer"))):s?Ke(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(ol);if(!c||!Oi(c).includes(il))throw new Error("The signing certificate is not for code signing")}function fl(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 hl(t){let e;try{e=JSON.parse(Ke(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 Mi(t,e){return t.notBefore<=e&&e<=t.notAfter}function Ki(t,e){return Date.parse(e.start)<=t&&(e.end===void 0||t<=Date.parse(e.end))}function ft(t){return new Date(t).toISOString()}function $r(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Lr=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-node-image-gcp.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),yl=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],an="https://cloud.calimero.network";async function $i(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await sn(r,e,{identity:n.identity??Lr.identity,issuer:n.issuer??Lr.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=>yl.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 cn(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 Li(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 ln(t,e={}){let n=await Bi(t,e.fetch??fetch);if(n===void 0)throw new Error(`${Hi(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 Hi(t){return`${t.replace(/\/+$/,"")}/admin-api/tee/info`}async function Bi(t,e){let n=Hi(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 Li(o)}function un(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${ht(e,"version")}`}async function qi(t){let e=ht(t.minReleaseVersion,"minReleaseVersion"),n=ht(t.release?.version,"The release version"),r=await $i(t.release.publishedMrtds,t.release.bundle,{expectedVersion:n,identity:t.identity,issuer:t.issuer});if(bl(n,e)<0)throw new Error(`Release ${n} is older than the minimum trusted, ${e}`);return Mr([r],{profile:t.profile,allowDebugProfile:t.allowDebugProfile})}function dn(t){return ht(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async n=>{let r=await qi({release:await t.release(),profile:t.profile,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer});return mt({dcapVerify:t.dcapVerify,fetchCollateral:t.fetchCollateral,now:t.now,...r})(n)},{includeCollateral:!0})}function wl(t){let{baseUrl:e,releaseSource:n,releaseVersion:r,applicationId:o,applicationHash:i,fetch:s,...a}=t;r!==void 0&&ht(r,"releaseVersion");let c=s??((d,l)=>fetch(d,l));return fe({baseUrl:e,verify:dn({...a,release:async()=>{let d=r===void 0?await ln(e,{fetch:c}):await Bi(e,c)??r;return typeof n=="function"?n({baseUrl:e,version:d,fetch:c}):cn(un(n??an,d),{fetch:c})}}),applicationId:o,applicationHash:i,fetch:c})}var ji=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ht(t,e){let n=typeof t=="string"?ji.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 bl(t,e){let[n,r]=Gi(t),[o,i]=Gi(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 Gi(t){let e=ji.exec(t);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var Al=new TextEncoder().encode("calimero.warrant.v2"),xl=new TextEncoder().encode("calimero.warrant.intent.v1"),Fi=64,Vi=256;async function Hr(t,e){let n=new TextEncoder().encode(JSON.stringify(e));return k(xl,[new TextEncoder().encode(t),n])}async function pn(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=Br(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 Hr(t.method,t.argsJson),x=C(t.nonce),v=C(t.notAfter),P=await k(Al,[e,n,d,r,o,i,s,l,p,C(a.length),...a,C(c.length),...c,x,v]),w=yt(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,w))}function yt(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 Br(t){let e=new TextEncoder().encode(t);return vl(e.length),e}function vl(t){if(t>Vi)throw new Error(`releaseVersion is ${t} bytes, over the ${Vi} a node accepts`)}function ce(t,e){let n=t??[];if(n.length>Fi)throw new Error(`${e} cites ${n.length} heads, over the ${Fi} a node accepts`);return n.map((r,o)=>m(r,`${e}[${o}]`,32))}var Rl=new TextEncoder().encode("calimero.context-creation-warrant.v1"),Cl=new TextEncoder().encode("calimero.context-creation.init.v1"),gn=256;async function qr(t){let e=new TextEncoder().encode(JSON.stringify(t));return k(Cl,[e])}async function Sl(t){return k(Rl,[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 mn(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=Wi(t.serviceName,"serviceName"),c=Wi(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 qr(t.initArgs),v=await Sl({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=yt(await l.sign(v));return{warrant:y(f(e,n,r,p,o,i,s,Ji(a),Ji(c),x,R(u.length),...u,R(d.length),...d,C(t.nonce),C(t.notAfter),P)),seed:y(n)}}function zi(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>gn)throw new Error(`${l} is ${x} bytes, over the ${gn} 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 Wi(t,e){if(t===void 0)return null;let n=new TextEncoder().encode(t);if(n.length>gn)throw new Error(`${e} is ${n.length} UTF-8 bytes, over the ${gn} a node accepts`);return n}function Ji(t){return t===null?new Uint8Array([0]):f(new Uint8Array([1]),R(t.length),t)}var El=new TextEncoder().encode("calimero.governance-warrant.v1"),kl=new TextEncoder().encode("calimero.governance-warrant.op.v1"),Il={group:0,root:1};async function jr(t){return k(kl,[new Uint8Array([Fr(t.kind)]),t.bytes])}async function Pl(t){return k(El,[t.scope,new Uint8Array([Fr(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 wt(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=Fr(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 Pl({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=yt(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 Qi(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 Fr(t){let e=Il[t];if(e===void 0)throw new Error(`op kind must be 'group' or 'root', got ${String(t)}`);return e}var Tl={Admin:0,Member:1,ReadOnly:2},G={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},bt={GroupCreated:0,GroupReparented:1,GroupDeleted:2,MemberJoinedOpen:7,NamespaceCreatedV2:9},Dl=new TextEncoder().encode("calimero.namespace.id.v1"),Wr=new Uint8Array(32),fn=R(0);function Xi(t){let e=Tl[t];if(e===void 0)throw new Error(`role must be Admin, Member or ReadOnly, got ${String(t)}`);return new Uint8Array([e])}function N(t){return new Uint8Array([t])}function Ge(t,e){return{kind:"group",bytes:f(N(G.MemberAdded),m(t,"member",32),Xi(e))}}function hn(t){return{kind:"group",bytes:f(N(G.MemberRemoved),m(t,"member",32),Wr,fn)}}function At(t){return{kind:"group",bytes:f(N(G.MemberLeft),m(t,"member",32),Wr,fn)}}function yn(t,e){return{kind:"group",bytes:f(N(G.MemberRoleSet),m(t,"member",32),Xi(e))}}var Nl=new TextEncoder().encode("calimero.subgroup.id.v1");async function Jr(t,e,n,r){return y(await k(Nl,[m(t,"admin",32),m(e,"parentId",32),new Uint8Array([n?1:0]),m(r,"salt",32)]))}function Yi(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 wn(t){return{kind:"group",bytes:f(N(G.TargetApplicationSet),Wr,m(t.applicationId,"applicationId",32),Yi(t.package,"package"),Yi(t.version,"version"))}}function $e(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(N(G.DefaultCapabilitiesSet),R(t))}}function zr(t){return{kind:"root",bytes:f(N(bt.GroupCreated),m(t.groupId,"groupId",32),m(t.parentId,"parentId",32),N(t.restricted?1:0),m(t.admin,"admin",32),m(t.salt,"salt",32))}}async function Le(t){let e=t.salt??y(crypto.getRandomValues(new Uint8Array(32))),n=await Jr(t.admin,t.parentId,t.restricted,e);return{groupId:n,salt:e,op:zr({...t,groupId:n,salt:e})}}function bn(t,e){return{kind:"root",bytes:f(N(bt.GroupReparented),m(t,"childGroupId",32),m(e,"newParentId",32))}}function An(t){return{kind:"root",bytes:f(N(bt.GroupDeleted),m(t,"rootGroupId",32),fn,fn)}}async function xn(t,e){return y(await k(Dl,[m(t,"founder",32),m(e,"salt",32)]))}function vn(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(N(bt.NamespaceCreatedV2),m(t.founder,"founder",32),e,m(t.salt,"salt",32))}}function Vr(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}function Qr(t){return t===void 0?N(0):f(N(1),Vr(t))}function Yr(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])=>[Vr(o),Vr(r)]))}function Ul(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 Rn(t,e){return{kind:"group",bytes:f(N(G.MemberCapabilitySet),m(t,"member",32),R(Ul(e,"capabilities")))}}function Cn(t){return{kind:"group",bytes:f(N(G.ContextDetached),m(t,"contextId",32))}}function Sn(t){if(t!=="open"&&t!=="restricted")throw new Error(`mode must be open or restricted, got ${String(t)}`);return{kind:"group",bytes:f(N(G.SubgroupVisibilitySet),N(t==="open"?0:1))}}function He(t={}){return{kind:"group",bytes:f(N(G.GroupMetadataSet),Qr(t.name),Yr(t.data))}}function En(t,e={}){return{kind:"group",bytes:f(N(G.MemberMetadataSet),m(t,"member",32),Qr(e.name),Yr(e.data))}}function kn(t,e={}){return{kind:"group",bytes:f(N(G.ContextMetadataSet),m(t,"contextId",32),Qr(e.name),Yr(e.data))}}function Zi(t){if(!Number.isInteger(t)||t<1||t>255)throw new Error(`capability must be a non-zero u8, got ${String(t)}`);return N(t)}function es(t,e,n){return{kind:"group",bytes:f(N(G.ContextCapabilityGranted),m(t,"contextId",32),m(e,"member",32),Zi(n))}}function ts(t,e,n){return{kind:"group",bytes:f(N(G.ContextCapabilityRevoked),m(t,"contextId",32),m(e,"member",32),Zi(n))}}function In(t){return{kind:"root",bytes:f(N(bt.MemberJoinedOpen),m(t.member,"member",32),m(t.groupId,"groupId",32),j(t.credential,"credential"))}}var Pn=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"}},Ol=t=>new Promise(e=>setTimeout(e,t));function _l(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??"";Br(a);let c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??Pn,l=await pn({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??Pn,{warrant:c}=await mn({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??Pn,a=await wt({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 xn(this.config.authorAccount,r),i=vn({founder:this.config.authorAccount,credential:this.config.authorProof,salt:r}),s=e.defaultCapabilities===void 0?void 0:$e(e.defaultCapabilities),a=e.application?wn(e.application):void 0,c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??Pn,l=await wt({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=w=>w instanceof Error?w.message:String(w);if(a)try{await this.govern({groupId:x.namespaceId,op:a}),v={...v,applicationSet:!0}}catch(w){v={...v,applicationSet:!1,applicationError:P(w)}}if(s)try{await this.govern({groupId:x.namespaceId,op:s}),v={...v,defaultCapabilitiesSet:!0}}catch(w){v={...v,defaultCapabilitiesSet:!1,defaultCapabilitiesError:P(w)}}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 D&&s.status===429)||i>=this.rateLimitRetries)throw s;let c=_l(s.headers);await Ol(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 D(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=Ml(c);throw new he(u,/nonce/i.test(u),a.status)}throw new D(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(a.status!==204)return await a.json()}};function Ml(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 Kl=new TextEncoder().encode("calimero.auth.login.v1"),ns={webOrigin:0,codeSigningId:1,cli:2};function rs(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 Gl(t){return f(Uint8Array.from([ns[t.kind]]),rs(t))}function $l(t){let e=Uint8Array.from([ns[t.kind]]);if(t.kind==="cli")return e;let n=rs(t);return f(e,R(n.length),n)}async function Tn(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 k(Kl,[e,Gl(t.audience),n,r,i,s,a]),u=await o.sign(c);return y(f(e,$l(t.audience),n,r,i,s,a,u))}var Ll=300;async function Xr(){let t=y(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:y(await re(t)),secret:t}}async function Be(t){let e=t.nodeUrl.replace(/\/+$/,""),n=t.timeoutMs??1e4,r=async(p,x)=>{let v=new AbortController,P=setTimeout(()=>v.abort(),n),w;try{let T={...x,signal:v.signal};w=t.fetch?await t.fetch(`${e}${p}`,T):await globalThis.fetch(`${e}${p}`,T)}catch(T){throw new D(0,T instanceof Error?T.name:"NetworkError",`${e}${p}`,new Headers,T instanceof Error?T.message:String(T))}finally{clearTimeout(P)}let E=await w.text().catch(()=>"");if(!w.ok)throw new D(w.status,w.statusText,`${e}${p}`,w.headers,E);return E?JSON.parse(E):{}},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 Xr(),a=Math.floor(Date.now()/1e3),c=await Tn({node:t.node,audience:t.audience,challenge:i,sessionKey:s.publicKey,issuedAt:a,expiresAt:a+(t.ttlSeconds??Ll),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 Hl=3e4;function je(){let t=globalThis.location?.origin;return t?{kind:"webOrigin",origin:t}:{kind:"cli"}}function Bl(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 qe=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-Hl>e?this.session.accessToken:(this.pending||(this.pending=this.loginNow().finally(()=>{this.pending=null})),(await this.pending).accessToken)}async loginNow(){let e=await Be({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=Bl(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 os=new TextEncoder().encode("calimero/presence/1");async function is(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 Zr(t){return f(os,m(t.contextId,"contextId",32),m(t.author,"author",32),C(t.seq),C(t.sentAtMs),await is(t.state))}var ql=2500,xt=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??ql,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 Jt(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 Zr({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 ss(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 jl(t,e,n){let r=e?.nodeKey;return r?new qe({nodeUrl:e?.nodeUrl??t.relayUrl,nodeKey:r,accountProof:e?.accountProof??t.authorProof,audience:e?.audience??je(),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 W?e.relay:new W({...e.relay,fetch:e.relay.fetch??o});if(this.relayObserver=jl(i,e.observe,o),this.rpcTransport=new ye(i,this.relayObserver),this.relayUrl=i.relayUrl,e.proof&&(this.proofAuthorizer=gr(e.proof)),e.session){let s=e.session;this.relayAdmin=Bo({baseUrl:i.relayUrl,getAuthToken:typeof s=="string"?async()=>s:s,fetch:o})}else if(this.proofAuthorizer){let s=this.proofAuthorizer;this.relayAdmin=qt(ot({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 Fe(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 ss("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 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 xt({relay:this.relay,events:()=>this.events})),this.relayPresence)}get cloud(){if(!this.nodeClient)throw ss("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 Dn(t){return new we(t)}var no="calimero.delegated.connection",ro="calimero.delegated.credential";function oo(){if(typeof sessionStorage>"u")return null;try{let t=sessionStorage.getItem(no);return t?JSON.parse(t):null}catch{return null}}function ls(t){try{sessionStorage.setItem(no,JSON.stringify(t))}catch{}}function us(){try{sessionStorage.removeItem(no)}catch{}}function ds(){let t=oo();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(ro);if(!e)return null;let n=JSON.parse(e);return!n.account||!n.credential||!n.deviceSecret?null:n}catch{return null}}function ps(t){try{sessionStorage.setItem(ro,JSON.stringify(t))}catch{}}function gs(){try{sessionStorage.removeItem(ro)}catch{}}function io(t){let e=Un(t);return{next:async()=>{let n=0n;try{n=ms(t)}catch{n=0n}try{localStorage.setItem(e,String(n+1n))}catch{}return n}}}function Un(t){return`calimero.nonce.${t}`}function ms(t){let e=localStorage.getItem(Un(t));if(e!==null)return BigInt(e);let n=`${Un(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{ms(t)<=n&&localStorage.setItem(Un(t),String(n+1n))}catch{}}var fs="calimero.delegated.relay-node-key.";function X(t){return t.replace(/\/+$/,"")}function so(t,e){localStorage.setItem(fs+X(t),e.trim().toLowerCase())}function Mn(t){try{let e=localStorage.getItem(fs+X(t));return e&&/^[0-9a-f]{64}$/.test(e)?e:null}catch{return null}}function ao(t){try{let{hostname:e}=new URL(t);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch{return!1}}var Fl="locked-read-only",Vl="2.3.99",eo;function Wl(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 Ve=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 cs(t,e){try{return await e()}catch(n){throw n instanceof Ve?n:new Ve(t,n)}}function Jl(t){return async(e,n)=>{let r;try{r=await globalThis.fetch(e,n)}catch(o){throw t.failure=o,new Ve(`reaching ${String(e)}`,o)}return r.ok||(t.failure??(t.failure=new Error(`${String(e)} answered HTTP ${r.status}`))),r}}function hs(t,e){return Object.assign(async r=>{let o=await cs("loading the quote verifier",()=>(eo??(eo=import("@phala/dcap-qvl").then(i=>Wl(i),i=>{throw eo=void 0,i})),eo));return dn({dcapVerify:o,release:()=>cs("fetching the release the relay runs",async()=>cn(un(an,await ln(t,{fetch:e})))),profile:Fl,minReleaseVersion:Vl})(r)},{includeCollateral:!0})}async function We(t,e={}){let n=e.fresh?null:Mn(t);if(n)return{kind:"learned",nodeKey:n};let r={failure:null},o=Jl(r);try{let i=ao(t),{nodeKey:s}=await nn({relayUrl:t,allowMock:i,fetch:o,...i?{}:{verify:hs(t,o)}});return so(t,s),{kind:"learned",nodeKey:s}}catch(i){return i instanceof Ve||r.failure?{kind:"unavailable",error:i}:{kind:"refused",error:i}}}async function Kn(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 On=[1e3,2e3,5e3,1e4,3e4];function zl(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 ys(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=On[Math.min(r,On.length-1)];console.warn(`[mero-js] could not reach what proves the relay's node key; retrying in ${i/1e3} s`,o.error),await zl(i,n)}return null}function Ql(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 to=new Map;function ws(){to.clear()}async function Yl(t){if(t.status!==403)return!1;try{return(await t.clone().json()).error?.code==="sealed_route_unguarded"}catch{return!1}}function Xl(t){return t.headers.has("authorization")||new URL(t.url).pathname.startsWith("/auth/")}function Zl(t){let e=(o,i)=>globalThis.fetch(o,i),n=fe({baseUrl:t,verify:hs(t,e),fetch:e}),r=!1;return async(o,i)=>{let s=new Request(o,i);if(r&&Xl(s))return e(s);let a=await n(s.clone());return await Yl(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 Je(t){if(ao(t))return;let e=X(t),n=to.get(e);return n||(n=Zl(t),to.set(e,n)),n}function eu(t,e){let n=null,r=null;return async()=>{let o=n?Ql(n):null;return n&&(o===null||o-Date.now()>3e4)?n:(r||(r=Be({nodeUrl:t.relayUrl,fetch:Je(t.relayUrl),node:e,deviceSecret:t.deviceSecret,accountProof:t.credential,audience:je()}).then(i=>(n=i.accessToken,n)).catch(i=>{console.warn("[mero-js] relay login failed",i),n=null}).finally(()=>{r=null})),r)}}var Nn=new Map;function bs(){Nn.clear()}function tu(t){return typeof t=="object"&&t!==null&&t.status===409}function nu(t,e){let n=t.rpc,r=X(e),o=async i=>{let s=`${r}|${i.contextId}|${i.method}`;if(Nn.get(s)!=="write")try{let{returns:a}=await t.admin.queryContext(i.contextId,{method:i.method,argsJson:i.argsJson??{}});return Nn.set(s,"read"),{returns:a,transport:"relay"}}catch(a){tu(a)&&Nn.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 ru(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 ou(t,e){let n=e.session?nu(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=ru(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 Gn(t,e){if(!t.relayUrl)return null;let n=Mn(t.relayUrl),r=Dn({transport:"relay",fetch:Je(t.relayUrl),relay:{relayUrl:t.relayUrl,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:io(t.relayUrl)},proof:{credential:t.credential,deviceSecret:t.deviceSecret},session:n?eu({...t,relayUrl:t.relayUrl},n):void 0,observe:n?{nodeKey:n}:void 0});return ou(r,{relayUrl:t.relayUrl,session:n!==null,attested:n!==null||ao(t.relayUrl)})}var As="calimero.delegated.relays.";function q(t){try{let e=localStorage.getItem(As+t),n=e?JSON.parse(e):{};return{namespaces:n.namespaces??{},contexts:n.contexts??{}}}catch{return{namespaces:{},contexts:{}}}}function co(t,e){try{localStorage.setItem(As+t,JSON.stringify(e))}catch{}}function be(t,e,n){let r=q(t),o=X(e);n.namespaceId&&(r.namespaces[n.namespaceId]=o),n.contextId&&(r.contexts[n.contextId]=o),co(t,r)}function xs(t,e){return q(t).contexts[e]??null}function $n(t,e){return e.executorAccount||!t?.executorAccount||!t.relayUrl||!e.relayUrl||X(t.relayUrl)!==X(e.relayUrl)?e:{...e,executorAccount:t.executorAccount}}function ze(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)]}async function vs(t){let e=[],n=q(t.account);for(let r of ze(t))try{if(!await Kn(r))continue;let o=Gn({...t,relayUrl:r},null);if(!o)continue;let{contexts:i}=await o.admin.getContexts();for(let s of i??[])e.push({...s,relayUrl:r}),n.contexts[s.id]=r}catch(o){console.warn(`[mero-js] could not list contexts on ${r}`,o)}return co(t.account,n),e}async function Rs(t){var o,i;let e=[],n=new Set,r=q(t.account);for(let s of ze(t))try{if(!await Kn(s))continue;let a=Gn({...t,relayUrl:s},null);if(!a)continue;for(let c of await a.admin.listNamespaces())n.has(c.namespaceId)||(n.add(c.namespaceId),e.push({...c,relayUrl:s}),(o=r.namespaces)[i=c.namespaceId]??(o[i]=s))}catch(a){console.warn(`[mero-js] could not list namespaces on ${s}`,a)}return co(t.account,r),e}function Hn(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 vt(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()}}}function iu(t){return{getWarrantNonce:(e,n)=>t.client.getWarrantNonceAsAuthor(e,t.authorProof)}}var Ln=class extends Error{constructor(n,r){super(`author device ${r} has spent every nonce in context ${n}; it must re-key to write again`);this.contextId=n;this.authorDeviceKey=r;this.name="WarrantNonceExhaustedError"}};function su(t){let e=Array.isArray(t.lookups)?t.lookups:[t.lookups];if(e.length===0)throw new Error("a recovering nonce source needs at least one node to ask");let n=t.local??Hn(1),r=t.onLookupFailure??"throw",o=null,i=null,s=async()=>{let a=await Promise.allSettled(e.map(d=>d.getWarrantNonce(t.contextId,t.authorDeviceKey))),c=null,u=!1;for(let d of a){if(d.status!=="fulfilled")continue;let l=d.value;if(l.kind==="exhausted"){u=!0;continue}(c===null||l.nextNonce>c)&&(c=l.nextNonce)}if(c===null&&u)throw new Ln(t.contextId,t.authorDeviceKey);if(c===null){let d=a.find(p=>p.status==="rejected"),l=d&&d.status==="rejected"?d.reason:void 0;if(r==="local"){o=0n;return}throw l instanceof Error?l:new Error(`no node could answer where the warrant-nonce sequence stands: ${String(l)}`)}o=c,await n.advanceTo?.(c)};return{async next(){o===null&&(i??(i=s().finally(()=>{i=null})),await i);let a=await n.next(),c=o!==null&&o>a?o:a;return o=c+1n,c},async advanceTo(a){(o===null||a>o)&&(o=a),await n.advanceTo?.(a)}}}async function Cs(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=cu(r,t.namespaceId),i=await n.getNamespaceRelays(o.namespaceId),s=lo(i);if(!s)throw new Error(lu(o,i));let a=new W({relayUrl:s.relayUrl,executorAccount:s.executorAccount,authorAccount:t.authorAccount,authorProof:t.authorProof,signer:e,nonces:t.nonces??uu(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 we({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 Cs({...r,deviceSecret:void 0,signer:o,sessionToken:a.sessionToken,authorAccount:n??i.accountId})}function cu(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 lu(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 uu(t){let e=`mero-js:warrant-nonce:${t}`;try{return vt(e)}catch{return Hn(1)}}var du=new TextEncoder().encode("calimero.mdma.routing-read.v1\0");async function Ss(t,e){m(e,"deviceSecret",32);let n=await ne(e),r=f(du,new TextEncoder().encode(t)),o=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,r));return pu(o)}async function Bn(t,e){return{"X-Calimero-Credential":e.credential,"X-Calimero-Nonce":t.nonce,"X-Calimero-Signature":await Ss(t.nonce,e.deviceSecret)}}function pu(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var Es="calimero.cloud.link.pending",uo="link_state";var po=/^[0-9a-f]{64}$/;function ks(t){try{let e=localStorage.getItem(Es),n=e?JSON.parse(e):{};return Object.fromEntries(Object.entries(n).filter(([,r])=>r&&typeof r.expiresAt=="number"&&r.expiresAt>t))}catch{return{}}}function Is(t){try{localStorage.setItem(Es,JSON.stringify(t))}catch{}}function qn(t,e){if(!po.test(t))throw new Error("accountId must be 64 lowercase hex characters");let n=new URL(e),r=Date.now(),o=ks(r),i=crypto.getRandomValues(new Uint8Array(16)),s=Array.from(i,a=>a.toString(16).padStart(2,"0")).join("");return o[s]={account:t,expiresAt:r+6e5},Is(Object.fromEntries(Object.entries(o).slice(-20))),n.searchParams.set(uo,s),n.toString()}function Qe(t){let e=new URLSearchParams(t).get(uo),n=ks(Date.now());if(!e||!Object.prototype.hasOwnProperty.call(n,e))return null;let r=n[e];return delete n[e],Is(n),r}function Ps(t){let e=new URLSearchParams(t);e.delete(uo);let n=e.toString();return n?`?${n}`:""}var gu="https://cloud.calimero.network";function Ts(t){let e=new URL(t.cloudWebUrl??gu);return e.searchParams.set("link-account",t.accountId),e.searchParams.set("callback-url",qn(t.accountId,t.returnTo)),e.toString()}function mu(t){throw window.location.assign(Ts(t)),new Error("redirecting to the cloud to authorise this link")}function fu(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Qe(t.search??""),go(),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;if(Qe(t.search??"")?.account!==o)throw go(),new Error("this account link answers a request this browser did not make - start the link again from here");return go(),{grant:r,account:o}}function go(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+Ps(location.search))}async function hu(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,signer:e.signer})}var yu="enrol-device",wu="enrol-kem",bu="callback-url",Au="state";function Us(t){Ns(t.devicePublicKey,"devicePublicKey"),Ns(t.kemPublicKey,"kemPublicKey"),Su(t.returnTo),Cu(t.returnTo);let e=new URL(t.walletUrl);return e.searchParams.set(yu,t.devicePublicKey),e.searchParams.set(wu,t.kemPublicKey),e.searchParams.set(bu,t.returnTo),t.state&&e.searchParams.set(Au,t.state),e.toString()}function xu(t){throw window.location.assign(Us(t)),new Error("redirecting to the wallet to approve this device")}function vu(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Ds(),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;Ds();let s=e.get("state");return{credential:r,account:o,device:i,...s?{state:s}:{}}}function Ds(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+location.search)}async function Ru(t){if(t.expectState!==void 0&&t.expectState!==t.state)throw new Error("this enrolment answers a request this app did not make \u2014 the state it carries is not the one sent");let e=await Qt(t.credential);if(e.signPublicKey!==Ae(t.devicePublicKey))throw new Error(`this credential certifies device key ${e.signPublicKey}, but this app holds ${Ae(t.devicePublicKey)} \u2014 it would sign with a key the certificate does not cover`);if(t.kemPublicKey!==void 0&&e.kemPublicKey!==Ae(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!==Ae(t.account))throw new Error(`the wallet reported account ${Ae(t.account)}, but the credential names ${e.account}`);if(e.device!==Ae(t.device))throw new Error(`the wallet reported device ${Ae(t.device)}, but the credential names ${e.device}`);return{credential:t.credential,account:e.account,device:e.device,certificate:e}}function Ns(t,e){if(!/^[0-9a-f]{64}$/.test(t))throw new Error(`${e} must be 64 lowercase hex characters`)}function Ae(t){return t.trim().toLowerCase()}function Os(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 Cu(t){Os(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 Su(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 jn(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 ku(t,e){if(e.size===0)return!0;let n=jn(t.account);return n!==null&&e.has(n)}async function Fn(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(jn).filter(p=>p!==null)),i=n.filter(p=>ku(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 Vn=1440*60,fo={Admin:0,Member:1,ReadOnly:2};function kt(t){let e=t.admitters??[];return f(mo(t.inviter_identity,"inviter_identity"),mo(t.group_id,"group_id"),C(t.expiration_timestamp),mo(t.secret_salt,"secret_salt"),new Uint8Array([t.invited_role]),R(e.length),...e.map((n,r)=>m(n,`admitters[${r}]`,32)))}async function ho(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",kt(t)))}function yo(t){return[...new Set(t.filter(n=>n.role==="Admin").map(n=>n.identity.toLowerCase()))].sort()}async function Wn(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=yo(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??fo.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??Vn,Vn);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 ho(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 mo(t,e){if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return new Uint8Array(t)}var wo=25,Iu=new TextEncoder().encode("calimero.namespace.v1"),Pu=0,_s={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreatedV2:9,MemberJoinedViaTeeAttestation:10};function Ms(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 Ks(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}function Jn(t){let e=t.invitation,n=t.admitter_addrs??[];return f(kt(e),Ks(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(Ks),Ms(t.application_id,"application_id"),Ms(t.app_key,"app_key"))}async function zn(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([_s.MemberJoinedAt]),m(t.member,"member",32),Jn(t.invitation),C(o),n):f(new Uint8Array([_s.MemberJoined]),m(t.member,"member",32),Jn(t.invitation),n),s=f(new Uint8Array([Pu]),i),a=await I(t.deviceSecret,t.signer,"deviceSecret"),c=m(a.publicKey,"signer.publicKey",32),u=f(new Uint8Array([wo]),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(Iu,u)),l=new Uint8Array([0]);return y(f(u,d,l))}function Tu(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 Du(t){let e=vt(`calimero.delegated.joinnonce.${t}`);return()=>e.next()}function Gs(t){return t.replace(/\/+$/,"")}async function Qn(t){let{account:e,credential:n,deviceSecret:r}=t.credential,o;try{o=await zn({namespaceId:t.namespaceId,member:e,invitation:t.invitation,credential:n,deviceSecret:r,nonce:await(t.deps?.nonce??Du(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??`${Gs(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:Tu(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:Gs(t.nodeUrl),account:e,credential:n,deviceSecret:r}}}async function Yn(t){let e=t.deps?.resolve??Fn,n=t.deps?.join??Qn,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 $s(t,e,n,r){let i=await(r.bootstrap??Yn)({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&&be(t.account,i.session.relayUrl,{namespaceId:e}),r.onJoined($n(t,i.session)),{namespaceId:e}}function Ls(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 bo(t,e){let n=Ls(t),r=Ls(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 Nu(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 It(t){return t.filter(e=>!e.yanked&&typeof e.appVersion=="string"&&e.appVersion.length>0).reduce((e,n)=>!e||Nu(n.appVersion,e.appVersion)?n:e,void 0)}async function Pt(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 Hs(t,e,n={}){let o=(await Pt(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=It(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 bo(e,a),signerId:a,version:s.appVersion}}function qs(t,e){return{next:async()=>Uu(t,e)}}function Uu(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 js(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 Ou(t){return!t||t.length===0?{}:JSON.parse(new TextDecoder().decode(Uint8Array.from(t)))}function Zn(t,e,n,r){return new W({relayUrl:e,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:n,fetch:r??Je(e)})}async function Tt(t,e,n={}){let r=js(t,e.namespaceId),o=0n,i=await Zn(t,r,{next:async()=>o},n.fetch).createContext({groupId:e.groupId??e.namespaceId,applicationId:e.applicationId,serviceName:e.serviceName,seed:e.contextSeed,initArgs:Ou(e.initializationParams),name:e.name});return _n(r,i.contextId,o),be(t.account,r,{namespaceId:e.namespaceId,contextId:i.contextId}),{contextId:i.contextId}}async function ve(t,e,n={}){let r=js(t,e.namespaceId);return Zn(t,r,qs(r,e.group),n.fetch).govern({groupId:e.group,op:e.op})}async function Fs(t,e,n={}){let{groupId:r}=await ve(t,{namespaceId:e.namespaceId,group:e.namespaceId,op:(await Le({parentId:e.namespaceId,restricted:!0,admin:t.account})).op},n);for(let i of e.members)await ve(t,{namespaceId:e.namespaceId,group:r,op:Ge(i,"Member")},n);let{contextId:o}=await Tt(t,{...e,groupId:r},n);return{contextId:o,groupId:r}}async function er(t,e={},n={}){let o=ze(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 _u(t,o,n.fetch),s=BigInt(Date.now()),a=await Zn(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(be(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 Ku(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 _u(t,e,n){let r=t.executorAccount&&t.relayUrl?.replace(/\/+$/,"")===e?t.executorAccount:null;if(r)return{executorAccount:r,executorKey:await Bs(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 Bs(e),s=await Zn(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 Bs(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 tr="link this account to your cloud user in the wallet so the cloud can host this namespace on its fleet",Xn={account_not_linked:tr,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 Mu(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 Ku(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 xe)return{haEnabled:!1,haError:tr};if(i instanceof J&&Xn[i.code]){let s=i.code==="ha_request_pending"?Mu(i):null,a=Xn[i.code];return{haEnabled:!1,haError:s?`${a} (waiting: ${s})`:a}}return{haEnabled:!1,haError:i instanceof Error?i.message:String(i)}}}async function Ye(t,e,n=globalThis.fetch){let r=It(await Pt(t,e,n));if(!r)throw new Error(`the registry lists no version of ${e}`);return r.appVersion}var Vs="calimero.delegated.group-namespace.",Ao=new Map;function Ws(t){let e={};try{e=JSON.parse(localStorage.getItem(Vs+t)??"{}")}catch{}return{...e,...Ao.get(t)}}function Dt(t,e,n){Ao.set(t,{...Ao.get(t),[e]:n});try{let r=Ws(t);r[e]=n,localStorage.setItem(Vs+t,JSON.stringify(r))}catch{}}function Nt(t,e){return q(t.account).namespaces[e]?e:Ws(t.account)[e]}function Js(t,e){let n=Nt(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 nr(t,e,n){return ve(t,{namespaceId:Js(t,e),group:e,op:n})}async function rr(t,e,n){let r=Js(t,e);return ve(t,{namespaceId:r,group:r,op:n})}var Re=class extends Error{constructor(n){super(`${n} is not available for an account: it needs a node`);this.method=n;this.name="NotForAccountError"}},Xe=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"}},Ze=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"}},zs={listNamespaces:async()=>[],listNamespacesForApplication:async()=>[],getContexts:async()=>({contexts:[]})},Gu=new Set(["upgradeGroup","retryGroupUpgrade","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 $u(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 Qs(t,e={}){let{session:n,read:r,app:o}=t,i=e.govern?.group??nr,s=e.govern?.root??rr,a=e.createContext??Tt,c=e.found??er,u=e.latestVersion??Ye,d=e.signInvitation??Wn,l=e.join,p=e.routing;async function x(h,b){if(!l)throw new Re("joinNamespace without a join handler");return l(h,b.invitation)}let v=()=>{if(r===null)throw new Xe("this call");return r};async function P(h){if(Nt(n,h))return;let b=await v().getGroupInfo(h);Dt(n.account,h,b.namespaceId??h)}let w=async(h,b,S)=>(await P(b),i(h,b,S)),E=async(h,b,S)=>(await P(b),s(h,b,S));async function T(h){try{return await E(n,h,In({member:n.account,groupId:h,credential:n.credential})),!0}catch(b){if($u(b))return!1;throw b}}async function H(h,b){let S=b??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(b=>b.targetApplicationId===h)},async getNodeIdentity(){return{accountId:n.account,deviceId:null,publicKey:"",deviceCertified:!0}},async createNamespace(h){if(!o.packageName)throw new Re("createNamespace without a packageName");let b=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:b}});return h.name&&await w(n,S,He({name:h.name})),{namespaceId:S,haEnabled:U,...M!==void 0?{haError:M}:{}}},async createGroupInNamespace(h,b={}){let{op:S}=await Le({parentId:h,restricted:b.visibility==="restricted",admin:n.account}),{groupId:U}=await E(n,h,S);return Dt(n.account,U,h),b.groupName&&await w(n,U,He({name:b.groupName})),{groupId:U}},async addGroupMembers(h,b){for(let S of b.members)await w(n,h,Ge(S.identity,S.role??"Member"))},async removeGroupMembers(h,b){for(let S of b.members)await w(n,h,hn(S))},async setGroupMetadata(h,b){await w(n,h,He(b))},async setMemberMetadata(h,b,S){await w(n,h,En(b,S))},async setContextMetadata(h,b,S){await w(n,h,kn(b,S))},async setDefaultCapabilities(h,b){await w(n,h,$e(b.defaultCapabilities))},async setSubgroupVisibility(h,b){await w(n,h,Sn(b.subgroupVisibility==="open"?"open":"restricted"))},async setMemberCapabilities(h,b,S){await w(n,h,Rn(b,S.capabilities))},async deleteGroup(h){return await E(n,h,An(h)),{isDeleted:!0}},async reparentGroup(h,b){return await E(n,h,bn(h,b.newParentId)),{reparented:!0}},async leaveGroup(h){await w(n,h,At(n.account))},async leaveNamespace(h){await w(n,h,At(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:b},S]=await Promise.all([v().listGroupMembers(h),v().getGroupInfo(h)]),U=b.filter(Q=>Q.role==="RelayTee").map(Q=>Q.identity.toLowerCase());if(p){let Q=new Set(U.length>0?U:b.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 Ze(h,"not-hosted");if(!ee.some(te=>te.account!==null&&Q.has(te.account.toLowerCase())))throw new Ze(h,"no-named-node")}}return{invitation:await d({groupId:h,inviterAccount:n.account,deviceSecret:n.deviceSecret,...U.length>0?{admitters:U}:{},members:b,applicationId:S.targetApplicationId,appKey:S.appKey})}},async syncGroup(h){return{groupId:h,synced:!0}},async syncContext(){},joinNamespace:x,async updateMemberRole(h,b,S){await w(n,h,yn(b,S.role))},async joinSubgroupInheritance(h){return{groupId:h,memberPublicKey:n.account,wasInherited:await T(h)}},async detachContextFromGroup(h,b){await w(n,h,Cn(b))}};return r===null?new Proxy({},{get(h,b){if(typeof b=="string")return b==="getNodeIdentity"?z.getNodeIdentity:b==="joinNamespace"?x:b in zs?zs[b]:async()=>{throw new Xe(b)}}}):new Proxy(r,{get(h,b,S){return typeof b=="string"&&b in z?z[b]:typeof b=="string"&&Gu.has(b)?async()=>{throw new Re(b)}:Reflect.get(h,b,S)}})}function Ys(t,e={}){let{admin:n,app:r}=t,o=e.latestVersion??Ye;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 Lu="https://manager.cloud.calimero.network";function xo(t,e){return typeof t.can_execute=="boolean"?t.can_execute:e}function vo(t){return typeof t.tee_role=="string"&&t.tee_role!==""?t.tee_role:null}function lo(t){return t.find(e=>e.canExecute&&e.relayUrl!==null&&e.executorAccount!==null)??null}function Hu(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 Bu(t){return typeof t=="string"&&po.test(t)?t:null}var J=class extends D{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.code=n;this.name="AccountHaRefusedError"}},xe=class extends J{constructor(){super(...arguments);this.name="AccountNotLinkedError"}};xe.CODE="account_not_linked";var Rt=class extends J{constructor(){super(...arguments);this.name="AccountLinkedToSeveralUsersError"}};Rt.CODE="account_linked_to_several_users";var Ct=class extends J{constructor(){super(...arguments);this.name="HaRequestPendingError"}};Ct.CODE="ha_request_pending";var St=class extends J{constructor(){super(...arguments);this.name="UnknownRelayError"}};St.CODE="unknown_relay";var Et=class extends J{constructor(){super(...arguments);this.name="RelayNotDialableError"}};Et.CODE="relay_not_dialable";var Xs={409:[xe,Rt,Ct],422:[St,Et]};function qu(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 ju="x-mdma-session-refresh",Fu="x-mdma-session-expires",$=class{constructor(e={}){this.session=null;this.baseUrl=(e.cloudBaseUrl||Lu).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 Zt({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:vo(r),canExecute:xo(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:Hu(r)}})}async findExecutingRelay(e){let n=await this.getNamespaceRelays(e);return lo(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:vo(r),canExecute:xo(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:Bu(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:vo(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:xo(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 Rr({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 D&&Xs[i.status]){let s=qu(i.bodyText),a=Xs[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 ct({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 accountLinkHandoff(e){let n=e.portalUrl.replace(/\/+$/,""),r=new URLSearchParams({"link-account":e.accountId,"callback-url":qn(e.accountId,e.callbackUrl)});return{url:`${n}/?${r.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={};return c&&Qe(o),s&&Qe(o)?.account!==a?{error:"unexpected_callback"}:(s&&(u.grant=s),a&&(u.accountId=a),c&&(u.error=c),u)}async linkAccountWithGrant(e){let{signer:n,publicKey:r,accountId:o}=await Xt(e.rootSecret,e.signer),i=await this.request("POST","/api/cloud/accounts/link",{body:{grant:e.grant,root_public_key:r,signature:await ct({signer:n,nonce:e.grant})},anonymous:!0});return{accountId:String(i.account_id??o),linkedAt:i.linked_at??null,alreadyLinked:i.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 D(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 D(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(ju);if(!n||!this.session)return;let r=e.headers.get(Fu),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 Eu(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 Vu(t){if(t)return typeof t=="function"?t:Ft(t)}var Wu="mero-js:token-refresh";function Ju(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function zu(t){try{let{origin:e,pathname:n}=new URL(t);return e==="null"?t:e+n.replace(/\/+$/,"")}catch{return t}}function Ro(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 Fe=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=zu(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=Vu(this.config.requestProof);this.httpClient=Ie({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=Ko(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs}),this.adminClient=qt(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 st({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 at({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:Ro(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=Ju();return n?n.request(Wu,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:Ro(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||Ro(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){return br(e)}static buildAuthLoginUrl(e,n){return Ar(e,n)}};function Qu(t){return new Fe(t)}var Co=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},Yu="mero-tokens",So=class{constructor(e=Yu){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 Xu=new TextEncoder().encode("calimero.account.owner-op.v1"),Zu=new TextEncoder().encode("calimero.account.owner-op.body.v1"),ed=new TextEncoder().encode("calimero.account.genesis.v1"),td=2,Eo={transferOwnership:0,adminChanged:1,groupDelete:2,teeAdmissionPolicy:3,teeAuthoringPolicy:4,teeReleaseAdmissionPolicy:5},et={GroupDelete:14,TransferOwnership:21,TeeAuthoringPolicySet:33,TeeAdmissionPolicySetV2:37,TeeReleaseAdmissionPolicySetV2:38,RootGuarded:42},ea={AdminChanged:3,RootGuarded:12},nd={replica:0,relay:1},rd=new TextEncoder;function L(t){return new Uint8Array([t])}function ta(t){let e=rd.encode(t);return f(R(e.length),e)}function Z(t){return f(R(t.length),...t.map(ta))}function na(t){return L(t?1:0)}function ra(t){let e=nd[t??"replica"];if(e===void 0)throw new Error(`mode must be replica or relay, got ${String(t)}`);return L(e)}function oa(t){return{kind:"transferOwnership",plane:"group",bytes:f(L(et.TransferOwnership),m(t,"newOwner",32))}}function ia(){return{kind:"groupDelete",plane:"group",bytes:L(et.GroupDelete)}}function sa(t){return{kind:"adminChanged",plane:"root",bytes:f(L(ea.AdminChanged),m(t,"newAdmin",32))}}function aa(t){return{kind:"teeAuthoringPolicy",plane:"group",bytes:f(L(et.TeeAuthoringPolicySet),Z(t))}}function ca(t){return{kind:"teeAdmissionPolicy",plane:"group",bytes:f(L(et.TeeAdmissionPolicySetV2),Z(t.allowedMrtd),Z(t.allowedRtmr0),Z(t.allowedRtmr1),Z(t.allowedRtmr2),Z(t.allowedRtmr3),Z(t.allowedTcbStatuses),na(t.acceptMock),ra(t.mode))}}function la(t){let e=t.minReleaseVersion===void 0?L(0):f(L(1),ta(t.minReleaseVersion));return{kind:"teeReleaseAdmissionPolicy",plane:"group",bytes:f(L(et.TeeReleaseAdmissionPolicySetV2),Z(t.allowedProfiles),e,Z(t.allowedTcbStatuses),na(t.acceptMock),ra(t.mode))}}async function ko(t){return k(Zu,[t])}async function Io(t){return k(Xu,[m(t.account,"account",32),m(t.namespaceId,"namespaceId",32),m(t.groupId,"groupId",32),L(ua(t.kind)),t.opDigest,C(t.counter),R(t.keyEpoch)])}function ua(t){let e=Eo[t];if(e===void 0)throw new Error(`unknown owner-op kind ${String(t)}`);return e}var Zs=132;async function da(t){let e=await re(t.rootSecret),n=f(L(td),e),r=y(await k(ed,[n])),o=t.keyEpoch??0,i=(t.chain??[]).map((d,l)=>{let p=j(d,`chain[${l}]`);if(p.length!==Zs)throw new Error(`chain[${l}] must be a ${Zs}-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 ko(t.op.bytes),a=await Io({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(ua(t.op.kind)),s,C(t.counter),R(o),u))}function pa(t,e){let n=t.plane==="group"?et.RootGuarded:ea.RootGuarded;return f(L(n),t.bytes,j(e,"rootProof"))}var ga=[2428,2429,2528,2529],od="localhost",id=2e3;function ma(t){return`http://${od}:${t}`}function fa(t,e){let n=t.endsWith("/")?t:`${t}/`;return new URL(e,n).toString()}async function ha(t,e={}){let{timeoutMs:n=id,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=fa(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 sd(t={}){let{ports:e=ga,timeoutMs:n,signal:r}=t;return(await Promise.all(e.map(async i=>{let s=ma(i);return await ha(s,{timeoutMs:n,signal:r})?s:null}))).filter(i=>i!==null)}function or(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]=or(t[o]^t[e],16),t[r]=t[r]+t[o]>>>0,t[n]=or(t[n]^t[r],12),t[e]=t[e]+t[n]>>>0,t[o]=or(t[o]^t[e],8),t[r]=t[r]+t[o]>>>0,t[n]=or(t[n]^t[r],7)}function ya(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function Aa(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]=ya(t,s*4);r[12]=e>>>0;for(let s=0;s<3;s+=1)r[13+s]=ya(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 ad(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=Aa(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 Po(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 ld(t,e){let n=Po(t.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,r=Po(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=Po(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 wa(t){return new Uint8Array((16-t%16)%16)}function ba(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function ud(t,e){let n=[t,wa(t.length),e,wa(e.length),ba(t.length),ba(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 dd(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 xa(t,e,n,r=new Uint8Array(0)){dd(t,e);let o=Aa(t,0,e).subarray(0,32),i=ad(t,1,e,n),s=ld(o,ud(r,i)),a=new Uint8Array(i.length+16);return a.set(i),a.set(s,i.length),a}var Ra=32,pd=1,gd=3,md=2,fd=32,hd=32,yd=12,tt=t=>new TextEncoder().encode(t),Ot=t=>new Uint8Array([t>>8&255,t&255]),va=f(tt("KEM"),Ot(Ra)),Ut=f(tt("HPKE"),Ot(Ra),Ot(pd),Ot(gd));async function Ca(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 wd(t,e,n){let r=new Uint8Array(n),o=new Uint8Array(0);for(let i=1,s=0;s<n;i+=1)o=await Ca(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 ir(t,e,n,r){return Ca(e,f(tt("HPKE-v1"),t,tt(n),r))}function To(t,e,n,r,o){return wd(e,f(Ot(o),tt("HPKE-v1"),t,tt(n),r),o)}async function bd(t,e){let n=await ir(va,new Uint8Array(0),"eae_prk",t);return To(va,n,"shared_secret",e,fd)}async function Ad(t,e){let n=new Uint8Array(0),r=await ir(Ut,n,"psk_id_hash",n),o=await ir(Ut,n,"info_hash",e),i=f(new Uint8Array([md]),r,o),s=await ir(Ut,t,"secret",n);return{key:await To(Ut,s,"key",i,hd),nonce:await To(Ut,s,"base_nonce",i,yd)}}async function Sa(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 Ne(i),a=await Ne(e),c=f(await lt(s.privateKey,t),await lt(a.privateKey,t)),u=await bd(c,f(s.publicKey,t,a.publicKey)),{key:d,nonce:l}=await Ad(u,n);return{enc:s.publicKey,ciphertext:xa(d,l,r,o)}}var Ia="mero-agent-gate/attest/v3",Pa="mero-agent-gate/provision/v2",xd=/^[a-z0-9][a-z0-9-]{0,62}$/,vd=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,Ea=64,ka=64*1024,ue=class extends Error{constructor(n,r,o){super(n);this.status=r;this.code=o;this.name="AgentGateError"}};function Ta(t){if(!xd.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 Da(t){let e=_t(t);return f(new Uint8Array([e.length]),e)}function Ce(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}function sr(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 Na(t,e,n,r){let o=new Uint8Array(32),i=f(_t(Ia),t,Da(e),n??o,r??o);return new Uint8Array(await crypto.subtle.digest("SHA-256",i))}function Ua(t,e){return f(_t(Pa),t,Da(e))}async function Rd(){let t=crypto.getRandomValues(new Uint8Array(32));return{secret:t,publicKey:await ar(t)}}async function ar(t){if(t.length!==32)throw new Error("An owner key is 32 bytes");return Ce((await Ne(t)).publicKey)}function Oa(t,e){return`${t.replace(/\/+$/,"")}${e}`}async function _a(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 Do(t){let e=t.agentId??"";e&&Ta(e);let n=crypto.getRandomValues(new Uint8Array(32)),r=await _a(t.fetch??fetch,Oa(t.gateUrl,"/attest"),{nonceB64:Ce(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=sr(r.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),i=r.signingPublicKeyB64?sr(r.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,s=r.ownerPublicKeyB64?sr(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 Na(o,e,i,s);return await t.verifier({quoteB64:r.quoteB64,nonce:y(n),reportDataSuffix:y(a)}),{agentId:e,provisioningPublicKey:Ce(o),...i?{signingPublicKey:Ce(i)}:{},...s?{ownerPublicKey:Ce(s)}:{}}}async function Ma(t,e){let n=await ar(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 Cd(t){let e=Object.keys(t);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>Ea)throw new Error(`At most ${Ea} secrets at once`);for(let n of e){if(!vd.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>ka)throw new Error(`Secret ${n} is over ${ka} bytes`)}}async function Ka(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 Ma(r,o),a=sr(r.provisioningPublicKey,"provisioningPublicKey",32),c=await Sa(a,o,Ua(a,r.agentId),_t(JSON.stringify(i)));return _a(t,Oa(e,n),{agentId:r.agentId,provisioningPublicKeyB64:r.provisioningPublicKey,senderPublicKeyB64:s,encappedKeyB64:Ce(c.enc),ciphertextB64:Ce(c.ciphertext)})}async function Sd(t){Cd(t.secrets);let e=t.fetch??fetch,n=await Ka(e,t.gateUrl,"/provision",t.agent,t.ownerSecret,{secrets:t.secrets}),r=await Do({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e}),o=await ar(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 Ed(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 Ka(e,t.gateUrl,"/release",t.agent,t.ownerSecret,{release:!0}),(await Do({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 No=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),kd=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function Id(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await sn(r,e,{identity:n.identity??No.identity,issuer:n.issuer??No.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??gt;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 Ga(o),o}function Ga(t){for(let e of kd)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 Pd=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function Td(t){let e=Pd.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 Mt=t=>t.trim().replace(/^0x/i,"");function Dd(t,e){return Ga(t),mt({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:t.allowed_tcb_statuses.map(Td),allowedMrtd:t.allowed_mrtd.map(Mt),allowedRtmr0:t.allowed_rtmr0.map(Mt),allowedRtmr1:t.allowed_rtmr1.map(Mt),allowedRtmr2:t.allowed_rtmr2.map(Mt),allowedRtmr3:t.allowed_rtmr3.map(Mt)})}export{Xo as ACCOUNT_HA_AUDIENCE,Yo as ACCOUNT_OWNERSHIP_AUDIENCE,Ia as AGENT_ATTEST_DOMAIN,Pa as AGENT_PROVISION_INFO_DOMAIN,J as AccountHaRefusedError,Rt as AccountLinkedToSeveralUsersError,xe as AccountNotLinkedError,me as AdminApiClient,ue as AgentGateError,pe as AuthApiClient,oe as AuthRevokedError,_ as CAPABILITIES,lp as CAPABILITY_PRESETS,$ as CloudClient,ga as DEFAULT_LOCAL_NODE_PORTS,an as DEFAULT_RELEASE_MIRROR,at as EphemeralClient,Ri as HANDSHAKE_PATH,tr as HA_ACCOUNT_NOT_LINKED_MESSAGE,Xn as HA_REFUSAL_MESSAGES,D as HTTPError,Ct as HaRequestPendingError,fo as INVITED_ROLE,he as IntentRefusedError,Ze as InvitationNotClaimableError,No as KMS_RELEASE_SIGNER,So as LocalStorageTokenStore,Vn as MAX_INVITATION_VALIDITY_SECS,Co as MemoryTokenStore,we as MeroClient,Fe as MeroJs,Lr as NODE_RELEASE_SIGNER,Xe as NoRelayError,Re as NotForAccountError,Eo as OWNER_OP_KIND,os as PRESENCE_DOMAIN,gt as PRODUCTION_PROFILE,On as RELAY_NODE_KEY_RETRY_MS,ke as REQUEST_PROOF_HEADER,W as RelayClient,Et as RelayNotDialableError,qe as RelayObserver,xt as RelayPresenceClient,ye as RelayTransport,st as RpcClient,Vt as RpcError,dt as SEALED_CONTENT_TYPE,Ci as SEALED_PATH,wo as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,Ue as SealedTransportError,B as SseClient,pt as StaleTransportKeyError,St as UnknownRelayError,Ln as WarrantNonceExhaustedError,Bt as WarrantNonceRouteUnavailableError,rt as WebHttpClient,ie as WsClient,Yt as accountForRoot,F as accountForRootPublicKey,ii as accountRootFromPhrase,Pr as accountRootFromSecret,ai as accountRootSignerFromPhrase,sa as adminChangedOp,Eu as admitterAddrsFromNetworkStatus,Na as agentKeyBinding,Dd as agentQuoteVerifier,bo as applicationIdForBundle,We as attemptRelayNodeKey,Do as attestAgent,tn as attestKeyBinding,nn as attestRelayNodeKey,iu as authorNonceLookup,mu as beginCloudLink,xu as beginDeviceEnrolment,Yn as bootstrapFromInvitation,Ar as buildAuthLoginUrl,Gn as buildDelegatedClient,Os as callbackIsForeign,jt as callerProof,up as capMask,dp as capNames,$n as carryExecutorAccount,Ma as checkOwner,yr as classifyError,gs as clearDelegatedCredential,us as clearDelegatedSession,Ts as cloudLinkUrl,un as cloudNodeReleaseUrl,lr as combineSignals,tc as compareSemver,hu as completeCloudLink,Ru as completeDeviceEnrolment,Cs as connectCloud,au as connectCloudWithAccount,es as contextCapabilityGrantedOp,ts as contextCapabilityRevokedOp,Cn as contextDetachedOp,kn as contextMetadataSetOp,Qs as createAccountAdmin,si as createAccountRootSigner,Bo as createAdminApiClient,qt as createAdminApiClientFromHttpClient,fe as createAttestedSealedFetch,ap as createAuthApiClient,Ko as createAuthApiClientFromHttpClient,Pp as createBrowserAdminApiClient,ip as createBrowserAuthApiClient,Ie as createBrowserHttpClient,Tt as createDelegatedContext,Fs as createDelegatedPrivateContext,ot as createHttpClient,vt as createLocalStorageNonceSource,Hn as createMemoryNonceSource,Dn as createMeroClient,Qu as createMeroJs,Ys as createNodeAdmin,Tp as createNodeAdminApiClient,sp as createNodeAuthApiClient,Lt as createNodeHttpClient,gr as createProofAuthorizer,Ft as createProofSigner,mt as createQuoteVerifier,su as createRecoveringNonceSource,Ja as createRetryableMethod,Ii as createSealedFetch,wl as createSignedReleaseSealedFetch,dn as createSignedReleaseVerifier,ur as createTimeoutSignal,mr as createUniversalHttpClient,Jr as createdSubgroupId,qr as creationInitHash,yo as defaultAdmitters,je as defaultAudience,$e as defaultCapabilitiesSetOp,ve as delegatedGovernance,zt as deviceCertPayload,Us as deviceEnrolmentUrl,Er as deviceScopePayload,sd as discoverLocalNodes,kt as encodeGroupInvitation,Jn as encodeSignedInvitation,ki as fetchAttestedTransportKey,cn as fetchNodeRelease,ln as fetchNodeReleaseVersion,Pt as fetchRegistryBundles,bs as forgetMethodKinds,ws as forgetRelaySealing,er as foundDelegatedNamespace,xn as foundedNamespaceId,oi as generateAccountRoot,Rd as generateOwnerKey,Xr as generateSessionKey,nr as governGroup,rr as governRoot,jr as governanceOpHash,zr as groupCreatedOp,ia as groupDeleteOp,An as groupDeletedOp,ho as groupInvitationHash,He as groupMetadataSetOp,bn as groupReparentedOp,ge as hasCap,Cp as hexEncodeUtf8,Hr as intentHash,Xa as isSettled,$s as joinAsAccount,Qn as joinWithNode,se as jsonCodec,ze as knownRelays,Ye as latestPublishedVersion,ys as learnRelayNodeKey,vs as listDelegatedContexts,Rs as listDelegatedNamespaces,ma as localNodeUrl,Be as login,_n as markContextNonceSpent,Ge as memberAddedOp,Rn as memberCapabilitySetOp,In as memberJoinedOpenOp,At as memberLeftOp,En as memberMetadataSetOp,hn as memberRemovedOp,yn as memberRoleSetOp,Cr as mintDeviceId,vn as namespaceCreatedOp,Nt as namespaceOfGroup,fa as nodeEndpoint,Li as nodeReleaseVersionFromImage,jn as normaliseAccount,ko as ownerOpDigest,Io as ownerOpSigningPayload,ar as ownerPublicKey,br as parseAuthCallback,zi as parseCreationWarrant,Sr as parseDeviceCredential,Qi as parseGovernanceWarrant,$o as parseWarrantNonce,io as persistedNonces,so as pinRelayNodeKey,Zr as presenceStatementBytes,ha as probeNodeHealth,Sd as provisionAgent,Ua as provisionInfo,fu as readCloudLinkCallback,ds as readDelegatedCredential,oo as readDelegatedSession,vu as readEnrolmentCallback,Mn as readPinnedRelayNodeKey,q as readRelayMap,Go as redeemInvitation,xs as relayForContext,Je as relayTransportFetch,Ed as releaseAgent,Dt as rememberGroupNamespace,be as rememberRelay,Dr as reportDataOf,nt as requestBodyHash,Hs as resolveApplicationIdFromRegistry,Fn as resolveRelayFromInvitation,Kn as resolveRelayNodeKey,Y as resolveRoot,Xt as resolveRootPair,pa as rootGuardedOpBytes,Bn as routingProofHeaders,ps as saveDelegatedCredential,ls as saveDelegatedSession,It as selectLatestBundle,hp as shouldRetain,Rr as signAccountHaClaim,ct as signAccountLink,Zt as signAccountLogin,dc as signAccountOwnershipClaim,mn as signCreationWarrant,ti as signDeviceCert,ni as signDeviceScope,wt as signGovernanceWarrant,Wn as signGroupInvitation,Tn as signLoginStatement,zn as signMemberJoinOp,da as signOwnerOpProof,Kt as signRequest,pr as signRequestProof,Ss as signRoutingChallenge,pn as signWarrant,de as signedPath,Vo as signerFromCryptoKey,Pe as signerFromSecret,is as stateHash,Le as subgroupCreation,Sn as subgroupVisibilitySetOp,Jt as subscribePresence,wn as targetApplicationSetOp,ca as teeAdmissionPolicyOp,aa as teeAuthoringPolicyOp,la as teeReleaseAdmissionPolicyOp,oa as transferOwnershipOp,Ei as transportKeyBinding,qi as trustSignedRelease,Mr as trustedMeasurementsFromReleases,Ta as validateAgentId,Qt as verifyDeviceCredential,Id as verifySignedAgentPolicy,$i as verifySignedNodeRelease,fr as withCap,Ht as withRetry,pp as withoutCap};
3
3
  //# sourceMappingURL=index.browser.mjs.map