@calimero-network/mero-js 26.2.0 → 26.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cloud/cloud-client.d.ts +10 -3
- package/dist/cloud/cloud-client.js +29 -10
- package/dist/cloud/link-redirect.d.ts +22 -13
- package/dist/cloud/link-redirect.js +33 -20
- package/dist/cloud/link-state.d.ts +24 -5
- package/dist/cloud/link-state.js +46 -9
- package/dist/index.browser.mjs +2 -2
- package/dist/index.browser.mjs.map +3 -3
- package/dist/index.cjs +81 -26
- package/dist/index.cjs.map +2 -2
- package/dist/index.mjs +81 -26
- package/dist/index.mjs.map +2 -2
- package/dist/namespace-op/namespace-op.d.ts +6 -1
- package/dist/namespace-op/namespace-op.js +6 -1
- package/package.json +1 -1
package/dist/index.browser.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
function cr(t){let e=t.filter(Boolean);if(e.length===0)return;let n=AbortSignal;if(typeof n.any=="function")try{return n.any(e)}catch{}let r=new AbortController,o=i=>{r.abort(i.target.reason);for(let s of e)s.removeEventListener("abort",o)};for(let i of e){if(i.aborted)return AbortSignal.abort(i.reason);i.addEventListener("abort",o,{once:!0})}return r.signal}function lr(t){if(typeof AbortSignal.timeout=="function")return AbortSignal.timeout(t);let e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("Timeout","TimeoutError"))},t),e.signal}var Oo=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 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=g(t,"deviceSecret",32),n=f(Oo,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 No(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 re(t){let e=g(t,"deviceSecret",32),n=f(Oo,e),r=await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),i=(await crypto.subtle.exportKey("jwk",r)).x;return Uint8Array.from(atob(i.replace(/-/g,"+").replace(/_/g,"/")),s=>s.charCodeAt(0))}var ur=new TextEncoder().encode("calimero.auth.request.v2"),Ha=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 rt(t=new Uint8Array(0)){let e=typeof t=="string"?new TextEncoder().encode(t):t;return k(Ha,[e])}async function $t(t){let e=await ne(t.signerSecret),n=await rt(t.body),r=C(t.issuedAt),o=C(t.expiresAt),i=new TextEncoder,s=await k(ur,[i.encode(t.method),i.encode(t.path),n,r,o]),a=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},e,s));return y(f(_o(t.method),_o(t.path),n,r,o,a))}var Ee=t=>new TextEncoder().encode(t),ke="X-Calimero-Proof",Ba=300;async function dr(t){let{method:e,path:n,credential:r}=t;if(!e)throw new Error("signRequestProof needs the method the request will use");if(!n.startsWith("/"))throw new Error(`signRequestProof needs a path, got ${JSON.stringify(n)}`);let o=await rt(t.body),i=Math.floor(t.now??Date.now()/1e3),s=i+(t.validForSeconds??Ba),a=await k(ur,[Ee(e),Ee(n),o,C(i),C(s)]),c=await qa(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=ja(r,"credential");return y(f(d,new Uint8Array([0]),u))}async function qa(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 ja(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 pr(t){if(!t.credential)throw new Error("a proof authorizer needs the `credential` from signDeviceCert");if(!t.deviceSecret&&!t.signer)throw new Error("a proof authorizer needs either `deviceSecret` or `signer`");return async({method:e,path:n,body:r})=>{let o=await dr({method:e,path:n,body:r,credential:t.credential,deviceSecret:t.deviceSecret,signer:t.signer,validForSeconds:t.validForSeconds});return{[ke]:o}}}function de(t){let e=new URL(t,globalThis.location?.href??"http://localhost");return e.pathname+e.search}var Fa=new Set(["token_reuse","token_revoked"]);function Va(t){if(t)try{let e=JSON.parse(t),n=e?.error;if(typeof n=="string"&&n.trim()!=="")return n;let r=n?.message;if(typeof r=="string"&&r.trim()!=="")return r;let o=e?.detail;if(typeof o=="string"&&o.trim()!=="")return o}catch{}}var O=class extends Error{constructor(n,r,o,i,s){let a=Va(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 O{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.reason=n;this.name="AuthRevokedError";this.message=`Authentication revoked (${n}): HTTP ${r} ${o}`}};function Mo(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function Wa(t){let e;try{e=new URL(t,globalThis.location?.href)}catch{return t}return e.search===""&&(e.search=""),e.href}function Lt(t){return Object.keys(t).some(e=>e.toLowerCase()===ke.toLowerCase())}function Ht(t,e){if(t.type==="opaqueredirect"||t.status>=300&&t.status<400)throw new O(0,"Redirect Not Followed",e,t.headers,`the node answered with a redirect; a request carrying ${ke} is not followed to another location`)}var ot=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=Wa(this.buildUrl(e)),a=o??Date.now(),c=this.createAbortSignal(n),u=await this.buildHeaders(n?.headers),d;u instanceof Headers?(d={},u.forEach((b,E)=>{d[E]=b})):d=u;let l=n?.method||"GET";if(this.transport.authorizeRequest){let b=n?.body;if(b!==void 0&&typeof b!="string"&&!(b instanceof Uint8Array))throw new Error("this transport authorizes each request against its body, so the body must be a string or Uint8Array \u2014 a stream cannot be signed, because the signature would have to read bytes the request then cannot send.");Object.assign(d,await this.transport.authorizeRequest({method:l,path:de(s),body:b}))}let p={method:l,headers:d},x=n?.body instanceof ReadableStream||typeof n?.body=="object"&&n?.body!==null&&"getReader"in n.body&&!(n.body instanceof Blob);(n?.body!==void 0&&!x||n?.body!==void 0&&x&&r===0)&&(p.body=n.body);let v;if(r>0&&o!==void 0){let b=n?.timeoutMs||this.transport.timeoutMs;if(b){let E=Date.now()-a,T=Math.max(0,b-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 b=await this.transport.getProof({method:p.method??"GET",path:de(s),body:p.body});b&&(d["X-Calimero-Proof"]=b)}let P=Lt(d);P&&p.redirect!=="error"&&(p.redirect="manual");try{let b=await this.transport.fetch(s,p);if(P&&Ht(b,s),!b.ok){let E=await this.getBodyText(b),T=new O(b.status,b.statusText,s,b.headers,E),H=b.headers.get("x-auth-error");if((b.status===401||b.status===403)&&H&&Fa.has(H)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new oe(H,b.status,b.statusText,s,b.headers,E)}let z=n?.signal?.aborted===!0;if(b.status===401&&this.transport.refreshToken&&H==="token_expired"&&r<1&&!x&&!z)try{let h=this.refreshTokenPromise;h||(h=this.transport.refreshToken(),this.refreshTokenPromise=h);let w=await h;if(!w||w.trim()==="")throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("Refresh token returned empty token");if(!this.transport.onTokenRefresh)throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("onTokenRefresh callback is required when refreshToken is provided. The callback must update the token storage so getAuthToken() returns the new token.");let S=this.onTokenRefreshPromise;S||(S=this.transport.onTokenRefresh(w),this.onTokenRefreshPromise=S),await S,this.refreshTokenPromise=null,this.onTokenRefreshPromise=null;let U=n?.timeoutMs||this.transport.timeoutMs;if(U&&o!==void 0){let M=Date.now()-a;if(U-M<=0)throw T}return this.makeRequest(e,n,r+1,a)}catch(h){throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,h instanceof Error&&h.message.includes("onTokenRefresh")?h:T}throw T}return this.parseResponse(b,n?.parse)}catch(b){throw b instanceof O||b instanceof Error&&b.message.includes("onTokenRefresh")?b:new O(0,"Network Error",s,new Headers,b instanceof Error?b.message:"Unknown error")}}buildUrl(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;let n=this.transport.baseUrl;return e.startsWith("/")?`${n.endsWith("/")?n.slice(0,-1):n}${e}`:`${n.endsWith("/")?n:`${n}/`}${e}`}createAbortSignal(e){let n=[];this.transport.defaultAbortSignal&&n.push(this.transport.defaultAbortSignal),e?.signal&&n.push(e.signal);let r=e?.timeoutMs||this.transport.timeoutMs;return r&&n.push(lr(r)),n.length>0?cr(n):void 0}async buildHeaders(e){let n={...this.transport.defaultHeaders};if(this.transport.getAuthToken)try{let r=await this.transport.getAuthToken();r&&r.trim()!==""&&(n.Authorization=`Bearer ${r}`)}catch{}return e&&(e instanceof Headers?e.forEach((r,o)=>{n[o]=r}):Array.isArray(e)?e.forEach(([r,o])=>{n[r]=o}):Object.assign(n,e)),n}async parseResponse(e,n){switch(n){case"text":return await e.text();case"blob":return await e.blob();case"arrayBuffer":return await e.arrayBuffer();case"response":return e;default:{let r=await e.text();if(!r)return null;try{return JSON.parse(r)}catch{throw new Error(`Expected a JSON response (status ${e.status}) but body was not JSON: ${r.slice(0,200)}`)}}}}async getBodyText(e){try{let n=await e.text();return n.length>65536?n.slice(0,65536)+"...":n}catch{return""}}};function it(t){return new ot(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 it(e)}function Bt(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 it(r)}function gr(t){return typeof window<"u"?Ie(t):Bt(t)}function Ja(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 za(t){let n=250*Math.pow(2,t-1),r=(Math.random()-.5)*.4*n;return Math.max(0,n+r)}async function qt(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,!Ja(r,n-o))throw r;let s=za(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 Qa(t,e={}){return async(...n)=>qt(()=>t(...n),e)}function m(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/${m(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/${m(e)}/clients/${m(n)}`)}async getKeyPermissions(e){return this.httpClient.get(`/admin/keys/${m(e)}/permissions`)}async updateKeyPermissions(e,n){return this.httpClient.put(`/admin/keys/${m(e)}/permissions`,{add:n.add,remove:n.remove})}};var st=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 cp(t){let e=new st;return new pe(e)}function lp(t){let e=new st;return new pe(e)}function up(t){let e=new st;return new pe(e)}function Go(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},pp={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 gp(...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 mp(t){return Object.keys(_).filter(e=>ge(t,_[e]))}function ge(t,e){let n=e>>>0;return(t&n)>>>0===n}function mr(t,e){return(t|e)>>>0}function fp(t,e){return(t&~e)>>>0}var Ya={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 Xa(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 Za(t){if(!t||typeof t!="object")return;let e=t;for(let n of[e.status,e.response?.status,e.statusCode])if(typeof n=="number"&&Number.isFinite(n))return n}function fr(t,e="Request failed"){if(typeof t=="string")return t.trim()||e;if(!t||typeof t!="object")return e;let n=t;for(let r of[n.explanation,n.response?.data?.error,n.response?.data?.message,n.data?.message,n.error,n.message])if(typeof r=="string"&&r.trim())return r;return e}function hr(t){let e=Za(t),n;return e!==void 0?n=Xa(e):t instanceof TypeError?n="unreachable":n="unknown",{kind:n,status:e,retryable:Ya[n],message:fr(t)}}function ec(t){return t.status!=="failed"||!t.retryable}function wp(t){return!ec(t)}var tc={invitation_expired:"expired",invitation_invalid:"invalid",invitation_already_used:"already-used",removed_from_group:"removed",reentry_blocked:"refused"};function nc(t){if(!t||typeof t!="object")return;let e=t;if(typeof e.response?.data?.code=="string")return e.response.data.code;if(typeof e.bodyText=="string")try{let n=JSON.parse(e.bodyText);return typeof n?.code=="string"?n.code:void 0}catch{return}}function rc(t){let e=t.toLowerCase();return e.includes("invitation has expired")||e.includes("invitation expired")||/\binvitation for group .+? expired at \d+/.test(e)?"expired":e.includes("malformed")||e.includes("does not match namespace_id")||e.includes("invalid invitation")||/\binvitation for group .+? is invalid:/.test(e)?"invalid":e.includes("has already used this invitation")?"already-used":/\bwas removed from group\b/.test(e)?"removed":null}var oc=new Set(["already-used","removed"]);function ic(t,e){let{kind:n,status:r}=hr(t),o=rc(e),i=nc(t),s=i?tc[i]:void 0;return s?{reason:s,retryable:!1}:o&&oc.has(o)?{reason:o,retryable:!1}:i==="join_refused_by_member"?{reason:"unknown",retryable:!0}:r===401?{reason:"signed-out",retryable:!0}:r===400?{reason:o??"invalid",retryable:!1}:r===410?{reason:"expired",retryable:!1}:r===403?{reason:"refused",retryable:!1}:r===409?{reason:o??"refused",retryable:!1}:n==="unavailable"?{reason:"no-one-online",retryable:!0}:n==="unreachable"?{reason:"node-unreachable",retryable:!0}:o?{reason:o,retryable:!1}:{reason:"unknown",retryable:!0}}async function Ko(t,e){let{namespaceId:n,invitation:r,teamName:o}=t,i=null;try{await e.join(n,r)}catch(d){i=d}let s=null;try{s=(await e.memberships()).includes(n)}catch{s=null}if(i===null)return{status:"joined",namespaceId:n,teamName:o};if(s===!0)return{status:"already-member",namespaceId:n,teamName:o};let a=fr(i,"Could not join. Check the invitation."),{reason:c,retryable:u}=ic(i,a);return{status:"failed",namespaceId:n,message:a,reason:c,retryable:u}}function A(t){return t?.data}function sc(t,e){let[n,r]=$o(t),[o,i]=$o(e),s=n.split("."),a=o.split("."),c=Math.max(s.length,a.length);for(let p=0;p<c;p++){let x=Lo(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=Lo(u[p],d[p]);if(x!==0)return x}return 0}function $o(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 Lo(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 ac(t,e,n){return qt(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 ac(r.toString(),"versions",n)).json();return(Array.isArray(i)?i:[]).map(s=>s.appVersion).filter(s=>typeof s=="string").sort((s,a)=>sc(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/${m(e)}`))}async listApplications(){return A(await this.httpClient.get("/admin-api/applications"))}async getApplication(e){return A(await this.httpClient.get(`/admin-api/applications/${m(e)}`))}async listApplicationVersions(e){return A(await this.httpClient.get(`/admin-api/applications/${m(e)}/versions`))}async getApplicationAbi(e,n){let r=n?`?service_name=${encodeURIComponent(n)}`:"";return A(await this.httpClient.get(`/admin-api/applications/${m(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/${m(e)}/versions`);return n?.data??n}async getLatestPackageVersion(e){return this.httpClient.get(`/admin-api/packages/${m(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/${m(e)}`))}async getContexts(){return A(await this.httpClient.get("/admin-api/contexts"))}async getContext(e){return A(await this.httpClient.get(`/admin-api/contexts/${m(e)}`))}async getContextsForApplication(e){return A(await this.httpClient.get(`/admin-api/contexts/for-application/${m(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/${m(e)}/identities`))}async getContextIdentitiesOwned(e){return A(await this.httpClient.get(`/admin-api/contexts/${m(e)}/identities-owned`))}async joinContext(e){return A(await this.httpClient.post(`/admin-api/contexts/${m(e)}/join`,{}))}async getContextGroup(e){return A(await this.httpClient.get(`/admin-api/contexts/${m(e)}/group`))}async getContextStorage(e){return A(await this.httpClient.get(`/admin-api/contexts/${m(e)}/storage`))}async syncContext(e){let n=e?`/admin-api/contexts/sync/${m(e)}`:"/admin-api/contexts/sync";await this.httpClient.post(n,{})}async resyncContext(e,n={}){return await this.httpClient.post(`/admin-api/contexts/${m(e)}/resync`,n)??{contextId:e,resyncStarted:!0}}async updateContextApplication(e,n){await this.httpClient.post(`/admin-api/contexts/${m(e)}/application`,n)}async getContextsWithExecutorsForApplication(e){let n=await this.httpClient.get(`/admin-api/contexts/with-executors/for-application/${m(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/${m(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/${m(e)}`;let r=new URLSearchParams({context_id:n.contextId});return`/admin-api/blobs/${m(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/${m(e)}`,{}))}async lookupApplicationAlias(e){return A(await this.httpClient.post(`/admin-api/alias/lookup/application/${m(e)}`,{}))}async deleteContextAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/context/${m(e)}`,{}))}async deleteApplicationAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/application/${m(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/${m(e)}`,{}))}async deleteDeviceAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/device/${m(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/${m(e)}`))}async getNodeIdentity(){return A(await this.httpClient.get("/admin-api/identity"))}async performIntent(e,n){return A(await this.httpClient.post(`/admin-api/contexts/${m(e)}/intents`,n))}async queryContext(e,n){return A(await this.httpClient.post(`/admin-api/contexts/${m(e)}/query`,n))}async getIntentRelay(e){return A(await this.httpClient.get(`/admin-api/contexts/${m(e)}/intents`))}async listNamespacesForApplication(e){return A(await this.httpClient.get(`/admin-api/namespaces/for-application/${m(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/${m(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async createNamespaceInvitation(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${m(e)}/invite`,n??{}))}async admitJoin(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${m(e)}/admit`,n,{timeoutMs:65e3}))}async joinNamespace(e,n){let r=A(await this.httpClient.post(`/admin-api/namespaces/${m(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 Ko({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/${m(e)}/groups`,n??{}))}async listNamespaceGroups(e){return A(await this.httpClient.get(`/admin-api/namespaces/${m(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/${m(e)}/relink`,n??{}))}async rescopeAccountDevice(e,n){return A(await this.httpClient.put(`/admin-api/account/devices/${m(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/${m(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/${m(e)}/account/revoke`,n))}async linkAccountDevice(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${m(e)}/account/link-device`,n))}async getGroupInfo(e){return A(await this.httpClient.get(`/admin-api/groups/${m(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/${m(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async listGroupMembers(e){let n=await this.httpClient.get(`/admin-api/groups/${m(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/${m(e)}/member-devices`;return(await this.httpClient.get(o?`${i}?${o}`:i)).members}async listMemberDevices(e,n={}){let r=new URLSearchParams;n.offset!==void 0&&r.set("offset",String(n.offset)),n.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${m(e)}/member-devices${o?`?${o}`:""}`;return this.httpClient.get(i)}async sealToAccount(e,n,r){return A(await this.httpClient.post(`/admin-api/groups/${m(e)}/accounts/${m(n)}/seal`,r))}async listGroupContexts(e){return A(await this.httpClient.get(`/admin-api/groups/${m(e)}/contexts`))}async addGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${m(e)}/members`,n)}async removeGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${m(e)}/members/remove`,n)}async updateMemberRole(e,n,r){await this.httpClient.put(`/admin-api/groups/${m(e)}/members/${m(n)}/role`,r)}async getMemberCapabilities(e,n){return A(await this.httpClient.get(`/admin-api/groups/${m(e)}/members/${m(n)}/capabilities`))}async setMemberCapabilities(e,n,r){await this.httpClient.put(`/admin-api/groups/${m(e)}/members/${m(n)}/capabilities`,r)}async setDefaultCapabilities(e,n){await this.httpClient.put(`/admin-api/groups/${m(e)}/settings/default-capabilities`,n)}async openToDelegatedExecution(e){let n=await this.getDefaultCapabilities(e);if(ge(n,_.CAN_AUTHOR_ON_BEHALF))return{changed:!1,defaultCapabilities:n};let r=mr(n,_.CAN_AUTHOR_ON_BEHALF);return await this.setDefaultCapabilities(e,{defaultCapabilities:r}),{changed:!0,defaultCapabilities:r}}async grantAuthorship(e,n){let{capabilities:r}=await this.getMemberCapabilities(e,n);if(ge(r,_.CAN_AUTHOR_ON_BEHALF))return{changed:!1,capabilities:r};let o=mr(r,_.CAN_AUTHOR_ON_BEHALF);return await this.setMemberCapabilities(e,n,{capabilities:o}),{changed:!0,capabilities:o}}async setSubgroupVisibility(e,n){await this.httpClient.put(`/admin-api/groups/${m(e)}/settings/subgroup-visibility`,n)}async setTeeAdmissionPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${m(e)}/settings/tee-admission-policy`,n)}async getTeeAdmissionPolicy(e){let n=await this.httpClient.get(`/admin-api/groups/${m(e)}/settings/tee-admission-policy`);return n.data??n}async setTeeAuthoringPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${m(e)}/settings/tee-authoring-policy`,n)}async disableTeeAuthoringPolicy(e,n={}){let r=`/admin-api/groups/${m(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/${m(e)}/transfer-ownership`,n)}async changeNamespaceAdmin(e,n){await this.httpClient.post(`/admin-api/namespaces/${m(e)}/admin`,n)}async ownerDeleteGroup(e,n={}){await this.httpClient.post(`/admin-api/groups/${m(e)}/owner-delete`,n)}async setGroupMetadata(e,n){await this.httpClient.put(`/admin-api/groups/${m(e)}/metadata`,n)}async getGroupMetadata(e){return(await this.httpClient.get(`/admin-api/groups/${m(e)}/metadata`))?.data??null}async setMemberMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${m(e)}/members/${m(n)}/metadata`,r)}async getMemberMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${m(e)}/members/${m(n)}/metadata`))?.data??null}async setContextMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${m(e)}/contexts/${m(n)}/metadata`,r)}async getContextMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${m(e)}/contexts/${m(n)}/metadata`))?.data??null}async syncGroup(e){return A(await this.httpClient.post(`/admin-api/groups/${m(e)}/sync`,{}))}async upgradeGroup(e,n){return A(await this.httpClient.post(`/admin-api/groups/${m(e)}/upgrade`,n))}async getGroupUpgradeStatus(e){return A(await this.httpClient.get(`/admin-api/groups/${m(e)}/upgrade/status`))}async getMigrationStatus(e){return this.httpClient.get(`/admin-api/groups/${m(e)}/migration-status`)}async listNamespaceRevokedDevices(e){return this.httpClient.get(`/admin-api/namespaces/${m(e)}/revoked-devices`)}async getCascadeStatus(e){return A(await this.httpClient.get(`/admin-api/groups/${m(e)}/cascade-status`))}async retryGroupUpgrade(e){return A(await this.httpClient.post(`/admin-api/groups/${m(e)}/upgrade/retry`,{}))}async reparentGroup(e,n){let r=await this.httpClient.post(`/admin-api/groups/${m(e)}/reparent`,n);return r?.data??r}async listSubgroups(e){let n=await this.httpClient.get(`/admin-api/groups/${m(e)}/subgroups`);return n.subgroups??n.data??[]}async detachContextFromGroup(e,n){await this.httpClient.post(`/admin-api/groups/${m(e)}/contexts/${m(n)}/remove`,{})}async createGroupInvitation(e,n){return A(await this.httpClient.post(`/admin-api/groups/${m(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/${m(e)}/join-via-inheritance`,{}))}async getTeeInfo(){return A(await this.httpClient.get("/admin-api/tee/info"))}async teeAttest(e){return A(await this.httpClient.post("/admin-api/tee/attest",e))}async getPeersCount(){return this.httpClient.get("/admin-api/peers")}async getNetworkStatus(){return this.httpClient.get("/admin-api/network/status")}async getUsage(){return this.httpClient.get("/admin-api/usage")}async createGroup(e){return A(await this.httpClient.post("/admin-api/groups",e))}async leaveGroup(e){await this.httpClient.post(`/admin-api/groups/${m(e)}/leave`,{})}async leaveContext(e){await this.httpClient.post(`/admin-api/contexts/${m(e)}/leave`,{})}async leaveNamespace(e){await this.httpClient.post(`/admin-api/namespaces/${m(e)}/leave`,{})}async issueOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${m(e)}/issue-ownership-proof`,n)}async issueNamespaceOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${m(e)}/issue-namespace-ownership-proof`,n)}async setMemberAutoFollow(e,n,r){await this.httpClient.put(`/admin-api/groups/${m(e)}/members/${m(n)}/auto-follow`,r)}async abortMigration(e){return this.httpClient.post(`/admin-api/groups/${m(e)}/migration/abort`,{})}};function kp(t){return Array.from(new TextEncoder().encode(t),e=>e.toString(16).padStart(2,"0")).join("")}function Up(t){return new me(Ie(t))}function Op(t){return new me(Bt(t))}function Ho(t){return new me(gr(t))}function jt(t,e){return new me(t)}var Bo="calimero.cloud.link.pending",yr="link_state";var br=/^[0-9a-f]{64}$/;function qo(t,e){try{let n=localStorage.getItem(t),r=n?JSON.parse(n):{};return Object.fromEntries(Object.entries(r).filter(([,o])=>o&&typeof o.expiresAt=="number"&&o.expiresAt>e))}catch{return{}}}function jo(t,e){try{localStorage.setItem(t,JSON.stringify(e))}catch{}}function at(t,e){let n=Date.now(),r=qo(t,n),o=crypto.getRandomValues(new Uint8Array(16)),i=Array.from(o,s=>s.toString(16).padStart(2,"0")).join("");return r[i]={...e,expiresAt:n+6e5},jo(t,Object.fromEntries(Object.entries(r).slice(-20))),i}function Pe(t,e){let n=qo(t,Date.now());if(!e||!Object.prototype.hasOwnProperty.call(n,e))return null;let r=n[e];return delete n[e],jo(t,n),r}function Ft(t,e){if(!br.test(t))throw new Error("accountId must be 64 lowercase hex characters");let n=new URL(e);return n.searchParams.set(yr,at(Bo,{account:t})),n.toString()}function Te(t){return Pe(Bo,new URLSearchParams(t).get(yr))}function Fo(t){let e=new URLSearchParams(t);e.delete(yr);let n=e.toString();return n?`?${n}`:""}var Vo="calimero.auth.login.pending",Wo="auth_state";function wr(t,e={}){try{let n=t.indexOf("#");if(n===-1)return null;let r=t.substring(n+1),o=new URLSearchParams(r),i=o.get("access_token");return i?!e.allowUnsolicited&&!Pe(Vo,cc(t,n))?(console.warn("[mero-js] ignoring auth callback tokens: they answer no login begun in this browser"),null):{accessToken:i,refreshToken:o.get("refresh_token")??"",applicationId:o.get("application_id")??"",contextId:o.get("context_id")??"",contextIdentity:o.get("context_identity")??"",nodeUrl:o.get("node_url")??""}:null}catch{return null}}function cc(t,e){let n=t.indexOf("?");return n===-1||n>e?null:new URLSearchParams(t.substring(n+1,e)).get(Wo)}function Ar(t,e){let n=new URL(e.callbackUrl);n.searchParams.set(Wo,at(Vo,{}));let r=new URLSearchParams;return r.set("callback-url",n.toString()),e.permissions&&e.permissions.length>0&&r.set("permissions",e.permissions.join(",")),r.set("mode",e.mode),e.packageName&&(r.set("package-name",e.packageName),e.packageVersion&&r.set("package-version",e.packageVersion),e.registryUrl&&r.set("registry-url",e.registryUrl)),`${t.replace(/\/+$/,"")}/auth/login?${r.toString()}`}function Vt(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 lc(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 Wt(t){let e=t.ttlSeconds??120,n=t.now??(()=>Math.floor(Date.now()/1e3));return async r=>{let o=n();return Vt({credential:t.credential,session:t.session,request:await $t({method:r.method,path:r.path,body:lc(r.body),issuedAt:o,expiresAt:o+e,signerSecret:t.signerSecret})})}}var Jt=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 Jt(o.code??-1,o.message??o.type??"RPC error",o.data,o.type)}return r.result}var ct=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 uc=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function Jo(t){return t.type!==void 0&&uc.has(t.type)}var dc=new Set(["token_reuse","token_revoked"]),pc=new Set([401,403]),gc=1e4;function zo(t){let e=t.headers.get("x-auth-error");return!e||!pc.has(t.status)?null:dc.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=>{Jo(r)&&e(r)};return this.on("event",n),()=>this.off("event",n)}emit(e,n){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(n)}catch{}}async connect(){if(this.abortController&&!this.closed)return;this.closed=!1;let e=new AbortController;this.abortController=e;try{let n=`${this.baseUrl}/sse`,r={...await this.authorize({method:"GET",path:de(n)}),Accept:"text/event-stream"},o=Lt(r),i=await this.fetchImpl(n,{headers:r,signal:e.signal,...o&&{redirect:"manual"}});if(o&&Ht(i,n),!i.ok){let s=zo(i),a=await i.text().catch(()=>{});throw s?new oe(s,i.status,i.statusText,n,i.headers,a):new O(i.status,i.statusText,n,i.headers,a)}if(!i.body)throw new Error("SSE response has no body");this.readStream(i.body,e).catch(s=>{if(this.superseded(e))return;let a=s instanceof Error?s:new Error(String(s));this.emit("error",a),this.scheduleReconnect()})}catch(n){if(this.superseded(e))return;let r=n instanceof Error?n:new Error(String(n));if(this.emit("error",r),r instanceof oe)return;this.scheduleReconnect()}}superseded(e){return this.closed||e.signal.aborted||this.abortController!==e}async readStream(e,n){let r=e.getReader(),o=new TextDecoder,i="";try{for(;;){let{done:s,value:a}=await r.read();if(s)break;i+=o.decode(a,{stream:!0});let c=i.split(`
|
|
2
|
-
`);i=c.pop()??"";for(let u of c)if(u.startsWith("data:")){let d=u.slice(5).trim();d&&this.handleMessage(d)}}if(i+=o.decode(),i.startsWith("data:")){let s=i.slice(5).trim();s&&this.handleMessage(s)}}catch(s){if(this.superseded(n))return;let a=s instanceof Error?s:new Error(String(s));this.emit("error",a)}this.superseded(n)||this.scheduleReconnect()}handleMessage(e){try{let n=JSON.parse(e);if(n.type==="connect"&&n.session_id){let o=n.session_id;if(this.sessionId=o,this.presence.clear(),this.subscribedContextIds.size===0&&this.subscribedGroupIds.size===0){this.emit("connect",o);return}this.postSubscription("subscribe",{contextIds:[...this.subscribedContextIds],groupIds:[...this.subscribedGroupIds]}).then(i=>{this.closed||this.sessionId!==o||(this.emit("connect",o),i&&this.emit("error",i))});return}if(!n.result)return;let r=n.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),i=new TextDecoder().decode(o);r=JSON.parse(i)}catch{}if(n.result.contextId){n.result.type==="Ephemeral"&&this.notePresence(n.result.contextId,r),this.emit("event",{contextId:n.result.contextId,type:n.result.type,data:r});return}n.result.groupId&&this.emit("event",{groupId:n.result.groupId,type:n.result.type,data:r})}catch{}}async subscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>!this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>!this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.add(i);for(let i of n.groupIds??[])this.subscribedGroupIds.add(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("subscribe",{contextIds:r,groupIds:o})}isSubscribed(e){return this.subscribedContextIds.has(e)}presenceSeed(e){let n=Date.now();return[...this.presence.get(e)?.values()??[]].map(({data:r,at:o})=>({...r,ageMs:(typeof r.ageMs=="number"?r.ageMs:0)+(n-o)}))}notePresence(e,n){if(!this.subscribedContextIds.has(e))return;let r=n;if(!r||typeof r.author!="string")return;let o=this.presence.get(e);o||this.presence.set(e,o=new Map),r.removed?o.delete(r.author):o.set(r.author,{data:r,at:Date.now()})}async unsubscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.delete(i),this.presence.delete(i);for(let i of n.groupIds??[])this.subscribedGroupIds.delete(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("unsubscribe",{contextIds:r,groupIds:o})}async sendSubscription(e,n){let r=await this.postSubscription(e,n);r&&this.emit("error",r)}async postSubscription(e,n){let r=new AbortController,o=setTimeout(()=>r.abort(new DOMException(`SSE ${e} timed out`,"TimeoutError")),gc);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=Lt(c),d=await this.fetchImpl(s,{method:"POST",headers:c,body:a,signal:r.signal,...u&&{redirect:"manual"}});if(u&&Ht(d,s),!d.ok){let l=zo(d),p=await d.text().catch(()=>{});return l?new oe(l,d.status,d.statusText,`${this.baseUrl}/sse/subscription`,d.headers,p):new O(d.status,d.statusText,`${this.baseUrl}/sse/subscription`,d.headers,p)}return null}catch(i){return i instanceof Error?i:new Error(`SSE ${e} failed`)}finally{clearTimeout(o)}}forceReconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.sessionId=null,this.connect()}scheduleReconnect(){this.closed||(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.forceReconnect()},this.reconnectDelayMs))}close(){this.closed=!0,this.abortController&&(this.abortController.abort(),this.abortController=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.sessionId=null,this.subscribedContextIds.clear(),this.subscribedGroupIds.clear()}};var zt=class zt{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),zt.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()}};zt.MAX_BACKOFF_MS=3e4;var ie=zt;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 lt=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 Qt(this.sse,e,n,r)}};function Qt(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 mc=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function Qo(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 De(t,e="secret"){let n=g(t,e,32),r=f(mc,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 Qo(s)}return Xo(o,i)}async function Yo(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 Xo(t,n)}function Xo(t,e){return{publicKey:e,async sign(n){try{return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},t,n))}catch(r){throw Qo(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 De(t,n);throw new Error(`${n} or signer is required`)}var fc=new TextEncoder().encode("calimero.mdma.account-ownership-claim.v1\0"),hc=6e4,Zo=5*6e4,ei=1024,ni="mdma:enable-ha-namespace",ri="mdma:enable-ha-namespace-as-account";function ti(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 oi(t,e,n,r){if(r!==void 0&&!(r.length>0&&r.length<=ei))throw new Error(`relayUrl must be a non-empty string of at most ${ei} characters`);let o=t.ttlMs??hc;if(!(o>0&&o<=Zo))throw new Error(`ttlMs must be in (0, ${Zo}]`);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(fc,l));return{kind:"account",credential:t.credential,signed_payload:ti(l),signature:ti(p)}}async function yc(t){if(!t.subject)throw new Error("subject must be the cloud login email");return oi(t,ni,t.subject)}async function Rr(t){return oi(t,ri,void 0,t.relayUrl)}var bc=new TextEncoder().encode("calimero.device.cert.v1"),wc=new TextEncoder().encode("calimero.account.genesis.v1"),Ac=new TextEncoder().encode("calimero.device.id.v1"),Ue=2,xc=237;async function Cr(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(Ac,[n,e]);return y(f(e,r.subarray(0,16)))}async function Yt(t){return k(bc,[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 ii(t){return f(new Uint8Array([Ue]),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 si(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=g(e.publicKey,"signer.publicKey",32),r=await F(e.publicKey),o=0,i=await Yt({account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch}),s=await e.sign(i),a=ii({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=g(t,"credential",xc);if(e[0]!==Ue)throw new Error(`this credential has account genesis version ${e[0]}, not ${Ue} \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 Xt(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=g(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 No(e.rootPublicKey,g(e.signature,"signature",64),await Yt(e)))throw new Error(`the root key of account ${e.account} did not sign this certificate`);return e}async function Zt(t){return F(y(await re(t)))}async function F(t){return y(await k(wc,[f(new Uint8Array([Ue]),g(t,"rootPublicKey",32))]))}var vc=new TextEncoder().encode("calimero.device.scope.v1");async function Er(t){return k(vc,[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 ai(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=g(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([Ue]),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 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 Rc=new TextEncoder().encode("calimero.mdma.account-link.v1\0"),Cc=new TextEncoder().encode("calimero.mdma.account-login.v1\0"),Oe=256,ci=Oe/32,Ir=(Oe+ci)/11;async function li(){let t=crypto.getRandomValues(new Uint8Array(Oe/8));return fi(y(t),await yi(t))}async function ui(t){let e=hi(t);return fi(y(await bi(e)),e.join(" "))}async function Pr(t){return g(t,"secret",32),{secret:t,publicKey:y(await re(t)),accountId:await Zt(t)}}async function di(){let t=crypto.getRandomValues(new Uint8Array(Oe/8)),e=await yi(t);return{...await gi(t),phrase:e}}async function pi(t){return gi(await bi(hi(t)))}async function gi(t){let e=await De(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 De(t,"rootSecret"):t;return mi(e)}async function en(t,e){return mi(await I(t,e,"rootSecret"))}async function mi(t){return{signer:t,publicKey:t.publicKey,accountId:await F(t.publicKey)}}async function ut(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(Rc,new TextEncoder().encode(t.nonce)));return xi(n)}async function tn(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(Cc,new TextEncoder().encode(t.nonce)));return xi(n)}async function fi(t,e){return{...await Pr(t),phrase:e}}function hi(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 yi(t){let e=Ai(t)+await wi(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 bi(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(Oe/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(Oe)!==await wi(n))throw new Error("recovery phrase checksum failed \u2014 check for a mistyped or transposed word");return n}async function wi(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return Ai(e).slice(0,ci)}function Ai(t){let e="";for(let n of t)e+=n.toString(2).padStart(8,"0");return e}function xi(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var Sc=new TextEncoder().encode("calimero.tee-attest.key-binding.v1"),nn=new TextEncoder().encode("MOCK_TDX_QUOTE_V1"),Ec=568;function kc(...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 Ic(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 Pc(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 rn(t){let e=await crypto.subtle.digest("SHA-256",kc(Sc,new Uint8Array(32),t));return new Uint8Array(e)}function Dr(t){let e=t.length>=nn.length&&Tr(t.subarray(0,nn.length),nn),n=e?nn.length:Ec;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 on(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=Pc(a.boundPublicKey,"boundPublicKey"),u=Ic(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 rn(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 rn(c)))throw new Error("the quote does not bind the key the relay named: refusing it");return{nodeKey:y(c),mock:l}}var Tc="Noise_NK_25519_AESGCM_SHA256",Ur=32,Dc=16,Uc=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Nr=class t{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(Tc),n=new Uint8Array(32);return n.set(e),new t(n)}async mixHash(e){this.h=await Oc(f(this.h,e))}async mixKey(e){let[n,r]=await Ri(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:vi(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:vi(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),n}split(){return Ri(this.ck,new Uint8Array)}};async function Ci(t,e,n){let r=await Nr.initialize();await r.mixHash(e),await r.mixHash(t);let o=await Ne(n);return await r.mixHash(o.publicKey),await r.mixKey(await dt(o.privateKey,t)),{message1:f(o.publicKey,await r.encryptAndHash(new Uint8Array)),async finish(s){if(s.length<Ur+Dc)throw new Error("Noise: message 2 is too short");let a=s.slice(0,Ur);return await r.mixHash(a),await r.mixKey(await dt(o.privateKey,a)),{payload:await r.decryptAndHash(s.slice(Ur)),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(Uc,t),{name:"X25519"},!0,["deriveBits"]),n=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Nc(n.x)}}async function dt(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 vi(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}async function Oc(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}async function Or(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 Ri(t,e){let n=await Or(t,e),r=await Or(n,new Uint8Array([1])),o=await Or(n,f(r,new Uint8Array([2])));return[r,o]}function Nc(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 Ii="/sealed/v2/handshake",Pi="/sealed/v2",gt="application/vnd.calimero.sealed",_r=2,_c=new TextEncoder().encode("calimero/sealed-http/v2"),pt=16,Mc=1+pt+8,Gc=0,Kc=1,$c=2,Lc=1+64*1024+16,Hc=1024,Bc=6e4,qc="calimero.tee-attest.transport-key.v1",jc=[101,204,205,304],Ti=new TextEncoder,mt=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},_e=class extends Error{constructor(n,r,o,i){super(o);this.status=n;this.code=r;this.retryAfterMs=i;this.name="SealedTransportError"}};async function Di(t,e){let n=await crypto.subtle.digest("SHA-256",f(Ti.encode(qc),t,e));return new Uint8Array(n)}async function Ui(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 Di(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 Oi({baseUrl:t.baseUrl,transportPublicKey:()=>Ui(r,t.verify,{applicationId:t.applicationId,applicationHash:t.applicationHash}),fetch:e})}function Oi(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 Ei(o,r,await Si(s))}catch(l){if(!(l instanceof mt)||!i)throw l;return s=Promise.resolve().then(i),Ei(o,r,await Si(s))}},u=async()=>{let l=a??d(void 0),p=await l;if(Date.now()<p.renewAt)return[p,l];let x=d(l);return[await x,x]},d=l=>{if(a===l){let p=c();a=p,p.catch(()=>{a===p&&(a=void 0)})}return a};return async(l,p)=>{let x=new Request(l,p),v=new URL(x.url);if(v.origin!==e.origin||!v.pathname.startsWith(`${n}/`))throw new Error(`Refusing to send ${v.href} outside the sealed node at ${t.baseUrl}`);let P=[];x.headers.forEach((h,w)=>P.push([w,h]));let b={method:x.method,path:v.pathname.slice(n.length)+v.search,headers:P},E=new Uint8Array(await x.arrayBuffer()),T=async h=>{let{requestId:w,header:S,envelope:U}=await Vc(h,b,E),M=await o(`${r}${Pi}`,{method:"POST",headers:{"content-type":gt},body:U,signal:x.signal});if(M.headers.get("content-type")!==gt)throw await _i(M);return Jc(M,h.responseKey,S,w)},[H,z]=await u();try{return await T(H)}catch(h){if(!(h instanceof _e)||h.code!=="unknown_session")throw h;return T(await d(z))}}}async function Si(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function Ei(t,e,n){try{return await ki(t,e,n)}catch(r){if(!(r instanceof _e)||r.code!=="busy")throw r;return await new Promise(o=>setTimeout(o,r.retryAfterMs??1e3)),ki(t,e,n)}}async function ki(t,e,n){let r=await Ci(n,_c),o=await t(`${e}${Ii}`,{method:"POST",headers:{"content-type":gt},body:f(new Uint8Array([_r]),n,r.message1)});if(o.headers.get("content-type")!==gt)throw await _i(o);let i=await Qc(o,Hc);return Fc(r,i)}async function Fc(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!==pt+4)throw new Error("The handshake reply is malformed");let i=r.slice(0,pt),s=new DataView(r.buffer,r.byteOffset).getUint32(pt,!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-Bc,header(u){let d=new Uint8Array(Mc);return d[0]=_r,d.set(i,1),new DataView(d.buffer).setBigUint64(1+pt,BigInt(u),!1),d}}}async function Vc(t,e,n){let r=t.nextRequestId;t.nextRequestId+=1;let o=t.header(r),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:Ni(r,0),additionalData:o},t.requestKey,Wc(e,n));return{requestId:r,header:o,envelope:f(o,new Uint8Array(i))}}function Ni(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 Wc(t,e){let n=Ti.encode(JSON.stringify(t)),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,n.length,!1),f(r,n,e)}async function Jc(t,e,n,r){if(!t.body)throw new Error("The sealed response has no body");let o=zc(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:Ni(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!==Gc)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(jc.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===Kc?d.enqueue(l.data):l.kind===$c?(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 zc(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>Lc)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 Qc(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 _i(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 mt;let r=Number(t.headers.get("retry-after")),o=Number.isFinite(r)&&r>0?Math.min(r,5)*1e3:void 0;return new _e(t.status,e,n,o)}var Yc=/^[0-9a-f]{96}$/,Xc=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function ht(t){let e=Me(t.allowedMrtd??[],"allowedMrtd"),n=(t.allowedMeasurements??[]).map((a,c)=>{let u=`allowedMeasurements[${c}]`;return Xc.map(d=>Me([a?.[d]??""],`${u}.${d}`)[0]).join()}),r=[Me(t.allowedRtmr0??[],"allowedRtmr0"),Me(t.allowedRtmr1??[],"allowedRtmr1"),Me(t.allowedRtmr2??[],"allowedRtmr2"),Me(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=el(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=Zc(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 Me(t,e){return t.map(n=>{let r=n.trim().toLowerCase();if(!Yc.test(r))throw new Error(`${e} holds ${JSON.stringify(n)}, which is not a 48-byte hex measurement`);return r})}function Zc(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 el(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 tl=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],ft="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!==ft&&!n)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(ft)}, or pass allowDebugProfile to test`);let u=(c.allowed_tcb_statuses??["uptodate"]).map(d=>nl(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 nl(t,e){let n=tl.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 Mi=[{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"]}],Gi=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var rl="1.2.840.10045.2.1",ol={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},il={"P-256":32,"P-384":48},sl={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function Ki(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 Ke(t){let e=Ki(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function G(t){let e=[];for(let n=t.start;n<t.end;){let r=Ki(t.bytes,n,t.end);e.push(r),n=r.end}return e}function N(t,e,n){if(!t||t.tag!==e)throw new Error(`${n} is not where it should be`);return t}function ae(t){return t.bytes.slice(t.start,t.end)}function sn(t){return t.bytes.slice(t.offset,t.end)}function Ge(t){let e=ae(N(t,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let n=[],r=0;for(let s of e)r=r*128+(s&127),s&128||(n.push(r),r=0);let o=n.shift();return[...o<80?[Math.floor(o/40),o%40]:[2,o-80],...n].join(".")}function al(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 Gr(t){try{let[e,n,r,...o]=G(N(Ke(t),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let i=G(N(e,48,"The signed part")),s=i[0]?.tag===160?1:0,[a,c,u,d,l,p,...x]=i.slice(s);N(a,2,"The serial number");let v=Ge(G(N(n,48,"The signature algorithm"))[0]);if(Ge(G(N(c,48,"The signature algorithm"))[0])!==v)throw new Error("it names two different signature algorithms");let b=sl[v];if(!b)throw new Error(`it is signed with ${v}, not ECDSA with SHA-256 or SHA-384`);let[E,T]=G(N(d,48,"The validity")).map(al);if(T===void 0)throw new Error("its validity is incomplete");let[H,z]=G(N(p,48,"The public key"));N(z,3,"The public key");let[h,w]=G(N(H,48,"The key algorithm"));if(Ge(h)!==rl)throw new Error("its key is not an elliptic-curve key");let S=ol[Ge(w)];if(!S)throw new Error("its key is on a curve other than P-256 or P-384");let U=new Map,M=x.find(ee=>ee.tag===163);if(M){let[ee]=G(M);for(let te of G(N(ee,48,"The extensions"))){let Se=G(N(te,48,"An extension"));if(Se.length===3)N(Se[1],1,"An extension's critical flag");else if(Se.length!==2)throw new Error("it has a malformed extension");let ar=Ge(Se[0]);if(U.has(ar))throw new Error(`it has extension ${ar} twice`);U.set(ar,ae(N(Se[Se.length-1],4,"An extension value")))}}let Q=ae(N(r,3,"The signature"));if(Q[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:sn(e),signatureHash:b,signature:Q.slice(1),issuer:sn(N(u,48,"The issuer")),subject:sn(N(l,48,"The subject")),notBefore:E,notAfter:T,spki:sn(p),curve:S,extensions:U}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function $i(t){return G(N(Ke(t),48,"The list")).map(Ge)}function cl(t,e){let n=il[e],r=G(N(Ke(t),48,"The signature"));if(r.length!==2)throw new Error("The signature is not an ECDSA signature");let o=new Uint8Array(n*2);return r.forEach((i,s)=>{let a=ae(N(i,2,"The signature"));if(a.length===0||a[0]&128)throw new Error("The signature is not an ECDSA signature");for(;a.length>1&&a[0]===0;)a=a.subarray(1);if(a.length>n)throw new Error("The signature is not an ECDSA signature");o.set(a,s*n+n-a.length)}),o}async function an(t,e,n,r,o){let i;try{i=cl(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 Kr(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 ll="2.5.29.17",ul="2.5.29.37",dl="1.3.6.1.5.5.7.3.3",pl="1.3.6.1.4.1.57264.1.8",gl="1.3.6.1.4.1.57264.1.1",ml=134,fl=12,hl=48,yl=new TextEncoder,$e=t=>new TextDecoder().decode(t);async function cn(t,e,n,r){let{base64Signature:o,cert:i,rekorBundle:s}=xl(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=Kr($e(V(i,"The bundle certificate")),"The bundle certificate"),d=Gr(u),l=Gi.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=yl.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await an(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(!Bi(v,l.validFor))throw new Error(`Rekor log ${l.baseUrl} was not in use at ${yt(v)}, when the entry says it was logged`);let P=vl(a.body),b=y(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(P.hash!==b)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!$r(V(P.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let E=Kr($e(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 an(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 bl(d,v),Al(d,n),{integratedTime:a.integratedTime}}async function bl(t,e){if(!Hi(t,e))throw new Error(`The signing certificate was valid ${yt(t.notBefore)} to ${yt(t.notAfter)}, not at ${yt(e)} when Rekor logged it`);let n=[];for(let r of Mi){let o=r.certChain.map(s=>Gr(V(s,"A Fulcio certificate")));if(!await Li(t,o[0]))continue;let i=await wl(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 ${yt(e)}: ${n.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function wl(t,e,n){if(!Bi(n,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of t.entries()){if(!Hi(o,n))return`its certificate ${r} was not valid then`;let i=t[r+1]??o;if(!await Li(o,i))return`its certificate ${r} is not signed by the next`}}async function Li(t,e){return $r(t.issuer,e.subject)?an(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function Al(t,e){let n=t.extensions.get(ll);if(!n)throw new Error("The signing certificate names no identity");let r=G(N(Ke(n),hl,"The subject alternative name")),o=r.filter(u=>u.tag===ml).map(u=>$e(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(pl),s=t.extensions.get(gl),a=i?$e(ae(N(Ke(i),fl,"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(ul);if(!c||!$i(c).includes(dl))throw new Error("The signing certificate is not for code signing")}function xl(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 vl(t){let e;try{e=JSON.parse($e(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 Hi(t,e){return t.notBefore<=e&&e<=t.notAfter}function Bi(t,e){return Date.parse(e.start)<=t&&(e.end===void 0||t<=Date.parse(e.end))}function yt(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"}),Rl=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],ln="https://cloud.calimero.network";async function ji(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await cn(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=>Rl.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 un(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 Fi(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 dn(t,e={}){let n=await Wi(t,e.fetch??fetch);if(n===void 0)throw new Error(`${Vi(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 Vi(t){return`${t.replace(/\/+$/,"")}/admin-api/tee/info`}async function Wi(t,e){let n=Vi(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 Fi(o)}function pn(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${bt(e,"version")}`}async function Ji(t){let e=bt(t.minReleaseVersion,"minReleaseVersion"),n=bt(t.release?.version,"The release version"),r=await ji(t.release.publishedMrtds,t.release.bundle,{expectedVersion:n,identity:t.identity,issuer:t.issuer});if(Sl(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 gn(t){return bt(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async n=>{let r=await Ji({release:await t.release(),profile:t.profile,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer});return ht({dcapVerify:t.dcapVerify,fetchCollateral:t.fetchCollateral,now:t.now,...r})(n)},{includeCollateral:!0})}function Cl(t){let{baseUrl:e,releaseSource:n,releaseVersion:r,applicationId:o,applicationHash:i,fetch:s,...a}=t;r!==void 0&&bt(r,"releaseVersion");let c=s??((d,l)=>fetch(d,l));return fe({baseUrl:e,verify:gn({...a,release:async()=>{let d=r===void 0?await dn(e,{fetch:c}):await Wi(e,c)??r;return typeof n=="function"?n({baseUrl:e,version:d,fetch:c}):un(pn(n??ln,d),{fetch:c})}}),applicationId:o,applicationHash:i,fetch:c})}var zi=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function bt(t,e){let n=typeof t=="string"?zi.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 Sl(t,e){let[n,r]=qi(t),[o,i]=qi(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 qi(t){let e=zi.exec(t);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var El=new TextEncoder().encode("calimero.warrant.v2"),kl=new TextEncoder().encode("calimero.warrant.intent.v1"),Qi=64,Yi=256;async function Hr(t,e){let n=new TextEncoder().encode(JSON.stringify(e));return k(kl,[new TextEncoder().encode(t),n])}async function mn(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=Br(t.releaseVersion??""),a=ce(t.accountHeads,"accountHeads"),c=ce(t.governanceFloor,"governanceFloor"),u=await I(t.deviceSecret,t.signer,"deviceSecret"),d=g(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(El,[e,n,d,r,o,i,s,l,p,C(a.length),...a,C(c.length),...c,x,v]),b=wt(await u.sign(P));return y(f(e,n,d,r,o,i,R(s.length),s,R(l.length),l,p,R(a.length),...a,R(c.length),...c,x,v,b))}function wt(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 Il(e.length),e}function Il(t){if(t>Yi)throw new Error(`releaseVersion is ${t} bytes, over the ${Yi} a node accepts`)}function ce(t,e){let n=t??[];if(n.length>Qi)throw new Error(`${e} cites ${n.length} heads, over the ${Qi} a node accepts`);return n.map((r,o)=>g(r,`${e}[${o}]`,32))}var Pl=new TextEncoder().encode("calimero.context-creation-warrant.v1"),Tl=new TextEncoder().encode("calimero.context-creation.init.v1"),fn=256;async function qr(t){let e=new TextEncoder().encode(JSON.stringify(t));return k(Tl,[e])}async function Dl(t){return k(Pl,[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 hn(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=Xi(t.serviceName,"serviceName"),c=Xi(t.name,"name"),u=ce(t.accountHeads,"accountHeads"),d=ce(t.governanceFloor,"governanceFloor"),l=await I(t.deviceSecret,t.signer,"deviceSecret"),p=g(l.publicKey,"signer.publicKey",32),x=await qr(t.initArgs),v=await Dl({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=wt(await l.sign(v));return{warrant:y(f(e,n,r,p,o,i,s,Zi(a),Zi(c),x,R(u.length),...u,R(d.length),...d,C(t.nonce),C(t.notAfter),P)),seed:y(n)}}function es(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>fn)throw new Error(`${l} is ${x} bytes, over the ${fn} 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 Xi(t,e){if(t===void 0)return null;let n=new TextEncoder().encode(t);if(n.length>fn)throw new Error(`${e} is ${n.length} UTF-8 bytes, over the ${fn} a node accepts`);return n}function Zi(t){return t===null?new Uint8Array([0]):f(new Uint8Array([1]),R(t.length),t)}var Ul=new TextEncoder().encode("calimero.governance-warrant.v1"),Ol=new TextEncoder().encode("calimero.governance-warrant.op.v1"),Nl={group:0,root:1};async function jr(t){return k(Ol,[new Uint8Array([Fr(t.kind)]),t.bytes])}async function _l(t){return k(Ul,[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 At(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=ce(t.accountHeads,"accountHeads"),s=ce(t.governanceFloor,"governanceFloor"),a=Fr(t.op.kind),c=await I(t.deviceSecret,t.signer,"deviceSecret"),u=g(c.publicKey,"signer.publicKey",32),d=await jr(t.op),l=await _l({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=wt(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 ts(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=Nl[t];if(e===void 0)throw new Error(`op kind must be 'group' or 'root', got ${String(t)}`);return e}var Ml={Admin:0,Member:1,ReadOnly:2},K={MemberAdded:1,MemberRemoved:2,MemberLeft:3,MemberRoleSet:4,MemberCapabilitySet:5,DefaultCapabilitiesSet:6,TargetApplicationSet:7,ContextDetached:9,SubgroupVisibilitySet:10,GroupMetadataSet:11,MemberMetadataSet:12,ContextMetadataSet:13,ContextCapabilityGranted:16,ContextCapabilityRevoked:17},xt={GroupCreated:0,GroupReparented:1,GroupDeleted:2,MemberJoinedOpen:7,NamespaceCreatedV2:9},Gl=new TextEncoder().encode("calimero.namespace.id.v1"),Wr=new Uint8Array(32),yn=R(0);function rs(t){let e=Ml[t];if(e===void 0)throw new Error(`role must be Admin, Member or ReadOnly, got ${String(t)}`);return new Uint8Array([e])}function D(t){return new Uint8Array([t])}function Le(t,e){return{kind:"group",bytes:f(D(K.MemberAdded),g(t,"member",32),rs(e))}}function bn(t){return{kind:"group",bytes:f(D(K.MemberRemoved),g(t,"member",32),Wr,yn)}}function vt(t){return{kind:"group",bytes:f(D(K.MemberLeft),g(t,"member",32),Wr,yn)}}function wn(t,e){return{kind:"group",bytes:f(D(K.MemberRoleSet),g(t,"member",32),rs(e))}}var Kl=new TextEncoder().encode("calimero.subgroup.id.v1");async function Jr(t,e,n,r){return y(await k(Kl,[g(t,"admin",32),g(e,"parentId",32),new Uint8Array([n?1:0]),g(r,"salt",32)]))}function ns(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 An(t){return{kind:"group",bytes:f(D(K.TargetApplicationSet),Wr,g(t.applicationId,"applicationId",32),ns(t.package,"package"),ns(t.version,"version"))}}function He(t){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`capabilities must be a u32 bit mask, got ${String(t)}`);if(ge(t,_.CAN_AUTHOR_ON_BEHALF))throw new Error("capabilities may not include CAN_AUTHOR_ON_BEHALF (512): a relay never carries a change to it");return{kind:"group",bytes:f(D(K.DefaultCapabilitiesSet),R(t))}}function zr(t){return{kind:"root",bytes:f(D(xt.GroupCreated),g(t.groupId,"groupId",32),g(t.parentId,"parentId",32),D(t.restricted?1:0),g(t.admin,"admin",32),g(t.salt,"salt",32))}}async function Be(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 xn(t,e){return{kind:"root",bytes:f(D(xt.GroupReparented),g(t,"childGroupId",32),g(e,"newParentId",32))}}function vn(t){return{kind:"root",bytes:f(D(xt.GroupDeleted),g(t,"rootGroupId",32),yn,yn)}}async function Rn(t,e){return y(await k(Gl,[g(t,"founder",32),g(e,"salt",32)]))}function Cn(t){let e=j(t.credential,"credential");if(e.length===0)throw new Error("credential must be the founder's AccountProof<DeviceCert>, got nothing");return{kind:"root",bytes:f(D(xt.NamespaceCreatedV2),g(t.founder,"founder",32),e,g(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?D(0):f(D(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 $l(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 Sn(t,e){return{kind:"group",bytes:f(D(K.MemberCapabilitySet),g(t,"member",32),R($l(e,"capabilities")))}}function En(t){return{kind:"group",bytes:f(D(K.ContextDetached),g(t,"contextId",32))}}function kn(t){if(t!=="open"&&t!=="restricted")throw new Error(`mode must be open or restricted, got ${String(t)}`);return{kind:"group",bytes:f(D(K.SubgroupVisibilitySet),D(t==="open"?0:1))}}function qe(t={}){return{kind:"group",bytes:f(D(K.GroupMetadataSet),Qr(t.name),Yr(t.data))}}function In(t,e={}){return{kind:"group",bytes:f(D(K.MemberMetadataSet),g(t,"member",32),Qr(e.name),Yr(e.data))}}function Pn(t,e={}){return{kind:"group",bytes:f(D(K.ContextMetadataSet),g(t,"contextId",32),Qr(e.name),Yr(e.data))}}function os(t){if(!Number.isInteger(t)||t<1||t>255)throw new Error(`capability must be a non-zero u8, got ${String(t)}`);return D(t)}function is(t,e,n){return{kind:"group",bytes:f(D(K.ContextCapabilityGranted),g(t,"contextId",32),g(e,"member",32),os(n))}}function ss(t,e,n){return{kind:"group",bytes:f(D(K.ContextCapabilityRevoked),g(t,"contextId",32),g(e,"member",32),os(n))}}function Tn(t){return{kind:"root",bytes:f(D(xt.MemberJoinedOpen),g(t.member,"member",32),g(t.groupId,"groupId",32),j(t.credential,"credential"))}}var Dn=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"}},Ll=t=>new Promise(e=>setTimeout(e,t));function Hl(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/${m(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??"";Br(a);let c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??Dn,l=await mn({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/${m(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/${m(e)}/presence-intents`,n)}async describeCreation(e,n={}){let r=n.author?`?author=${encodeURIComponent(n.author)}`:"";return(await this.json("GET",`/admin-api/groups/${m(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??Dn,{warrant:c}=await hn({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/${m(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/${m(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??Dn,a=await At({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 Rn(this.config.authorAccount,r),i=Cn({founder:this.config.authorAccount,credential:this.config.authorProof,salt:r}),s=e.defaultCapabilities===void 0?void 0:He(e.defaultCapabilities),a=e.application?An(e.application):void 0,c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??Dn,l=await At({scope:o,op:i,authorAccount:this.config.authorAccount,executor:n.executorAccount,executorKey:n.executorKey,nonce:u,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(d),signer:c}),p=await this.postGovernance(o,i,l),x={namespaceId:p.groupId,salt:r,teeEnabled:p.teeEnabled??!1,...p.teeError?{teeError:p.teeError}:{}},v=x,P=b=>b instanceof Error?b.message:String(b);if(a)try{await this.govern({groupId:x.namespaceId,op:a}),v={...v,applicationSet:!0}}catch(b){v={...v,applicationSet:!1,applicationError:P(b)}}if(s)try{await this.govern({groupId:x.namespaceId,op:s}),v={...v,defaultCapabilitiesSet:!0}}catch(b){v={...v,defaultCapabilitiesSet:!1,defaultCapabilitiesError:P(b)}}return v}async postGovernance(e,n,r){return(await this.json("POST",`/admin-api/groups/${m(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 O&&s.status===429)||i>=this.rateLimitRetries)throw s;let c=Hl(s.headers);await Ll(c??o),o*=2}}async jsonOnce(e,n,r){let o={Accept:"application/json"};r!==void 0&&(o["Content-Type"]="application/json");let i=new AbortController,s=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r===void 0?void 0:JSON.stringify(r),signal:i.signal})}catch(c){throw new O(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(!a.ok){let c=await a.text().catch(()=>"");if(a.status===400||a.status===403){let u=Bl(c);throw new he(u,/nonce/i.test(u),a.status)}throw new O(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(a.status!==204)return await a.json()}};function Bl(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 ql=new TextEncoder().encode("calimero.auth.login.v1"),as={webOrigin:0,codeSigningId:1,cli:2};function cs(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 jl(t){return f(Uint8Array.from([as[t.kind]]),cs(t))}function Fl(t){let e=Uint8Array.from([as[t.kind]]);if(t.kind==="cli")return e;let n=cs(t);return f(e,R(n.length),n)}async function Un(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=C(t.issuedAt),a=C(t.expiresAt),c=await k(ql,[e,jl(t.audience),n,r,i,s,a]),u=await o.sign(c);return y(f(e,Fl(t.audience),n,r,i,s,a,u))}var Vl=300;async function Xr(){let t=y(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:y(await re(t)),secret:t}}async function je(t){let e=t.nodeUrl.replace(/\/+$/,""),n=t.timeoutMs??1e4,r=async(p,x)=>{let v=new AbortController,P=setTimeout(()=>v.abort(),n),b;try{let T={...x,signal:v.signal};b=t.fetch?await t.fetch(`${e}${p}`,T):await globalThis.fetch(`${e}${p}`,T)}catch(T){throw new O(0,T instanceof Error?T.name:"NetworkError",`${e}${p}`,new Headers,T instanceof Error?T.message:String(T))}finally{clearTimeout(P)}let E=await b.text().catch(()=>"");if(!b.ok)throw new O(b.status,b.statusText,`${e}${p}`,b.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 Un({node:t.node,audience:t.audience,challenge:i,sessionKey:s.publicKey,issuedAt:a,expiresAt:a+(t.ttlSeconds??Vl),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 Wl=3e4;function Ve(){let t=globalThis.location?.origin;return t?{kind:"webOrigin",origin:t}:{kind:"cli"}}function Jl(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 Fe=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-Wl>e?this.session.accessToken:(this.pending||(this.pending=this.loginNow().finally(()=>{this.pending=null})),(await this.pending).accessToken)}async loginNow(){let e=await je({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=Jl(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 ls=new TextEncoder().encode("calimero/presence/1");async function us(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(ls,g(t.contextId,"contextId",32),g(t.author,"author",32),C(t.seq),C(t.sentAtMs),await us(t.state))}var zl=2500,Rt=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??zl,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 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 ds(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 ps(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 Ql(t,e,n){let r=e?.nodeKey;return r?new Fe({nodeUrl:e?.nodeUrl??t.relayUrl,nodeKey:r,accountProof:e?.accountProof??t.authorProof,audience:e?.audience??Ve(),signer:e?.signer?async()=>e.signer:()=>t.authorSigner(),clientName:e?.clientName,ttlSeconds:e?.ttlSeconds,fetch:e?.fetch??n,timeoutMs:e?.timeoutMs}):null}var be=class{constructor(e){this.relayObserver=null;this.relayAdmin=null;this.proofAuthorizer=null;this.relayUrl=null;this.proofEvents=null;this.relayFetch=void 0;this.relayPresence=null;if(e.transport==="relay"){this.transport="relay",this.nodeClient=null;let o=e.fetch;this.relayFetch=o;let i=e.relay instanceof W?e.relay:new W({...e.relay,fetch:e.relay.fetch??o});if(this.relayObserver=Ql(i,e.observe,o),this.rpcTransport=new ye(i,this.relayObserver),this.relayUrl=i.relayUrl,e.proof&&(this.proofAuthorizer=pr(e.proof)),e.session){let s=e.session;this.relayAdmin=Ho({baseUrl:i.relayUrl,getAuthToken:typeof s=="string"?async()=>s:s,fetch:o})}else if(this.proofAuthorizer){let s=this.proofAuthorizer;this.relayAdmin=jt(it({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 We(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 ds("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 ps("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."):ps("WebSocket events")}get ephemeral(){return this.nodeClient?this.nodeClient.ephemeral:(this.relayPresence??(this.relayPresence=new Rt({relay:this.relay,events:()=>this.events})),this.relayPresence)}get cloud(){if(!this.nodeClient)throw ds("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 On(t){return new be(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 ms(t){try{sessionStorage.setItem(no,JSON.stringify(t))}catch{}}function fs(){try{sessionStorage.removeItem(no)}catch{}}function hs(){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 ys(t){try{sessionStorage.setItem(ro,JSON.stringify(t))}catch{}}function bs(){try{sessionStorage.removeItem(ro)}catch{}}function io(t){let e=_n(t);return{next:async()=>{let n=0n;try{n=ws(t)}catch{n=0n}try{localStorage.setItem(e,String(n+1n))}catch{}return n}}}function _n(t){return`calimero.nonce.${t}`}function ws(t){let e=localStorage.getItem(_n(t));if(e!==null)return BigInt(e);let n=`${_n(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 Gn(t,e,n){try{ws(t)<=n&&localStorage.setItem(_n(t),String(n+1n))}catch{}}var As="calimero.delegated.relay-node-key.";function X(t){return t.replace(/\/+$/,"")}function so(t,e){localStorage.setItem(As+X(t),e.trim().toLowerCase())}function Kn(t){try{let e=localStorage.getItem(As+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 Yl="locked-read-only",Xl="2.3.99",eo;function Zl(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 gs(t,e){try{return await e()}catch(n){throw n instanceof Je?n:new Je(t,n)}}function eu(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 xs(t,e){return Object.assign(async r=>{let o=await gs("loading the quote verifier",()=>(eo??(eo=import("@phala/dcap-qvl").then(i=>Zl(i),i=>{throw eo=void 0,i})),eo));return gn({dcapVerify:o,release:()=>gs("fetching the release the relay runs",async()=>un(pn(ln,await dn(t,{fetch:e})))),profile:Yl,minReleaseVersion:Xl})(r)},{includeCollateral:!0})}async function ze(t,e={}){let n=e.fresh?null:Kn(t);if(n)return{kind:"learned",nodeKey:n};let r={failure:null},o=eu(r);try{let i=ao(t),{nodeKey:s}=await on({relayUrl:t,allowMock:i,fetch:o,...i?{}:{verify:xs(t,o)}});return so(t,s),{kind:"learned",nodeKey:s}}catch(i){return i instanceof Je||r.failure?{kind:"unavailable",error:i}:{kind:"refused",error:i}}}async function $n(t){let e=await ze(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 Mn=[1e3,2e3,5e3,1e4,3e4];function tu(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 vs(t,e={}){let{signal:n}=e;for(let r=0;!n?.aborted;r+=1){let o=await ze(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=Mn[Math.min(r,Mn.length-1)];console.warn(`[mero-js] could not reach what proves the relay's node key; retrying in ${i/1e3} s`,o.error),await tu(i,n)}return null}function nu(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 Rs(){to.clear()}async function ru(t){if(t.status!==403)return!1;try{return(await t.clone().json()).error?.code==="sealed_route_unguarded"}catch{return!1}}function ou(t){return t.headers.has("authorization")||new URL(t.url).pathname.startsWith("/auth/")}function iu(t){let e=(o,i)=>globalThis.fetch(o,i),n=fe({baseUrl:t,verify:xs(t,e),fetch:e}),r=!1;return async(o,i)=>{let s=new Request(o,i);if(r&&ou(s))return e(s);let a=await n(s.clone());return await ru(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 Qe(t){if(ao(t))return;let e=X(t),n=to.get(e);return n||(n=iu(t),to.set(e,n)),n}function su(t,e){let n=null,r=null;return async()=>{let o=n?nu(n):null;return n&&(o===null||o-Date.now()>3e4)?n:(r||(r=je({nodeUrl:t.relayUrl,fetch:Qe(t.relayUrl),node:e,deviceSecret:t.deviceSecret,accountProof:t.credential,audience:Ve()}).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 Cs(){Nn.clear()}function au(t){return typeof t=="object"&&t!==null&&t.status===409}function cu(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){au(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 lu(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 uu(t,e){let n=e.session?cu(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=lu(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 Ln(t,e){if(!t.relayUrl)return null;let n=Kn(t.relayUrl),r=On({transport:"relay",fetch:Qe(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?su({...t,relayUrl:t.relayUrl},n):void 0,observe:n?{nodeKey:n}:void 0});return uu(r,{relayUrl:t.relayUrl,session:n!==null,attested:n!==null||ao(t.relayUrl)})}var Ss="calimero.delegated.relays.";function q(t){try{let e=localStorage.getItem(Ss+t),n=e?JSON.parse(e):{};return{namespaces:n.namespaces??{},contexts:n.contexts??{}}}catch{return{namespaces:{},contexts:{}}}}function co(t,e){try{localStorage.setItem(Ss+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),co(t,r)}function Es(t,e){return q(t).contexts[e]??null}function Hn(t,e){return e.executorAccount||!t?.executorAccount||!t.relayUrl||!e.relayUrl||X(t.relayUrl)!==X(e.relayUrl)?e:{...e,executorAccount:t.executorAccount}}function Ye(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 ks(t){let e=[],n=q(t.account);for(let r of Ye(t))try{if(!await $n(r))continue;let o=Ln({...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 Is(t){var o,i;let e=[],n=new Set,r=q(t.account);for(let s of Ye(t))try{if(!await $n(s))continue;let a=Ln({...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 lo(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 Ct(t,e){let n=e??globalThis.localStorage;if(!n)throw new Error("no localStorage in this runtime: pass a storage implementation, or use createMemoryNonceSource for a process that owns its whole sequence");let r=()=>{let o=n.getItem(t);if(o===null||o==="")return 0n;try{let i=BigInt(o);return i>0n?i:0n}catch{return 0n}};return{next(){let o=r()+1n;return n.setItem(t,o.toString()),Promise.resolve(o)},advanceTo(o){let i=o>0n?o-1n:0n;return i>r()&&n.setItem(t,i.toString()),Promise.resolve()}}}async function Ps(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=pu(r,t.namespaceId),i=await n.getNamespaceRelays(o.namespaceId),s=uo(i);if(!s)throw new Error(gu(o,i));let a=new W({relayUrl:s.relayUrl,executorAccount:s.executorAccount,authorAccount:t.authorAccount,authorProof:t.authorProof,signer:e,nonces:t.nonces??mu(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 du(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 Ps({...r,deviceSecret:void 0,signer:o,sessionToken:a.sessionToken,authorAccount:n??i.accountId})}function pu(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 gu(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 mu(t){let e=`mero-js:warrant-nonce:${t}`;try{return Ct(e)}catch{return lo(1)}}var fu=new TextEncoder().encode("calimero.mdma.routing-read.v1\0");async function Ts(t,e){g(e,"deviceSecret",32);let n=await ne(e),r=f(fu,new TextEncoder().encode(t)),o=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,r));return hu(o)}async function Bn(t,e){return{"X-Calimero-Credential":e.credential,"X-Calimero-Nonce":t.nonce,"X-Calimero-Signature":await Ts(t.nonce,e.deviceSecret)}}function hu(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var yu="https://cloud.calimero.network";function Ds(t){let e=new URL(t.cloudWebUrl??yu);return e.searchParams.set("link-account",t.accountId),e.searchParams.set("callback-url",Ft(t.accountId,t.returnTo)),e.toString()}function bu(t){throw window.location.assign(Ds(t)),new Error("redirecting to the cloud to authorise this link")}function wu(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Te(t.search??""),po(),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(Te(t.search??"")?.account!==o)throw po(),new Error("this account link answers a request this browser did not make - start the link again from here");return po(),{grant:r,account:o}}function po(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+Fo(location.search))}async function Au(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 xu="enrol-device",vu="enrol-kem",Ru="callback-url",Ns="state",go="calimero.device.enrol.pending";function _s(t){Os(t.devicePublicKey,"devicePublicKey"),Os(t.kemPublicKey,"kemPublicKey"),Iu(t.returnTo),ku(t.returnTo);let e=new URL(t.walletUrl);return e.searchParams.set(xu,t.devicePublicKey),e.searchParams.set(vu,t.kemPublicKey),e.searchParams.set(Ru,t.returnTo),e.searchParams.set(Ns,at(go,{})),e.toString()}function Cu(t){throw window.location.assign(_s(t)),new Error("redirecting to the wallet to approve this device")}function Su(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Pe(go,e.get(Ns)),Us(),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;Us();let s=e.get("state");return{credential:r,account:o,device:i,...s?{state:s}:{}}}function Us(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+location.search)}async function Eu(t){if(!Pe(go,t.state))throw new Error("this enrolment answers a request this app did not make - start the enrolment again from here");let e=await Xt(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 Os(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 Ms(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 ku(t){Ms(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 Iu(t){let e;try{e=new URL(t)}catch{throw new Error(`returnTo must be an absolute URL, got ${t}`)}let n=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]"||e.hostname==="::1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new Error(`returnTo must be https:, or http: on localhost \u2014 got ${e.protocol}//${e.hostname}`)}function qn(t){if(!t)return null;let e=t.trim().toLowerCase(),n=e.startsWith("0x")?e.slice(2):e;return n.length>0?n:null}function Tu(t,e){if(e.size===0)return!0;let n=qn(t.account);return n!==null&&e.has(n)}async function jn(t){let e=t.cloud??new $({cloudBaseUrl:t.cloudBaseUrl,routingCredential:{credential:t.credential,deviceSecret:t.deviceSecret}}),n,r;try{let p=await e.getNamespaceRouting(t.namespaceId);n=p.nodes,r=p.servable}catch(p){return{ok:!1,step:"admitters-lookup",reason:`The cloud could not be asked which nodes serve namespace ${t.namespaceId}: ${p instanceof Error?p.message:String(p)}. Nothing is known about the invitation yet \u2014 this is the lookup failing, not the invitation.`}}if(n.length===0)return{ok:!1,step:"no-nodes",reason:"The cloud lists no nodes serving this namespace, so there is no hosted node to be admitted through. The namespace has no fleet assignment \u2014 whoever invited you is running their own node, and admission has to go through a node the cloud routes to."};let o=new Set((t.admitters??[]).map(qn).filter(p=>p!==null)),i=n.filter(p=>Tu(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/${m(t.namespaceId)}/admit`,admitterAccount:l.account,peerId:l.peerId,writable:l.canExecute,stale:!l.fresh||c}}var Fn=1440*60,fo={Admin:0,Member:1,ReadOnly:2};function Pt(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)=>g(n,`admitters[${r}]`,32)))}async function ho(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",Pt(t)))}function yo(t){return[...new Set(t.filter(n=>n.role==="Admin").map(n=>n.identity.toLowerCase()))].sort()}async function Vn(t){let e=await I(t.deviceSecret,t.signer,"deviceSecret"),n=g(e.publicKey,"signer.publicKey",32),r=g(t.groupId,"groupId",32);g(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)=>g(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??Fn,Fn);if(!Number.isInteger(a)||a<=0)throw new Error(`validForSecs must be a positive whole number, got ${t.validForSecs}`);let c=t.nonce??crypto.getRandomValues(new Uint8Array(32));if(c.length!==32)throw new Error(`nonce must be 32 bytes, got ${c.length}`);let u={inviter_identity:Array.from(n),group_id:Array.from(r),expiration_timestamp:s+a,secret_salt:Array.from(c),invited_role:i,admitters:o},d=await e.sign(await 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(g(t.applicationId,"applicationId",32))),t.appKey&&(l.app_key=Array.from(g(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 bo=25,Du=new TextEncoder().encode("calimero.namespace.v1"),Uu=0,Gs={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreatedV2:9,MemberJoinedViaTeeAttestation:10};function Ks(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 $s(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}function Wn(t){let e=t.invitation,n=t.admitter_addrs??[];return f(Pt(e),$s(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($s),Ks(t.application_id,"application_id"),Ks(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([Gs.MemberJoinedAt]),g(t.member,"member",32),Wn(t.invitation),C(o),n):f(new Uint8Array([Gs.MemberJoined]),g(t.member,"member",32),Wn(t.invitation),n),s=f(new Uint8Array([Uu]),i),a=await I(t.deviceSecret,t.signer,"deviceSecret"),c=g(a.publicKey,"signer.publicKey",32),u=f(new Uint8Array([bo]),g(t.namespaceId,"namespaceId",32),R(e.length),...e.map((p,x)=>g(p,`parentOpHashes[${x}]`,32)),c,C(t.nonce),s),d=await a.sign(f(Du,u)),l=new Uint8Array([0]);return y(f(u,d,l))}function Ou(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 Nu(t){let e=Ct(`calimero.delegated.joinnonce.${t}`);return()=>e.next()}function Ls(t){return t.replace(/\/+$/,"")}async function zn(t){let{account:e,credential:n,deviceSecret:r}=t.credential,o;try{o=await Jn({namespaceId:t.namespaceId,member:e,invitation:t.invitation,credential:n,deviceSecret:r,nonce:await(t.deps?.nonce??Nu(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??`${Ls(t.nodeUrl)}/admin-api/namespaces/${m(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:Ou(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:Ls(t.nodeUrl),account:e,credential:n,deviceSecret:r}}}async function Qn(t){let e=t.deps?.resolve??jn,n=t.deps?.join??zn,r=null,o=t.nodeUrl,i;if(!o){let a=await e({namespaceId:t.namespaceId,admitters:t.invitation.invitation.admitters,credential:t.credential.credential,deviceSecret:t.credential.deviceSecret,cloudBaseUrl:t.cloudBaseUrl});if(a.ok===!1)return a;r=a,o=a.relayUrl,i=a.admitUrl}let s=await n({nodeUrl:o,admitUrl:i,namespaceId:t.namespaceId,invitation:t.invitation,credential:t.credential,deps:{fetch:t.deps?.fetch,nonce:t.deps?.nonce}});return s.ok===!1?s:{ok:!0,published:s.published,relay:r,session:s.session}}async function Hs(t,e,n,r){let i=await(r.bootstrap??Qn)({namespaceId:e,invitation:n,credential:{account:t.account,credential:t.credential,deviceSecret:t.deviceSecret},cloudBaseUrl:r.cloudBaseUrl});if(i.ok===!1)throw Object.assign(new Error(i.reason),{step:i.step,...i.status!==void 0?{status:i.status}:{}});return i.session.relayUrl&&we(t.account,i.session.relayUrl,{namespaceId:e}),r.onJoined(Hn(t,i.session)),{namespaceId:e}}function Bs(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 wo(t,e){let n=Bs(t),r=Bs(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 _u(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 Tt(t){return t.filter(e=>!e.yanked&&typeof e.appVersion=="string"&&e.appVersion.length>0).reduce((e,n)=>!e||_u(n.appVersion,e.appVersion)?n:e,void 0)}async function Dt(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 qs(t,e,n={}){let o=(await Dt(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=Tt(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 wo(e,a),signerId:a,version:s.appVersion}}function Fs(t,e){return{next:async()=>Mu(t,e)}}function Mu(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 Vs(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 Gu(t){return!t||t.length===0?{}:JSON.parse(new TextDecoder().decode(Uint8Array.from(t)))}function Xn(t,e,n,r){return new W({relayUrl:e,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:n,fetch:r??Qe(e)})}async function Ut(t,e,n={}){let r=Vs(t,e.namespaceId),o=0n,i=await Xn(t,r,{next:async()=>o},n.fetch).createContext({groupId:e.groupId??e.namespaceId,applicationId:e.applicationId,serviceName:e.serviceName,seed:e.contextSeed,initArgs:Gu(e.initializationParams),name:e.name});return Gn(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=Vs(t,e.namespaceId);return Xn(t,r,Fs(r,e.group),n.fetch).govern({groupId:e.group,op:e.op})}async function Ws(t,e,n={}){let{groupId:r}=await ve(t,{namespaceId:e.namespaceId,group:e.namespaceId,op:(await Be({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:Le(i,"Member")},n);let{contextId:o}=await Ut(t,{...e,groupId:r},n);return{contextId:o,groupId:r}}async function Zn(t,e={},n={}){let o=Ye(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 Ku(t,o,n.fetch),s=BigInt(Date.now()),a=await Xn(t,o,{next:async()=>s++},n.fetch).foundNamespace({executor:i,...e.defaultCapabilities!==void 0?{defaultCapabilities:e.defaultCapabilities}:{},...e.application?{application:e.application}:{}});try{localStorage.setItem(`calimero.governance-nonce.${o}.${a.namespaceId}`,String(s))}catch{}if(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 Lu(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 Ku(t,e,n){let r=t.executorAccount&&t.relayUrl?.replace(/\/+$/,"")===e?t.executorAccount:null;if(r)return{executorAccount:r,executorKey:await js(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 js(e),s=await Xn(t,e,Fs(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 js(t){let e=await ze(t,{fresh:!0});if(e.kind==="learned")return e.nodeKey;throw new Error(e.kind==="unavailable"?"the relay's signing key could not be learned: its attestation did not answer, try again":"the relay's attestation was refused, so founding through it is not possible: it is not a signed locked-read-only release")}var er="link this account to your cloud user in the wallet so the cloud can host this namespace on its fleet",Yn={account_not_linked:er,account_linked_to_several_users:"this account is linked to more than one cloud user, so the cloud cannot tell whose plan hosts the namespace: unlink it from all but one in the wallet",ha_request_pending:"another namespace of this account is still waiting to be hosted; the cloud hosts one new namespace at a time without a cloud sign-in. Sign in to the cloud and turn off hosting for the waiting namespace, or wait until it is hosted",unknown_relay:"the cloud does not run the relay this namespace was founded on, so it cannot host it",relay_not_dialable:"the relay this namespace was founded on has not reported its address to the cloud yet; try enabling hosting again shortly"};function $u(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 Lu(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:er};if(i instanceof J&&Yn[i.code]){let s=i.code==="ha_request_pending"?$u(i):null,a=Yn[i.code];return{haEnabled:!1,haError:s?`${a} (waiting: ${s})`:a}}return{haEnabled:!1,haError:i instanceof Error?i.message:String(i)}}}async function Xe(t,e,n=globalThis.fetch){let r=Tt(await Dt(t,e,n));if(!r)throw new Error(`the registry lists no version of ${e}`);return r.appVersion}var Js="calimero.delegated.group-namespace.",Ao=new Map;function zs(t){let e={};try{e=JSON.parse(localStorage.getItem(Js+t)??"{}")}catch{}return{...e,...Ao.get(t)}}function Ot(t,e,n){Ao.set(t,{...Ao.get(t),[e]:n});try{let r=zs(t);r[e]=n,localStorage.setItem(Js+t,JSON.stringify(r))}catch{}}function Nt(t,e){return q(t.account).namespaces[e]?e:zs(t.account)[e]}function Qs(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 tr(t,e,n){return ve(t,{namespaceId:Qs(t,e),group:e,op:n})}async function nr(t,e,n){let r=Qs(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"}},Ze=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"}},et=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"}},Ys={listNamespaces:async()=>[],listNamespacesForApplication:async()=>[],getContexts:async()=>({contexts:[]})},Hu=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 Bu(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 Xs(t,e={}){let{session:n,read:r,app:o}=t,i=e.govern?.group??tr,s=e.govern?.root??nr,a=e.createContext??Ut,c=e.found??Zn,u=e.latestVersion??Xe,d=e.signInvitation??Vn,l=e.join,p=e.routing;async function x(h,w){if(!l)throw new Re("joinNamespace without a join handler");return l(h,w.invitation)}let v=()=>{if(r===null)throw new Ze("this call");return r};async function P(h){if(Nt(n,h))return;let w=await v().getGroupInfo(h);Ot(n.account,h,w.namespaceId??h)}let b=async(h,w,S)=>(await P(w),i(h,w,S)),E=async(h,w,S)=>(await P(w),s(h,w,S));async function T(h){try{return await E(n,h,Tn({member:n.account,groupId:h,credential:n.credential})),!0}catch(w){if(Bu(w))return!1;throw w}}async function H(h,w){let S=w??String(await v().getContextGroup(h)),{members:U}=await v().listGroupMembers(S);return U.some(M=>M.identity.toLowerCase()===n.account.toLowerCase())}let z={async listNamespacesForApplication(h){return(await v().listNamespaces()).filter(w=>w.targetApplicationId===h)},async getNodeIdentity(){return{accountId:n.account,deviceId:null,publicKey:"",deviceCertified:!0}},async createNamespace(h){if(!o.packageName)throw new Re("createNamespace without a packageName");let w=o.packageVersion??await u(o.registryUrl??"https://apps.calimero.network",o.packageName),{namespaceId:S,haEnabled:U,haError:M}=await c(n,{defaultCapabilities:231,application:{applicationId:h.applicationId,package:o.packageName,version:w}});return h.name&&await b(n,S,qe({name:h.name})),{namespaceId:S,haEnabled:U,...M!==void 0?{haError:M}:{}}},async createGroupInNamespace(h,w={}){let{op:S}=await Be({parentId:h,restricted:w.visibility==="restricted",admin:n.account}),{groupId:U}=await E(n,h,S);return Ot(n.account,U,h),w.groupName&&await b(n,U,qe({name:w.groupName})),{groupId:U}},async addGroupMembers(h,w){for(let S of w.members)await b(n,h,Le(S.identity,S.role??"Member"))},async removeGroupMembers(h,w){for(let S of w.members)await b(n,h,bn(S))},async setGroupMetadata(h,w){await b(n,h,qe(w))},async setMemberMetadata(h,w,S){await b(n,h,In(w,S))},async setContextMetadata(h,w,S){await b(n,h,Pn(w,S))},async setDefaultCapabilities(h,w){await b(n,h,He(w.defaultCapabilities))},async setSubgroupVisibility(h,w){await b(n,h,kn(w.subgroupVisibility==="open"?"open":"restricted"))},async setMemberCapabilities(h,w,S){await b(n,h,Sn(w,S.capabilities))},async deleteGroup(h){return await E(n,h,vn(h)),{isDeleted:!0}},async reparentGroup(h,w){return await E(n,h,xn(h,w.newParentId)),{reparented:!0}},async leaveGroup(h){await b(n,h,vt(n.account))},async leaveNamespace(h){await b(n,h,vt(n.account))},async getContextIdentitiesOwned(h){return{identities:await H(h)?[n.account]:[]}},async joinContext(h){return await T(String(await v().getContextGroup(h))),{contextId:h,memberPublicKey:n.account}},async createContext(h){let S=(await v().getGroupInfo(h.groupId)).namespaceId??h.groupId,{contextId:U}=await a(n,{namespaceId:S,groupId:h.groupId,applicationId:h.applicationId,serviceName:h.serviceName,contextSeed:h.contextSeed,name:h.name,initializationParams:h.initializationParams});return{contextId:U,memberPublicKey:n.account,groupId:h.groupId}},async createNamespaceInvitation(h){let[{members:w},S]=await Promise.all([v().listGroupMembers(h),v().getGroupInfo(h)]),U=w.filter(Q=>Q.role==="RelayTee").map(Q=>Q.identity.toLowerCase());if(p){let Q=new Set(U.length>0?U:w.filter(te=>te.role==="Admin").map(te=>te.identity.toLowerCase())),ee=null;try{ee=(await p(h)).nodes}catch{}if(ee!==null){if(ee.length===0)throw new et(h,"not-hosted");if(!ee.some(te=>te.account!==null&&Q.has(te.account.toLowerCase())))throw new et(h,"no-named-node")}}return{invitation:await d({groupId:h,inviterAccount:n.account,deviceSecret:n.deviceSecret,...U.length>0?{admitters:U}:{},members:w,applicationId:S.targetApplicationId,appKey:S.appKey})}},async syncGroup(h){return{groupId:h,synced:!0}},async syncContext(){},joinNamespace:x,async updateMemberRole(h,w,S){await b(n,h,wn(w,S.role))},async joinSubgroupInheritance(h){return{groupId:h,memberPublicKey:n.account,wasInherited:await T(h)}},async detachContextFromGroup(h,w){await b(n,h,En(w))}};return r===null?new Proxy({},{get(h,w){if(typeof w=="string")return w==="getNodeIdentity"?z.getNodeIdentity:w==="joinNamespace"?x:w in Ys?Ys[w]:async()=>{throw new Ze(w)}}}):new Proxy(r,{get(h,w,S){return typeof w=="string"&&w in z?z[w]:typeof w=="string"&&Hu.has(w)?async()=>{throw new Re(w)}:Reflect.get(h,w,S)}})}function Zs(t,e={}){let{admin:n,app:r}=t,o=e.latestVersion??Xe;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 qu="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 uo(t){return t.find(e=>e.canExecute&&e.relayUrl!==null&&e.executorAccount!==null)??null}function ju(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 Fu(t){return typeof t=="string"&&br.test(t)?t:null}var J=class extends O{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.code=n;this.name="AccountHaRefusedError"}},xe=class extends J{constructor(){super(...arguments);this.name="AccountNotLinkedError"}};xe.CODE="account_not_linked";var St=class extends J{constructor(){super(...arguments);this.name="AccountLinkedToSeveralUsersError"}};St.CODE="account_linked_to_several_users";var Et=class extends J{constructor(){super(...arguments);this.name="HaRequestPendingError"}};Et.CODE="ha_request_pending";var kt=class extends J{constructor(){super(...arguments);this.name="UnknownRelayError"}};kt.CODE="unknown_relay";var It=class extends J{constructor(){super(...arguments);this.name="RelayNotDialableError"}};It.CODE="relay_not_dialable";var ea={409:[xe,St,Et],422:[kt,It]};function Vu(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 Wu="x-mdma-session-refresh",Ju="x-mdma-session-expires",$=class{constructor(e={}){this.session=null;this.baseUrl=(e.cloudBaseUrl||qu).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 tn({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/${m(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:ju(r)}})}async findExecutingRelay(e){let n=await this.getNamespaceRelays(e);return uo(n)}async getNamespaceRouting(e){let n=await this.request("GET",`/api/cloud/namespaces/${m(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/${m(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/${m(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/${m(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:Fu(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/${m(e)}/enable-ha`,{body:r})}async enableFoundedNamespaceHa(e,n){return this.request("POST",`/api/cloud/me/namespaces/${m(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/${m(r)}/namespaces/${m(o)}/enable-ha`,{body:{ownership_proof:n},anonymous:!0})}catch(i){if(i instanceof O&&ea[i.status]){let s=Vu(i.bodyText),a=ea[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/${m(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 ut({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":Ft(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&&Te(o),s&&Te(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 en(e.rootSecret,e.signer),i=await this.request("POST","/api/cloud/accounts/link",{body:{grant:e.grant,root_public_key:r,signature:await ut({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 O(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(this.adoptRollingRefresh(a),!a.ok){let c=await a.text().catch(()=>{});throw new O(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(!(r.parse==="none"||a.status===204))return await a.json()}adoptRollingRefresh(e){let n=e.headers.get(Wu);if(!n||!this.session)return;let r=e.headers.get(Ju),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 Pu(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 zu(t){if(t)return typeof t=="function"?t:Wt(t)}var Qu="mero-js:token-refresh";function Yu(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function Xu(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 We=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=Xu(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=zu(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=Go(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs}),this.adminClient=jt(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 ct({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 lt({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=Yu();return n?n.request(Qu,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,n){return wr(e,n)}static buildAuthLoginUrl(e,n){return Ar(e,n)}};function Zu(t){return new We(t)}var Co=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},ed="mero-tokens",So=class{constructor(e=ed){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 td=new TextEncoder().encode("calimero.account.owner-op.v1"),nd=new TextEncoder().encode("calimero.account.owner-op.body.v1"),rd=new TextEncoder().encode("calimero.account.genesis.v1"),od=2,Eo={transferOwnership:0,adminChanged:1,groupDelete:2,teeAdmissionPolicy:3,teeAuthoringPolicy:4,teeReleaseAdmissionPolicy:5},tt={GroupDelete:14,TransferOwnership:21,TeeAuthoringPolicySet:33,TeeAdmissionPolicySetV2:37,TeeReleaseAdmissionPolicySetV2:38,RootGuarded:42},na={AdminChanged:3,RootGuarded:12},id={replica:0,relay:1},sd=new TextEncoder;function L(t){return new Uint8Array([t])}function ra(t){let e=sd.encode(t);return f(R(e.length),e)}function Z(t){return f(R(t.length),...t.map(ra))}function oa(t){return L(t?1:0)}function ia(t){let e=id[t??"replica"];if(e===void 0)throw new Error(`mode must be replica or relay, got ${String(t)}`);return L(e)}function sa(t){return{kind:"transferOwnership",plane:"group",bytes:f(L(tt.TransferOwnership),g(t,"newOwner",32))}}function aa(){return{kind:"groupDelete",plane:"group",bytes:L(tt.GroupDelete)}}function ca(t){return{kind:"adminChanged",plane:"root",bytes:f(L(na.AdminChanged),g(t,"newAdmin",32))}}function la(t){return{kind:"teeAuthoringPolicy",plane:"group",bytes:f(L(tt.TeeAuthoringPolicySet),Z(t))}}function ua(t){return{kind:"teeAdmissionPolicy",plane:"group",bytes:f(L(tt.TeeAdmissionPolicySetV2),Z(t.allowedMrtd),Z(t.allowedRtmr0),Z(t.allowedRtmr1),Z(t.allowedRtmr2),Z(t.allowedRtmr3),Z(t.allowedTcbStatuses),oa(t.acceptMock),ia(t.mode))}}function da(t){let e=t.minReleaseVersion===void 0?L(0):f(L(1),ra(t.minReleaseVersion));return{kind:"teeReleaseAdmissionPolicy",plane:"group",bytes:f(L(tt.TeeReleaseAdmissionPolicySetV2),Z(t.allowedProfiles),e,Z(t.allowedTcbStatuses),oa(t.acceptMock),ia(t.mode))}}async function ko(t){return k(nd,[t])}async function Io(t){return k(td,[g(t.account,"account",32),g(t.namespaceId,"namespaceId",32),g(t.groupId,"groupId",32),L(pa(t.kind)),t.opDigest,C(t.counter),R(t.keyEpoch)])}function pa(t){let e=Eo[t];if(e===void 0)throw new Error(`unknown owner-op kind ${String(t)}`);return e}var ta=132;async function ga(t){let e=await re(t.rootSecret),n=f(L(od),e),r=y(await k(rd,[n])),o=t.keyEpoch??0,i=(t.chain??[]).map((d,l)=>{let p=j(d,`chain[${l}]`);if(p.length!==ta)throw new Error(`chain[${l}] must be a ${ta}-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,g(r,"account",32),g(t.namespaceId,"namespaceId",32),g(t.groupId,"groupId",32),L(pa(t.op.kind)),s,C(t.counter),R(o),u))}function ma(t,e){let n=t.plane==="group"?tt.RootGuarded:na.RootGuarded;return f(L(n),t.bytes,j(e,"rootProof"))}var fa=[2428,2429,2528,2529],ad="localhost",cd=2e3;function ha(t){return`http://${ad}:${t}`}function ya(t,e){let n=t.endsWith("/")?t:`${t}/`;return new URL(e,n).toString()}async function ba(t,e={}){let{timeoutMs:n=cd,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=ya(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 ld(t={}){let{ports:e=fa,timeoutMs:n,signal:r}=t;return(await Promise.all(e.map(async i=>{let s=ha(i);return await ba(s,{timeoutMs:n,signal:r})?s:null}))).filter(i=>i!==null)}function rr(t,e){return(t<<e|t>>>32-e)>>>0}function le(t,e,n,r,o){t[e]=t[e]+t[n]>>>0,t[o]=rr(t[o]^t[e],16),t[r]=t[r]+t[o]>>>0,t[n]=rr(t[n]^t[r],12),t[e]=t[e]+t[n]>>>0,t[o]=rr(t[o]^t[e],8),t[r]=t[r]+t[o]>>>0,t[n]=rr(t[n]^t[r],7)}function wa(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function va(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]=wa(t,s*4);r[12]=e>>>0;for(let s=0;s<3;s+=1)r[13+s]=wa(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 ud(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=va(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 dd=(1n<<130n)-5n;function pd(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%dd}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 Aa(t){return new Uint8Array((16-t%16)%16)}function xa(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function gd(t,e){let n=[t,Aa(t.length),e,Aa(e.length),xa(t.length),xa(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 md(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 Ra(t,e,n,r=new Uint8Array(0)){md(t,e);let o=va(t,0,e).subarray(0,32),i=ud(t,1,e,n),s=pd(o,gd(r,i)),a=new Uint8Array(i.length+16);return a.set(i),a.set(s,i.length),a}var Sa=32,fd=1,hd=3,yd=2,bd=32,wd=32,Ad=12,nt=t=>new TextEncoder().encode(t),Mt=t=>new Uint8Array([t>>8&255,t&255]),Ca=f(nt("KEM"),Mt(Sa)),_t=f(nt("HPKE"),Mt(Sa),Mt(fd),Mt(hd));async function Ea(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 xd(t,e,n){let r=new Uint8Array(n),o=new Uint8Array(0);for(let i=1,s=0;s<n;i+=1)o=await Ea(t,f(o,e,new Uint8Array([i]))),r.set(o.subarray(0,Math.min(o.length,n-s)),s),s+=o.length;return r}function or(t,e,n,r){return Ea(e,f(nt("HPKE-v1"),t,nt(n),r))}function To(t,e,n,r,o){return xd(e,f(Mt(o),nt("HPKE-v1"),t,nt(n),r),o)}async function vd(t,e){let n=await or(Ca,new Uint8Array(0),"eae_prk",t);return To(Ca,n,"shared_secret",e,bd)}async function Rd(t,e){let n=new Uint8Array(0),r=await or(_t,n,"psk_id_hash",n),o=await or(_t,n,"info_hash",e),i=f(new Uint8Array([yd]),r,o),s=await or(_t,t,"secret",n);return{key:await To(_t,s,"key",i,wd),nonce:await To(_t,s,"base_nonce",i,Ad)}}async function ka(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 dt(s.privateKey,t),await dt(a.privateKey,t)),u=await vd(c,f(s.publicKey,t,a.publicKey)),{key:d,nonce:l}=await Rd(u,n);return{enc:s.publicKey,ciphertext:Ra(d,l,r,o)}}var Ta="mero-agent-gate/attest/v3",Da="mero-agent-gate/provision/v2",Cd=/^[a-z0-9][a-z0-9-]{0,62}$/,Sd=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,Ia=64,Pa=64*1024,ue=class extends Error{constructor(n,r,o){super(n);this.status=r;this.code=o;this.name="AgentGateError"}};function Ua(t){if(!Cd.test(t))throw new Error(`Agent id ${JSON.stringify(t)} must match [a-z0-9][a-z0-9-]{0,62}`)}function Gt(t){return new TextEncoder().encode(t)}function Oa(t){let e=Gt(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 ir(t,e,n){let r;try{r=Uint8Array.from(atob(t.trim()),o=>o.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(n!==void 0&&r.length!==n)throw new Error(`${e} is not ${n} bytes`);return r}async function Na(t,e,n,r){let o=new Uint8Array(32),i=f(Gt(Ta),t,Oa(e),n??o,r??o);return new Uint8Array(await crypto.subtle.digest("SHA-256",i))}function _a(t,e){return f(Gt(Da),t,Oa(e))}async function Ed(){let t=crypto.getRandomValues(new Uint8Array(32));return{secret:t,publicKey:await sr(t)}}async function sr(t){if(t.length!==32)throw new Error("An owner key is 32 bytes");return Ce((await Ne(t)).publicKey)}function Ma(t,e){return`${t.replace(/\/+$/,"")}${e}`}async function Ga(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&&Ua(e);let n=crypto.getRandomValues(new Uint8Array(32)),r=await Ga(t.fetch??fetch,Ma(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=ir(r.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),i=r.signingPublicKeyB64?ir(r.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,s=r.ownerPublicKeyB64?ir(r.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!i!=!s)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let a=await 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 Ka(t,e){let n=await sr(e);if(t.ownerPublicKey&&t.ownerPublicKey!==n)throw new ue(`This agent is claimed by another key (${t.ownerPublicKey}); it is not yours. Send it nothing and do not authorize its signing key`,void 0,"not_yours");return n}function kd(t){let e=Object.keys(t);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>Ia)throw new Error(`At most ${Ia} secrets at once`);for(let n of e){if(!Sd.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(Gt(t[n]).length>Pa)throw new Error(`Secret ${n} is over ${Pa} bytes`)}}async function $a(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 Ka(r,o),a=ir(r.provisioningPublicKey,"provisioningPublicKey",32),c=await ka(a,o,_a(a,r.agentId),Gt(JSON.stringify(i)));return Ga(t,Ma(e,n),{agentId:r.agentId,provisioningPublicKeyB64:r.provisioningPublicKey,senderPublicKeyB64:s,encappedKeyB64:Ce(c.enc),ciphertextB64:Ce(c.ciphertext)})}async function Id(t){kd(t.secrets);let e=t.fetch??fetch,n=await $a(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 sr(t.ownerSecret);if(r.ownerPublicKey!==o||!r.signingPublicKey)throw new ue("The gate accepted the secrets, but its quote does not name your key as owner");if(t.agent.signingPublicKey&&t.agent.signingPublicKey!==r.signingPublicKey)throw new ue("The agent's signing key changed while provisioning");return{agentId:r.agentId,provisioningPublicKey:r.provisioningPublicKey,signingPublicKey:r.signingPublicKey,ownerPublicKey:o,written:n?.written??[],claimed:n?.claimed===!0}}async function Pd(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 $a(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 Uo=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),Td=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function Dd(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await cn(r,e,{identity:n.identity??Uo.identity,issuer:n.issuer??Uo.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??ft;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 La(o),o}function La(t){for(let e of Td)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 Ud=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function Od(t){let e=Ud.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 Kt=t=>t.trim().replace(/^0x/i,"");function Nd(t,e){return La(t),ht({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:t.allowed_tcb_statuses.map(Od),allowedMrtd:t.allowed_mrtd.map(Kt),allowedRtmr0:t.allowed_rtmr0.map(Kt),allowedRtmr1:t.allowed_rtmr1.map(Kt),allowedRtmr2:t.allowed_rtmr2.map(Kt),allowedRtmr3:t.allowed_rtmr3.map(Kt)})}export{ri as ACCOUNT_HA_AUDIENCE,ni as ACCOUNT_OWNERSHIP_AUDIENCE,Ta as AGENT_ATTEST_DOMAIN,Da as AGENT_PROVISION_INFO_DOMAIN,J as AccountHaRefusedError,St as AccountLinkedToSeveralUsersError,xe as AccountNotLinkedError,me as AdminApiClient,ue as AgentGateError,pe as AuthApiClient,oe as AuthRevokedError,_ as CAPABILITIES,pp as CAPABILITY_PRESETS,$ as CloudClient,fa as DEFAULT_LOCAL_NODE_PORTS,ln as DEFAULT_RELEASE_MIRROR,lt as EphemeralClient,Ii as HANDSHAKE_PATH,er as HA_ACCOUNT_NOT_LINKED_MESSAGE,Yn as HA_REFUSAL_MESSAGES,O as HTTPError,Et as HaRequestPendingError,fo as INVITED_ROLE,he as IntentRefusedError,et as InvitationNotClaimableError,Uo as KMS_RELEASE_SIGNER,So as LocalStorageTokenStore,Fn as MAX_INVITATION_VALIDITY_SECS,Co as MemoryTokenStore,be as MeroClient,We as MeroJs,Lr as NODE_RELEASE_SIGNER,Ze as NoRelayError,Re as NotForAccountError,Eo as OWNER_OP_KIND,ls as PRESENCE_DOMAIN,ft as PRODUCTION_PROFILE,Mn as RELAY_NODE_KEY_RETRY_MS,ke as REQUEST_PROOF_HEADER,W as RelayClient,It as RelayNotDialableError,Fe as RelayObserver,Rt as RelayPresenceClient,ye as RelayTransport,ct as RpcClient,Jt as RpcError,gt as SEALED_CONTENT_TYPE,Pi as SEALED_PATH,bo as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,_e as SealedTransportError,B as SseClient,mt as StaleTransportKeyError,kt as UnknownRelayError,ot as WebHttpClient,ie as WsClient,Zt as accountForRoot,F as accountForRootPublicKey,ui as accountRootFromPhrase,Pr as accountRootFromSecret,pi as accountRootSignerFromPhrase,ca as adminChangedOp,Pu as admitterAddrsFromNetworkStatus,Na as agentKeyBinding,Nd as agentQuoteVerifier,wo as applicationIdForBundle,ze as attemptRelayNodeKey,Do as attestAgent,rn as attestKeyBinding,on as attestRelayNodeKey,bu as beginCloudLink,Cu as beginDeviceEnrolment,Qn as bootstrapFromInvitation,Ar as buildAuthLoginUrl,Ln as buildDelegatedClient,Ms as callbackIsForeign,Vt as callerProof,gp as capMask,mp as capNames,Hn as carryExecutorAccount,Ka as checkOwner,hr as classifyError,bs as clearDelegatedCredential,fs as clearDelegatedSession,Ds as cloudLinkUrl,pn as cloudNodeReleaseUrl,cr as combineSignals,sc as compareSemver,Au as completeCloudLink,Eu as completeDeviceEnrolment,Ps as connectCloud,du as connectCloudWithAccount,is as contextCapabilityGrantedOp,ss as contextCapabilityRevokedOp,En as contextDetachedOp,Pn as contextMetadataSetOp,Xs as createAccountAdmin,di as createAccountRootSigner,Ho as createAdminApiClient,jt as createAdminApiClientFromHttpClient,fe as createAttestedSealedFetch,up as createAuthApiClient,Go as createAuthApiClientFromHttpClient,Up as createBrowserAdminApiClient,cp as createBrowserAuthApiClient,Ie as createBrowserHttpClient,Ut as createDelegatedContext,Ws as createDelegatedPrivateContext,it as createHttpClient,Ct as createLocalStorageNonceSource,lo as createMemoryNonceSource,On as createMeroClient,Zu as createMeroJs,Zs as createNodeAdmin,Op as createNodeAdminApiClient,lp as createNodeAuthApiClient,Bt as createNodeHttpClient,pr as createProofAuthorizer,Wt as createProofSigner,ht as createQuoteVerifier,Qa as createRetryableMethod,Oi as createSealedFetch,Cl as createSignedReleaseSealedFetch,gn as createSignedReleaseVerifier,lr as createTimeoutSignal,gr as createUniversalHttpClient,Jr as createdSubgroupId,qr as creationInitHash,yo as defaultAdmitters,Ve as defaultAudience,He as defaultCapabilitiesSetOp,ve as delegatedGovernance,Yt as deviceCertPayload,_s as deviceEnrolmentUrl,Er as deviceScopePayload,ld as discoverLocalNodes,Pt as encodeGroupInvitation,Wn as encodeSignedInvitation,Ui as fetchAttestedTransportKey,un as fetchNodeRelease,dn as fetchNodeReleaseVersion,Dt as fetchRegistryBundles,Cs as forgetMethodKinds,Rs as forgetRelaySealing,Zn as foundDelegatedNamespace,Rn as foundedNamespaceId,li as generateAccountRoot,Ed as generateOwnerKey,Xr as generateSessionKey,tr as governGroup,nr as governRoot,jr as governanceOpHash,zr as groupCreatedOp,aa as groupDeleteOp,vn as groupDeletedOp,ho as groupInvitationHash,qe as groupMetadataSetOp,xn as groupReparentedOp,ge as hasCap,kp as hexEncodeUtf8,Hr as intentHash,ec as isSettled,Hs as joinAsAccount,zn as joinWithNode,se as jsonCodec,Ye as knownRelays,Xe as latestPublishedVersion,vs as learnRelayNodeKey,ks as listDelegatedContexts,Is as listDelegatedNamespaces,ha as localNodeUrl,je as login,Gn as markContextNonceSpent,Le as memberAddedOp,Sn as memberCapabilitySetOp,Tn as memberJoinedOpenOp,vt as memberLeftOp,In as memberMetadataSetOp,bn as memberRemovedOp,wn as memberRoleSetOp,Cr as mintDeviceId,Cn as namespaceCreatedOp,Nt as namespaceOfGroup,ya as nodeEndpoint,Fi as nodeReleaseVersionFromImage,qn as normaliseAccount,ko as ownerOpDigest,Io as ownerOpSigningPayload,sr as ownerPublicKey,wr as parseAuthCallback,es as parseCreationWarrant,Sr as parseDeviceCredential,ts as parseGovernanceWarrant,io as persistedNonces,so as pinRelayNodeKey,Zr as presenceStatementBytes,ba as probeNodeHealth,Id as provisionAgent,_a as provisionInfo,wu as readCloudLinkCallback,hs as readDelegatedCredential,oo as readDelegatedSession,Su as readEnrolmentCallback,Kn as readPinnedRelayNodeKey,q as readRelayMap,Ko as redeemInvitation,Es as relayForContext,Qe as relayTransportFetch,Pd as releaseAgent,Ot as rememberGroupNamespace,we as rememberRelay,Dr as reportDataOf,rt as requestBodyHash,qs as resolveApplicationIdFromRegistry,jn as resolveRelayFromInvitation,$n as resolveRelayNodeKey,Y as resolveRoot,en as resolveRootPair,ma as rootGuardedOpBytes,Bn as routingProofHeaders,ys as saveDelegatedCredential,ms as saveDelegatedSession,Tt as selectLatestBundle,wp as shouldRetain,Rr as signAccountHaClaim,ut as signAccountLink,tn as signAccountLogin,yc as signAccountOwnershipClaim,hn as signCreationWarrant,si as signDeviceCert,ai as signDeviceScope,At as signGovernanceWarrant,Vn as signGroupInvitation,Un as signLoginStatement,Jn as signMemberJoinOp,ga as signOwnerOpProof,$t as signRequest,dr as signRequestProof,Ts as signRoutingChallenge,mn as signWarrant,de as signedPath,Yo as signerFromCryptoKey,De as signerFromSecret,us as stateHash,Be as subgroupCreation,kn as subgroupVisibilitySetOp,Qt as subscribePresence,An as targetApplicationSetOp,ua as teeAdmissionPolicyOp,la as teeAuthoringPolicyOp,da as teeReleaseAdmissionPolicyOp,sa as transferOwnershipOp,Di as transportKeyBinding,Ji as trustSignedRelease,Mr as trustedMeasurementsFromReleases,Ua as validateAgentId,Xt as verifyDeviceCredential,Dd as verifySignedAgentPolicy,ji as verifySignedNodeRelease,mr as withCap,qt as withRetry,fp 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 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 j(t,e){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2!==0)throw new Error(`${e} must be an even number of hex characters`);let r=new Uint8Array(n.length/2);for(let o=0;o<r.length;o+=1)r[o]=Number.parseInt(n.slice(o*2,o*2+2),16);return r}function C(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function f(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}async function E(t,e){let n=[C(t.length),t];for(let r of e)n.push(C(r.length),r);return new Uint8Array(await crypto.subtle.digest("SHA-256",f(...n)))}async function ne(t){let e=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 Go(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 re(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 dr=new TextEncoder().encode("calimero.auth.request.v2"),ja=new TextEncoder().encode("calimero.auth.request.body.v1");function Ko(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}async function rt(t=new Uint8Array(0)){let e=typeof t=="string"?new TextEncoder().encode(t):t;return E(ja,[e])}async function Lt(t){let e=await ne(t.signerSecret),n=await rt(t.body),r=C(t.issuedAt),o=C(t.expiresAt),i=new TextEncoder,s=await E(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(Ko(t.method),Ko(t.path),n,r,o,a))}var ke=t=>new TextEncoder().encode(t),Ee="X-Calimero-Proof",Fa=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 rt(t.body),i=Math.floor(t.now??Date.now()/1e3),s=i+(t.validForSeconds??Fa),a=await E(dr,[ke(e),ke(n),o,C(i),C(s)]),c=await Va(a,t);if(c.length!==64)throw new Error(`the signer returned ${c.length} bytes, not a 64-byte signature`);let u=f(R(ke(e).length),ke(e),R(ke(n).length),ke(n),o,C(i),C(s),c),d=Wa(r,"credential");return y(f(d,new Uint8Array([0]),u))}async function Va(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 Wa(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 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{[Ee]:o}}}function de(t){let e=new URL(t,globalThis.location?.href??"http://localhost");return e.pathname+e.search}var Ja=new Set(["token_reuse","token_revoked"]);function za(t){if(t)try{let e=JSON.parse(t),n=e?.error;if(typeof n=="string"&&n.trim()!=="")return n;let r=n?.message;if(typeof r=="string"&&r.trim()!=="")return r;let o=e?.detail;if(typeof o=="string"&&o.trim()!=="")return o}catch{}}var O=class extends Error{constructor(n,r,o,i,s){let a=za(s)??(n===0&&s?.trim()?s.trim():void 0);super(a?`HTTP ${n} ${r}: ${a}`:`HTTP ${n} ${r}`);this.status=n;this.statusText=r;this.url=o;this.headers=i;this.bodyText=s;this.name="HTTPError";this.explanation=a}toJSON(){return{status:this.status,statusText:this.statusText,url:this.url,headers:$o(this.headers),bodyText:this.bodyText}}},oe=class extends O{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.reason=n;this.name="AuthRevokedError";this.message=`Authentication revoked (${n}): HTTP ${r} ${o}`}};function $o(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function Qa(t){let e;try{e=new URL(t,globalThis.location?.href)}catch{return t}return e.search===""&&(e.search=""),e.href}function Ht(t){return Object.keys(t).some(e=>e.toLowerCase()===Ee.toLowerCase())}function Bt(t,e){if(t.type==="opaqueredirect"||t.status>=300&&t.status<400)throw new O(0,"Redirect Not Followed",e,t.headers,`the node answered with a redirect; a request carrying ${Ee} is not followed to another location`)}var ot=class{constructor(e){this.transport=e;this.refreshTokenPromise=null;this.onTokenRefreshPromise=null}async get(e,n){return this.request(e,{...n,method:"GET"})}async post(e,n,r){return this.request(e,{...r,method:"POST",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async put(e,n,r){return this.request(e,{...r,method:"PUT",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async delete(e,n){return this.request(e,{...n,method:"DELETE"})}async patch(e,n,r){return this.request(e,{...r,method:"PATCH",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async head(e,n){let r=await this.makeRequest(e,{...n,method:"HEAD",parse:"response"});return{headers:$o(r.headers),status:r.status}}async request(e,n){return this.makeRequest(e,n)}async makeRequest(e,n,r=0,o){let s=Qa(this.buildUrl(e)),a=o??Date.now(),c=this.createAbortSignal(n),u=await this.buildHeaders(n?.headers),d;u instanceof Headers?(d={},u.forEach((b,k)=>{d[k]=b})):d=u;let l=n?.method||"GET";if(this.transport.authorizeRequest){let b=n?.body;if(b!==void 0&&typeof b!="string"&&!(b instanceof Uint8Array))throw new Error("this transport authorizes each request against its body, so the body must be a string or Uint8Array \u2014 a stream cannot be signed, because the signature would have to read bytes the request then cannot send.");Object.assign(d,await this.transport.authorizeRequest({method:l,path:de(s),body:b}))}let p={method:l,headers:d},x=n?.body instanceof ReadableStream||typeof n?.body=="object"&&n?.body!==null&&"getReader"in n.body&&!(n.body instanceof Blob);(n?.body!==void 0&&!x||n?.body!==void 0&&x&&r===0)&&(p.body=n.body);let v;if(r>0&&o!==void 0){let b=n?.timeoutMs||this.transport.timeoutMs;if(b){let k=Date.now()-a,T=Math.max(0,b-k);v=this.createAbortSignal({...n,timeoutMs:T})}else v=this.createAbortSignal(n)}else v=c;if(v&&(p.signal=v),this.transport.credentials!==void 0&&(p.credentials=this.transport.credentials),n?.mode!==void 0&&(p.mode=n.mode),n?.cache!==void 0&&(p.cache=n.cache),n?.redirect!==void 0&&(p.redirect=n.redirect),n?.referrer!==void 0&&(p.referrer=n.referrer),n?.referrerPolicy!==void 0&&(p.referrerPolicy=n.referrerPolicy),n?.integrity!==void 0&&(p.integrity=n.integrity),n?.keepalive!==void 0&&(p.keepalive=n.keepalive),this.transport.getProof){let b=await this.transport.getProof({method:p.method??"GET",path:de(s),body:p.body});b&&(d["X-Calimero-Proof"]=b)}let P=Ht(d);P&&p.redirect!=="error"&&(p.redirect="manual");try{let b=await this.transport.fetch(s,p);if(P&&Bt(b,s),!b.ok){let k=await this.getBodyText(b),T=new O(b.status,b.statusText,s,b.headers,k),H=b.headers.get("x-auth-error");if((b.status===401||b.status===403)&&H&&Ja.has(H)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new oe(H,b.status,b.statusText,s,b.headers,k)}let z=n?.signal?.aborted===!0;if(b.status===401&&this.transport.refreshToken&&H==="token_expired"&&r<1&&!x&&!z)try{let h=this.refreshTokenPromise;h||(h=this.transport.refreshToken(),this.refreshTokenPromise=h);let w=await h;if(!w||w.trim()==="")throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("Refresh token returned empty token");if(!this.transport.onTokenRefresh)throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("onTokenRefresh callback is required when refreshToken is provided. The callback must update the token storage so getAuthToken() returns the new token.");let S=this.onTokenRefreshPromise;S||(S=this.transport.onTokenRefresh(w),this.onTokenRefreshPromise=S),await S,this.refreshTokenPromise=null,this.onTokenRefreshPromise=null;let U=n?.timeoutMs||this.transport.timeoutMs;if(U&&o!==void 0){let M=Date.now()-a;if(U-M<=0)throw T}return this.makeRequest(e,n,r+1,a)}catch(h){throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,h instanceof Error&&h.message.includes("onTokenRefresh")?h:T}throw T}return this.parseResponse(b,n?.parse)}catch(b){throw b instanceof O||b instanceof Error&&b.message.includes("onTokenRefresh")?b:new O(0,"Network Error",s,new Headers,b instanceof Error?b.message:"Unknown error")}}buildUrl(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;let n=this.transport.baseUrl;return e.startsWith("/")?`${n.endsWith("/")?n.slice(0,-1):n}${e}`:`${n.endsWith("/")?n:`${n}/`}${e}`}createAbortSignal(e){let n=[];this.transport.defaultAbortSignal&&n.push(this.transport.defaultAbortSignal),e?.signal&&n.push(e.signal);let r=e?.timeoutMs||this.transport.timeoutMs;return r&&n.push(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 it(t){return new ot(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 it(e)}function qt(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 it(r)}function mr(t){return typeof window<"u"?Ie(t):qt(t)}function Ya(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 Xa(t){let n=250*Math.pow(2,t-1),r=(Math.random()-.5)*.4*n;return Math.max(0,n+r)}async function jt(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,!Ya(r,n-o))throw r;let s=Xa(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 Za(t,e={}){return async(...n)=>jt(()=>t(...n),e)}function m(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/${m(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/${m(e)}/clients/${m(n)}`)}async getKeyPermissions(e){return this.httpClient.get(`/admin/keys/${m(e)}/permissions`)}async updateKeyPermissions(e,n){return this.httpClient.put(`/admin/keys/${m(e)}/permissions`,{add:n.add,remove:n.remove})}};var st=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 fp(t){let e=new st;return new pe(e)}function hp(t){let e=new st;return new pe(e)}function yp(t){let e=new st;return new pe(e)}function Lo(t,e){return new pe(t)}var _={CAN_CREATE_CONTEXT:1,CAN_INVITE_MEMBERS:2,CAN_JOIN_OPEN_SUBGROUPS:4,MANAGE_MEMBERS:8,MANAGE_APPLICATION:16,CAN_CREATE_SUBGROUP:32,CAN_DELETE_SUBGROUP:64,CAN_MANAGE_VISIBILITY:128,CAN_MANAGE_METADATA:256,CAN_AUTHOR_ON_BEHALF:512},wp={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 Ap(...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 xp(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 vp(t,e){return(t&~e)>>>0}var ec={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 tc(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 nc(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=nc(t),n;return e!==void 0?n=tc(e):t instanceof TypeError?n="unreachable":n="unknown",{kind:n,status:e,retryable:ec[n],message:hr(t)}}function rc(t){return t.status!=="failed"||!t.retryable}function kp(t){return!rc(t)}var oc={invitation_expired:"expired",invitation_invalid:"invalid",invitation_already_used:"already-used",removed_from_group:"removed",reentry_blocked:"refused"};function ic(t){if(!t||typeof t!="object")return;let e=t;if(typeof e.response?.data?.code=="string")return e.response.data.code;if(typeof e.bodyText=="string")try{let n=JSON.parse(e.bodyText);return typeof n?.code=="string"?n.code:void 0}catch{return}}function sc(t){let e=t.toLowerCase();return e.includes("invitation has expired")||e.includes("invitation expired")||/\binvitation for group .+? expired at \d+/.test(e)?"expired":e.includes("malformed")||e.includes("does not match namespace_id")||e.includes("invalid invitation")||/\binvitation for group .+? is invalid:/.test(e)?"invalid":e.includes("has already used this invitation")?"already-used":/\bwas removed from group\b/.test(e)?"removed":null}var ac=new Set(["already-used","removed"]);function cc(t,e){let{kind:n,status:r}=yr(t),o=sc(e),i=ic(t),s=i?oc[i]:void 0;return s?{reason:s,retryable:!1}:o&&ac.has(o)?{reason:o,retryable:!1}:i==="join_refused_by_member"?{reason:"unknown",retryable:!0}:r===401?{reason:"signed-out",retryable:!0}:r===400?{reason:o??"invalid",retryable:!1}:r===410?{reason:"expired",retryable:!1}:r===403?{reason:"refused",retryable:!1}:r===409?{reason:o??"refused",retryable:!1}:n==="unavailable"?{reason:"no-one-online",retryable:!0}:n==="unreachable"?{reason:"node-unreachable",retryable:!0}:o?{reason:o,retryable:!1}:{reason:"unknown",retryable:!0}}async function Ho(t,e){let{namespaceId:n,invitation:r,teamName:o}=t,i=null;try{await e.join(n,r)}catch(d){i=d}let s=null;try{s=(await e.memberships()).includes(n)}catch{s=null}if(i===null)return{status:"joined",namespaceId:n,teamName:o};if(s===!0)return{status:"already-member",namespaceId:n,teamName:o};let a=hr(i,"Could not join. Check the invitation."),{reason:c,retryable:u}=cc(i,a);return{status:"failed",namespaceId:n,message:a,reason:c,retryable:u}}function A(t){return t?.data}function lc(t,e){let[n,r]=Bo(t),[o,i]=Bo(e),s=n.split("."),a=o.split("."),c=Math.max(s.length,a.length);for(let p=0;p<c;p++){let x=qo(s[p]??"0",a[p]??"0");if(x!==0)return x}if(r===void 0&&i===void 0)return 0;if(r===void 0)return 1;if(i===void 0)return-1;let u=r.split("."),d=i.split("."),l=Math.max(u.length,d.length);for(let p=0;p<l;p++){if(p>=u.length)return-1;if(p>=d.length)return 1;let x=qo(u[p],d[p]);if(x!==0)return x}return 0}function Bo(t){let e=t.split("+",1)[0],n=e.indexOf("-");return n===-1?[e,void 0]:[e.slice(0,n),e.slice(n+1)]}function qo(t,e){let n=/^\d+$/.test(t),r=/^\d+$/.test(e);if(n&&r){let o=Number(t)-Number(e);return o<0?-1:o>0?1:0}return n?-1:r?1:t<e?-1:t>e?1:0}async function uc(t,e,n){return jt(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 uc(r.toString(),"versions",n)).json();return(Array.isArray(i)?i:[]).map(s=>s.appVersion).filter(s=>typeof s=="string").sort((s,a)=>lc(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/${m(e)}`))}async listApplications(){return A(await this.httpClient.get("/admin-api/applications"))}async getApplication(e){return A(await this.httpClient.get(`/admin-api/applications/${m(e)}`))}async listApplicationVersions(e){return A(await this.httpClient.get(`/admin-api/applications/${m(e)}/versions`))}async getApplicationAbi(e,n){let r=n?`?service_name=${encodeURIComponent(n)}`:"";return A(await this.httpClient.get(`/admin-api/applications/${m(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/${m(e)}/versions`);return n?.data??n}async getLatestPackageVersion(e){return this.httpClient.get(`/admin-api/packages/${m(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/${m(e)}`))}async getContexts(){return A(await this.httpClient.get("/admin-api/contexts"))}async getContext(e){return A(await this.httpClient.get(`/admin-api/contexts/${m(e)}`))}async getContextsForApplication(e){return A(await this.httpClient.get(`/admin-api/contexts/for-application/${m(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/${m(e)}/identities`))}async getContextIdentitiesOwned(e){return A(await this.httpClient.get(`/admin-api/contexts/${m(e)}/identities-owned`))}async joinContext(e){return A(await this.httpClient.post(`/admin-api/contexts/${m(e)}/join`,{}))}async getContextGroup(e){return A(await this.httpClient.get(`/admin-api/contexts/${m(e)}/group`))}async getContextStorage(e){return A(await this.httpClient.get(`/admin-api/contexts/${m(e)}/storage`))}async syncContext(e){let n=e?`/admin-api/contexts/sync/${m(e)}`:"/admin-api/contexts/sync";await this.httpClient.post(n,{})}async resyncContext(e,n={}){return await this.httpClient.post(`/admin-api/contexts/${m(e)}/resync`,n)??{contextId:e,resyncStarted:!0}}async updateContextApplication(e,n){await this.httpClient.post(`/admin-api/contexts/${m(e)}/application`,n)}async getContextsWithExecutorsForApplication(e){let n=await this.httpClient.get(`/admin-api/contexts/with-executors/for-application/${m(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/${m(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/${m(e)}`;let r=new URLSearchParams({context_id:n.contextId});return`/admin-api/blobs/${m(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/${m(e)}`,{}))}async lookupApplicationAlias(e){return A(await this.httpClient.post(`/admin-api/alias/lookup/application/${m(e)}`,{}))}async deleteContextAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/context/${m(e)}`,{}))}async deleteApplicationAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/application/${m(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/${m(e)}`,{}))}async deleteDeviceAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/device/${m(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/${m(e)}`))}async getNodeIdentity(){return A(await this.httpClient.get("/admin-api/identity"))}async performIntent(e,n){return A(await this.httpClient.post(`/admin-api/contexts/${m(e)}/intents`,n))}async queryContext(e,n){return A(await this.httpClient.post(`/admin-api/contexts/${m(e)}/query`,n))}async getIntentRelay(e){return A(await this.httpClient.get(`/admin-api/contexts/${m(e)}/intents`))}async listNamespacesForApplication(e){return A(await this.httpClient.get(`/admin-api/namespaces/for-application/${m(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/${m(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async createNamespaceInvitation(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${m(e)}/invite`,n??{}))}async admitJoin(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${m(e)}/admit`,n,{timeoutMs:65e3}))}async joinNamespace(e,n){let r=A(await this.httpClient.post(`/admin-api/namespaces/${m(e)}/join`,n,{timeoutMs:65e3}));return r&&r.namespaceId===void 0&&r.groupId!==void 0?{...r,namespaceId:r.groupId}:r}async redeemInvitation(e,n,r={}){let{groupName:o,teamName:i}=r;return Ho({namespaceId:e,invitation:n,teamName:i},{join:async()=>{await this.joinNamespace(e,o===void 0?{invitation:n}:{invitation:n,groupName:o})},memberships:async()=>(await this.listNamespaces()??[]).map(s=>s.namespaceId)})}async createGroupInNamespace(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${m(e)}/groups`,n??{}))}async listNamespaceGroups(e){return A(await this.httpClient.get(`/admin-api/namespaces/${m(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/${m(e)}/relink`,n??{}))}async rescopeAccountDevice(e,n){return A(await this.httpClient.put(`/admin-api/account/devices/${m(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/${m(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/${m(e)}/account/revoke`,n))}async linkAccountDevice(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${m(e)}/account/link-device`,n))}async getGroupInfo(e){return A(await this.httpClient.get(`/admin-api/groups/${m(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/${m(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async listGroupMembers(e){let n=await this.httpClient.get(`/admin-api/groups/${m(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/${m(e)}/member-devices`;return(await this.httpClient.get(o?`${i}?${o}`:i)).members}async listMemberDevices(e,n={}){let r=new URLSearchParams;n.offset!==void 0&&r.set("offset",String(n.offset)),n.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${m(e)}/member-devices${o?`?${o}`:""}`;return this.httpClient.get(i)}async sealToAccount(e,n,r){return A(await this.httpClient.post(`/admin-api/groups/${m(e)}/accounts/${m(n)}/seal`,r))}async listGroupContexts(e){return A(await this.httpClient.get(`/admin-api/groups/${m(e)}/contexts`))}async addGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${m(e)}/members`,n)}async removeGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${m(e)}/members/remove`,n)}async updateMemberRole(e,n,r){await this.httpClient.put(`/admin-api/groups/${m(e)}/members/${m(n)}/role`,r)}async getMemberCapabilities(e,n){return A(await this.httpClient.get(`/admin-api/groups/${m(e)}/members/${m(n)}/capabilities`))}async setMemberCapabilities(e,n,r){await this.httpClient.put(`/admin-api/groups/${m(e)}/members/${m(n)}/capabilities`,r)}async setDefaultCapabilities(e,n){await this.httpClient.put(`/admin-api/groups/${m(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/${m(e)}/settings/subgroup-visibility`,n)}async setTeeAdmissionPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${m(e)}/settings/tee-admission-policy`,n)}async getTeeAdmissionPolicy(e){let n=await this.httpClient.get(`/admin-api/groups/${m(e)}/settings/tee-admission-policy`);return n.data??n}async setTeeAuthoringPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${m(e)}/settings/tee-authoring-policy`,n)}async disableTeeAuthoringPolicy(e,n={}){let r=`/admin-api/groups/${m(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/${m(e)}/transfer-ownership`,n)}async changeNamespaceAdmin(e,n){await this.httpClient.post(`/admin-api/namespaces/${m(e)}/admin`,n)}async ownerDeleteGroup(e,n={}){await this.httpClient.post(`/admin-api/groups/${m(e)}/owner-delete`,n)}async setGroupMetadata(e,n){await this.httpClient.put(`/admin-api/groups/${m(e)}/metadata`,n)}async getGroupMetadata(e){return(await this.httpClient.get(`/admin-api/groups/${m(e)}/metadata`))?.data??null}async setMemberMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${m(e)}/members/${m(n)}/metadata`,r)}async getMemberMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${m(e)}/members/${m(n)}/metadata`))?.data??null}async setContextMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${m(e)}/contexts/${m(n)}/metadata`,r)}async getContextMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${m(e)}/contexts/${m(n)}/metadata`))?.data??null}async syncGroup(e){return A(await this.httpClient.post(`/admin-api/groups/${m(e)}/sync`,{}))}async upgradeGroup(e,n){return A(await this.httpClient.post(`/admin-api/groups/${m(e)}/upgrade`,n))}async getGroupUpgradeStatus(e){return A(await this.httpClient.get(`/admin-api/groups/${m(e)}/upgrade/status`))}async getMigrationStatus(e){return this.httpClient.get(`/admin-api/groups/${m(e)}/migration-status`)}async listNamespaceRevokedDevices(e){return this.httpClient.get(`/admin-api/namespaces/${m(e)}/revoked-devices`)}async getCascadeStatus(e){return A(await this.httpClient.get(`/admin-api/groups/${m(e)}/cascade-status`))}async retryGroupUpgrade(e){return A(await this.httpClient.post(`/admin-api/groups/${m(e)}/upgrade/retry`,{}))}async reparentGroup(e,n){let r=await this.httpClient.post(`/admin-api/groups/${m(e)}/reparent`,n);return r?.data??r}async listSubgroups(e){let n=await this.httpClient.get(`/admin-api/groups/${m(e)}/subgroups`);return n.subgroups??n.data??[]}async detachContextFromGroup(e,n){await this.httpClient.post(`/admin-api/groups/${m(e)}/contexts/${m(n)}/remove`,{})}async createGroupInvitation(e,n){return A(await this.httpClient.post(`/admin-api/groups/${m(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/${m(e)}/join-via-inheritance`,{}))}async getTeeInfo(){return A(await this.httpClient.get("/admin-api/tee/info"))}async teeAttest(e){return A(await this.httpClient.post("/admin-api/tee/attest",e))}async getPeersCount(){return this.httpClient.get("/admin-api/peers")}async getNetworkStatus(){return this.httpClient.get("/admin-api/network/status")}async getUsage(){return this.httpClient.get("/admin-api/usage")}async createGroup(e){return A(await this.httpClient.post("/admin-api/groups",e))}async leaveGroup(e){await this.httpClient.post(`/admin-api/groups/${m(e)}/leave`,{})}async leaveContext(e){await this.httpClient.post(`/admin-api/contexts/${m(e)}/leave`,{})}async leaveNamespace(e){await this.httpClient.post(`/admin-api/namespaces/${m(e)}/leave`,{})}async issueOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${m(e)}/issue-ownership-proof`,n)}async issueNamespaceOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${m(e)}/issue-namespace-ownership-proof`,n)}async setMemberAutoFollow(e,n,r){await this.httpClient.put(`/admin-api/groups/${m(e)}/members/${m(n)}/auto-follow`,r)}async abortMigration(e){return this.httpClient.post(`/admin-api/groups/${m(e)}/migration/abort`,{})}};function Np(t){return Array.from(new TextEncoder().encode(t),e=>e.toString(16).padStart(2,"0")).join("")}function $p(t){return new me(Ie(t))}function Lp(t){return new me(qt(t))}function jo(t){return new me(mr(t))}function Ft(t,e){return new me(t)}var Fo="calimero.cloud.link.pending",br="link_state",dc=600*1e3,wr=/^[0-9a-f]{64}$/,pc=20,gc=32,Ar=/^[0-9a-f]{64}$/,mc="account-link-grant";function Vo(t,e){try{let n=localStorage.getItem(t),r=n?JSON.parse(n):{};return Object.fromEntries(Object.entries(r).filter(([,o])=>o&&typeof o.expiresAt=="number"&&o.expiresAt>e))}catch{return{}}}function Wo(t,e){try{localStorage.setItem(t,JSON.stringify(e))}catch{}}function at(t,e){let n=Date.now(),r=Vo(t,n),o=y(crypto.getRandomValues(new Uint8Array(16)));return r[o]={...e,expiresAt:n+dc},Wo(t,Object.fromEntries(Object.entries(r).slice(-pc))),o}function Pe(t,e){let n=Vo(t,Date.now());if(!e||!Object.prototype.hasOwnProperty.call(n,e))return null;let r=n[e];return delete n[e],Wo(t,n),r}async function xr(t){let e=Uint8Array.from(t.match(/../g)??[],n=>parseInt(n,16));return y(new Uint8Array(await crypto.subtle.digest("SHA-256",e)))}async function Vt(t,e){if(!wr.test(t))throw new Error("accountId must be 64 lowercase hex characters");let n=new URL(e),r=y(crypto.getRandomValues(new Uint8Array(gc))),o=await xr(r);return n.searchParams.set(br,at(Fo,{account:t,verifier:r})),{callbackUrl:n.toString(),challenge:o}}function Te(t,e){let n=Pe(Fo,new URLSearchParams(t).get(br));return!n||n.account!==e?null:typeof n.verifier=="string"&&Ar.test(n.verifier)?n.verifier:null}function ct(t){try{let e=t.split(".")[0].replace(/-/g,"+").replace(/_/g,"/"),n=JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(e),a=>a.charCodeAt(0)))),{use:r,sub:o,acc:i,chal:s}=n;return r!==mc||typeof o!="string"||typeof i!="string"||typeof s!="string"?null:{login:o,account:i,challenge:s}}catch{return null}}function Jo(t){let e=new URLSearchParams(t);e.delete(br);let n=e.toString();return n?`?${n}`:""}var zo="calimero.auth.login.pending",Qo="auth_state";function vr(t,e={}){try{let n=t.indexOf("#");if(n===-1)return null;let r=t.substring(n+1),o=new URLSearchParams(r),i=o.get("access_token");return i?!e.allowUnsolicited&&!Pe(zo,fc(t,n))?(console.warn("[mero-js] ignoring auth callback tokens: they answer no login begun in this browser"),null):{accessToken:i,refreshToken:o.get("refresh_token")??"",applicationId:o.get("application_id")??"",contextId:o.get("context_id")??"",contextIdentity:o.get("context_identity")??"",nodeUrl:o.get("node_url")??""}:null}catch{return null}}function fc(t,e){let n=t.indexOf("?");return n===-1||n>e?null:new URLSearchParams(t.substring(n+1,e)).get(Qo)}function Rr(t,e){let n=new URL(e.callbackUrl);n.searchParams.set(Qo,at(zo,{}));let r=new URLSearchParams;return r.set("callback-url",n.toString()),e.permissions&&e.permissions.length>0&&r.set("permissions",e.permissions.join(",")),r.set("mode",e.mode),e.packageName&&(r.set("package-name",e.packageName),e.packageVersion&&r.set("package-version",e.packageVersion),e.registryUrl&&r.set("registry-url",e.registryUrl)),`${t.replace(/\/+$/,"")}/auth/login?${r.toString()}`}function Wt(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 hc(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 Jt(t){let e=t.ttlSeconds??120,n=t.now??(()=>Math.floor(Date.now()/1e3));return async r=>{let o=n();return Wt({credential:t.credential,session:t.session,request:await Lt({method:r.method,path:r.path,body:hc(r.body),issuedAt:o,expiresAt:o+e,signerSecret:t.signerSecret})})}}var zt=class extends Error{constructor(e,n,r,o){super(n),this.name="RpcError",this.code=e,this.data=r,this.type=o}};async function Cr(t,e,n){let r=await t.post("/jsonrpc",{jsonrpc:"2.0",id:1,method:e,params:n});if(r.error){let o=r.error;throw new zt(o.code??-1,o.message??o.type??"RPC error",o.data,o.type)}return r.result}var lt=class{constructor(e){this.kind="node";this.canSubscribe=!0;this.httpClient=e.httpClient}async execute(e){let n=await Cr(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 yc=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function Yo(t){return t.type!==void 0&&yc.has(t.type)}var bc=new Set(["token_reuse","token_revoked"]),wc=new Set([401,403]),Ac=1e4;function Xo(t){let e=t.headers.get("x-auth-error");return!e||!wc.has(t.status)?null:bc.has(e)?e:null}var B=class{constructor(e){this.sessionId=null;this.abortController=null;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.presence=new Map;this.closed=!1;this.listeners={connect:[],event:[],error:[]};if(this.baseUrl=e.baseUrl.replace(/\/+$/,""),e.authorize)this.authorize=e.authorize;else if(e.getAuthToken){let n=e.getAuthToken;this.authorize=async()=>({Authorization:`Bearer ${await n()}`})}else throw new Error("SseClient needs either `getAuthToken` or `authorize`");this.reconnectDelayMs=e.reconnectDelayMs??3e3,this.fetchImpl=(n,r)=>e.fetch?e.fetch(n,r):globalThis.fetch(n,r)}on(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(n)||o.push(n)}}off(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r],i=o.indexOf(n);i!==-1&&o.splice(i,1)}}onAppVersionChanged(e){let n=r=>{if(r.type!=="AppVersionChanged")return;let o=r.data;e({contextId:r.contextId,fromVersion:o?.fromVersion,toVersion:o?.toVersion})};return this.on("event",n),()=>this.off("event",n)}onMigrationEvent(e){let n=r=>{Yo(r)&&e(r)};return this.on("event",n),()=>this.off("event",n)}emit(e,n){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(n)}catch{}}async connect(){if(this.abortController&&!this.closed)return;this.closed=!1;let e=new AbortController;this.abortController=e;try{let n=`${this.baseUrl}/sse`,r={...await this.authorize({method:"GET",path:de(n)}),Accept:"text/event-stream"},o=Ht(r),i=await this.fetchImpl(n,{headers:r,signal:e.signal,...o&&{redirect:"manual"}});if(o&&Bt(i,n),!i.ok){let s=Xo(i),a=await i.text().catch(()=>{});throw s?new oe(s,i.status,i.statusText,n,i.headers,a):new O(i.status,i.statusText,n,i.headers,a)}if(!i.body)throw new Error("SSE response has no body");this.readStream(i.body,e).catch(s=>{if(this.superseded(e))return;let a=s instanceof Error?s:new Error(String(s));this.emit("error",a),this.scheduleReconnect()})}catch(n){if(this.superseded(e))return;let r=n instanceof Error?n:new Error(String(n));if(this.emit("error",r),r instanceof oe)return;this.scheduleReconnect()}}superseded(e){return this.closed||e.signal.aborted||this.abortController!==e}async readStream(e,n){let r=e.getReader(),o=new TextDecoder,i="";try{for(;;){let{done:s,value:a}=await r.read();if(s)break;i+=o.decode(a,{stream:!0});let c=i.split(`
|
|
2
|
+
`);i=c.pop()??"";for(let u of c)if(u.startsWith("data:")){let d=u.slice(5).trim();d&&this.handleMessage(d)}}if(i+=o.decode(),i.startsWith("data:")){let s=i.slice(5).trim();s&&this.handleMessage(s)}}catch(s){if(this.superseded(n))return;let a=s instanceof Error?s:new Error(String(s));this.emit("error",a)}this.superseded(n)||this.scheduleReconnect()}handleMessage(e){try{let n=JSON.parse(e);if(n.type==="connect"&&n.session_id){let o=n.session_id;if(this.sessionId=o,this.presence.clear(),this.subscribedContextIds.size===0&&this.subscribedGroupIds.size===0){this.emit("connect",o);return}this.postSubscription("subscribe",{contextIds:[...this.subscribedContextIds],groupIds:[...this.subscribedGroupIds]}).then(i=>{this.closed||this.sessionId!==o||(this.emit("connect",o),i&&this.emit("error",i))});return}if(!n.result)return;let r=n.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),i=new TextDecoder().decode(o);r=JSON.parse(i)}catch{}if(n.result.contextId){n.result.type==="Ephemeral"&&this.notePresence(n.result.contextId,r),this.emit("event",{contextId:n.result.contextId,type:n.result.type,data:r});return}n.result.groupId&&this.emit("event",{groupId:n.result.groupId,type:n.result.type,data:r})}catch{}}async subscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>!this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>!this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.add(i);for(let i of n.groupIds??[])this.subscribedGroupIds.add(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("subscribe",{contextIds:r,groupIds:o})}isSubscribed(e){return this.subscribedContextIds.has(e)}presenceSeed(e){let n=Date.now();return[...this.presence.get(e)?.values()??[]].map(({data:r,at:o})=>({...r,ageMs:(typeof r.ageMs=="number"?r.ageMs:0)+(n-o)}))}notePresence(e,n){if(!this.subscribedContextIds.has(e))return;let r=n;if(!r||typeof r.author!="string")return;let o=this.presence.get(e);o||this.presence.set(e,o=new Map),r.removed?o.delete(r.author):o.set(r.author,{data:r,at:Date.now()})}async unsubscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.delete(i),this.presence.delete(i);for(let i of n.groupIds??[])this.subscribedGroupIds.delete(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("unsubscribe",{contextIds:r,groupIds:o})}async sendSubscription(e,n){let r=await this.postSubscription(e,n);r&&this.emit("error",r)}async postSubscription(e,n){let r=new AbortController,o=setTimeout(()=>r.abort(new DOMException(`SSE ${e} timed out`,"TimeoutError")),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=Ht(c),d=await this.fetchImpl(s,{method:"POST",headers:c,body:a,signal:r.signal,...u&&{redirect:"manual"}});if(u&&Bt(d,s),!d.ok){let l=Xo(d),p=await d.text().catch(()=>{});return l?new oe(l,d.status,d.statusText,`${this.baseUrl}/sse/subscription`,d.headers,p):new O(d.status,d.statusText,`${this.baseUrl}/sse/subscription`,d.headers,p)}return null}catch(i){return i instanceof Error?i:new Error(`SSE ${e} failed`)}finally{clearTimeout(o)}}forceReconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.sessionId=null,this.connect()}scheduleReconnect(){this.closed||(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.forceReconnect()},this.reconnectDelayMs))}close(){this.closed=!0,this.abortController&&(this.abortController.abort(),this.abortController=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.sessionId=null,this.subscribedContextIds.clear(),this.subscribedGroupIds.clear()}};var Qt=class Qt{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),Qt.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()}};Qt.MAX_BACKOFF_MS=3e4;var ie=Qt;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 ut=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,n,r=se()){await Cr(this.httpClient,"set_ephemeral",{contextId:e,state:r.encode(n)})}subscribe(e,n,r=se()){return Yt(this.sse,e,n,r)}};function Yt(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 xc=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function Zo(t){let e=t instanceof Error?`: ${t.message}`:"";return new Error("this runtime has no WebCrypto Ed25519, so nothing can be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it"+e)}async function De(t,e="secret"){let n=g(t,e,32),r=f(xc,n),o,i;try{let s=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!0,["sign"]),a=await crypto.subtle.exportKey("jwk",s);i=y(Uint8Array.from(atob(a.x.replace(/-/g,"+").replace(/_/g,"/")),c=>c.charCodeAt(0))),o=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!1,["sign"])}catch(s){throw Zo(s)}return ti(o,i)}async function ei(t,e){if(t.type!=="private")throw new Error(`signerFromCryptoKey needs the private half of the pair, got a ${t.type} key`);if(!t.usages.includes("sign"))throw new Error("this CryptoKey cannot sign: generate it with usages ['sign', 'verify']");let n;if(typeof e=="string")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 ti(t,n)}function ti(t,e){return{publicKey:e,async sign(n){try{return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},t,n))}catch(r){throw Zo(r)}}}}async function I(t,e,n){if(e&&t!==void 0)throw new Error(`pass either ${n} or signer, not both \u2014 they may name different keys`);if(e)return e;if(t!==void 0)return De(t,n);throw new Error(`${n} or signer is required`)}var vc=new TextEncoder().encode("calimero.mdma.account-ownership-claim.v1\0"),Rc=6e4,ni=5*6e4,ri=1024,ii="mdma:enable-ha-namespace",si="mdma:enable-ha-namespace-as-account";function oi(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var Sr=(t,e)=>{if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);return t.toLowerCase()};async function ai(t,e,n,r){if(r!==void 0&&!(r.length>0&&r.length<=ri))throw new Error(`relayUrl must be a non-empty string of at most ${ri} characters`);let o=t.ttlMs??Rc;if(!(o>0&&o<=ni))throw new Error(`ttlMs must be in (0, ${ni}]`);let i=Sr(t.namespaceId,"namespaceId"),s=Sr(t.accountId,"accountId"),a=Sr(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(vc,l));return{kind:"account",credential:t.credential,signed_payload:oi(l),signature:oi(p)}}async function Cc(t){if(!t.subject)throw new Error("subject must be the cloud login email");return ai(t,ii,t.subject)}async function kr(t){return ai(t,si,void 0,t.relayUrl)}var Sc=new TextEncoder().encode("calimero.device.cert.v1"),kc=new TextEncoder().encode("calimero.account.genesis.v1"),Ec=new TextEncoder().encode("calimero.device.id.v1"),Ue=2,Ic=237;async function Er(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 E(Ec,[n,e]);return y(f(e,r.subarray(0,16)))}async function Xt(t){return E(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 ci(t){return f(new Uint8Array([Ue]),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 li(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=g(e.publicKey,"signer.publicKey",32),r=await F(e.publicKey),o=0,i=await Xt({account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch}),s=await e.sign(i),a=ci({rootPublicKey:n,account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch,signature:s});return y(a)}function Ir(t){let e=g(t,"credential",Ic);if(e[0]!==Ue)throw new Error(`this credential has account genesis version ${e[0]}, not ${Ue} \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 Zt(t){let e=Ir(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=g(e.device,"device",32).subarray(0,16);if(await Er(e.account,r)!==e.device)throw new Error(`this credential names device ${e.device}, which was not minted for account ${e.account}; core refuses it`);if(!await Go(e.rootPublicKey,g(e.signature,"signature",64),await Xt(e)))throw new Error(`the root key of account ${e.account} did not sign this certificate`);return e}async function en(t){return F(y(await re(t)))}async function F(t){return y(await E(kc,[f(new Uint8Array([Ue]),g(t,"rootPublicKey",32))]))}var Pc=new TextEncoder().encode("calimero.device.scope.v1");async function Pr(t){return E(Pc,[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 ui(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=g(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 Pr({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([Ue]),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 Tr=["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 Tc=new TextEncoder().encode("calimero.mdma.account-link.v1\0"),Dc=new TextEncoder().encode("calimero.mdma.account-login.v1\0"),Oe=256,di=Oe/32,Dr=(Oe+di)/11;async function pi(){let t=crypto.getRandomValues(new Uint8Array(Oe/8));return bi(y(t),await Ai(t))}async function gi(t){let e=wi(t);return bi(y(await xi(e)),e.join(" "))}async function Ur(t){return g(t,"secret",32),{secret:t,publicKey:y(await re(t)),accountId:await en(t)}}async function mi(){let t=crypto.getRandomValues(new Uint8Array(Oe/8)),e=await Ai(t);return{...await hi(t),phrase:e}}async function fi(t){return hi(await xi(wi(t)))}async function hi(t){let e=await De(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 De(t,"rootSecret"):t;return yi(e)}async function tn(t,e){return yi(await I(t,e,"rootSecret"))}async function yi(t){return{signer:t,publicKey:t.publicKey,accountId:await F(t.publicKey)}}async function dt(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(Tc,new TextEncoder().encode(t.nonce)));return Ci(n)}async function nn(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(Dc,new TextEncoder().encode(t.nonce)));return Ci(n)}async function bi(t,e){return{...await Ur(t),phrase:e}}function wi(t){let e=t.normalize("NFKD").toLowerCase().trim().split(/\s+/),n=e[0]===""?0:e.length;if(n!==Dr)throw new Error(`recovery phrase must be ${Dr} words, got ${n}`);return e}async function Ai(t){let e=Ri(t)+await vi(t),n=[];for(let r=0;r<Dr;r+=1){let o=Number.parseInt(e.slice(r*11,r*11+11),2);n.push(Tr[o])}return n.join(" ")}async function xi(t){let e="";for(let r of t){let o=Tr.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(Oe/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(Oe)!==await vi(n))throw new Error("recovery phrase checksum failed \u2014 check for a mistyped or transposed word");return n}async function vi(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return Ri(e).slice(0,di)}function Ri(t){let e="";for(let n of t)e+=n.toString(2).padStart(8,"0");return e}function Ci(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var Uc=new TextEncoder().encode("calimero.tee-attest.key-binding.v1"),rn=new TextEncoder().encode("MOCK_TDX_QUOTE_V1"),Oc=568;function Nc(...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 Or(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 _c(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 Mc(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 on(t){let e=await crypto.subtle.digest("SHA-256",Nc(Uc,new Uint8Array(32),t));return new Uint8Array(e)}function Nr(t){let e=t.length>=rn.length&&Or(t.subarray(0,rn.length),rn),n=e?rn.length:Oc;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 sn(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=Mc(a.boundPublicKey,"boundPublicKey"),u=_c(a.quoteB64),{reportData:d,mock:l}=Nr(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 on(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(!Or(d.subarray(0,32),e))throw new Error("the quote does not carry our nonce: it was not made for this request");if(!Or(d.subarray(32,64),await on(c)))throw new Error("the quote does not bind the key the relay named: refusing it");return{nodeKey:y(c),mock:l}}var Gc="Noise_NK_25519_AESGCM_SHA256",_r=32,Kc=16,$c=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Gr=class t{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(Gc),n=new Uint8Array(32);return n.set(e),new t(n)}async mixHash(e){this.h=await Lc(f(this.h,e))}async mixKey(e){let[n,r]=await ki(this.ck,e);this.ck=n,this.k=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:Si(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(n),n}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let n=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Si(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),n}split(){return ki(this.ck,new Uint8Array)}};async function Ei(t,e,n){let r=await Gr.initialize();await r.mixHash(e),await r.mixHash(t);let o=await Ne(n);return await r.mixHash(o.publicKey),await r.mixKey(await pt(o.privateKey,t)),{message1:f(o.publicKey,await r.encryptAndHash(new Uint8Array)),async finish(s){if(s.length<_r+Kc)throw new Error("Noise: message 2 is too short");let a=s.slice(0,_r);return await r.mixHash(a),await r.mixKey(await pt(o.privateKey,a)),{payload:await r.decryptAndHash(s.slice(_r)),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($c,t),{name:"X25519"},!0,["deriveBits"]),n=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Hc(n.x)}}async function pt(t,e){let n=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:n},t,256))}function Si(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}async function Lc(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}async function Mr(t,e){let n=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",n,e))}async function ki(t,e){let n=await Mr(t,e),r=await Mr(n,new Uint8Array([1])),o=await Mr(n,f(r,new Uint8Array([2])));return[r,o]}function Hc(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}var Di="/sealed/v2/handshake",Ui="/sealed/v2",mt="application/vnd.calimero.sealed",Kr=2,Bc=new TextEncoder().encode("calimero/sealed-http/v2"),gt=16,qc=1+gt+8,jc=0,Fc=1,Vc=2,Wc=1+64*1024+16,Jc=1024,zc=6e4,Qc="calimero.tee-attest.transport-key.v1",Yc=[101,204,205,304],Oi=new TextEncoder,ft=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},_e=class extends Error{constructor(n,r,o,i){super(o);this.status=n;this.code=r;this.retryAfterMs=i;this.name="SealedTransportError"}};async function Ni(t,e){let n=await crypto.subtle.digest("SHA-256",f(Oi.encode(Qc),t,e));return new Uint8Array(n)}async function _i(t,e,n={}){if(n.applicationId===void 0!=(n.applicationHash===void 0))throw new Error("applicationId and applicationHash are given together or not at all");let r=y(crypto.getRandomValues(new Uint8Array(32))),o=await t.teeAttest({nonce:r,applicationId:n.applicationId,bindTransportKey:!0,...e.includeCollateral?{includeCollateral:!0}:{}});if(!o.transportPublicKey)throw new Error("The node did not report a transport key; it predates sealed transport");let i=g(o.transportPublicKey,"transportPublicKey",32),s=n.applicationHash?g(n.applicationHash,"applicationHash",32):new Uint8Array(32),a=y(await Ni(s,i));if(!await e({quoteB64:o.quoteB64,nonce:r,reportDataSuffix:a,collateral:o.collateral}))throw new Error("The attestation did not verify, so its transport key is not trusted");return i}function fe(t){let e=t.fetch??((o,i)=>fetch(o,i)),n=`${t.baseUrl.replace(/\/+$/,"")}/admin-api/tee/attest`,r={async teeAttest(o){let i=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)});if(!i.ok)throw new Error(`The node refused to attest: HTTP ${i.status}`);let s=await i.json();if(!s.data)throw new Error("The attestation response is malformed");return s.data}};return Mi({baseUrl:t.baseUrl,transportPublicKey:()=>_i(r,t.verify,{applicationId:t.applicationId,applicationHash:t.applicationHash}),fetch:e})}function Mi(t){let e=new URL(t.baseUrl),n=e.pathname.replace(/\/+$/,""),r=`${e.origin}${n}`,o=t.fetch??((l,p)=>fetch(l,p)),i=typeof t.transportPublicKey=="function"?t.transportPublicKey:void 0,s=i?Promise.resolve().then(i):Promise.resolve(t.transportPublicKey);s.catch(()=>{});let a,c=async()=>{try{return await Pi(o,r,await Ii(s))}catch(l){if(!(l instanceof ft)||!i)throw l;return s=Promise.resolve().then(i),Pi(o,r,await Ii(s))}},u=async()=>{let l=a??d(void 0),p=await l;if(Date.now()<p.renewAt)return[p,l];let x=d(l);return[await x,x]},d=l=>{if(a===l){let p=c();a=p,p.catch(()=>{a===p&&(a=void 0)})}return a};return async(l,p)=>{let x=new Request(l,p),v=new URL(x.url);if(v.origin!==e.origin||!v.pathname.startsWith(`${n}/`))throw new Error(`Refusing to send ${v.href} outside the sealed node at ${t.baseUrl}`);let P=[];x.headers.forEach((h,w)=>P.push([w,h]));let b={method:x.method,path:v.pathname.slice(n.length)+v.search,headers:P},k=new Uint8Array(await x.arrayBuffer()),T=async h=>{let{requestId:w,header:S,envelope:U}=await Zc(h,b,k),M=await o(`${r}${Ui}`,{method:"POST",headers:{"content-type":mt},body:U,signal:x.signal});if(M.headers.get("content-type")!==mt)throw await Ki(M);return tl(M,h.responseKey,S,w)},[H,z]=await u();try{return await T(H)}catch(h){if(!(h instanceof _e)||h.code!=="unknown_session")throw h;return T(await d(z))}}}async function Ii(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function Pi(t,e,n){try{return await Ti(t,e,n)}catch(r){if(!(r instanceof _e)||r.code!=="busy")throw r;return await new Promise(o=>setTimeout(o,r.retryAfterMs??1e3)),Ti(t,e,n)}}async function Ti(t,e,n){let r=await Ei(n,Bc),o=await t(`${e}${Di}`,{method:"POST",headers:{"content-type":mt},body:f(new Uint8Array([Kr]),n,r.message1)});if(o.headers.get("content-type")!==mt)throw await Ki(o);let i=await rl(o,Jc);return Xc(r,i)}async function Xc(t,e){if(e[0]!==Kr)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!==gt+4)throw new Error("The handshake reply is malformed");let i=r.slice(0,gt),s=new DataView(r.buffer,r.byteOffset).getUint32(gt,!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-zc,header(u){let d=new Uint8Array(qc);return d[0]=Kr,d.set(i,1),new DataView(d.buffer).setBigUint64(1+gt,BigInt(u),!1),d}}}async function Zc(t,e,n){let r=t.nextRequestId;t.nextRequestId+=1;let o=t.header(r),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:Gi(r,0),additionalData:o},t.requestKey,el(e,n));return{requestId:r,header:o,envelope:f(o,new Uint8Array(i))}}function Gi(t,e){let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setBigUint64(0,BigInt(t),!1),r.setUint32(8,e,!1),n}function el(t,e){let n=Oi.encode(JSON.stringify(t)),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,n.length,!1),f(r,n,e)}async function tl(t,e,n,r){if(!t.body)throw new Error("The sealed response has no body");let o=nl(t.body.getReader()),i=0,s=async()=>{let d=await o.next();if(!d)return null;let l;try{l=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Gi(r,i),additionalData:n},e,d))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return i+=1,{kind:l[0],data:l.slice(1)}},a=await s();if(!a||a.kind!==jc)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(Yc.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===Fc?d.enqueue(l.data):l.kind===Vc?(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 nl(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>Wc)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 rl(t,e){if(!t.body)return new Uint8Array;let n=t.body.getReader(),r=new Uint8Array;for(;;){let{done:o,value:i}=await n.read();if(o)return r;if(r=f(r,i),r.length>e)throw await n.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function Ki(t){let e,n=`Sealed request refused: HTTP ${t.status}`;try{let i=await t.json();e=i?.error?.code,i?.error?.message&&(n=`Sealed request refused: ${i.error.message}`)}catch{}if(e==="stale_transport_key")return new ft;let r=Number(t.headers.get("retry-after")),o=Number.isFinite(r)&&r>0?Math.min(r,5)*1e3:void 0;return new _e(t.status,e,n,o)}var ol=/^[0-9a-f]{96}$/,il=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function yt(t){let e=Me(t.allowedMrtd??[],"allowedMrtd"),n=(t.allowedMeasurements??[]).map((a,c)=>{let u=`allowedMeasurements[${c}]`;return il.map(d=>Me([a?.[d]??""],`${u}.${d}`)[0]).join()}),r=[Me(t.allowedRtmr0??[],"allowedRtmr0"),Me(t.allowedRtmr1??[],"allowedRtmr1"),Me(t.allowedRtmr2??[],"allowedRtmr2"),Me(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=al(a),p=d??await t.fetchCollateral?.(l);if(!p)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let x;try{x=t.dcapVerify(l,p,Math.floor(i()/1e3))}catch(k){throw new Error(`The quote did not verify: ${k?.message??String(k)}`)}if(x.status==="Revoked"||!o.includes(x.status))throw new Error(`The platform's TCB status is ${x.status}, which is not accepted`);let v=sl(x.report);if(v.tdAttributes?.length!==8||(v.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let P=[v.mrTd,v.rtMr0,v.rtMr1,v.rtMr2,v.rtMr3].map(k=>y(k));if(n.length>0&&!n.includes(P.join()))throw new Error(`The measurements (MRTD ${P[0]}, RTMR0-3 ${P.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(P[0]))throw new Error(`MRTD ${P[0]} is not an image this verifier trusts`);if([v.rtMr0,v.rtMr1,v.rtMr2,v.rtMr3].forEach((k,T)=>{let H=r[T];if(H.length>0&&!H.includes(y(k)))throw new Error(`RTMR${T} ${y(k)} is not one this verifier trusts`)}),y(v.reportData)!==`${c}${u}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function Me(t,e){return t.map(n=>{let r=n.trim().toLowerCase();if(!ol.test(r))throw new Error(`${e} holds ${JSON.stringify(n)}, which is not a 48-byte hex measurement`);return r})}function sl(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 al(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 cl=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],ht="locked-read-only";function $r(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!==ht&&!n)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(ht)}, or pass allowDebugProfile to test`);let u=(c.allowed_tcb_statuses??["uptodate"]).map(d=>ll(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 ll(t,e){let n=cl.find(r=>r.toLowerCase()===String(t).toLowerCase());if(!n)throw new Error(`${e} accepts TCB status ${JSON.stringify(t)}, which this verifier does not know`);return n}var $i=[{uri:"https://fulcio.sigstore.dev",validFor:{start:"2021-03-07T03:20:29Z",end:"2022-12-31T23:59:59.999Z"},certChain:["MIIB+DCCAX6gAwIBAgITNVkDZoCiofPDsy7dfm6geLbuhzAKBggqhkjOPQQDAzAqMRUwEwYDVQQKEwxzaWdzdG9yZS5kZXYxETAPBgNVBAMTCHNpZ3N0b3JlMB4XDTIxMDMwNzAzMjAyOVoXDTMxMDIyMzAzMjAyOVowKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTB2MBAGByqGSM49AgEGBSuBBAAiA2IABLSyA7Ii5k+pNO8ZEWY0ylemWDowOkNa3kL+GZE5Z5GWehL9/A9bRNA3RbrsZ5i0JcastaRL7Sp5fp/jD5dxqc/UdTVnlvS16an+2Yfswe/QuLolRUCrcOE2+2iA5+tzd6NmMGQwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwHQYDVR0OBBYEFMjFHQBBmiQpMlEk6w2uSu1KBtPsMB8GA1UdIwQYMBaAFMjFHQBBmiQpMlEk6w2uSu1KBtPsMAoGCCqGSM49BAMDA2gAMGUCMH8liWJfMui6vXXBhjDgY4MwslmN/TJxVe/83WrFomwmNf056y1X48F9c4m3a3ozXAIxAKjRay5/aj/jsKKGIkmQatjI8uupHr/+CxFvaJWmpYqNkLDGRU+9orzh5hI2RrcuaQ=="]},{uri:"https://fulcio.sigstore.dev",validFor:{start:"2022-04-13T20:06:15Z"},certChain:["MIICGjCCAaGgAwIBAgIUALnViVfnU0brJasmRkHrn/UnfaQwCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMjA0MTMyMDA2MTVaFw0zMTEwMDUxMzU2NThaMDcxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjEeMBwGA1UEAxMVc2lnc3RvcmUtaW50ZXJtZWRpYXRlMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8RVS/ysH+NOvuDZyPIZtilgUF9NlarYpAd9HP1vBBH1U5CV77LSS7s0ZiH4nE7Hv7ptS6LvvR/STk798LVgMzLlJ4HeIfF3tHSaexLcYpSASr1kS0N/RgBJz/9jWCiXno3sweTAOBgNVHQ8BAf8EBAMCAQYwEwYDVR0lBAwwCgYIKwYBBQUHAwMwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQU39Ppz1YkEZb5qNjpKFWixi4YZD8wHwYDVR0jBBgwFoAUWMAeX5FFpWapesyQoZMi0CrFxfowCgYIKoZIzj0EAwMDZwAwZAIwPCsQK4DYiZYDPIaDi5HFKnfxXx6ASSVmERfsynYBiX2X6SJRnZU84/9DZdnFvvxmAjBOt6QpBlc4J/0DxvkTCqpclvziL6BCCPnjdlIB3Pu3BxsPmygUY7Ii2zbdCdliiow=","MIIB9zCCAXygAwIBAgIUALZNAPFdxHPwjeDloDwyYChAO/4wCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMTEwMDcxMzU2NTlaFw0zMTEwMDUxMzU2NThaMCoxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjERMA8GA1UEAxMIc2lnc3RvcmUwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT7XeFT4rb3PQGwS4IajtLk3/OlnpgangaBclYpsYBr5i+4ynB07ceb3LP0OIOZdxexX69c5iVuyJRQ+Hz05yi+UF3uBWAlHpiS5sh0+H2GHE7SXrk1EC5m1Tr19L9gg92jYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRYwB5fkUWlZql6zJChkyLQKsXF+jAfBgNVHSMEGDAWgBRYwB5fkUWlZql6zJChkyLQKsXF+jAKBggqhkjOPQQDAwNpADBmAjEAj1nHeXZp+13NWBNa+EDsDP8G1WWg1tCMWP/WHPqpaVo0jhsweNFZgSs0eE7wYI4qAjEA2WB9ot98sIkoF3vZYdd3/VtWB5b9TNMea7Ix/stJ5TfcLLeABLE4BNJOsQ4vnBHJ"]}],Li=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var ul="1.2.840.10045.2.1",dl={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},pl={"P-256":32,"P-384":48},gl={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function Hi(t,e,n){if(e+2>n)throw new Error("it is truncated");let r=t[e];if((r&31)===31)throw new Error("it uses a tag this parser does not read");let o=t[e+1],i=e+2;if(o&128){let a=o&127;if(a===0||a>4||i+a>n)throw new Error("it has a length this parser does not read");o=0;for(let c=0;c<a;c+=1)o=o*256+t[i+c];i+=a}let s=i+o;if(s>n)throw new Error("it is truncated");return{tag:r,bytes:t,offset:e,start:i,end:s}}function Ke(t){let e=Hi(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function G(t){let e=[];for(let n=t.start;n<t.end;){let r=Hi(t.bytes,n,t.end);e.push(r),n=r.end}return e}function N(t,e,n){if(!t||t.tag!==e)throw new Error(`${n} is not where it should be`);return t}function ae(t){return t.bytes.slice(t.start,t.end)}function an(t){return t.bytes.slice(t.offset,t.end)}function Ge(t){let e=ae(N(t,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let n=[],r=0;for(let s of e)r=r*128+(s&127),s&128||(n.push(r),r=0);let o=n.shift();return[...o<80?[Math.floor(o/40),o%40]:[2,o-80],...n].join(".")}function ml(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 Lr(t){try{let[e,n,r,...o]=G(N(Ke(t),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let i=G(N(e,48,"The signed part")),s=i[0]?.tag===160?1:0,[a,c,u,d,l,p,...x]=i.slice(s);N(a,2,"The serial number");let v=Ge(G(N(n,48,"The signature algorithm"))[0]);if(Ge(G(N(c,48,"The signature algorithm"))[0])!==v)throw new Error("it names two different signature algorithms");let b=gl[v];if(!b)throw new Error(`it is signed with ${v}, not ECDSA with SHA-256 or SHA-384`);let[k,T]=G(N(d,48,"The validity")).map(ml);if(T===void 0)throw new Error("its validity is incomplete");let[H,z]=G(N(p,48,"The public key"));N(z,3,"The public key");let[h,w]=G(N(H,48,"The key algorithm"));if(Ge(h)!==ul)throw new Error("its key is not an elliptic-curve key");let S=dl[Ge(w)];if(!S)throw new Error("its key is on a curve other than P-256 or P-384");let U=new Map,M=x.find(ee=>ee.tag===163);if(M){let[ee]=G(M);for(let te of G(N(ee,48,"The extensions"))){let Se=G(N(te,48,"An extension"));if(Se.length===3)N(Se[1],1,"An extension's critical flag");else if(Se.length!==2)throw new Error("it has a malformed extension");let cr=Ge(Se[0]);if(U.has(cr))throw new Error(`it has extension ${cr} twice`);U.set(cr,ae(N(Se[Se.length-1],4,"An extension value")))}}let Q=ae(N(r,3,"The signature"));if(Q[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:an(e),signatureHash:b,signature:Q.slice(1),issuer:an(N(u,48,"The issuer")),subject:an(N(l,48,"The subject")),notBefore:k,notAfter:T,spki:an(p),curve:S,extensions:U}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function Bi(t){return G(N(Ke(t),48,"The list")).map(Ge)}function fl(t,e){let n=pl[e],r=G(N(Ke(t),48,"The signature"));if(r.length!==2)throw new Error("The signature is not an ECDSA signature");let o=new Uint8Array(n*2);return r.forEach((i,s)=>{let a=ae(N(i,2,"The signature"));if(a.length===0||a[0]&128)throw new Error("The signature is not an ECDSA signature");for(;a.length>1&&a[0]===0;)a=a.subarray(1);if(a.length>n)throw new Error("The signature is not an ECDSA signature");o.set(a,s*n+n-a.length)}),o}async function cn(t,e,n,r,o){let i;try{i=fl(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 Hr(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 hl="2.5.29.17",yl="2.5.29.37",bl="1.3.6.1.5.5.7.3.3",wl="1.3.6.1.4.1.57264.1.8",Al="1.3.6.1.4.1.57264.1.1",xl=134,vl=12,Rl=48,Cl=new TextEncoder,$e=t=>new TextDecoder().decode(t);async function ln(t,e,n,r){let{base64Signature:o,cert:i,rekorBundle:s}=Il(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=Hr($e(V(i,"The bundle certificate")),"The bundle certificate"),d=Lr(u),l=Li.find(T=>T.logId===a.logID.toLowerCase());if(!l)throw new Error(`The bundle names Rekor log ${a.logID}, which the Sigstore trust root does not know`);let p=Cl.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await cn(V(l.publicKey,"The Rekor key"),"P-256","SHA-256",V(s.SignedEntryTimestamp,"The signed entry timestamp"),p))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let v=a.integratedTime*1e3;if(!Fi(v,l.validFor))throw new Error(`Rekor log ${l.baseUrl} was not in use at ${bt(v)}, when the entry says it was logged`);let P=Pl(a.body),b=y(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(P.hash!==b)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!Br(V(P.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let k=Hr($e(V(P.publicKey,"The logged certificate")),"The logged certificate");if(!Br(k,u))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await cn(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),El(d,n),{integratedTime:a.integratedTime}}async function Sl(t,e){if(!ji(t,e))throw new Error(`The signing certificate was valid ${bt(t.notBefore)} to ${bt(t.notAfter)}, not at ${bt(e)} when Rekor logged it`);let n=[];for(let r of $i){let o=r.certChain.map(s=>Lr(V(s,"A Fulcio certificate")));if(!await qi(t,o[0]))continue;let i=await kl(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 ${bt(e)}: ${n.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function kl(t,e,n){if(!Fi(n,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of t.entries()){if(!ji(o,n))return`its certificate ${r} was not valid then`;let i=t[r+1]??o;if(!await qi(o,i))return`its certificate ${r} is not signed by the next`}}async function qi(t,e){return Br(t.issuer,e.subject)?cn(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function El(t,e){let n=t.extensions.get(hl);if(!n)throw new Error("The signing certificate names no identity");let r=G(N(Ke(n),Rl,"The subject alternative name")),o=r.filter(u=>u.tag===xl).map(u=>$e(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(wl),s=t.extensions.get(Al),a=i?$e(ae(N(Ke(i),vl,"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(yl);if(!c||!Bi(c).includes(bl))throw new Error("The signing certificate is not for code signing")}function Il(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 Pl(t){let e;try{e=JSON.parse($e(V(t,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let n=e?.spec?.data?.hash,r=e?.spec?.signature;if(e?.kind!=="hashedrekord"||n?.algorithm!=="sha256"||typeof n.value!="string"||typeof r?.content!="string"||typeof r.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:n.value.toLowerCase(),signature:r.content,publicKey:r.publicKey.content}}function ji(t,e){return t.notBefore<=e&&e<=t.notAfter}function Fi(t,e){return Date.parse(e.start)<=t&&(e.end===void 0||t<=Date.parse(e.end))}function bt(t){return new Date(t).toISOString()}function Br(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var qr=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"}),Tl=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],un="https://cloud.calimero.network";async function Wi(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await ln(r,e,{identity:n.identity??qr.identity,issuer:n.issuer??qr.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=>Tl.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 dn(t,e={}){let n=await(e.fetch??fetch)(t,{headers:{accept:"application/json"}});if(!n.ok)throw new Error(`Fetching the node release from ${t} failed: HTTP ${n.status}`);let r;try{r=(await n.json())?.data}catch{throw new Error(`${t} did not answer with JSON`)}if(typeof r?.version!="string"||typeof r.publishedMrtds!="string"||typeof r.bundle!="string")throw new Error(`${t} did not answer with a signed node release`);return{version:r.version,publishedMrtds:r.publishedMrtds,bundle:r.bundle}}function Ji(t){let e=/^merotee-.+-(\d+)-(\d+)-(\d+)$/.exec(t);if(!e)throw new Error(`${JSON.stringify(t)} is not the image of a mero-tee node release`);return`${Number(e[1])}.${Number(e[2])}.${Number(e[3])}`}async function pn(t,e={}){let n=await Qi(t,e.fetch??fetch);if(n===void 0)throw new Error(`${zi(t)} was refused unsealed: the node requires sealing and is too old to name its release before a session exists. Name the release it runs yourself (createSignedReleaseSealedFetch's \`releaseVersion\`), or upgrade the node`);return n}function zi(t){return`${t.replace(/\/+$/,"")}/admin-api/tee/info`}async function Qi(t,e){let n=zi(t),r=await e(n,{headers:{accept:"application/json"}});if(r.status===403&&await r.json().then(s=>s?.error?.code).catch(()=>{})==="sealed_required")return;if(!r.ok)throw new Error(`Fetching ${n} failed: HTTP ${r.status}`);let o;try{o=(await r.json())?.data?.osImage}catch{throw new Error(`${n} did not answer with JSON`)}if(typeof o!="string")throw new Error(`${n} did not name the node's image`);return Ji(o)}function gn(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${wt(e,"version")}`}async function Yi(t){let e=wt(t.minReleaseVersion,"minReleaseVersion"),n=wt(t.release?.version,"The release version"),r=await Wi(t.release.publishedMrtds,t.release.bundle,{expectedVersion:n,identity:t.identity,issuer:t.issuer});if(Ul(n,e)<0)throw new Error(`Release ${n} is older than the minimum trusted, ${e}`);return $r([r],{profile:t.profile,allowDebugProfile:t.allowDebugProfile})}function mn(t){return wt(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async n=>{let r=await Yi({release:await t.release(),profile:t.profile,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer});return yt({dcapVerify:t.dcapVerify,fetchCollateral:t.fetchCollateral,now:t.now,...r})(n)},{includeCollateral:!0})}function Dl(t){let{baseUrl:e,releaseSource:n,releaseVersion:r,applicationId:o,applicationHash:i,fetch:s,...a}=t;r!==void 0&&wt(r,"releaseVersion");let c=s??((d,l)=>fetch(d,l));return fe({baseUrl:e,verify:mn({...a,release:async()=>{let d=r===void 0?await pn(e,{fetch:c}):await Qi(e,c)??r;return typeof n=="function"?n({baseUrl:e,version:d,fetch:c}):dn(gn(n??un,d),{fetch:c})}}),applicationId:o,applicationHash:i,fetch:c})}var Xi=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function wt(t,e){let n=typeof t=="string"?Xi.exec(t):null,r=n?.[4];if(!n||r!==void 0&&r.split(".").some(o=>o===""))throw new Error(`${e} is ${JSON.stringify(t)}, not a release version like 2.3.87`);return t}function Ul(t,e){let[n,r]=Vi(t),[o,i]=Vi(e);for(let c=0;c<3;c+=1)if(n[c]!==o[c])return n[c]<o[c]?-1:1;if(r===void 0||i===void 0)return r===i?0:r===void 0?1:-1;let s=r.split("."),a=i.split(".");for(let c=0;c<Math.max(s.length,a.length);c+=1){let[u,d]=[s[c],a[c]];if(u===void 0||d===void 0)return u===void 0?-1:1;let[l,p]=[/^\d+$/.test(u),/^\d+$/.test(d)],x=l&&p?Math.sign(Number(u)-Number(d)):l!==p?l?-1:1:u<d?-1:u>d?1:0;if(x!==0)return x}return 0}function Vi(t){let e=Xi.exec(t);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var Ol=new TextEncoder().encode("calimero.warrant.v2"),Nl=new TextEncoder().encode("calimero.warrant.intent.v1"),Zi=64,es=256;async function jr(t,e){let n=new TextEncoder().encode(JSON.stringify(e));return E(Nl,[new TextEncoder().encode(t),n])}async function fn(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=Fr(t.releaseVersion??""),a=ce(t.accountHeads,"accountHeads"),c=ce(t.governanceFloor,"governanceFloor"),u=await I(t.deviceSecret,t.signer,"deviceSecret"),d=g(u.publicKey,"signer.publicKey",32),l=new TextEncoder().encode(t.method),p=await jr(t.method,t.argsJson),x=C(t.nonce),v=C(t.notAfter),P=await E(Ol,[e,n,d,r,o,i,s,l,p,C(a.length),...a,C(c.length),...c,x,v]),b=At(await u.sign(P));return y(f(e,n,d,r,o,i,R(s.length),s,R(l.length),l,p,R(a.length),...a,R(c.length),...c,x,v,b))}function At(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 Fr(t){let e=new TextEncoder().encode(t);return _l(e.length),e}function _l(t){if(t>es)throw new Error(`releaseVersion is ${t} bytes, over the ${es} a node accepts`)}function ce(t,e){let n=t??[];if(n.length>Zi)throw new Error(`${e} cites ${n.length} heads, over the ${Zi} a node accepts`);return n.map((r,o)=>g(r,`${e}[${o}]`,32))}var Ml=new TextEncoder().encode("calimero.context-creation-warrant.v1"),Gl=new TextEncoder().encode("calimero.context-creation.init.v1"),hn=256;async function Vr(t){let e=new TextEncoder().encode(JSON.stringify(t));return E(Gl,[e])}async function Kl(t){return E(Ml,[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 yn(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=ts(t.serviceName,"serviceName"),c=ts(t.name,"name"),u=ce(t.accountHeads,"accountHeads"),d=ce(t.governanceFloor,"governanceFloor"),l=await I(t.deviceSecret,t.signer,"deviceSecret"),p=g(l.publicKey,"signer.publicKey",32),x=await Vr(t.initArgs),v=await Kl({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=At(await l.sign(v));return{warrant:y(f(e,n,r,p,o,i,s,ns(a),ns(c),x,R(u.length),...u,R(d.length),...d,C(t.nonce),C(t.notAfter),P)),seed:y(n)}}function rs(t){let e=t.trim();if(!/^[0-9a-fA-F]*$/.test(e)||e.length%2!==0)throw new Error("creation warrant must be an even number of hex characters");let n=new Uint8Array(e.length/2);for(let l=0;l<n.length;l+=1)n[l]=Number.parseInt(e.slice(l*2,l*2+2),16);let r=new DataView(n.buffer),o=0,i=(l,p)=>{if(o+l>n.length)throw new Error(`creation warrant ends inside ${p} (${n.length} bytes)`);let x=n.subarray(o,o+l);return o+=l,x},s=l=>r.getUint32(i(4,l).byteOffset,!0),a=l=>r.getBigUint64(i(8,l).byteOffset,!0),c=l=>{let p=i(1,l)[0];if(p===0)return null;if(p!==1)throw new Error(`${l} has option tag ${p}, expected 0 or 1`);let x=s(l);if(x>hn)throw new Error(`${l} is ${x} bytes, over the ${hn} a node accepts`);return new TextDecoder("utf-8",{fatal:!0}).decode(i(x,l))},u=l=>{let p=s(l);if(p>64)throw new Error(`${l} cites ${p} heads, over the 64 a node accepts`);return Array.from({length:p},()=>y(i(32,l)))},d={group:y(i(32,"group")),seed:y(i(32,"seed")),authorAccount:y(i(32,"authorAccount")),deviceKey:y(i(32,"deviceKey")),executor:y(i(32,"executor")),executorKey:y(i(32,"executorKey")),applicationId:y(i(32,"applicationId")),serviceName:c("serviceName"),name:c("name"),initHash:y(i(32,"initHash")),accountHeads:u("accountHeads"),governanceFloor:u("governanceFloor"),nonce:a("nonce"),notAfter:a("notAfter"),signature:y(i(64,"signature"))};if(o!==n.length)throw new Error(`creation warrant is ${n.length} bytes but its fields account for ${o}`);return d}function ts(t,e){if(t===void 0)return null;let n=new TextEncoder().encode(t);if(n.length>hn)throw new Error(`${e} is ${n.length} UTF-8 bytes, over the ${hn} a node accepts`);return n}function ns(t){return t===null?new Uint8Array([0]):f(new Uint8Array([1]),R(t.length),t)}var $l=new TextEncoder().encode("calimero.governance-warrant.v1"),Ll=new TextEncoder().encode("calimero.governance-warrant.op.v1"),Hl={group:0,root:1};async function Wr(t){return E(Ll,[new Uint8Array([Jr(t.kind)]),t.bytes])}async function Bl(t){return E($l,[t.scope,new Uint8Array([Jr(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 xt(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=ce(t.accountHeads,"accountHeads"),s=ce(t.governanceFloor,"governanceFloor"),a=Jr(t.op.kind),c=await I(t.deviceSecret,t.signer,"deviceSecret"),u=g(c.publicKey,"signer.publicKey",32),d=await Wr(t.op),l=await Bl({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=At(await c.sign(l));return y(f(e,new Uint8Array([a]),n,u,r,o,d,R(i.length),...i,R(s.length),...s,C(t.nonce),C(t.notAfter),p))}function os(t){let e=t.trim();if(!/^[0-9a-fA-F]*$/.test(e)||e.length%2!==0)throw new Error("governance warrant must be an even number of hex characters");let n=new Uint8Array(e.length/2);for(let l=0;l<n.length;l+=1)n[l]=Number.parseInt(e.slice(l*2,l*2+2),16);let r=new DataView(n.buffer),o=0,i=(l,p)=>{if(o+l>n.length)throw new Error(`governance warrant ends inside ${p} (${n.length} bytes)`);let x=n.subarray(o,o+l);return o+=l,x},s=l=>r.getUint32(i(4,l).byteOffset,!0),a=l=>r.getBigUint64(i(8,l).byteOffset,!0),c=l=>{let p=s(l);if(p>64)throw new Error(`${l} cites ${p} heads, over the 64 a node accepts`);return Array.from({length:p},()=>y(i(32,l)))},u=()=>{let l=i(1,"kind")[0];if(l===0)return"group";if(l===1)return"root";throw new Error(`governance warrant has kind ${l}, expected 0 (group) or 1 (root)`)},d={scope:y(i(32,"scope")),kind:u(),authorAccount:y(i(32,"authorAccount")),deviceKey:y(i(32,"deviceKey")),executor:y(i(32,"executor")),executorKey:y(i(32,"executorKey")),opHash:y(i(32,"opHash")),accountHeads:c("accountHeads"),governanceFloor:c("governanceFloor"),nonce:a("nonce"),notAfter:a("notAfter"),signature:y(i(64,"signature"))};if(o!==n.length)throw new Error(`governance warrant is ${n.length} bytes but its fields account for ${o}`);return d}function Jr(t){let e=Hl[t];if(e===void 0)throw new Error(`op kind must be 'group' or 'root', got ${String(t)}`);return e}var ql={Admin:0,Member:1,ReadOnly:2},K={MemberAdded:1,MemberRemoved:2,MemberLeft:3,MemberRoleSet:4,MemberCapabilitySet:5,DefaultCapabilitiesSet:6,TargetApplicationSet:7,ContextDetached:9,SubgroupVisibilitySet:10,GroupMetadataSet:11,MemberMetadataSet:12,ContextMetadataSet:13,ContextCapabilityGranted:16,ContextCapabilityRevoked:17},vt={GroupCreated:0,GroupReparented:1,GroupDeleted:2,MemberJoinedOpen:7,NamespaceCreatedV2:9},jl=new TextEncoder().encode("calimero.namespace.id.v1"),Qr=new Uint8Array(32),bn=R(0);function ss(t){let e=ql[t];if(e===void 0)throw new Error(`role must be Admin, Member or ReadOnly, got ${String(t)}`);return new Uint8Array([e])}function D(t){return new Uint8Array([t])}function Le(t,e){return{kind:"group",bytes:f(D(K.MemberAdded),g(t,"member",32),ss(e))}}function wn(t){return{kind:"group",bytes:f(D(K.MemberRemoved),g(t,"member",32),Qr,bn)}}function Rt(t){return{kind:"group",bytes:f(D(K.MemberLeft),g(t,"member",32),Qr,bn)}}function An(t,e){return{kind:"group",bytes:f(D(K.MemberRoleSet),g(t,"member",32),ss(e))}}var Fl=new TextEncoder().encode("calimero.subgroup.id.v1");async function Yr(t,e,n,r){return y(await E(Fl,[g(t,"admin",32),g(e,"parentId",32),new Uint8Array([n?1:0]),g(r,"salt",32)]))}function is(t,e){if(t.length===0)throw new Error(`${e} must not be empty`);let n=new TextEncoder().encode(t);return f(R(n.length),n)}function xn(t){return{kind:"group",bytes:f(D(K.TargetApplicationSet),Qr,g(t.applicationId,"applicationId",32),is(t.package,"package"),is(t.version,"version"))}}function He(t){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`capabilities must be a u32 bit mask, got ${String(t)}`);if(ge(t,_.CAN_AUTHOR_ON_BEHALF))throw new Error("capabilities may not include CAN_AUTHOR_ON_BEHALF (512): a relay never carries a change to it");return{kind:"group",bytes:f(D(K.DefaultCapabilitiesSet),R(t))}}function Xr(t){return{kind:"root",bytes:f(D(vt.GroupCreated),g(t.groupId,"groupId",32),g(t.parentId,"parentId",32),D(t.restricted?1:0),g(t.admin,"admin",32),g(t.salt,"salt",32))}}async function Be(t){let e=t.salt??y(crypto.getRandomValues(new Uint8Array(32))),n=await Yr(t.admin,t.parentId,t.restricted,e);return{groupId:n,salt:e,op:Xr({...t,groupId:n,salt:e})}}function vn(t,e){return{kind:"root",bytes:f(D(vt.GroupReparented),g(t,"childGroupId",32),g(e,"newParentId",32))}}function Rn(t){return{kind:"root",bytes:f(D(vt.GroupDeleted),g(t,"rootGroupId",32),bn,bn)}}async function Cn(t,e){return y(await E(jl,[g(t,"founder",32),g(e,"salt",32)]))}function Sn(t){let e=j(t.credential,"credential");if(e.length===0)throw new Error("credential must be the founder's AccountProof<DeviceCert>, got nothing");return{kind:"root",bytes:f(D(vt.NamespaceCreatedV2),g(t.founder,"founder",32),e,g(t.salt,"salt",32))}}function zr(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}function Zr(t){return t===void 0?D(0):f(D(1),zr(t))}function eo(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])=>[zr(o),zr(r)]))}function Vl(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 kn(t,e){return{kind:"group",bytes:f(D(K.MemberCapabilitySet),g(t,"member",32),R(Vl(e,"capabilities")))}}function En(t){return{kind:"group",bytes:f(D(K.ContextDetached),g(t,"contextId",32))}}function In(t){if(t!=="open"&&t!=="restricted")throw new Error(`mode must be open or restricted, got ${String(t)}`);return{kind:"group",bytes:f(D(K.SubgroupVisibilitySet),D(t==="open"?0:1))}}function qe(t={}){return{kind:"group",bytes:f(D(K.GroupMetadataSet),Zr(t.name),eo(t.data))}}function Pn(t,e={}){return{kind:"group",bytes:f(D(K.MemberMetadataSet),g(t,"member",32),Zr(e.name),eo(e.data))}}function Tn(t,e={}){return{kind:"group",bytes:f(D(K.ContextMetadataSet),g(t,"contextId",32),Zr(e.name),eo(e.data))}}function as(t){if(!Number.isInteger(t)||t<1||t>255)throw new Error(`capability must be a non-zero u8, got ${String(t)}`);return D(t)}function cs(t,e,n){return{kind:"group",bytes:f(D(K.ContextCapabilityGranted),g(t,"contextId",32),g(e,"member",32),as(n))}}function ls(t,e,n){return{kind:"group",bytes:f(D(K.ContextCapabilityRevoked),g(t,"contextId",32),g(e,"member",32),as(n))}}function Dn(t){return{kind:"root",bytes:f(D(vt.MemberJoinedOpen),g(t.member,"member",32),g(t.groupId,"groupId",32),j(t.credential,"credential"))}}var Un=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"}},Wl=t=>new Promise(e=>setTimeout(e,t));function Jl(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/${m(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??"";Fr(a);let c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??Un,l=await fn({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/${m(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/${m(e)}/presence-intents`,n)}async describeCreation(e,n={}){let r=n.author?`?author=${encodeURIComponent(n.author)}`:"";return(await this.json("GET",`/admin-api/groups/${m(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??Un,{warrant:c}=await yn({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/${m(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/${m(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??Un,a=await xt({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 Cn(this.config.authorAccount,r),i=Sn({founder:this.config.authorAccount,credential:this.config.authorProof,salt:r}),s=e.defaultCapabilities===void 0?void 0:He(e.defaultCapabilities),a=e.application?xn(e.application):void 0,c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??Un,l=await xt({scope:o,op:i,authorAccount:this.config.authorAccount,executor:n.executorAccount,executorKey:n.executorKey,nonce:u,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(d),signer:c}),p=await this.postGovernance(o,i,l),x={namespaceId:p.groupId,salt:r,teeEnabled:p.teeEnabled??!1,...p.teeError?{teeError:p.teeError}:{}},v=x,P=b=>b instanceof Error?b.message:String(b);if(a)try{await this.govern({groupId:x.namespaceId,op:a}),v={...v,applicationSet:!0}}catch(b){v={...v,applicationSet:!1,applicationError:P(b)}}if(s)try{await this.govern({groupId:x.namespaceId,op:s}),v={...v,defaultCapabilitiesSet:!0}}catch(b){v={...v,defaultCapabilitiesSet:!1,defaultCapabilitiesError:P(b)}}return v}async postGovernance(e,n,r){return(await this.json("POST",`/admin-api/groups/${m(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 O&&s.status===429)||i>=this.rateLimitRetries)throw s;let c=Jl(s.headers);await Wl(c??o),o*=2}}async jsonOnce(e,n,r){let o={Accept:"application/json"};r!==void 0&&(o["Content-Type"]="application/json");let i=new AbortController,s=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r===void 0?void 0:JSON.stringify(r),signal:i.signal})}catch(c){throw new O(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(!a.ok){let c=await a.text().catch(()=>"");if(a.status===400||a.status===403){let u=zl(c);throw new he(u,/nonce/i.test(u),a.status)}throw new O(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(a.status!==204)return await a.json()}};function zl(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 Ql=new TextEncoder().encode("calimero.auth.login.v1"),us={webOrigin:0,codeSigningId:1,cli:2};function ds(t){let e=new TextEncoder;switch(t.kind){case"webOrigin":return e.encode(t.origin);case"codeSigningId":return e.encode(t.id);case"cli":return new Uint8Array(0)}}function Yl(t){return f(Uint8Array.from([us[t.kind]]),ds(t))}function Xl(t){let e=Uint8Array.from([us[t.kind]]);if(t.kind==="cli")return e;let n=ds(t);return f(e,R(n.length),n)}async function On(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=C(t.issuedAt),a=C(t.expiresAt),c=await E(Ql,[e,Yl(t.audience),n,r,i,s,a]),u=await o.sign(c);return y(f(e,Xl(t.audience),n,r,i,s,a,u))}var Zl=300;async function to(){let t=y(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:y(await re(t)),secret:t}}async function je(t){let e=t.nodeUrl.replace(/\/+$/,""),n=t.timeoutMs??1e4,r=async(p,x)=>{let v=new AbortController,P=setTimeout(()=>v.abort(),n),b;try{let T={...x,signal:v.signal};b=t.fetch?await t.fetch(`${e}${p}`,T):await globalThis.fetch(`${e}${p}`,T)}catch(T){throw new O(0,T instanceof Error?T.name:"NetworkError",`${e}${p}`,new Headers,T instanceof Error?T.message:String(T))}finally{clearTimeout(P)}let k=await b.text().catch(()=>"");if(!b.ok)throw new O(b.status,b.statusText,`${e}${p}`,b.headers,k);return k?JSON.parse(k):{}},o=await r("/auth/challenge",{method:"GET",headers:{Accept:"application/json"}}),i=o.challenge??o.data?.challenge;if(!i)throw new Error("the node issued no challenge");let s=await to(),a=Math.floor(Date.now()/1e3),c=await On({node:t.node,audience:t.audience,challenge:i,sessionKey:s.publicKey,issuedAt:a,expiresAt:a+(t.ttlSeconds??Zl),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 eu=3e4;function Ve(){let t=globalThis.location?.origin;return t?{kind:"webOrigin",origin:t}:{kind:"cli"}}function tu(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 Fe=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-eu>e?this.session.accessToken:(this.pending||(this.pending=this.loginNow().finally(()=>{this.pending=null})),(await this.pending).accessToken)}async loginNow(){let e=await je({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=tu(e.accessToken),e}get events(){return this.sseClient||(this.sseClient=new B({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.sseClient}get ws(){return this.wsClient||(this.wsClient=new ie({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.wsClient}close(){this.sseClient?.close(),this.wsClient?.close()}};var ps=new TextEncoder().encode("calimero/presence/1");async function gs(t){let e=t===null?new Uint8Array([0]):f(new Uint8Array([1]),R(t.length),t);return new Uint8Array(await crypto.subtle.digest("SHA-256",e))}async function no(t){return f(ps,g(t.contextId,"contextId",32),g(t.author,"author",32),C(t.seq),C(t.sentAtMs),await gs(t.state))}var nu=2500,Ct=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??nu,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 Yt(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 no({contextId:e,author:r.publicKey,seq:BigInt(o),sentAtMs:BigInt(i),state:n}),a=y(await r.sign(s));try{await this.relay.presenceIntent(e,{state:n===null?null:y(n),seq:o,sentAtMs:i,signature:a,authorProof:this.relay.authorProof})}catch(c){let u=c.status;if(u===void 0||u===0||u===429||u>=500)return;throw this.refused.add(e),this.stop(e),c}}};function ms(t,e){return new Error(`this client was constructed with the relay transport, which has no ${t}: ${e}. Construct a node client (createMeroClient({ baseUrl })) for that surface \u2014 nothing here will silently connect to a node you did not choose.`)}function fs(t){return new Error(`this relay-transport client cannot open ${t}: it was given no relay node key. A relay is an ordinary node and does serve /sse and /ws \u2014 but the login statement must be signed against the node's device signing key, learned out of band (never read from the node, and never derived from its peerId). Pass it as \`observe: { nodeKey }\`. For a cloud-hosted relay the cloud does not publish it yet \u2014 see mdma #312.`)}function ru(t,e,n){let r=e?.nodeKey;return r?new Fe({nodeUrl:e?.nodeUrl??t.relayUrl,nodeKey:r,accountProof:e?.accountProof??t.authorProof,audience:e?.audience??Ve(),signer:e?.signer?async()=>e.signer:()=>t.authorSigner(),clientName:e?.clientName,ttlSeconds:e?.ttlSeconds,fetch:e?.fetch??n,timeoutMs:e?.timeoutMs}):null}var be=class{constructor(e){this.relayObserver=null;this.relayAdmin=null;this.proofAuthorizer=null;this.relayUrl=null;this.proofEvents=null;this.relayFetch=void 0;this.relayPresence=null;if(e.transport==="relay"){this.transport="relay",this.nodeClient=null;let o=e.fetch;this.relayFetch=o;let i=e.relay instanceof W?e.relay:new W({...e.relay,fetch:e.relay.fetch??o});if(this.relayObserver=ru(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=jo({baseUrl:i.relayUrl,getAuthToken:typeof s=="string"?async()=>s:s,fetch:o})}else if(this.proofAuthorizer){let s=this.proofAuthorizer;this.relayAdmin=Ft(it({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 We(r),this.rpcTransport=this.nodeClient.rpc}get rpc(){return this.rpcTransport}get canSubscribe(){return this.rpcTransport.canSubscribe||this.proofAuthorizer!==null}get node(){if(!this.nodeClient)throw ms("node connection","it holds a signing key and a relay URL, not a node");return this.nodeClient}get relay(){if(!(this.rpcTransport instanceof ye))throw new Error("this client was constructed with the node transport and has no relay");return this.rpcTransport.client}get admin(){if(this.nodeClient)return this.nodeClient.admin;if(this.relayAdmin)return this.relayAdmin;throw new Error("this relay-transport client has no admin surface because it was given neither a `proof` nor a `session`. A warrant authorises one intent and is not a credential for reading. The caller-scoped reads (getContexts, listNamespaces) want one of the other two: pass `proof: { credential, deviceSecret }` \u2014 the device cert you already hold, which needs no login and no node key \u2014 or a `session` minted with `login()`. Context STATE reads work through execute/query either way.")}get auth(){return this.node.auth}get events(){if(this.nodeClient)return this.nodeClient.events;if(this.relayObserver)return this.relayObserver.events;if(this.proofAuthorizer&&this.relayUrl)return this.proofEvents??(this.proofEvents=new B({baseUrl:this.relayUrl,authorize:this.proofAuthorizer,fetch:this.relayFetch})),this.proofEvents;throw fs("SSE events")}get ws(){if(this.nodeClient)return this.nodeClient.ws;if(this.relayObserver)return this.relayObserver.ws;throw this.proofAuthorizer?new Error("this client authenticates with a request proof, which cannot open a WebSocket from a browser: `WebSocket` cannot set the X-Calimero-Proof header, and core's guard reads the proof from a header only (the ?token= query parameter is the session equivalent and has no proof counterpart). Use `client.events` \u2014 SSE is fetch-based, carries the header, and is the recommended transport anyway."):fs("WebSocket events")}get ephemeral(){return this.nodeClient?this.nodeClient.ephemeral:(this.relayPresence??(this.relayPresence=new Ct({relay:this.relay,events:()=>this.events})),this.relayPresence)}get cloud(){if(!this.nodeClient)throw ms("bundled cloud client","a relay client is built from a cloud connection rather than owning one \u2014 reach it through the `cloud` field that `connectCloud` returns, or construct a `CloudClient` directly");return this.nodeClient.cloud}close(){this.nodeClient?.close(),this.relayObserver?.close(),this.proofEvents?.close()}};function Nn(t){return new be(t)}var io="calimero.delegated.connection",so="calimero.delegated.credential";function ao(){if(typeof sessionStorage>"u")return null;try{let t=sessionStorage.getItem(io);return t?JSON.parse(t):null}catch{return null}}function ys(t){try{sessionStorage.setItem(io,JSON.stringify(t))}catch{}}function bs(){try{sessionStorage.removeItem(io)}catch{}}function ws(){let t=ao();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(so);if(!e)return null;let n=JSON.parse(e);return!n.account||!n.credential||!n.deviceSecret?null:n}catch{return null}}function As(t){try{sessionStorage.setItem(so,JSON.stringify(t))}catch{}}function xs(){try{sessionStorage.removeItem(so)}catch{}}function co(t){let e=Mn(t);return{next:async()=>{let n=0n;try{n=vs(t)}catch{n=0n}try{localStorage.setItem(e,String(n+1n))}catch{}return n}}}function Mn(t){return`calimero.nonce.${t}`}function vs(t){let e=localStorage.getItem(Mn(t));if(e!==null)return BigInt(e);let n=`${Mn(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 Kn(t,e,n){try{vs(t)<=n&&localStorage.setItem(Mn(t),String(n+1n))}catch{}}var Rs="calimero.delegated.relay-node-key.";function X(t){return t.replace(/\/+$/,"")}function lo(t,e){localStorage.setItem(Rs+X(t),e.trim().toLowerCase())}function $n(t){try{let e=localStorage.getItem(Rs+X(t));return e&&/^[0-9a-f]{64}$/.test(e)?e:null}catch{return null}}function uo(t){try{let{hostname:e}=new URL(t);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch{return!1}}var ou="locked-read-only",iu="2.3.99",ro;function su(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 hs(t,e){try{return await e()}catch(n){throw n instanceof Je?n:new Je(t,n)}}function au(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 Cs(t,e){return Object.assign(async r=>{let o=await hs("loading the quote verifier",()=>(ro??(ro=import("@phala/dcap-qvl").then(i=>su(i),i=>{throw ro=void 0,i})),ro));return mn({dcapVerify:o,release:()=>hs("fetching the release the relay runs",async()=>dn(gn(un,await pn(t,{fetch:e})))),profile:ou,minReleaseVersion:iu})(r)},{includeCollateral:!0})}async function ze(t,e={}){let n=e.fresh?null:$n(t);if(n)return{kind:"learned",nodeKey:n};let r={failure:null},o=au(r);try{let i=uo(t),{nodeKey:s}=await sn({relayUrl:t,allowMock:i,fetch:o,...i?{}:{verify:Cs(t,o)}});return lo(t,s),{kind:"learned",nodeKey:s}}catch(i){return i instanceof Je||r.failure?{kind:"unavailable",error:i}:{kind:"refused",error:i}}}async function Ln(t){let e=await ze(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 Gn=[1e3,2e3,5e3,1e4,3e4];function cu(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 Ss(t,e={}){let{signal:n}=e;for(let r=0;!n?.aborted;r+=1){let o=await ze(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=Gn[Math.min(r,Gn.length-1)];console.warn(`[mero-js] could not reach what proves the relay's node key; retrying in ${i/1e3} s`,o.error),await cu(i,n)}return null}function lu(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 oo=new Map;function ks(){oo.clear()}async function uu(t){if(t.status!==403)return!1;try{return(await t.clone().json()).error?.code==="sealed_route_unguarded"}catch{return!1}}function du(t){return t.headers.has("authorization")||new URL(t.url).pathname.startsWith("/auth/")}function pu(t){let e=(o,i)=>globalThis.fetch(o,i),n=fe({baseUrl:t,verify:Cs(t,e),fetch:e}),r=!1;return async(o,i)=>{let s=new Request(o,i);if(r&&du(s))return e(s);let a=await n(s.clone());return await uu(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 Qe(t){if(uo(t))return;let e=X(t),n=oo.get(e);return n||(n=pu(t),oo.set(e,n)),n}function gu(t,e){let n=null,r=null;return async()=>{let o=n?lu(n):null;return n&&(o===null||o-Date.now()>3e4)?n:(r||(r=je({nodeUrl:t.relayUrl,fetch:Qe(t.relayUrl),node:e,deviceSecret:t.deviceSecret,accountProof:t.credential,audience:Ve()}).then(i=>(n=i.accessToken,n)).catch(i=>{console.warn("[mero-js] relay login failed",i),n=null}).finally(()=>{r=null})),r)}}var _n=new Map;function Es(){_n.clear()}function mu(t){return typeof t=="object"&&t!==null&&t.status===409}function fu(t,e){let n=t.rpc,r=X(e),o=async i=>{let s=`${r}|${i.contextId}|${i.method}`;if(_n.get(s)!=="write")try{let{returns:a}=await t.admin.queryContext(i.contextId,{method:i.method,argsJson:i.argsJson??{}});return _n.set(s,"read"),{returns:a,transport:"relay"}}catch(a){mu(a)&&_n.set(s,"write")}return n.executeWithMetadata(i)};return{get kind(){return n.kind},get canSubscribe(){return n.canSubscribe},execute:async i=>(await o(i)).returns,executeWithMetadata:o,migrateMyEntries:i=>n.migrateMyEntries(i),countMyPending:i=>n.countMyPending(i)}}function hu(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 yu(t,e){let n=e.session?fu(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=hu(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 Hn(t,e){if(!t.relayUrl)return null;let n=$n(t.relayUrl),r=Nn({transport:"relay",fetch:Qe(t.relayUrl),relay:{relayUrl:t.relayUrl,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:co(t.relayUrl)},proof:{credential:t.credential,deviceSecret:t.deviceSecret},session:n?gu({...t,relayUrl:t.relayUrl},n):void 0,observe:n?{nodeKey:n}:void 0});return yu(r,{relayUrl:t.relayUrl,session:n!==null,attested:n!==null||uo(t.relayUrl)})}var Is="calimero.delegated.relays.";function q(t){try{let e=localStorage.getItem(Is+t),n=e?JSON.parse(e):{};return{namespaces:n.namespaces??{},contexts:n.contexts??{}}}catch{return{namespaces:{},contexts:{}}}}function po(t,e){try{localStorage.setItem(Is+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),po(t,r)}function Ps(t,e){return q(t).contexts[e]??null}function Bn(t,e){return e.executorAccount||!t?.executorAccount||!t.relayUrl||!e.relayUrl||X(t.relayUrl)!==X(e.relayUrl)?e:{...e,executorAccount:t.executorAccount}}function Ye(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 Ts(t){let e=[],n=q(t.account);for(let r of Ye(t))try{if(!await Ln(r))continue;let o=Hn({...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 po(t.account,n),e}async function Ds(t){var o,i;let e=[],n=new Set,r=q(t.account);for(let s of Ye(t))try{if(!await Ln(s))continue;let a=Hn({...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 po(t.account,r),e}function go(t=1){let e=BigInt(t);if(e<1n)throw new Error("nonce sequence starts at 1");return{next(){let n=e;return e+=1n,Promise.resolve(n)},advanceTo(n){return n>e&&(e=n),Promise.resolve()}}}function St(t,e){let n=e??globalThis.localStorage;if(!n)throw new Error("no localStorage in this runtime: pass a storage implementation, or use createMemoryNonceSource for a process that owns its whole sequence");let r=()=>{let o=n.getItem(t);if(o===null||o==="")return 0n;try{let i=BigInt(o);return i>0n?i:0n}catch{return 0n}};return{next(){let o=r()+1n;return n.setItem(t,o.toString()),Promise.resolve(o)},advanceTo(o){let i=o>0n?o-1n:0n;return i>r()&&n.setItem(t,i.toString()),Promise.resolve()}}}async function Us(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=wu(r,t.namespaceId),i=await n.getNamespaceRelays(o.namespaceId),s=mo(i);if(!s)throw new Error(Au(o,i));let a=new W({relayUrl:s.relayUrl,executorAccount:s.executorAccount,authorAccount:t.authorAccount,authorProof:t.authorProof,signer:e,nonces:t.nonces??xu(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 bu(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 Us({...r,deviceSecret:void 0,signer:o,sessionToken:a.sessionToken,authorAccount:n??i.accountId})}function wu(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 Au(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 xu(t){let e=`mero-js:warrant-nonce:${t}`;try{return St(e)}catch{return go(1)}}var vu=new TextEncoder().encode("calimero.mdma.routing-read.v1\0");async function Os(t,e){g(e,"deviceSecret",32);let n=await ne(e),r=f(vu,new TextEncoder().encode(t)),o=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,r));return Ru(o)}async function qn(t,e){return{"X-Calimero-Credential":e.credential,"X-Calimero-Nonce":t.nonce,"X-Calimero-Signature":await Os(t.nonce,e.deviceSecret)}}function Ru(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var Cu="https://cloud.calimero.network";async function Ns(t){let e=new URL(t.cloudWebUrl??Cu),{callbackUrl:n,challenge:r}=await Vt(t.accountId,t.returnTo);return e.searchParams.set("link-account",t.accountId),e.searchParams.set("challenge",r),e.searchParams.set("callback-url",n),e.toString()}async function Su(t){throw window.location.assign(await Ns(t)),new Error("redirecting to the cloud to authorise this link")}function ku(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Te(t.search??"",null),fo(),new Error(n==="denied"?"the account link was declined at the cloud":`the cloud refused this link: ${n}`);let r=e.get("grant"),o=e.get("account");if(!r||!o)return null;let i=Te(t.search??"",o),s=ct(r);if(!i||s?.account!==o)throw fo(),new Error("this account link answers a request this browser did not make - start the link again from here");return fo(),{grant:r,account:o,login:s.login,verifier:i}}function fo(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+Jo(location.search))}async function Eu(t){let e=await Y(t.root);if(e.accountId!==t.account)throw new Error(`this grant is for account ${t.account}, but the root here derives ${e.accountId} \u2014 it was minted for a different account`);return new $({cloudBaseUrl:t.cloudBaseUrl,fetch:t.fetch}).linkAccountWithGrant({grant:t.grant,verifier:t.verifier,signer:e.signer})}var Iu="enrol-device",Pu="enrol-kem",Tu="callback-url",Gs="state",ho="calimero.device.enrol.pending";function Ks(t){Ms(t.devicePublicKey,"devicePublicKey"),Ms(t.kemPublicKey,"kemPublicKey"),_u(t.returnTo),Nu(t.returnTo);let e=new URL(t.walletUrl);return e.searchParams.set(Iu,t.devicePublicKey),e.searchParams.set(Pu,t.kemPublicKey),e.searchParams.set(Tu,t.returnTo),e.searchParams.set(Gs,at(ho,{})),e.toString()}function Du(t){throw window.location.assign(Ks(t)),new Error("redirecting to the wallet to approve this device")}function Uu(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Pe(ho,e.get(Gs)),_s(),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;_s();let s=e.get("state");return{credential:r,account:o,device:i,...s?{state:s}:{}}}function _s(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+location.search)}async function Ou(t){if(!Pe(ho,t.state))throw new Error("this enrolment answers a request this app did not make - start the enrolment again from here");let e=await Zt(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 Ms(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 $s(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 Nu(t){$s(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 _u(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 Gu(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=>Gu(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/${m(t.namespaceId)}/admit`,admitterAccount:l.account,peerId:l.peerId,writable:l.canExecute,stale:!l.fresh||c}}var Vn=1440*60,bo={Admin:0,Member:1,ReadOnly:2};function Tt(t){let e=t.admitters??[];return f(yo(t.inviter_identity,"inviter_identity"),yo(t.group_id,"group_id"),C(t.expiration_timestamp),yo(t.secret_salt,"secret_salt"),new Uint8Array([t.invited_role]),R(e.length),...e.map((n,r)=>g(n,`admitters[${r}]`,32)))}async function wo(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",Tt(t)))}function Ao(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=g(e.publicKey,"signer.publicKey",32),r=g(t.groupId,"groupId",32);g(t.inviterAccount,"inviterAccount",32);let o=[...t.admitters??[]].map(p=>p.trim().toLowerCase());if(o.length===0){if(!t.members)throw new Error("name the admitters, or pass the group members to default them to its admins: an invitation with no admitters is claimable by broadcast");if(o=Ao(t.members),o.length===0)throw new Error("the member list names no admin, so there is nobody to default the admitters to")}o.forEach((p,x)=>g(p,`admitters[${x}]`,32));let i=t.invitedRole??bo.Member;if(![0,1,2].includes(i))throw new Error(`invitedRole must be 0 (Admin), 1 (Member) or 2 (ReadOnly), got ${i}`);let s=t.now??Math.floor(Date.now()/1e3),a=Math.min(t.validForSecs??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 wo(u));if(d.length!==64)throw new Error(`signer returned ${d.length} bytes, expected a 64-byte Ed25519 signature`);let l={invitation:u,inviter_signature:y(d),inviter_account:t.inviterAccount.trim().toLowerCase()};return t.admitterAddrs?.length&&(l.admitter_addrs=[...t.admitterAddrs]),t.applicationId&&(l.application_id=Array.from(g(t.applicationId,"applicationId",32))),t.appKey&&(l.app_key=Array.from(g(t.appKey,"appKey",32))),l}function yo(t,e){if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return new Uint8Array(t)}var xo=26,Ku=new TextEncoder().encode("calimero.namespace.v1"),$u=0,Ls={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreatedV2:9,MemberJoinedViaTeeAttestation:10};function Hs(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 Bs(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(Tt(e),Bs(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(Bs),Hs(t.application_id,"application_id"),Hs(t.app_key,"app_key"))}async function zn(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([Ls.MemberJoinedAt]),g(t.member,"member",32),Jn(t.invitation),C(o),n):f(new Uint8Array([Ls.MemberJoined]),g(t.member,"member",32),Jn(t.invitation),n),s=f(new Uint8Array([$u]),i),a=await I(t.deviceSecret,t.signer,"deviceSecret"),c=g(a.publicKey,"signer.publicKey",32),u=f(new Uint8Array([xo]),g(t.namespaceId,"namespaceId",32),R(e.length),...e.map((p,x)=>g(p,`parentOpHashes[${x}]`,32)),c,C(t.nonce),s),d=await a.sign(f(Ku,u)),l=new Uint8Array([0]);return y(f(u,d,l))}function Lu(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 Hu(t){let e=St(`calimero.delegated.joinnonce.${t}`);return()=>e.next()}function qs(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??Hu(e))()})}catch(l){return{ok:!1,step:"sign",reason:`The join op could not be signed, so nothing was sent: ${l instanceof Error?l.message:String(l)}`}}let i={invitation:t.invitation,signedOp:o},s=t.admitUrl??`${qs(t.nodeUrl)}/admin-api/namespaces/${m(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:Lu(c.status,u)};let d=!1;try{d=(u?JSON.parse(u):{}).data?.published===!0}catch{d=!1}return{ok:!0,published:d,session:{relayUrl:qs(t.nodeUrl),account:e,credential:n,deviceSecret:r}}}async function 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 js(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&&we(t.account,i.session.relayUrl,{namespaceId:e}),r.onJoined(Bn(t,i.session)),{namespaceId:e}}function Fs(t){let e=new TextEncoder().encode(t),n=new Uint8Array(4+e.length);return new DataView(n.buffer).setUint32(0,e.length,!0),n.set(e,4),n}async function vo(t,e){let n=Fs(t),r=Fs(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 Bu(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 Dt(t){return t.filter(e=>!e.yanked&&typeof e.appVersion=="string"&&e.appVersion.length>0).reduce((e,n)=>!e||Bu(n.appVersion,e.appVersion)?n:e,void 0)}async function Ut(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 Vs(t,e,n={}){let o=(await Ut(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=Dt(o);if(!s)throw new Error(`the registry lists no version of ${e}`);let a=s.signerId;if(!a)throw new Error(`the registry names no publisher for ${e} ${s.appVersion}`);return{applicationId:await vo(e,a),signerId:a,version:s.appVersion}}function Js(t,e){return{next:async()=>qu(t,e)}}function qu(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 zs(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 ju(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??Qe(e)})}async function Ot(t,e,n={}){let r=zs(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:ju(e.initializationParams),name:e.name});return Kn(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=zs(t,e.namespaceId);return Zn(t,r,Js(r,e.group),n.fetch).govern({groupId:e.group,op:e.op})}async function Qs(t,e,n={}){let{groupId:r}=await ve(t,{namespaceId:e.namespaceId,group:e.namespaceId,op:(await Be({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:Le(i,"Member")},n);let{contextId:o}=await Ot(t,{...e,groupId:r},n);return{contextId:o,groupId:r}}async function er(t,e={},n={}){let o=Ye(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 Fu(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(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 Wu(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 Fu(t,e,n){let r=t.executorAccount&&t.relayUrl?.replace(/\/+$/,"")===e?t.executorAccount:null;if(r)return{executorAccount:r,executorKey:await Ws(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 Ws(e),s=await Zn(t,e,Js(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 Ws(t){let e=await ze(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 Vu(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 Wu(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"?Vu(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 Xe(t,e,n=globalThis.fetch){let r=Dt(await Ut(t,e,n));if(!r)throw new Error(`the registry lists no version of ${e}`);return r.appVersion}var Ys="calimero.delegated.group-namespace.",Ro=new Map;function Xs(t){let e={};try{e=JSON.parse(localStorage.getItem(Ys+t)??"{}")}catch{}return{...e,...Ro.get(t)}}function Nt(t,e,n){Ro.set(t,{...Ro.get(t),[e]:n});try{let r=Xs(t);r[e]=n,localStorage.setItem(Ys+t,JSON.stringify(r))}catch{}}function _t(t,e){return q(t.account).namespaces[e]?e:Xs(t.account)[e]}function Zs(t,e){let n=_t(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:Zs(t,e),group:e,op:n})}async function rr(t,e,n){let r=Zs(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"}},Ze=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"}},et=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"}},ea={listNamespaces:async()=>[],listNamespacesForApplication:async()=>[],getContexts:async()=>({contexts:[]})},Ju=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 zu(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 ta(t,e={}){let{session:n,read:r,app:o}=t,i=e.govern?.group??nr,s=e.govern?.root??rr,a=e.createContext??Ot,c=e.found??er,u=e.latestVersion??Xe,d=e.signInvitation??Wn,l=e.join,p=e.routing;async function x(h,w){if(!l)throw new Re("joinNamespace without a join handler");return l(h,w.invitation)}let v=()=>{if(r===null)throw new Ze("this call");return r};async function P(h){if(_t(n,h))return;let w=await v().getGroupInfo(h);Nt(n.account,h,w.namespaceId??h)}let b=async(h,w,S)=>(await P(w),i(h,w,S)),k=async(h,w,S)=>(await P(w),s(h,w,S));async function T(h){try{return await k(n,h,Dn({member:n.account,groupId:h,credential:n.credential})),!0}catch(w){if(zu(w))return!1;throw w}}async function H(h,w){let S=w??String(await v().getContextGroup(h)),{members:U}=await v().listGroupMembers(S);return U.some(M=>M.identity.toLowerCase()===n.account.toLowerCase())}let z={async listNamespacesForApplication(h){return(await v().listNamespaces()).filter(w=>w.targetApplicationId===h)},async getNodeIdentity(){return{accountId:n.account,deviceId:null,publicKey:"",deviceCertified:!0}},async createNamespace(h){if(!o.packageName)throw new Re("createNamespace without a packageName");let w=o.packageVersion??await u(o.registryUrl??"https://apps.calimero.network",o.packageName),{namespaceId:S,haEnabled:U,haError:M}=await c(n,{defaultCapabilities:231,application:{applicationId:h.applicationId,package:o.packageName,version:w}});return h.name&&await b(n,S,qe({name:h.name})),{namespaceId:S,haEnabled:U,...M!==void 0?{haError:M}:{}}},async createGroupInNamespace(h,w={}){let{op:S}=await Be({parentId:h,restricted:w.visibility==="restricted",admin:n.account}),{groupId:U}=await k(n,h,S);return Nt(n.account,U,h),w.groupName&&await b(n,U,qe({name:w.groupName})),{groupId:U}},async addGroupMembers(h,w){for(let S of w.members)await b(n,h,Le(S.identity,S.role??"Member"))},async removeGroupMembers(h,w){for(let S of w.members)await b(n,h,wn(S))},async setGroupMetadata(h,w){await b(n,h,qe(w))},async setMemberMetadata(h,w,S){await b(n,h,Pn(w,S))},async setContextMetadata(h,w,S){await b(n,h,Tn(w,S))},async setDefaultCapabilities(h,w){await b(n,h,He(w.defaultCapabilities))},async setSubgroupVisibility(h,w){await b(n,h,In(w.subgroupVisibility==="open"?"open":"restricted"))},async setMemberCapabilities(h,w,S){await b(n,h,kn(w,S.capabilities))},async deleteGroup(h){return await k(n,h,Rn(h)),{isDeleted:!0}},async reparentGroup(h,w){return await k(n,h,vn(h,w.newParentId)),{reparented:!0}},async leaveGroup(h){await b(n,h,Rt(n.account))},async leaveNamespace(h){await b(n,h,Rt(n.account))},async getContextIdentitiesOwned(h){return{identities:await H(h)?[n.account]:[]}},async joinContext(h){return await T(String(await v().getContextGroup(h))),{contextId:h,memberPublicKey:n.account}},async createContext(h){let S=(await v().getGroupInfo(h.groupId)).namespaceId??h.groupId,{contextId:U}=await a(n,{namespaceId:S,groupId:h.groupId,applicationId:h.applicationId,serviceName:h.serviceName,contextSeed:h.contextSeed,name:h.name,initializationParams:h.initializationParams});return{contextId:U,memberPublicKey:n.account,groupId:h.groupId}},async createNamespaceInvitation(h){let[{members:w},S]=await Promise.all([v().listGroupMembers(h),v().getGroupInfo(h)]),U=w.filter(Q=>Q.role==="RelayTee").map(Q=>Q.identity.toLowerCase());if(p){let Q=new Set(U.length>0?U:w.filter(te=>te.role==="Admin").map(te=>te.identity.toLowerCase())),ee=null;try{ee=(await p(h)).nodes}catch{}if(ee!==null){if(ee.length===0)throw new et(h,"not-hosted");if(!ee.some(te=>te.account!==null&&Q.has(te.account.toLowerCase())))throw new et(h,"no-named-node")}}return{invitation:await d({groupId:h,inviterAccount:n.account,deviceSecret:n.deviceSecret,...U.length>0?{admitters:U}:{},members:w,applicationId:S.targetApplicationId,appKey:S.appKey})}},async syncGroup(h){return{groupId:h,synced:!0}},async syncContext(){},joinNamespace:x,async updateMemberRole(h,w,S){await b(n,h,An(w,S.role))},async joinSubgroupInheritance(h){return{groupId:h,memberPublicKey:n.account,wasInherited:await T(h)}},async detachContextFromGroup(h,w){await b(n,h,En(w))}};return r===null?new Proxy({},{get(h,w){if(typeof w=="string")return w==="getNodeIdentity"?z.getNodeIdentity:w==="joinNamespace"?x:w in ea?ea[w]:async()=>{throw new Ze(w)}}}):new Proxy(r,{get(h,w,S){return typeof w=="string"&&w in z?z[w]:typeof w=="string"&&Ju.has(w)?async()=>{throw new Re(w)}:Reflect.get(h,w,S)}})}function na(t,e={}){let{admin:n,app:r}=t,o=e.latestVersion??Xe;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 Qu="https://manager.cloud.calimero.network";function Co(t,e){return typeof t.can_execute=="boolean"?t.can_execute:e}function So(t){return typeof t.tee_role=="string"&&t.tee_role!==""?t.tee_role:null}function mo(t){return t.find(e=>e.canExecute&&e.relayUrl!==null&&e.executorAccount!==null)??null}function Yu(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 Xu(t){return typeof t=="string"&&wr.test(t)?t:null}var J=class extends O{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.code=n;this.name="AccountHaRefusedError"}},xe=class extends J{constructor(){super(...arguments);this.name="AccountNotLinkedError"}};xe.CODE="account_not_linked";var kt=class extends J{constructor(){super(...arguments);this.name="AccountLinkedToSeveralUsersError"}};kt.CODE="account_linked_to_several_users";var Et=class extends J{constructor(){super(...arguments);this.name="HaRequestPendingError"}};Et.CODE="ha_request_pending";var It=class extends J{constructor(){super(...arguments);this.name="UnknownRelayError"}};It.CODE="unknown_relay";var Pt=class extends J{constructor(){super(...arguments);this.name="RelayNotDialableError"}};Pt.CODE="relay_not_dialable";var ra={409:[xe,kt,Et],422:[It,Pt]};function Zu(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 ed="x-mdma-session-refresh",td="x-mdma-session-expires",$=class{constructor(e={}){this.session=null;this.baseUrl=(e.cloudBaseUrl||Qu).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 nn({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/${m(e)}/relays`)).relays??[]).map(r=>{let o=r.relay_url??null,i=r.executor_account??null,s=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),relayUrl:o,executorAccount:i,nodeKey:r.node_key??r.node_public_key??null,status:String(r.status??""),authorshipReady:s,teeRole:So(r),canExecute:Co(r,s&&o!==null&&i!==null),lastSeenAt:r.last_seen_at??null,confirmedAt:r.confirmed_at??null,admission:typeof r.admission=="string"?r.admission:null,admissionHint:typeof r.admission_hint=="string"?r.admission_hint:null,join:Yu(r)}})}async findExecutingRelay(e){let n=await this.getNamespaceRelays(e);return mo(n)}async getNamespaceRouting(e){let n=await this.request("GET",`/api/cloud/namespaces/${m(e)}/admitters`,{anonymous:!0,headers:await this.routingProof(e)});return{namespaceId:String(n.namespace_id??e),nodes:(n.admitters??[]).map(r=>{let o=r.account??null,i=r.relay_url??null,s=r.fresh===!0,a=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),account:o,relayUrl:i,admitUrl:r.admit_url??null,status:String(r.status??""),fresh:s,canAdmit:r.can_admit===!0,authorshipReady:a,teeRole:So(r),canExecute:Co(r,a&&i!==null&&o!==null&&s)}}),servable:n.servable===!0,writable:n.writable===!0}}async getRoutingChallenge(e){let n=await this.request("GET",`/api/cloud/namespaces/${m(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 qn(n,this.routingCredential)}async getAccountRelaysChallenge(e){let n=await this.request("GET",`/api/cloud/accounts/${m(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/${m(e)}/relays`,{anonymous:!0,headers:await qn(n,this.routingCredential)})).relays??[]).map(o=>({peerId:String(o.peer_id??""),relayUrl:o.relay_url??null,fresh:o.fresh===!0,executorAccount:Xu(o.executor_account),assigned:o.assigned===!0}))}async findAdmitter(e,n){let{nodes:r}=await this.getNamespaceRouting(e),o=n&&n.length>0?new Set(n.map(i=>i.toLowerCase())):null;return r.find(i=>i.canAdmit&&(o===null||i.account!==null&&o.has(i.account.toLowerCase())))??null}async getMyMachines(){return((await this.request("GET","/api/cloud/me/machines")).machines??[]).map(n=>{let r=n.relay_url??null,o=n.executor_account??null,i=(Array.isArray(n.namespaces)?n.namespaces:[]).map(s=>{let a=s;return{namespaceId:String(a.namespace_id??""),status:String(a.status??""),authorshipReady:a.authorship_ready===!0,teeRole:So(a),fresh:a.fresh===!0,confirmedAt:a.confirmed_at??null,lastSeenAt:a.last_seen_at??null}});return{peerId:String(n.peer_id??""),relayUrl:r,executorAccount:o,canExecute:Co(n,r!==null&&o!==null&&i.some(s=>s.authorshipReady)),namespaces:i}})}async claimNamespace(e,n){await this.request("POST","/api/cloud/namespaces/claim",{body:{namespace_id:e,ownership_proof:n}})}async enableNamespaceHa(e,n={}){let r=n.admitterAddrs===void 0?{}:{admitter_addrs:[...n.admitterAddrs]};return this.request("POST",`/api/cloud/namespaces/${m(e)}/enable-ha`,{body:r})}async enableFoundedNamespaceHa(e,n){return this.request("POST",`/api/cloud/me/namespaces/${m(e)}/enable-ha`,{body:{groups:[],ownership_proof:n}})}async enableHaAsAccount(e){let n=await kr({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/${m(r)}/namespaces/${m(o)}/enable-ha`,{body:{ownership_proof:n},anonymous:!0})}catch(i){if(i instanceof O&&ra[i.status]){let s=Zu(i.bodyText),a=ra[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/${m(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 dt({signer:n,nonce:i})})}async getAccountLinkChallenge(){let e=await this.request("GET","/api/cloud/me/accounts/challenge");return{nonce:e.nonce,expiresAtMs:e.expires_at_ms??null}}async submitAccountLink(e){let n=await this.request("POST","/api/cloud/me/accounts",{body:{account_id:e.accountId,root_public_key:e.rootPublicKey,nonce:e.nonce,signature:e.signature}});return{accountId:String(n.account_id??e.accountId),linkedAt:n.linked_at??null,alreadyLinked:n.already_linked===!0}}static async accountLinkHandoff(e){let n=e.portalUrl.replace(/\/+$/,""),{callbackUrl:r,challenge:o}=await Vt(e.accountId,e.callbackUrl),i=new URLSearchParams({"link-account":e.accountId,challenge:o,"callback-url":r});return{url:`${n}/?${i.toString()}`,accountId:e.accountId}}static readAccountLinkCallback(e){let n=e??(typeof window>"u"?"":window.location.href);if(!n)return{};let r,o;try{({hash:r,search:o}=new URL(n))}catch{return{}}let i=new URLSearchParams(r.replace(/^#/,"")),s=i.get("grant"),a=i.get("account"),c=i.get("error"),u={};if(c&&Te(o,null),s){let d=Te(o,a),l=ct(s);if(!d||l?.account!==a)return{error:"unexpected_callback"};u.grant=s,u.login=l.login,u.verifier=d}return a&&(u.accountId=a),c&&(u.error=c),u}async linkAccountWithGrant(e){if(typeof e.verifier!="string"||!Ar.test(e.verifier))throw new Error("no verifier for this grant - start the link again from this browser");let n=ct(e.grant);if(n?.challenge!==await xr(e.verifier))throw new Error("this grant was not issued to this link request - start the link again from this browser");let{signer:r,publicKey:o,accountId:i}=await tn(e.rootSecret,e.signer);if(n.account!==i)throw new Error(`this grant is for account ${n.account}, but the root here derives ${i} - it was minted for a different account`);let s=await this.request("POST","/api/cloud/accounts/link",{body:{grant:e.grant,verifier:e.verifier,root_public_key:o,signature:await dt({signer:r,nonce:e.grant})},anonymous:!0});return{accountId:String(s.account_id??i),linkedAt:s.linked_at??null,alreadyLinked:s.already_linked===!0}}async getMyAccounts(){let e=await this.request("GET","/api/cloud/me/accounts");return{accounts:(e.accounts??[]).map(n=>({accountId:String(n.account_id??""),linkedAt:n.linked_at??null,hasRecoveryEnvelope:n.has_recovery_envelope===!0})),limit:e.limit??null}}adoptSession(e){return this.session={sessionToken:e.session_token,expiresAt:e.expires_at,user:e.user},this.notifySession(this.session),this.session}async notifySession(e){try{await this.onSession?.(e)}catch{}}async request(e,n,r={}){if(!r.anonymous&&!this.session)throw new Error("Not signed in to Calimero Cloud: call signInWithGoogle() or construct the client with a sessionToken");let o={...r.headers,Accept:"application/json"};r.body!==void 0&&(o["Content-Type"]="application/json"),!r.anonymous&&this.session&&(o.Authorization=`Bearer ${this.session.sessionToken}`);let i=new AbortController,s=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r.body===void 0?void 0:JSON.stringify(r.body),signal:i.signal})}catch(c){throw new O(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(this.adoptRollingRefresh(a),!a.ok){let c=await a.text().catch(()=>{});throw new O(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(!(r.parse==="none"||a.status===204))return await a.json()}adoptRollingRefresh(e){let n=e.headers.get(ed);if(!n||!this.session)return;let r=e.headers.get(td),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 Mu(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 nd(t){if(t)return typeof t=="function"?t:Jt(t)}var rd="mero-js:token-refresh";function od(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function id(t){try{let{origin:e,pathname:n}=new URL(t);return e==="null"?t:e+n.replace(/\/+$/,"")}catch{return t}}function ko(t,e){try{let n=t.split(".");if(n.length===3){let r=n[1].replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4;)r+="=";let o=JSON.parse(atob(r));if(typeof o.exp=="number")return o.exp*1e3}}catch{}return e}var We=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=id(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=nd(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=Lo(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs}),this.adminClient=Ft(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 lt({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 ut({httpClient:this.httpClient,sse:this.events})),this.ephemeralClient}get cloud(){return this.cloudClient||(this.cloudClient=new $(this.config.cloud??{})),this.cloudClient}get ws(){return this.wsWarned||(this.wsWarned=!0,console.warn("[mero-js] WsClient is experimental. Use mero.events (SSE) for production.")),this.wsClient||(this.wsClient=new ie({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.wsClient}async authenticate(e){let n=e||this.config.credentials;if(!n)throw new Error("No credentials provided for authentication");try{let r={auth_method:"user_password",public_key:n.username,client_name:"mero-js-sdk",permissions:["admin"],timestamp:Math.floor(Date.now()/1e3),provider_data:{username:n.username,password:n.password}},o=await this.authClient.generateTokens(r),i=o.data.access_token;return this.tokenData={access_token:i,refresh_token:o.data.refresh_token,expires_at:ko(i,Date.now()+36e5)},this.persistTokens(),this.tokenData}catch(r){throw new Error(`Authentication failed: ${r instanceof Error?r.message:"Unknown error"}`)}}persistTokens(){!this.tokenStore||!this.tokenData||(this.tokenStore.setTokens({...this.tokenData,node_origin:this.nodeKey}),this.storeHoldsTokens=this.tokenStore.getTokens()!==null)}readStoredTokens(){let e=this.tokenStore?.getTokens();return!e||e.node_origin!==this.nodeKey?null:{access_token:e.access_token,refresh_token:e.refresh_token,expires_at:e.expires_at}}signedOutElsewhere(){return this.storeHoldsTokens&&!this.tokenStore?.getTokens()}dropLocalTokens(){this.tokenGeneration++,this.refreshPromise=null,this.tokenData=null,this.storeHoldsTokens=!1}async getValidToken(){return this.tokenData}async performTokenRefresh(){if(this.refreshPromise)return this.refreshPromise;let e=this.tokenData?.access_token,n=this.withRefreshLock(()=>this.performTokenRefreshLocked(e));this.refreshPromise=n;try{return await n}finally{this.refreshPromise===n&&(this.refreshPromise=null)}}withRefreshLock(e){if(this.tokenStore?.withLock)return this.tokenStore.withLock(e);let n=od();return n?n.request(rd,e):e()}async performTokenRefreshLocked(e){if(this.signedOutElsewhere())throw this.dropLocalTokens(),new Error("Signed out in another tab");let n=this.readStoredTokens();if(n?.refresh_token&&(this.storeHoldsTokens=!0,this.tokenData=n,e&&n.access_token!==e))return n;if(!this.tokenData?.refresh_token)throw new Error("No refresh token available");let r=this.tokenGeneration,o=this.tokenData.access_token,i=this.tokenStore?.getTokens()?.access_token===o;try{let s=await this.authClient.refreshToken({access_token:this.tokenData.access_token,refresh_token:this.tokenData.refresh_token});if(r!==this.tokenGeneration)throw new Error("Signed out during token refresh");if(i&&this.tokenStore?.getTokens()?.access_token!==o)throw this.tokenData=this.tokenStore?.getTokens()??null,this.storeHoldsTokens=this.tokenData!==null,new Error("Signed out during token refresh");let a=s.data.access_token;return this.tokenData={access_token:a,refresh_token:s.data.refresh_token,expires_at:ko(a,Date.now()+36e5)},this.persistTokens(),this.tokenData}catch(s){throw new Error(`Token refresh failed: ${s instanceof Error?s.message:"Unknown error"}`)}}clearToken(){this.dropLocalTokens(),this.tokenStore?.clear()}isAuthenticated(){return this.tokenData!==null}setTokenData(e){let n=e.expires_at||ko(e.access_token,Date.now()+36e5);this.tokenData={...e,expires_at:n},this.persistTokens()}getTokenData(){return this.tokenData}close(){typeof window<"u"&&window.removeEventListener("storage",this.onStorage),this.sseClient?.close(),this.wsClient?.close()}static parseAuthCallback(e,n){return vr(e,n)}static buildAuthLoginUrl(e,n){return Rr(e,n)}};function sd(t){return new We(t)}var Eo=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},ad="mero-tokens",Io=class{constructor(e=ad){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 cd=new TextEncoder().encode("calimero.account.owner-op.v1"),ld=new TextEncoder().encode("calimero.account.owner-op.body.v1"),ud=new TextEncoder().encode("calimero.account.genesis.v1"),dd=2,Po={transferOwnership:0,adminChanged:1,groupDelete:2,teeAdmissionPolicy:3,teeAuthoringPolicy:4,teeReleaseAdmissionPolicy:5},tt={GroupDelete:14,TransferOwnership:21,TeeAuthoringPolicySet:33,TeeAdmissionPolicySetV2:37,TeeReleaseAdmissionPolicySetV2:38,RootGuarded:42},ia={AdminChanged:3,RootGuarded:12},pd={replica:0,relay:1},gd=new TextEncoder;function L(t){return new Uint8Array([t])}function sa(t){let e=gd.encode(t);return f(R(e.length),e)}function Z(t){return f(R(t.length),...t.map(sa))}function aa(t){return L(t?1:0)}function ca(t){let e=pd[t??"replica"];if(e===void 0)throw new Error(`mode must be replica or relay, got ${String(t)}`);return L(e)}function la(t){return{kind:"transferOwnership",plane:"group",bytes:f(L(tt.TransferOwnership),g(t,"newOwner",32))}}function ua(){return{kind:"groupDelete",plane:"group",bytes:L(tt.GroupDelete)}}function da(t){return{kind:"adminChanged",plane:"root",bytes:f(L(ia.AdminChanged),g(t,"newAdmin",32))}}function pa(t){return{kind:"teeAuthoringPolicy",plane:"group",bytes:f(L(tt.TeeAuthoringPolicySet),Z(t))}}function ga(t){return{kind:"teeAdmissionPolicy",plane:"group",bytes:f(L(tt.TeeAdmissionPolicySetV2),Z(t.allowedMrtd),Z(t.allowedRtmr0),Z(t.allowedRtmr1),Z(t.allowedRtmr2),Z(t.allowedRtmr3),Z(t.allowedTcbStatuses),aa(t.acceptMock),ca(t.mode))}}function ma(t){let e=t.minReleaseVersion===void 0?L(0):f(L(1),sa(t.minReleaseVersion));return{kind:"teeReleaseAdmissionPolicy",plane:"group",bytes:f(L(tt.TeeReleaseAdmissionPolicySetV2),Z(t.allowedProfiles),e,Z(t.allowedTcbStatuses),aa(t.acceptMock),ca(t.mode))}}async function To(t){return E(ld,[t])}async function Do(t){return E(cd,[g(t.account,"account",32),g(t.namespaceId,"namespaceId",32),g(t.groupId,"groupId",32),L(fa(t.kind)),t.opDigest,C(t.counter),R(t.keyEpoch)])}function fa(t){let e=Po[t];if(e===void 0)throw new Error(`unknown owner-op kind ${String(t)}`);return e}var oa=132;async function ha(t){let e=await re(t.rootSecret),n=f(L(dd),e),r=y(await E(ud,[n])),o=t.keyEpoch??0,i=(t.chain??[]).map((d,l)=>{let p=j(d,`chain[${l}]`);if(p.length!==oa)throw new Error(`chain[${l}] must be a ${oa}-byte RootKeyHandoff, got ${p.length}`);return p});if(o>i.length)throw new Error(`keyEpoch ${o} needs ${o} handoffs in chain, got ${i.length}`);let s=await To(t.op.bytes),a=await Do({account:r,namespaceId:t.namespaceId,groupId:t.groupId,kind:t.op.kind,opDigest:s,counter:t.counter,keyEpoch:o}),c=await ne(t.rootSecret),u=new Uint8Array(await crypto.subtle.sign("Ed25519",c,a));return y(f(n,R(i.length),...i,g(r,"account",32),g(t.namespaceId,"namespaceId",32),g(t.groupId,"groupId",32),L(fa(t.op.kind)),s,C(t.counter),R(o),u))}function ya(t,e){let n=t.plane==="group"?tt.RootGuarded:ia.RootGuarded;return f(L(n),t.bytes,j(e,"rootProof"))}var ba=[2428,2429,2528,2529],md="localhost",fd=2e3;function wa(t){return`http://${md}:${t}`}function Aa(t,e){let n=t.endsWith("/")?t:`${t}/`;return new URL(e,n).toString()}async function xa(t,e={}){let{timeoutMs:n=fd,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=Aa(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 hd(t={}){let{ports:e=ba,timeoutMs:n,signal:r}=t;return(await Promise.all(e.map(async i=>{let s=wa(i);return await xa(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 va(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function Sa(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]=va(t,s*4);r[12]=e>>>0;for(let s=0;s<3;s+=1)r[13+s]=va(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 yd(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=Sa(t,s,n),c=Math.min(i+64,r.length);for(let u=i;u<c;u+=1)o[u]=r[u]^a[u-i]}return o}function Uo(t){let e=0n;for(let n=t.length-1;n>=0;n-=1)e=e<<8n|BigInt(t[n]);return e}var bd=(1n<<130n)-5n;function wd(t,e){let n=Uo(t.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,r=Uo(t.subarray(16,32)),o=0n;for(let a=0;a<e.length;a+=16){let c=e.subarray(a,Math.min(a+16,e.length)),u=Uo(c)+(1n<<BigInt(8*c.length));o=(o+u)*n%bd}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 Ra(t){return new Uint8Array((16-t%16)%16)}function Ca(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function Ad(t,e){let n=[t,Ra(t.length),e,Ra(e.length),Ca(t.length),Ca(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 xd(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 ka(t,e,n,r=new Uint8Array(0)){xd(t,e);let o=Sa(t,0,e).subarray(0,32),i=yd(t,1,e,n),s=wd(o,Ad(r,i)),a=new Uint8Array(i.length+16);return a.set(i),a.set(s,i.length),a}var Ia=32,vd=1,Rd=3,Cd=2,Sd=32,kd=32,Ed=12,nt=t=>new TextEncoder().encode(t),Gt=t=>new Uint8Array([t>>8&255,t&255]),Ea=f(nt("KEM"),Gt(Ia)),Mt=f(nt("HPKE"),Gt(Ia),Gt(vd),Gt(Rd));async function Pa(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 Id(t,e,n){let r=new Uint8Array(n),o=new Uint8Array(0);for(let i=1,s=0;s<n;i+=1)o=await Pa(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 Pa(e,f(nt("HPKE-v1"),t,nt(n),r))}function Oo(t,e,n,r,o){return Id(e,f(Gt(o),nt("HPKE-v1"),t,nt(n),r),o)}async function Pd(t,e){let n=await ir(Ea,new Uint8Array(0),"eae_prk",t);return Oo(Ea,n,"shared_secret",e,Sd)}async function Td(t,e){let n=new Uint8Array(0),r=await ir(Mt,n,"psk_id_hash",n),o=await ir(Mt,n,"info_hash",e),i=f(new Uint8Array([Cd]),r,o),s=await ir(Mt,t,"secret",n);return{key:await Oo(Mt,s,"key",i,kd),nonce:await Oo(Mt,s,"base_nonce",i,Ed)}}async function Ta(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 pt(s.privateKey,t),await pt(a.privateKey,t)),u=await Pd(c,f(s.publicKey,t,a.publicKey)),{key:d,nonce:l}=await Td(u,n);return{enc:s.publicKey,ciphertext:ka(d,l,r,o)}}var Oa="mero-agent-gate/attest/v3",Na="mero-agent-gate/provision/v2",Dd=/^[a-z0-9][a-z0-9-]{0,62}$/,Ud=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,Da=64,Ua=64*1024,ue=class extends Error{constructor(n,r,o){super(n);this.status=r;this.code=o;this.name="AgentGateError"}};function _a(t){if(!Dd.test(t))throw new Error(`Agent id ${JSON.stringify(t)} must match [a-z0-9][a-z0-9-]{0,62}`)}function Kt(t){return new TextEncoder().encode(t)}function Ma(t){let e=Kt(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 Ga(t,e,n,r){let o=new Uint8Array(32),i=f(Kt(Oa),t,Ma(e),n??o,r??o);return new Uint8Array(await crypto.subtle.digest("SHA-256",i))}function Ka(t,e){return f(Kt(Na),t,Ma(e))}async function Od(){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 $a(t,e){return`${t.replace(/\/+$/,"")}${e}`}async function La(t,e,n){let r=await t(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}),o=await r.text(),i;try{i=o?JSON.parse(o):void 0}catch{}if(!r.ok){let s=i;throw new ue(`The gate answered ${r.status}${s?.error?` ${s.error}`:""}: ${s?.details??o.slice(0,200)}`,r.status,s?.error)}return i}async function No(t){let e=t.agentId??"";e&&_a(e);let n=crypto.getRandomValues(new Uint8Array(32)),r=await La(t.fetch??fetch,$a(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 Ga(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 Ha(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 Nd(t){let e=Object.keys(t);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>Da)throw new Error(`At most ${Da} secrets at once`);for(let n of e){if(!Ud.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(Kt(t[n]).length>Ua)throw new Error(`Secret ${n} is over ${Ua} bytes`)}}async function Ba(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 Ha(r,o),a=sr(r.provisioningPublicKey,"provisioningPublicKey",32),c=await Ta(a,o,Ka(a,r.agentId),Kt(JSON.stringify(i)));return La(t,$a(e,n),{agentId:r.agentId,provisioningPublicKeyB64:r.provisioningPublicKey,senderPublicKeyB64:s,encappedKeyB64:Ce(c.enc),ciphertextB64:Ce(c.ciphertext)})}async function _d(t){Nd(t.secrets);let e=t.fetch??fetch,n=await Ba(e,t.gateUrl,"/provision",t.agent,t.ownerSecret,{secrets:t.secrets}),r=await No({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e}),o=await 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 Md(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 Ba(e,t.gateUrl,"/release",t.agent,t.ownerSecret,{release:!0}),(await No({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e})).ownerPublicKey)throw new ue("The gate says it released the agent, but its quote still names an owner")}var _o=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),Gd=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function Kd(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await ln(r,e,{identity:n.identity??_o.identity,issuer:n.issuer??_o.issuer});let o;try{o=JSON.parse(new TextDecoder().decode(r))}catch{throw new Error("The signed agent policy is not JSON")}if(o?.role!=="agent")throw new Error(`The signed file is a ${JSON.stringify(o?.role)} policy, not an agent one`);let i=n.profile??ht;if(o.profile!==i)throw new Error(`The signed agent policy is for the ${JSON.stringify(o.profile)} profile, not ${i}`);if(n.expectedVersion!==void 0&&o.version!==n.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(o.version)}, not ${n.expectedVersion}`);return qa(o),o}function qa(t){for(let e of Gd)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 $d=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function Ld(t){let e=$d.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 $t=t=>t.trim().replace(/^0x/i,"");function Hd(t,e){return qa(t),yt({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:t.allowed_tcb_statuses.map(Ld),allowedMrtd:t.allowed_mrtd.map($t),allowedRtmr0:t.allowed_rtmr0.map($t),allowedRtmr1:t.allowed_rtmr1.map($t),allowedRtmr2:t.allowed_rtmr2.map($t),allowedRtmr3:t.allowed_rtmr3.map($t)})}export{si as ACCOUNT_HA_AUDIENCE,ii as ACCOUNT_OWNERSHIP_AUDIENCE,Oa as AGENT_ATTEST_DOMAIN,Na as AGENT_PROVISION_INFO_DOMAIN,J as AccountHaRefusedError,kt as AccountLinkedToSeveralUsersError,xe as AccountNotLinkedError,me as AdminApiClient,ue as AgentGateError,pe as AuthApiClient,oe as AuthRevokedError,_ as CAPABILITIES,wp as CAPABILITY_PRESETS,$ as CloudClient,ba as DEFAULT_LOCAL_NODE_PORTS,un as DEFAULT_RELEASE_MIRROR,ut as EphemeralClient,Di as HANDSHAKE_PATH,tr as HA_ACCOUNT_NOT_LINKED_MESSAGE,Xn as HA_REFUSAL_MESSAGES,O as HTTPError,Et as HaRequestPendingError,bo as INVITED_ROLE,he as IntentRefusedError,et as InvitationNotClaimableError,_o as KMS_RELEASE_SIGNER,Io as LocalStorageTokenStore,Vn as MAX_INVITATION_VALIDITY_SECS,Eo as MemoryTokenStore,be as MeroClient,We as MeroJs,qr as NODE_RELEASE_SIGNER,Ze as NoRelayError,Re as NotForAccountError,Po as OWNER_OP_KIND,ps as PRESENCE_DOMAIN,ht as PRODUCTION_PROFILE,Gn as RELAY_NODE_KEY_RETRY_MS,Ee as REQUEST_PROOF_HEADER,W as RelayClient,Pt as RelayNotDialableError,Fe as RelayObserver,Ct as RelayPresenceClient,ye as RelayTransport,lt as RpcClient,zt as RpcError,mt as SEALED_CONTENT_TYPE,Ui as SEALED_PATH,xo as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,_e as SealedTransportError,B as SseClient,ft as StaleTransportKeyError,It as UnknownRelayError,ot as WebHttpClient,ie as WsClient,en as accountForRoot,F as accountForRootPublicKey,gi as accountRootFromPhrase,Ur as accountRootFromSecret,fi as accountRootSignerFromPhrase,da as adminChangedOp,Mu as admitterAddrsFromNetworkStatus,Ga as agentKeyBinding,Hd as agentQuoteVerifier,vo as applicationIdForBundle,ze as attemptRelayNodeKey,No as attestAgent,on as attestKeyBinding,sn as attestRelayNodeKey,Su as beginCloudLink,Du as beginDeviceEnrolment,Yn as bootstrapFromInvitation,Rr as buildAuthLoginUrl,Hn as buildDelegatedClient,$s as callbackIsForeign,Wt as callerProof,Ap as capMask,xp as capNames,Bn as carryExecutorAccount,Ha as checkOwner,yr as classifyError,xs as clearDelegatedCredential,bs as clearDelegatedSession,Ns as cloudLinkUrl,gn as cloudNodeReleaseUrl,lr as combineSignals,lc as compareSemver,Eu as completeCloudLink,Ou as completeDeviceEnrolment,Us as connectCloud,bu as connectCloudWithAccount,cs as contextCapabilityGrantedOp,ls as contextCapabilityRevokedOp,En as contextDetachedOp,Tn as contextMetadataSetOp,ta as createAccountAdmin,mi as createAccountRootSigner,jo as createAdminApiClient,Ft as createAdminApiClientFromHttpClient,fe as createAttestedSealedFetch,yp as createAuthApiClient,Lo as createAuthApiClientFromHttpClient,$p as createBrowserAdminApiClient,fp as createBrowserAuthApiClient,Ie as createBrowserHttpClient,Ot as createDelegatedContext,Qs as createDelegatedPrivateContext,it as createHttpClient,St as createLocalStorageNonceSource,go as createMemoryNonceSource,Nn as createMeroClient,sd as createMeroJs,na as createNodeAdmin,Lp as createNodeAdminApiClient,hp as createNodeAuthApiClient,qt as createNodeHttpClient,gr as createProofAuthorizer,Jt as createProofSigner,yt as createQuoteVerifier,Za as createRetryableMethod,Mi as createSealedFetch,Dl as createSignedReleaseSealedFetch,mn as createSignedReleaseVerifier,ur as createTimeoutSignal,mr as createUniversalHttpClient,Yr as createdSubgroupId,Vr as creationInitHash,Ao as defaultAdmitters,Ve as defaultAudience,He as defaultCapabilitiesSetOp,ve as delegatedGovernance,Xt as deviceCertPayload,Ks as deviceEnrolmentUrl,Pr as deviceScopePayload,hd as discoverLocalNodes,Tt as encodeGroupInvitation,Jn as encodeSignedInvitation,_i as fetchAttestedTransportKey,dn as fetchNodeRelease,pn as fetchNodeReleaseVersion,Ut as fetchRegistryBundles,Es as forgetMethodKinds,ks as forgetRelaySealing,er as foundDelegatedNamespace,Cn as foundedNamespaceId,pi as generateAccountRoot,Od as generateOwnerKey,to as generateSessionKey,nr as governGroup,rr as governRoot,Wr as governanceOpHash,Xr as groupCreatedOp,ua as groupDeleteOp,Rn as groupDeletedOp,wo as groupInvitationHash,qe as groupMetadataSetOp,vn as groupReparentedOp,ge as hasCap,Np as hexEncodeUtf8,jr as intentHash,rc as isSettled,js as joinAsAccount,Qn as joinWithNode,se as jsonCodec,Ye as knownRelays,Xe as latestPublishedVersion,Ss as learnRelayNodeKey,Ts as listDelegatedContexts,Ds as listDelegatedNamespaces,wa as localNodeUrl,je as login,Kn as markContextNonceSpent,Le as memberAddedOp,kn as memberCapabilitySetOp,Dn as memberJoinedOpenOp,Rt as memberLeftOp,Pn as memberMetadataSetOp,wn as memberRemovedOp,An as memberRoleSetOp,Er as mintDeviceId,Sn as namespaceCreatedOp,_t as namespaceOfGroup,Aa as nodeEndpoint,Ji as nodeReleaseVersionFromImage,jn as normaliseAccount,To as ownerOpDigest,Do as ownerOpSigningPayload,ar as ownerPublicKey,vr as parseAuthCallback,rs as parseCreationWarrant,Ir as parseDeviceCredential,os as parseGovernanceWarrant,co as persistedNonces,lo as pinRelayNodeKey,no as presenceStatementBytes,xa as probeNodeHealth,_d as provisionAgent,Ka as provisionInfo,ku as readCloudLinkCallback,ws as readDelegatedCredential,ao as readDelegatedSession,Uu as readEnrolmentCallback,$n as readPinnedRelayNodeKey,q as readRelayMap,Ho as redeemInvitation,Ps as relayForContext,Qe as relayTransportFetch,Md as releaseAgent,Nt as rememberGroupNamespace,we as rememberRelay,Nr as reportDataOf,rt as requestBodyHash,Vs as resolveApplicationIdFromRegistry,Fn as resolveRelayFromInvitation,Ln as resolveRelayNodeKey,Y as resolveRoot,tn as resolveRootPair,ya as rootGuardedOpBytes,qn as routingProofHeaders,As as saveDelegatedCredential,ys as saveDelegatedSession,Dt as selectLatestBundle,kp as shouldRetain,kr as signAccountHaClaim,dt as signAccountLink,nn as signAccountLogin,Cc as signAccountOwnershipClaim,yn as signCreationWarrant,li as signDeviceCert,ui as signDeviceScope,xt as signGovernanceWarrant,Wn as signGroupInvitation,On as signLoginStatement,zn as signMemberJoinOp,ha as signOwnerOpProof,Lt as signRequest,pr as signRequestProof,Os as signRoutingChallenge,fn as signWarrant,de as signedPath,ei as signerFromCryptoKey,De as signerFromSecret,gs as stateHash,Be as subgroupCreation,In as subgroupVisibilitySetOp,Yt as subscribePresence,xn as targetApplicationSetOp,ga as teeAdmissionPolicyOp,pa as teeAuthoringPolicyOp,ma as teeReleaseAdmissionPolicyOp,la as transferOwnershipOp,Ni as transportKeyBinding,Yi as trustSignedRelease,$r as trustedMeasurementsFromReleases,_a as validateAgentId,Zt as verifyDeviceCredential,Kd as verifySignedAgentPolicy,Wi as verifySignedNodeRelease,fr as withCap,jt as withRetry,vp as withoutCap};
|
|
3
3
|
//# sourceMappingURL=index.browser.mjs.map
|