@calimero-network/mero-js 25.3.1 → 25.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/auth/index.d.ts +11 -2
- package/dist/auth/index.js +20 -3
- package/dist/cloud/enrol-redirect.d.ts +10 -24
- package/dist/cloud/enrol-redirect.js +16 -8
- package/dist/cloud/link-state.d.ts +5 -1
- package/dist/cloud/link-state.js +28 -21
- package/dist/events/sse.d.ts +8 -0
- package/dist/events/sse.js +19 -8
- package/dist/index.browser.mjs +2 -2
- package/dist/index.browser.mjs.map +4 -4
- package/dist/index.cjs +111 -78
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +111 -78
- package/dist/index.mjs.map +4 -4
- package/dist/mero-js.d.ts +2 -2
- package/dist/mero-js.js +2 -2
- package/package.json +1 -1
package/dist/index.browser.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
function lr(t){let e=t.filter(Boolean);if(e.length===0)return;let n=AbortSignal;if(typeof n.any=="function")try{return n.any(e)}catch{}let r=new AbortController,o=i=>{r.abort(i.target.reason);for(let s of e)s.removeEventListener("abort",o)};for(let i of e){if(i.aborted)return AbortSignal.abort(i.reason);i.addEventListener("abort",o,{once:!0})}return r.signal}function ur(t){if(typeof AbortSignal.timeout=="function")return AbortSignal.timeout(t);let e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("Timeout","TimeoutError"))},t),e.signal}var Uo=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function R(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),e}function y(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function m(t,e,n){let r=t.trim();if(!/^[0-9a-fA-F]*$/.test(r)||r.length!==n*2)throw new Error(`${e} must be ${n*2} hex characters, got ${r.length}`);let o=new Uint8Array(n);for(let i=0;i<n;i+=1)o[i]=Number.parseInt(r.slice(i*2,i*2+2),16);return o}function j(t,e){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2!==0)throw new Error(`${e} must be an even number of hex characters`);let r=new Uint8Array(n.length/2);for(let o=0;o<r.length;o+=1)r[o]=Number.parseInt(n.slice(o*2,o*2+2),16);return r}function C(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function f(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}async function k(t,e){let n=[C(t.length),t];for(let r of e)n.push(C(r.length),r);return new Uint8Array(await crypto.subtle.digest("SHA-256",f(...n)))}async function ne(t){let e=m(t,"deviceSecret",32),n=f(Uo,e);try{return await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!1,["sign"])}catch(r){let o=r instanceof Error?`: ${r.message}`:"";throw new Error("this runtime has no WebCrypto Ed25519, so a warrant cannot be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it; otherwise mint the warrant with `merod account warrant`"+o)}}async function Oo(t,e,n){let r=await crypto.subtle.importKey("raw",m(t,"publicKey",32),{name:"Ed25519"},!1,["verify"]);return crypto.subtle.verify({name:"Ed25519"},r,e,n)}async function re(t){let e=m(t,"deviceSecret",32),n=f(Uo,e),r=await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),i=(await crypto.subtle.exportKey("jwk",r)).x;return Uint8Array.from(atob(i.replace(/-/g,"+").replace(/_/g,"/")),s=>s.charCodeAt(0))}var dr=new TextEncoder().encode("calimero.auth.request.v2"),$a=new TextEncoder().encode("calimero.auth.request.body.v1");function _o(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}async function nt(t=new Uint8Array(0)){let e=typeof t=="string"?new TextEncoder().encode(t):t;return k($a,[e])}async function Kt(t){let e=await ne(t.signerSecret),n=await nt(t.body),r=C(t.issuedAt),o=C(t.expiresAt),i=new TextEncoder,s=await k(dr,[i.encode(t.method),i.encode(t.path),n,r,o]),a=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},e,s));return y(f(_o(t.method),_o(t.path),n,r,o,a))}var Ee=t=>new TextEncoder().encode(t),ke="X-Calimero-Proof",La=300;async function pr(t){let{method:e,path:n,credential:r}=t;if(!e)throw new Error("signRequestProof needs the method the request will use");if(!n.startsWith("/"))throw new Error(`signRequestProof needs a path, got ${JSON.stringify(n)}`);let o=await nt(t.body),i=Math.floor(t.now??Date.now()/1e3),s=i+(t.validForSeconds??La),a=await k(dr,[Ee(e),Ee(n),o,C(i),C(s)]),c=await Ha(a,t);if(c.length!==64)throw new Error(`the signer returned ${c.length} bytes, not a 64-byte signature`);let u=f(R(Ee(e).length),Ee(e),R(Ee(n).length),Ee(n),o,C(i),C(s),c),d=Ba(r,"credential");return y(f(d,new Uint8Array([0]),u))}async function Ha(t,e){if(e.signer)return e.signer.sign(t);if(!e.deviceSecret)throw new Error("signRequestProof needs either `deviceSecret` or `signer`");let n=await ne(e.deviceSecret);return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,t))}function Ba(t,e){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2!==0)throw new Error(`${e} is not an even-length hex string`);return m(n,e,n.length/2)}function gr(t){if(!t.credential)throw new Error("a proof authorizer needs the `credential` from signDeviceCert");if(!t.deviceSecret&&!t.signer)throw new Error("a proof authorizer needs either `deviceSecret` or `signer`");return async({method:e,path:n,body:r})=>{let o=await pr({method:e,path:n,body:r,credential:t.credential,deviceSecret:t.deviceSecret,signer:t.signer,validForSeconds:t.validForSeconds});return{[ke]:o}}}function de(t){let e=new URL(t,globalThis.location?.href??"http://localhost");return e.pathname+e.search}var qa=new Set(["token_reuse","token_revoked"]);function ja(t){if(t)try{let e=JSON.parse(t),n=e?.error;if(typeof n=="string"&&n.trim()!=="")return n;let r=n?.message;if(typeof r=="string"&&r.trim()!=="")return r;let o=e?.detail;if(typeof o=="string"&&o.trim()!=="")return o}catch{}}var D=class extends Error{constructor(n,r,o,i,s){let a=ja(s)??(n===0&&s?.trim()?s.trim():void 0);super(a?`HTTP ${n} ${r}: ${a}`:`HTTP ${n} ${r}`);this.status=n;this.statusText=r;this.url=o;this.headers=i;this.bodyText=s;this.name="HTTPError";this.explanation=a}toJSON(){return{status:this.status,statusText:this.statusText,url:this.url,headers:Mo(this.headers),bodyText:this.bodyText}}},oe=class extends D{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.reason=n;this.name="AuthRevokedError";this.message=`Authentication revoked (${n}): HTTP ${r} ${o}`}};function Mo(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function Fa(t){let e;try{e=new URL(t,globalThis.location?.href)}catch{return t}return e.search===""&&(e.search=""),e.href}function Gt(t){return Object.keys(t).some(e=>e.toLowerCase()===ke.toLowerCase())}function $t(t,e){if(t.type==="opaqueredirect"||t.status>=300&&t.status<400)throw new D(0,"Redirect Not Followed",e,t.headers,`the node answered with a redirect; a request carrying ${ke} is not followed to another location`)}var rt=class{constructor(e){this.transport=e;this.refreshTokenPromise=null;this.onTokenRefreshPromise=null}async get(e,n){return this.request(e,{...n,method:"GET"})}async post(e,n,r){return this.request(e,{...r,method:"POST",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async put(e,n,r){return this.request(e,{...r,method:"PUT",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async delete(e,n){return this.request(e,{...n,method:"DELETE"})}async patch(e,n,r){return this.request(e,{...r,method:"PATCH",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async head(e,n){let r=await this.makeRequest(e,{...n,method:"HEAD",parse:"response"});return{headers:Mo(r.headers),status:r.status}}async request(e,n){return this.makeRequest(e,n)}async makeRequest(e,n,r=0,o){let s=Fa(this.buildUrl(e)),a=o??Date.now(),c=this.createAbortSignal(n),u=await this.buildHeaders(n?.headers),d;u instanceof Headers?(d={},u.forEach((w,E)=>{d[E]=w})):d=u;let l=n?.method||"GET";if(this.transport.authorizeRequest){let w=n?.body;if(w!==void 0&&typeof w!="string"&&!(w instanceof Uint8Array))throw new Error("this transport authorizes each request against its body, so the body must be a string or Uint8Array \u2014 a stream cannot be signed, because the signature would have to read bytes the request then cannot send.");Object.assign(d,await this.transport.authorizeRequest({method:l,path:de(s),body:w}))}let p={method:l,headers:d},x=n?.body instanceof ReadableStream||typeof n?.body=="object"&&n?.body!==null&&"getReader"in n.body&&!(n.body instanceof Blob);(n?.body!==void 0&&!x||n?.body!==void 0&&x&&r===0)&&(p.body=n.body);let v;if(r>0&&o!==void 0){let w=n?.timeoutMs||this.transport.timeoutMs;if(w){let E=Date.now()-a,T=Math.max(0,w-E);v=this.createAbortSignal({...n,timeoutMs:T})}else v=this.createAbortSignal(n)}else v=c;if(v&&(p.signal=v),this.transport.credentials!==void 0&&(p.credentials=this.transport.credentials),n?.mode!==void 0&&(p.mode=n.mode),n?.cache!==void 0&&(p.cache=n.cache),n?.redirect!==void 0&&(p.redirect=n.redirect),n?.referrer!==void 0&&(p.referrer=n.referrer),n?.referrerPolicy!==void 0&&(p.referrerPolicy=n.referrerPolicy),n?.integrity!==void 0&&(p.integrity=n.integrity),n?.keepalive!==void 0&&(p.keepalive=n.keepalive),this.transport.getProof){let w=await this.transport.getProof({method:p.method??"GET",path:de(s),body:p.body});w&&(d["X-Calimero-Proof"]=w)}let P=Gt(d);P&&p.redirect!=="error"&&(p.redirect="manual");try{let w=await this.transport.fetch(s,p);if(P&&$t(w,s),!w.ok){let E=await this.getBodyText(w),T=new D(w.status,w.statusText,s,w.headers,E),H=w.headers.get("x-auth-error");if((w.status===401||w.status===403)&&H&&qa.has(H)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new oe(H,w.status,w.statusText,s,w.headers,E)}let z=n?.signal?.aborted===!0;if(w.status===401&&this.transport.refreshToken&&H==="token_expired"&&r<1&&!x&&!z)try{let h=this.refreshTokenPromise;h||(h=this.transport.refreshToken(),this.refreshTokenPromise=h);let b=await h;if(!b||b.trim()==="")throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("Refresh token returned empty token");if(!this.transport.onTokenRefresh)throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("onTokenRefresh callback is required when refreshToken is provided. The callback must update the token storage so getAuthToken() returns the new token.");let S=this.onTokenRefreshPromise;S||(S=this.transport.onTokenRefresh(b),this.onTokenRefreshPromise=S),await S,this.refreshTokenPromise=null,this.onTokenRefreshPromise=null;let U=n?.timeoutMs||this.transport.timeoutMs;if(U&&o!==void 0){let M=Date.now()-a;if(U-M<=0)throw T}return this.makeRequest(e,n,r+1,a)}catch(h){throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,h instanceof Error&&h.message.includes("onTokenRefresh")?h:T}throw T}return this.parseResponse(w,n?.parse)}catch(w){throw w instanceof D||w instanceof Error&&w.message.includes("onTokenRefresh")?w:new D(0,"Network Error",s,new Headers,w instanceof Error?w.message:"Unknown error")}}buildUrl(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;let n=this.transport.baseUrl;return e.startsWith("/")?`${n.endsWith("/")?n.slice(0,-1):n}${e}`:`${n.endsWith("/")?n:`${n}/`}${e}`}createAbortSignal(e){let n=[];this.transport.defaultAbortSignal&&n.push(this.transport.defaultAbortSignal),e?.signal&&n.push(e.signal);let r=e?.timeoutMs||this.transport.timeoutMs;return r&&n.push(ur(r)),n.length>0?lr(n):void 0}async buildHeaders(e){let n={...this.transport.defaultHeaders};if(this.transport.getAuthToken)try{let r=await this.transport.getAuthToken();r&&r.trim()!==""&&(n.Authorization=`Bearer ${r}`)}catch{}return e&&(e instanceof Headers?e.forEach((r,o)=>{n[o]=r}):Array.isArray(e)?e.forEach(([r,o])=>{n[r]=o}):Object.assign(n,e)),n}async parseResponse(e,n){switch(n){case"text":return await e.text();case"blob":return await e.blob();case"arrayBuffer":return await e.arrayBuffer();case"response":return e;default:{let r=await e.text();if(!r)return null;try{return JSON.parse(r)}catch{throw new Error(`Expected a JSON response (status ${e.status}) but body was not JSON: ${r.slice(0,200)}`)}}}}async getBodyText(e){try{let n=await e.text();return n.length>65536?n.slice(0,65536)+"...":n}catch{return""}}};function ot(t){return new rt(t)}function Ie(t){let e={fetch:(n,r)=>t.fetch?t.fetch(n,r):globalThis.fetch(n,r),baseUrl:t.baseUrl,getAuthToken:t.getAuthToken,getProof:t.getProof,onTokenRefresh:t.onTokenRefresh,refreshToken:t.refreshToken,onAuthRevoked:t.onAuthRevoked,defaultHeaders:t.defaultHeaders,timeoutMs:t.timeoutMs,credentials:t.credentials,defaultAbortSignal:t.defaultAbortSignal};return ot(e)}function Lt(t){let e=t.fetch??globalThis.fetch;if(!e)throw new Error("No fetch implementation available. Please provide a fetch implementation (e.g., undici.fetch) or use Node.js 18+ which has native fetch support.");let r={fetch:e===globalThis.fetch?(o,i)=>globalThis.fetch(o,i):(o,i)=>e(o,i),baseUrl:t.baseUrl,getAuthToken:t.getAuthToken,getProof:t.getProof,onTokenRefresh:t.onTokenRefresh,refreshToken:t.refreshToken,onAuthRevoked:t.onAuthRevoked,defaultHeaders:t.defaultHeaders,timeoutMs:t.timeoutMs,credentials:t.credentials,defaultAbortSignal:t.defaultAbortSignal};return ot(r)}function mr(t){return typeof window<"u"?Ie(t):Lt(t)}function Va(t,e){if(e<=0)return!1;let r=t?.name;if(r==="TimeoutError")return!0;if(r==="AbortError")return!1;let o=t;if("status"in o&&typeof o.status=="number"){let i=o.status;return i>=500||i===429}return r==="TypeError"}function Wa(t){let n=250*Math.pow(2,t-1),r=(Math.random()-.5)*.4*n;return Math.max(0,n+r)}async function Ht(t,e={}){let{attempts:n=3}=e,r;for(let o=1;o<=n;o++)try{return await t(o)}catch(i){if(r=i,!Va(r,n-o))throw r;let s=Wa(o),u=r.headers?.get?.("Retry-After");if(u){let d=parseInt(u,10);if(!isNaN(d))s=Math.max(s,d*1e3);else{let l=new Date(u);if(!isNaN(l.getTime())){let p=Math.max(0,l.getTime()-Date.now());s=Math.max(s,Math.min(p,6e4))}}}await new Promise(d=>setTimeout(d,s))}throw r||new Error("Retry failed without error")}function Ja(t,e={}){return async(...n)=>Ht(()=>t(...n),e)}function g(t){if(t===""||t==="."||t==="..")throw new TypeError(`invalid request path segment: ${JSON.stringify(t)}`);return encodeURIComponent(t)}var pe=class{constructor(e){this.httpClient=e}async getHealth(){let e=await this.httpClient.get("/auth/health");if(!e.data)throw new Error("Health response data is null");return e.data}async getIdentity(){let e=await this.httpClient.get("/admin/identity");if(!e.data)throw new Error("Identity response data is null");return e.data}async getProviders(){let e=await this.httpClient.get("/auth/providers");if(!e.data)throw new Error("Providers response data is null");return e.data}async getLoginPage(){return this.httpClient.get("/auth/login",{parse:"text"})}async generateTokens(e){return this.httpClient.post("/auth/token",e)}async refreshToken(e){return this.httpClient.post("/auth/refresh",e)}async generateMockTokens(e){return this.httpClient.post("/auth/mock-token",e)}async validateToken(e){try{let n=await this.validateTokenGet(e);return{valid:n.status===200,headers:n.headers,status:n.status}}catch{return{valid:!1,headers:{},status:401}}}async validateTokenGet(e){let n=await this.httpClient.head("/auth/validate",{headers:{Authorization:`Bearer ${e}`}});return{status:n.status,headers:n.headers}}async revokeTokens(e){let n=await this.httpClient.post("/admin/revoke",e);if(!n.data)throw new Error("Revoke tokens response data is null");return n.data}async listRootKeys(){let e=await this.httpClient.get("/admin/keys");if(!e.data)throw new Error("Root keys response data is null");return e.data}async createRootKey(e){let n=await this.httpClient.post("/admin/keys",e);if(!n.data)throw new Error("Create root key response data is null");return n.data}async deleteRootKey(e){return this.httpClient.delete(`/admin/keys/${g(e)}`)}async listClientKeys(){let e=await this.httpClient.get("/admin/keys/clients");if(!e.data)throw new Error("Client keys response data is null");return e.data}async generateClientKey(e){return this.httpClient.post("/admin/client-key",e)}async deleteClientKey(e,n){return this.httpClient.delete(`/admin/keys/${g(e)}/clients/${g(n)}`)}async getKeyPermissions(e){return this.httpClient.get(`/admin/keys/${g(e)}/permissions`)}async updateKeyPermissions(e,n){return this.httpClient.put(`/admin/keys/${g(e)}/permissions`,{add:n.add,remove:n.remove})}};var it=class{async get(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async post(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async put(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async delete(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async patch(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async head(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async request(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}};function ip(t){let e=new it;return new pe(e)}function sp(t){let e=new it;return new pe(e)}function ap(t){let e=new it;return new pe(e)}function Ko(t,e){return new pe(t)}var _={CAN_CREATE_CONTEXT:1,CAN_INVITE_MEMBERS:2,CAN_JOIN_OPEN_SUBGROUPS:4,MANAGE_MEMBERS:8,MANAGE_APPLICATION:16,CAN_CREATE_SUBGROUP:32,CAN_DELETE_SUBGROUP:64,CAN_MANAGE_VISIBILITY:128,CAN_MANAGE_METADATA:256,CAN_AUTHOR_ON_BEHALF:512},lp={NONE:0,JOIN_ONLY:_.CAN_JOIN_OPEN_SUBGROUPS,CONTRIBUTOR:_.CAN_CREATE_CONTEXT|_.CAN_INVITE_MEMBERS|_.CAN_JOIN_OPEN_SUBGROUPS,COLLABORATOR:_.CAN_CREATE_CONTEXT|_.CAN_INVITE_MEMBERS|_.CAN_JOIN_OPEN_SUBGROUPS|_.CAN_CREATE_SUBGROUP|_.CAN_DELETE_SUBGROUP|_.CAN_MANAGE_VISIBILITY};function up(...t){let e=0;for(let n of t)if(typeof n=="number")e|=n;else if(Object.prototype.hasOwnProperty.call(_,n))e|=_[n];else throw new Error(`unknown capability: ${String(n)}`);return e>>>0}function dp(t){return Object.keys(_).filter(e=>ge(t,_[e]))}function ge(t,e){let n=e>>>0;return(t&n)>>>0===n}function fr(t,e){return(t|e)>>>0}function pp(t,e){return(t&~e)>>>0}var za={invalid:!1,unauthorized:!0,forbidden:!1,"not-found":!0,conflict:!1,gone:!1,"too-large":!1,"rate-limited":!0,unavailable:!0,server:!0,unreachable:!0,unknown:!0};function Qa(t){switch(t){case 0:return"unreachable";case 400:return"invalid";case 401:return"unauthorized";case 403:return"forbidden";case 404:return"not-found";case 409:return"conflict";case 410:return"gone";case 413:return"too-large";case 429:return"rate-limited";case 503:case 504:return"unavailable"}return t>=500&&t<600?"server":t>=400&&t<500?"invalid":"unknown"}function Ya(t){if(!t||typeof t!="object")return;let e=t;for(let n of[e.status,e.response?.status,e.statusCode])if(typeof n=="number"&&Number.isFinite(n))return n}function hr(t,e="Request failed"){if(typeof t=="string")return t.trim()||e;if(!t||typeof t!="object")return e;let n=t;for(let r of[n.explanation,n.response?.data?.error,n.response?.data?.message,n.data?.message,n.error,n.message])if(typeof r=="string"&&r.trim())return r;return e}function yr(t){let e=Ya(t),n;return e!==void 0?n=Qa(e):t instanceof TypeError?n="unreachable":n="unknown",{kind:n,status:e,retryable:za[n],message:hr(t)}}function Xa(t){return t.status!=="failed"||!t.retryable}function hp(t){return!Xa(t)}function Za(t){let e=t.toLowerCase();return e.includes("invitation has expired")||e.includes("invitation expired")||/\binvitation for group .+? expired at \d+/.test(e)?"expired":e.includes("malformed")||e.includes("does not match namespace_id")||e.includes("invalid invitation")||/\binvitation for group .+? is invalid:/.test(e)?"invalid":null}function ec(t,e){let{kind:n,status:r}=yr(t),o=Za(e);return r===401?{reason:"signed-out",retryable:!0}:r===400?{reason:o??"invalid",retryable:!1}:r===410?{reason:"expired",retryable:!1}:r===403?{reason:"refused",retryable:!1}:r===409?{reason:o??"refused",retryable:!1}:n==="unavailable"?{reason:"no-one-online",retryable:!0}:n==="unreachable"?{reason:"node-unreachable",retryable:!0}:o?{reason:o,retryable:!1}:{reason:"unknown",retryable:!0}}async function Go(t,e){let{namespaceId:n,invitation:r,teamName:o}=t,i=null;try{await e.join(n,r)}catch(d){i=d}let s=null;try{s=(await e.memberships()).includes(n)}catch{s=null}if(i===null)return{status:"joined",namespaceId:n,teamName:o};if(s===!0)return{status:"already-member",namespaceId:n,teamName:o};let a=hr(i,"Could not join. Check the invitation."),{reason:c,retryable:u}=ec(i,a);return{status:"failed",namespaceId:n,message:a,reason:c,retryable:u}}var Bt=class extends Error{constructor(n,r){super(`this node does not serve warrant-nonce discovery (404 on ${n}); it predates the route, so a client must fall back to its own nonce counter`);this.path=n;this.cause=r;this.name="WarrantNonceRouteUnavailableError"}};function wr(t,e,n){let r=e[n];if(r==null)return;let o=new RegExp(`"${n}"\\s*:\\s*(\\d+)`).exec(t);if(o)return BigInt(o[1]);if(typeof r=="string"&&/^\d+$/.test(r))return BigInt(r);throw new Error(`warrant-nonce response field \`${n}\` is not a u64: ${JSON.stringify(r)}`)}function $o(t){let n=JSON.parse(t)?.data;if(!n||typeof n!="object")throw new Error(`warrant-nonce response had no \`data\`: ${t.slice(0,200)}`);let r={contextId:String(n.contextId??""),authorDeviceKey:String(n.authorDeviceKey??""),seen:n.seen===!0,highWaterNonce:wr(t,n,"highWaterNonce"),windowWidth:wr(t,n,"windowWidth")??0n},o=wr(t,n,"nextNonce");return o===void 0?{...r,kind:"exhausted",seen:!0,highWaterNonce:r.highWaterNonce??0xffffffffffffffffn}:{...r,kind:"open",nextNonce:o}}function A(t){return t?.data}function tc(t,e){let[n,r]=Lo(t),[o,i]=Lo(e),s=n.split("."),a=o.split("."),c=Math.max(s.length,a.length);for(let p=0;p<c;p++){let x=Ho(s[p]??"0",a[p]??"0");if(x!==0)return x}if(r===void 0&&i===void 0)return 0;if(r===void 0)return 1;if(i===void 0)return-1;let u=r.split("."),d=i.split("."),l=Math.max(u.length,d.length);for(let p=0;p<l;p++){if(p>=u.length)return-1;if(p>=d.length)return 1;let x=Ho(u[p],d[p]);if(x!==0)return x}return 0}function Lo(t){let e=t.split("+",1)[0],n=e.indexOf("-");return n===-1?[e,void 0]:[e.slice(0,n),e.slice(n+1)]}function Ho(t,e){let n=/^\d+$/.test(t),r=/^\d+$/.test(e);if(n&&r){let o=Number(t)-Number(e);return o<0?-1:o>0?1:0}return n?-1:r?1:t<e?-1:t>e?1:0}async function nc(t,e,n){return Ht(async()=>{let r=await fetch(t,{signal:AbortSignal.timeout(1e4)});if(!r.ok){let o=new Error(`registry ${e} fetch failed (${r.status}) for ${n}`);throw o.status=r.status,o}return r},{attempts:3})}var me=class{constructor(e){this.httpClient=e}async healthCheck(){return A(await this.httpClient.get("/admin-api/health"))}async readinessCheck(){return A(await this.httpClient.get("/admin-api/ready"))}async isAuthed(){return this.httpClient.get("/admin-api/is-authed")}async installApplication(e){return A(await this.httpClient.post("/admin-api/install-application",e))}async getRegistryVersions(e,n){let r=new URL("/api/v2/bundles",new URL(e).origin);r.searchParams.set("package",n);let i=await(await nc(r.toString(),"versions",n)).json();return(Array.isArray(i)?i:[]).map(s=>s.appVersion).filter(s=>typeof s=="string").sort((s,a)=>tc(a,s))}async installDevApplication(e){return A(await this.httpClient.post("/admin-api/install-dev-application",e))}async uninstallApplication(e){return A(await this.httpClient.delete(`/admin-api/applications/${g(e)}`))}async listApplications(){return A(await this.httpClient.get("/admin-api/applications"))}async getApplication(e){return A(await this.httpClient.get(`/admin-api/applications/${g(e)}`))}async listApplicationVersions(e){return A(await this.httpClient.get(`/admin-api/applications/${g(e)}/versions`))}async getApplicationAbi(e,n){let r=n?`?service_name=${encodeURIComponent(n)}`:"";return A(await this.httpClient.get(`/admin-api/applications/${g(e)}/abi${r}`))}async listPackages(){let e=await this.httpClient.get("/admin-api/packages");return e?.data??e}async listPackageVersions(e){let n=await this.httpClient.get(`/admin-api/packages/${g(e)}/versions`);return n?.data??n}async getLatestPackageVersion(e){return this.httpClient.get(`/admin-api/packages/${g(e)}/latest`)}async createContext(e){let n={...e,initializationParams:e.initializationParams??[]};return A(await this.httpClient.post("/admin-api/contexts",n))}async deleteContext(e){return A(await this.httpClient.delete(`/admin-api/contexts/${g(e)}`))}async getContexts(){return A(await this.httpClient.get("/admin-api/contexts"))}async getContext(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}`))}async getContextsForApplication(e){return A(await this.httpClient.get(`/admin-api/contexts/for-application/${g(e)}`))}async generateContextIdentity(){return A(await this.httpClient.post("/admin-api/identity/context",{}))}async getContextIdentities(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/identities`))}async getContextIdentitiesOwned(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/identities-owned`))}async joinContext(e){return A(await this.httpClient.post(`/admin-api/contexts/${g(e)}/join`,{}))}async getContextGroup(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/group`))}async getContextStorage(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/storage`))}async syncContext(e){let n=e?`/admin-api/contexts/sync/${g(e)}`:"/admin-api/contexts/sync";await this.httpClient.post(n,{})}async resyncContext(e,n={}){return await this.httpClient.post(`/admin-api/contexts/${g(e)}/resync`,n)??{contextId:e,resyncStarted:!0}}async inviteSpecializedNode(e){return A(await this.httpClient.post("/admin-api/contexts/invite-specialized-node",e))}async updateContextApplication(e,n){await this.httpClient.post(`/admin-api/contexts/${g(e)}/application`,n)}async getContextsWithExecutorsForApplication(e){let n=await this.httpClient.get(`/admin-api/contexts/with-executors/for-application/${g(e)}`);return Array.isArray(n)?n:n?.contexts??n?.data??[]}async uploadBlob(e){let n=new URLSearchParams;e.hash&&n.set("hash",e.hash),e.contextId&&n.set("context_id",e.contextId);let r=n.toString(),o=r?`/admin-api/blobs?${r}`:"/admin-api/blobs",i=A(await this.httpClient.request(o,{method:"PUT",body:e.data,headers:{"Content-Type":"application/octet-stream"}}));return{blobId:i.blob_id,size:i.size}}async deleteBlob(e){let n=await this.httpClient.delete(`/admin-api/blobs/${g(e)}`);return{blobId:n.blob_id,deleted:n.deleted}}async listBlobs(){return{blobs:A(await this.httpClient.get("/admin-api/blobs")).blobs.map(n=>({blobId:n.blob_id,size:n.size}))}}blobPath(e,n){if(!n?.contextId)return`/admin-api/blobs/${g(e)}`;let r=new URLSearchParams({context_id:n.contextId});return`/admin-api/blobs/${g(e)}?${r.toString()}`}async getBlob(e,n){return this.httpClient.get(this.blobPath(e,n),{parse:"arrayBuffer"})}async getBlobInfo(e,n){let{headers:r}=await this.httpClient.head(this.blobPath(e,n)),o=Number(r["content-length"]);return{blobId:r["x-blob-id"]??e,size:Number.isFinite(o)?o:0,hash:r["x-blob-hash"],mimeType:r["x-blob-mime-type"],source:r["x-blob-source"]}}async createContextAlias(e){return A(await this.httpClient.post("/admin-api/alias/create/context",{alias:e.alias,contextId:e.contextId}))}async createApplicationAlias(e){return A(await this.httpClient.post("/admin-api/alias/create/application",{alias:e.alias,applicationId:e.applicationId}))}async lookupContextAlias(e){return A(await this.httpClient.post(`/admin-api/alias/lookup/context/${g(e)}`,{}))}async lookupApplicationAlias(e){return A(await this.httpClient.post(`/admin-api/alias/lookup/application/${g(e)}`,{}))}async deleteContextAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/context/${g(e)}`,{}))}async deleteApplicationAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/application/${g(e)}`,{}))}async listContextAliases(){return A(await this.httpClient.get("/admin-api/alias/list/context"))}async listApplicationAliases(){return A(await this.httpClient.get("/admin-api/alias/list/application"))}async createDeviceAlias(e){return A(await this.httpClient.post("/admin-api/alias/create/device",{alias:e.alias,deviceId:e.deviceId}))}async lookupDeviceAlias(e){return A(await this.httpClient.post(`/admin-api/alias/lookup/device/${g(e)}`,{}))}async deleteDeviceAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/device/${g(e)}`,{}))}async listDeviceAliases(){return A(await this.httpClient.get("/admin-api/alias/list/device"))}async listNamespaces(){return A(await this.httpClient.get("/admin-api/namespaces"))}async getNamespace(e){return A(await this.httpClient.get(`/admin-api/namespaces/${g(e)}`))}async getNodeIdentity(){return A(await this.httpClient.get("/admin-api/identity"))}async getNamespaceIdentity(e){let n=await this.getNodeIdentity();return{namespaceId:e,publicKey:n.publicKey,account:n.accountId}}async performIntent(e,n){return A(await this.httpClient.post(`/admin-api/contexts/${g(e)}/intents`,n))}async queryContext(e,n){return A(await this.httpClient.post(`/admin-api/contexts/${g(e)}/query`,n))}async getIntentRelay(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/intents`))}async listNamespacesForApplication(e){return A(await this.httpClient.get(`/admin-api/namespaces/for-application/${g(e)}`))}async createNamespace(e){return A(await this.httpClient.post("/admin-api/namespaces",e))}async deleteNamespace(e){return A(await this.httpClient.request(`/admin-api/namespaces/${g(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async createNamespaceInvitation(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/invite`,n??{}))}async admitJoin(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/admit`,n,{timeoutMs:65e3}))}async joinNamespace(e,n){let r=A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/join`,n,{timeoutMs:65e3}));return r&&r.namespaceId===void 0&&r.groupId!==void 0?{...r,namespaceId:r.groupId}:r}async redeemInvitation(e,n,r={}){let{groupName:o,teamName:i}=r;return Go({namespaceId:e,invitation:n,teamName:i},{join:async()=>{await this.joinNamespace(e,o===void 0?{invitation:n}:{invitation:n,groupName:o})},memberships:async()=>(await this.listNamespaces()??[]).map(s=>s.namespaceId)})}async createGroupInNamespace(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/groups`,n??{}))}async listNamespaceGroups(e){return A(await this.httpClient.get(`/admin-api/namespaces/${g(e)}/groups`))}async initAccountPairing(e){return A(await this.httpClient.post("/admin-api/account/pair-init",e))}async completeAccountPairing(e){return A(await this.httpClient.post("/admin-api/account/pair-complete",e))}async relinkAccountDevice(e,n){return A(await this.httpClient.post(`/admin-api/account/devices/${g(e)}/relink`,n??{}))}async rescopeAccountDevice(e,n){return A(await this.httpClient.put(`/admin-api/account/devices/${g(e)}/scope`,n))}async signWithAccountRoot(e){return A(await this.httpClient.post("/admin-api/account/sign-with-root",e))}async labelAccountDevice(e,n){return A(await this.httpClient.put(`/admin-api/account/devices/${g(e)}/label`,n))}async listAccountDevices(){return(await this.httpClient.get("/admin-api/account/devices")).devices}async listAccountApplications(){return(await this.httpClient.get("/admin-api/account/applications")).applications}async revokeAccountDevice(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/account/revoke`,n))}async linkAccountDevice(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/account/link-device`,n))}async getGroupInfo(e){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}`))}async getDefaultCapabilities(e){return(await this.getGroupInfo(e)).defaultCapabilities}async getSubgroupVisibility(e){return(await this.getGroupInfo(e)).subgroupVisibility}async deleteGroup(e){return A(await this.httpClient.request(`/admin-api/groups/${g(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async listGroupMembers(e){let n=await this.httpClient.get(`/admin-api/groups/${g(e)}/members`);if(!Array.isArray(n?.members)){let r=String(e).replace(/[\r\n\t\s]/g,"").slice(0,64);throw new Error(`Invalid listGroupMembers response for group ${r}: missing or non-array \`members\` field`)}return n}async listGroupMemberDevices(e,n){let r=new URLSearchParams;n?.offset!==void 0&&r.set("offset",String(n.offset)),n?.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${g(e)}/member-devices`;return(await this.httpClient.get(o?`${i}?${o}`:i)).members}async getWarrantNonce(e,n){let r=`/admin-api/contexts/${g(e)}/warrant-nonce/${g(n)}`,o;try{o=await this.httpClient.get(r,{parse:"text"})}catch(i){throw i instanceof D&&i.status===404?new Bt(r,i):i}return $o(o)}async getWarrantNonceAsAuthor(e,n){let r=`/admin-api/contexts/${g(e)}/warrant-nonce`,o;try{o=await this.httpClient.post(r,{authorProof:n},{parse:"text"})}catch(i){throw i instanceof D&&i.status===404?new Bt(r,i):i}return $o(o)}async listMemberDevices(e,n={}){let r=new URLSearchParams;n.offset!==void 0&&r.set("offset",String(n.offset)),n.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${g(e)}/member-devices${o?`?${o}`:""}`;return this.httpClient.get(i)}async sealToAccount(e,n,r){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/accounts/${g(n)}/seal`,r))}async listGroupContexts(e){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}/contexts`))}async addGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${g(e)}/members`,n)}async removeGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${g(e)}/members/remove`,n)}async updateMemberRole(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/members/${g(n)}/role`,r)}async getMemberCapabilities(e,n){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}/members/${g(n)}/capabilities`))}async setMemberCapabilities(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/members/${g(n)}/capabilities`,r)}async setDefaultCapabilities(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/settings/default-capabilities`,n)}async openToDelegatedExecution(e){let n=await this.getDefaultCapabilities(e);if(ge(n,_.CAN_AUTHOR_ON_BEHALF))return{changed:!1,defaultCapabilities:n};let r=fr(n,_.CAN_AUTHOR_ON_BEHALF);return await this.setDefaultCapabilities(e,{defaultCapabilities:r}),{changed:!0,defaultCapabilities:r}}async grantAuthorship(e,n){let{capabilities:r}=await this.getMemberCapabilities(e,n);if(ge(r,_.CAN_AUTHOR_ON_BEHALF))return{changed:!1,capabilities:r};let o=fr(r,_.CAN_AUTHOR_ON_BEHALF);return await this.setMemberCapabilities(e,n,{capabilities:o}),{changed:!0,capabilities:o}}async setSubgroupVisibility(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/settings/subgroup-visibility`,n)}async setTeeAdmissionPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/settings/tee-admission-policy`,n)}async getTeeAdmissionPolicy(e){let n=await this.httpClient.get(`/admin-api/groups/${g(e)}/settings/tee-admission-policy`);return n.data??n}async setTeeAuthoringPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/settings/tee-authoring-policy`,n)}async disableTeeAuthoringPolicy(e,n={}){let r=`/admin-api/groups/${g(e)}/settings/tee-authoring-policy`;if(n.rootProof===void 0){await this.httpClient.delete(r);return}await this.httpClient.request(r,{method:"DELETE",body:JSON.stringify({rootProof:n.rootProof}),headers:{"Content-Type":"application/json"}})}async transferOwnership(e,n){await this.httpClient.post(`/admin-api/groups/${g(e)}/transfer-ownership`,n)}async changeNamespaceAdmin(e,n){await this.httpClient.post(`/admin-api/namespaces/${g(e)}/admin`,n)}async ownerDeleteGroup(e,n={}){await this.httpClient.post(`/admin-api/groups/${g(e)}/owner-delete`,n)}async setGroupMetadata(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/metadata`,n)}async getGroupMetadata(e){return(await this.httpClient.get(`/admin-api/groups/${g(e)}/metadata`))?.data??null}async setMemberMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/members/${g(n)}/metadata`,r)}async getMemberMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${g(e)}/members/${g(n)}/metadata`))?.data??null}async setContextMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/contexts/${g(n)}/metadata`,r)}async getContextMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${g(e)}/contexts/${g(n)}/metadata`))?.data??null}async syncGroup(e){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/sync`,{}))}async upgradeGroup(e,n){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/upgrade`,n))}async getGroupUpgradeStatus(e){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}/upgrade/status`))}async getMigrationStatus(e){return this.httpClient.get(`/admin-api/groups/${g(e)}/migration-status`)}async listNamespaceRevokedDevices(e){return this.httpClient.get(`/admin-api/namespaces/${g(e)}/revoked-devices`)}async getCascadeStatus(e){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}/cascade-status`))}async retryGroupUpgrade(e){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/upgrade/retry`,{}))}async reparentGroup(e,n){let r=await this.httpClient.post(`/admin-api/groups/${g(e)}/reparent`,n);return r?.data??r}async listSubgroups(e){let n=await this.httpClient.get(`/admin-api/groups/${g(e)}/subgroups`);return n.subgroups??n.data??[]}async detachContextFromGroup(e,n){await this.httpClient.post(`/admin-api/groups/${g(e)}/contexts/${g(n)}/remove`,{})}async createGroupInvitation(e,n){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/invite`,n??{}))}async joinGroup(e){return A(await this.httpClient.post("/admin-api/groups/join",e))}async joinSubgroupInheritance(e){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/join-via-inheritance`,{}))}async getTeeInfo(){return A(await this.httpClient.get("/admin-api/tee/info"))}async teeAttest(e){return A(await this.httpClient.post("/admin-api/tee/attest",e))}async teeVerifyQuote(e){return A(await this.httpClient.post("/admin-api/tee/verify-quote",e))}async getPeersCount(){return this.httpClient.get("/admin-api/peers")}async getNetworkStatus(){return this.httpClient.get("/admin-api/network/status")}async getUsage(){return this.httpClient.get("/admin-api/usage")}async createGroup(e){return A(await this.httpClient.post("/admin-api/groups",e))}async leaveGroup(e){await this.httpClient.post(`/admin-api/groups/${g(e)}/leave`,{})}async leaveContext(e){await this.httpClient.post(`/admin-api/contexts/${g(e)}/leave`,{})}async leaveNamespace(e){await this.httpClient.post(`/admin-api/namespaces/${g(e)}/leave`,{})}async issueOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${g(e)}/issue-ownership-proof`,n)}async issueNamespaceOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${g(e)}/issue-namespace-ownership-proof`,n)}async setMemberAutoFollow(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/members/${g(n)}/auto-follow`,r)}async abortMigration(e){return this.httpClient.post(`/admin-api/groups/${g(e)}/migration/abort`,{})}};function Cp(t){return Array.from(new TextEncoder().encode(t),e=>e.toString(16).padStart(2,"0")).join("")}function Pp(t){return new me(Ie(t))}function Tp(t){return new me(Lt(t))}function Bo(t){return new me(mr(t))}function qt(t,e){return new me(t)}function br(t){try{let e=t.indexOf("#");if(e===-1)return null;let n=t.substring(e+1),r=new URLSearchParams(n),o=r.get("access_token");return o?{accessToken:o,refreshToken:r.get("refresh_token")??"",applicationId:r.get("application_id")??"",contextId:r.get("context_id")??"",contextIdentity:r.get("context_identity")??"",nodeUrl:r.get("node_url")??""}:null}catch{return null}}function Ar(t,e){let n=new URLSearchParams;return n.set("callback-url",e.callbackUrl),e.permissions&&e.permissions.length>0&&n.set("permissions",e.permissions.join(",")),n.set("mode",e.mode),e.packageName&&(n.set("package-name",e.packageName),e.packageVersion&&n.set("package-version",e.packageVersion),e.registryUrl&&n.set("registry-url",e.registryUrl)),`${t.replace(/\/+$/,"")}/auth/login?${n.toString()}`}function jt(t){let e=j(t.credential,"credential"),n=j(t.request,"request signature"),r=t.session===void 0?new Uint8Array([0]):f(new Uint8Array([1]),j(t.session,"session statement"));return y(f(e,r,n))}function rc(t){if(t==null)return new Uint8Array(0);if(typeof t=="string"||t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error(`a request-carried proof cannot commit to a ${t?.constructor?.name??typeof t} body: pass a string or bytes, or use a session for this call`)}function Ft(t){let e=t.ttlSeconds??120,n=t.now??(()=>Math.floor(Date.now()/1e3));return async r=>{let o=n();return jt({credential:t.credential,session:t.session,request:await Kt({method:r.method,path:r.path,body:rc(r.body),issuedAt:o,expiresAt:o+e,signerSecret:t.signerSecret})})}}var Vt=class extends Error{constructor(e,n,r,o){super(n),this.name="RpcError",this.code=e,this.data=r,this.type=o}};async function xr(t,e,n){let r=await t.post("/jsonrpc",{jsonrpc:"2.0",id:1,method:e,params:n});if(r.error){let o=r.error;throw new Vt(o.code??-1,o.message??o.type??"RPC error",o.data,o.type)}return r.result}var st=class{constructor(e){this.kind="node";this.canSubscribe=!0;this.httpClient=e.httpClient}async execute(e){let n=await xr(this.httpClient,"execute",{contextId:e.contextId,method:e.method,argsJson:e.argsJson??{}});return n&&"output"in n?n.output:n}async executeWithMetadata(e){return{returns:await this.execute(e),transport:"node"}}async migrateMyEntries(e){return this.execute({contextId:e,method:"migrate_my_entries"})}async countMyPending(e){return this.execute({contextId:e,method:"count_my_pending"})}};var oc=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function qo(t){return t.type!==void 0&&oc.has(t.type)}var ic=new Set(["token_reuse","token_revoked"]),sc=new Set([401,403]),ac=1e4;function jo(t){let e=t.headers.get("x-auth-error");return!e||!sc.has(t.status)?null:ic.has(e)?e:null}var B=class{constructor(e){this.sessionId=null;this.abortController=null;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.presence=new Map;this.closed=!1;this.listeners={connect:[],event:[],error:[]};if(this.baseUrl=e.baseUrl.replace(/\/+$/,""),e.authorize)this.authorize=e.authorize;else if(e.getAuthToken){let n=e.getAuthToken;this.authorize=async()=>({Authorization:`Bearer ${await n()}`})}else throw new Error("SseClient needs either `getAuthToken` or `authorize`");this.reconnectDelayMs=e.reconnectDelayMs??3e3,this.fetchImpl=(n,r)=>e.fetch?e.fetch(n,r):globalThis.fetch(n,r)}on(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(n)||o.push(n)}}off(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r],i=o.indexOf(n);i!==-1&&o.splice(i,1)}}onAppVersionChanged(e){let n=r=>{if(r.type!=="AppVersionChanged")return;let o=r.data;e({contextId:r.contextId,fromVersion:o?.fromVersion,toVersion:o?.toVersion})};return this.on("event",n),()=>this.off("event",n)}onMigrationEvent(e){let n=r=>{qo(r)&&e(r)};return this.on("event",n),()=>this.off("event",n)}emit(e,n){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(n)}catch{}}async connect(){if(!(this.abortController&&!this.closed)){this.closed=!1,this.abortController=new AbortController;try{let e=`${this.baseUrl}/sse`,n={...await this.authorize({method:"GET",path:de(e)}),Accept:"text/event-stream"},r=Gt(n),o=await this.fetchImpl(e,{headers:n,signal:this.abortController.signal,...r&&{redirect:"manual"}});if(r&&$t(o,e),!o.ok){let i=jo(o),s=await o.text().catch(()=>{});throw i?new oe(i,o.status,o.statusText,e,o.headers,s):new D(o.status,o.statusText,e,o.headers,s)}if(!o.body)throw new Error("SSE response has no body");this.readStream(o.body).catch(i=>{if(this.closed)return;let s=i instanceof Error?i:new Error(String(i));this.emit("error",s),this.scheduleReconnect()})}catch(e){if(this.closed)return;let n=e instanceof Error?e:new Error(String(e));if(this.emit("error",n),n instanceof oe)return;this.scheduleReconnect()}}}async readStream(e){let n=e.getReader(),r=new TextDecoder,o="";try{for(;;){let{done:i,value:s}=await n.read();if(i)break;o+=r.decode(s,{stream:!0});let a=o.split(`
|
|
2
|
-
`);o=a.pop()??"";for(let c of a)if(c.startsWith("data:")){let u=c.slice(5).trim();u&&this.handleMessage(u)}}if(o+=r.decode(),o.startsWith("data:")){let i=o.slice(5).trim();i&&this.handleMessage(i)}}catch(i){if(this.closed)return;let s=i instanceof Error?i:new Error(String(i));this.emit("error",s)}this.closed||this.scheduleReconnect()}handleMessage(e){try{let n=JSON.parse(e);if(n.type==="connect"&&n.session_id){let o=n.session_id;if(this.sessionId=o,this.presence.clear(),this.subscribedContextIds.size===0&&this.subscribedGroupIds.size===0){this.emit("connect",o);return}this.postSubscription("subscribe",{contextIds:[...this.subscribedContextIds],groupIds:[...this.subscribedGroupIds]}).then(i=>{this.closed||this.sessionId!==o||(this.emit("connect",o),i&&this.emit("error",i))});return}if(!n.result)return;let r=n.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),i=new TextDecoder().decode(o);r=JSON.parse(i)}catch{}if(n.result.contextId){n.result.type==="Ephemeral"&&this.notePresence(n.result.contextId,r),this.emit("event",{contextId:n.result.contextId,type:n.result.type,data:r});return}n.result.groupId&&this.emit("event",{groupId:n.result.groupId,type:n.result.type,data:r})}catch{}}async subscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>!this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>!this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.add(i);for(let i of n.groupIds??[])this.subscribedGroupIds.add(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("subscribe",{contextIds:r,groupIds:o})}isSubscribed(e){return this.subscribedContextIds.has(e)}presenceSeed(e){let n=Date.now();return[...this.presence.get(e)?.values()??[]].map(({data:r,at:o})=>({...r,ageMs:(typeof r.ageMs=="number"?r.ageMs:0)+(n-o)}))}notePresence(e,n){if(!this.subscribedContextIds.has(e))return;let r=n;if(!r||typeof r.author!="string")return;let o=this.presence.get(e);o||this.presence.set(e,o=new Map),r.removed?o.delete(r.author):o.set(r.author,{data:r,at:Date.now()})}async unsubscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.delete(i),this.presence.delete(i);for(let i of n.groupIds??[])this.subscribedGroupIds.delete(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("unsubscribe",{contextIds:r,groupIds:o})}async sendSubscription(e,n){let r=await this.postSubscription(e,n);r&&this.emit("error",r)}async postSubscription(e,n){let r=new AbortController,o=setTimeout(()=>r.abort(new DOMException(`SSE ${e} timed out`,"TimeoutError")),ac);try{let i={};n.contextIds&&n.contextIds.length>0&&(i.contextIds=n.contextIds),n.groupIds&&n.groupIds.length>0&&(i.groupIds=n.groupIds);let s=`${this.baseUrl}/sse/subscription`,a=JSON.stringify({id:this.sessionId,method:e,params:i}),c={...await this.authorize({method:"POST",path:de(s),body:a}),"Content-Type":"application/json"},u=Gt(c),d=await this.fetchImpl(s,{method:"POST",headers:c,body:a,signal:r.signal,...u&&{redirect:"manual"}});if(u&&$t(d,s),!d.ok){let l=jo(d),p=await d.text().catch(()=>{});return l?new oe(l,d.status,d.statusText,`${this.baseUrl}/sse/subscription`,d.headers,p):new D(d.status,d.statusText,`${this.baseUrl}/sse/subscription`,d.headers,p)}return null}catch(i){return i instanceof Error?i:new Error(`SSE ${e} failed`)}finally{clearTimeout(o)}}forceReconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.sessionId=null,this.connect()}scheduleReconnect(){this.closed||(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.forceReconnect()},this.reconnectDelayMs))}close(){this.closed=!0,this.abortController&&(this.abortController.abort(),this.abortController=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.sessionId=null,this.subscribedContextIds.clear(),this.subscribedGroupIds.clear()}};var Wt=class Wt{constructor(e){this.ws=null;this.closed=!1;this.reconnectAttempt=0;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.listeners={connect:[],event:[],error:[]};this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.getAuthToken=e.getAuthToken}on(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(n)||o.push(n)}}off(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r],i=o.indexOf(n);i!==-1&&o.splice(i,1)}}emit(e,n){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(n)}catch{}}async connect(){if(!(this.ws&&(this.ws.readyState===0||this.ws.readyState===1))){this.closed=!1;try{let e=await this.getAuthToken();if(!e)throw new Error("No authentication token available for WebSocket connection");let n=this.baseUrl.replace(/^http/,"ws");this.ws=new WebSocket(`${n}/ws?token=${encodeURIComponent(e)}`),this.ws.onopen=()=>{this.reconnectAttempt=0,this.emit("connect"),this.resubscribeAfterReconnect()},this.ws.onmessage=r=>{this.handleMessage(r.data)},this.ws.onerror=()=>{this.emit("error",new Error("WebSocket error"))},this.ws.onclose=()=>{this.closed||this.scheduleReconnect()}}catch(e){if(this.closed)return;let n=e instanceof Error?e:new Error(String(e));this.emit("error",n),this.scheduleReconnect()}}}handleMessage(e){if(typeof e=="string")try{let n=JSON.parse(e);if(!n.result)return;let r=n.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),i=new TextDecoder().decode(o);r=JSON.parse(i)}catch{}if(n.result.contextId){this.emit("event",{contextId:n.result.contextId,type:n.result.type,data:r});return}n.result.groupId&&this.emit("event",{groupId:n.result.groupId,type:n.result.type,data:r})}catch{}}subscribe(e){let n=Array.isArray(e)?{contextIds:e}:e;for(let r of n.contextIds??[])this.subscribedContextIds.add(r);for(let r of n.groupIds??[])this.subscribedGroupIds.add(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams(n.contextIds??[],n.groupIds??[])})}unsubscribe(e){let n=Array.isArray(e)?{contextIds:e}:e;for(let r of n.contextIds??[])this.subscribedContextIds.delete(r);for(let r of n.groupIds??[])this.subscribedGroupIds.delete(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"unsubscribe",params:this.buildSubscriptionParams(n.contextIds??[],n.groupIds??[])})}resubscribeAfterReconnect(){this.subscribedContextIds.size===0&&this.subscribedGroupIds.size===0||this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams([...this.subscribedContextIds],[...this.subscribedGroupIds])})}buildSubscriptionParams(e,n){let r={};return e.length>0&&(r.contextIds=e),n.length>0&&(r.groupIds=n),r}sendMessage(e){this.ws&&this.ws.readyState===1&&this.ws.send(JSON.stringify(e))}scheduleReconnect(){if(this.closed)return;this.reconnectTimer&&clearTimeout(this.reconnectTimer);let e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),Wt.MAX_BACKOFF_MS);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e)}close(){this.closed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscribedContextIds.clear(),this.subscribedGroupIds.clear()}};Wt.MAX_BACKOFF_MS=3e4;var ie=Wt;function se(){return{encode(t){return Array.from(new TextEncoder().encode(JSON.stringify(t)))},decode(t){return JSON.parse(new TextDecoder().decode(new Uint8Array(t)))}}}var at=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,n,r=se()){await xr(this.httpClient,"set_ephemeral",{contextId:e,state:r.encode(n)})}subscribe(e,n,r=se()){return Jt(this.sse,e,n,r)}};function Jt(t,e,n,r=se()){let o=i=>{let s=i;if(s.type!=="Ephemeral"||s.contextId!==e)return;let a=s.data;if(!a?.author)return;let c=!!a.removed,u={author:a.author,state:c||a.state===void 0?void 0:r.decode(a.state),removed:c};a.ageMs!==void 0&&(u.ageMs=a.ageMs),a.account!==void 0&&(u.account=a.account),n(u)};if(t.on("event",o),t.isSubscribed?.(e))for(let i of t.presenceSeed?.(e)??[])o({contextId:e,type:"Ephemeral",data:i});return t.connect().catch(()=>{}),t.subscribe([e]).catch(()=>{}),()=>{t.off("event",o)}}var cc=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function Fo(t){let e=t instanceof Error?`: ${t.message}`:"";return new Error("this runtime has no WebCrypto Ed25519, so nothing can be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it"+e)}async function Pe(t,e="secret"){let n=m(t,e,32),r=f(cc,n),o,i;try{let s=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!0,["sign"]),a=await crypto.subtle.exportKey("jwk",s);i=y(Uint8Array.from(atob(a.x.replace(/-/g,"+").replace(/_/g,"/")),c=>c.charCodeAt(0))),o=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!1,["sign"])}catch(s){throw Fo(s)}return Wo(o,i)}async function Vo(t,e){if(t.type!=="private")throw new Error(`signerFromCryptoKey needs the private half of the pair, got a ${t.type} key`);if(!t.usages.includes("sign"))throw new Error("this CryptoKey cannot sign: generate it with usages ['sign', 'verify']");let n;if(typeof e=="string")m(e,"publicKey",32),n=e.trim().toLowerCase();else try{n=y(new Uint8Array(await crypto.subtle.exportKey("raw",e)))}catch(r){let o=r instanceof Error?`: ${r.message}`:"";throw new Error("could not read the public half of this key pair; pass the public key as 64 hex instead"+o)}return Wo(t,n)}function Wo(t,e){return{publicKey:e,async sign(n){try{return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},t,n))}catch(r){throw Fo(r)}}}}async function I(t,e,n){if(e&&t!==void 0)throw new Error(`pass either ${n} or signer, not both \u2014 they may name different keys`);if(e)return e;if(t!==void 0)return Pe(t,n);throw new Error(`${n} or signer is required`)}var lc=new TextEncoder().encode("calimero.mdma.account-ownership-claim.v1\0"),uc=6e4,Jo=5*6e4,zo=1024,Yo="mdma:enable-ha-namespace",Xo="mdma:enable-ha-namespace-as-account";function Qo(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var vr=(t,e)=>{if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);return t.toLowerCase()};async function Zo(t,e,n,r){if(r!==void 0&&!(r.length>0&&r.length<=zo))throw new Error(`relayUrl must be a non-empty string of at most ${zo} characters`);let o=t.ttlMs??uc;if(!(o>0&&o<=Jo))throw new Error(`ttlMs must be in (0, ${Jo}]`);let i=vr(t.namespaceId,"namespaceId"),s=vr(t.accountId,"accountId"),a=vr(t.salt,"salt"),c=await I(t.deviceSecret,t.signer,"deviceSecret"),u=(t.now??Date.now)(),d=Array.from(crypto.getRandomValues(new Uint8Array(16)),x=>x.toString(16).padStart(2,"0")).join(""),l=new TextEncoder().encode(JSON.stringify({v:1,audience:e,group_id:i,account_id:s,salt:a,...n===void 0?{}:{subject:n},nonce:d,issued_at_ms:u,expires_at_ms:u+o,...r===void 0?{}:{relay_url:r}})),p=await c.sign(f(lc,l));return{kind:"account",credential:t.credential,signed_payload:Qo(l),signature:Qo(p)}}async function dc(t){if(!t.subject)throw new Error("subject must be the cloud login email");return Zo(t,Yo,t.subject)}async function Rr(t){return Zo(t,Xo,void 0,t.relayUrl)}var pc=new TextEncoder().encode("calimero.device.cert.v1"),gc=new TextEncoder().encode("calimero.account.genesis.v1"),mc=new TextEncoder().encode("calimero.device.id.v1"),Te=2,fc=237;async function Cr(t,e){if(e.length!==16)throw new Error(`nonce must be 16 bytes, got ${e.length}`);let n=m(t,"account",32),r=await k(mc,[n,e]);return y(f(e,r.subarray(0,16)))}async function zt(t){return k(pc,[m(t.account,"account",32),m(t.device,"device",32),m(t.signPublicKey,"signPublicKey",32),m(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch)])}function ei(t){return f(new Uint8Array([Te]),t.rootPublicKey,R(0),m(t.account,"account",32),m(t.device,"device",32),m(t.signPublicKey,"signPublicKey",32),m(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch),t.signature)}async function ti(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=m(e.publicKey,"signer.publicKey",32),r=await F(e.publicKey),o=0,i=await zt({account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch}),s=await e.sign(i),a=ei({rootPublicKey:n,account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch,signature:s});return y(a)}function Sr(t){let e=m(t,"credential",fc);if(e[0]!==Te)throw new Error(`this credential has account genesis version ${e[0]}, not ${Te} \u2014 it names a different account than its root key derives here, and core would refuse it`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint32(33,!0);if(r!==0)throw new Error(`this credential carries a ${r}-handoff root chain, which this SDK cannot verify yet \u2014 the signing root is not the genesis root, so checking it means walking the chain`);let o=(i,s)=>y(e.subarray(i,i+s));return{rootPublicKey:o(1,32),account:o(37,32),device:o(69,32),signPublicKey:o(101,32),kemPublicKey:o(133,32),keyEpoch:n.getUint32(165,!0),deviceEpoch:n.getUint32(169,!0),signature:o(173,64)}}async function Qt(t){let e=Sr(t),n=await F(e.rootPublicKey);if(n!==e.account)throw new Error(`this credential names account ${e.account}, but its root key derives ${n} \u2014 the certificate was re-pointed at another account`);let r=m(e.device,"device",32).subarray(0,16);if(await Cr(e.account,r)!==e.device)throw new Error(`this credential names device ${e.device}, which was not minted for account ${e.account}; core refuses it`);if(!await Oo(e.rootPublicKey,m(e.signature,"signature",64),await zt(e)))throw new Error(`the root key of account ${e.account} did not sign this certificate`);return e}async function Yt(t){return F(y(await re(t)))}async function F(t){return y(await k(gc,[f(new Uint8Array([Te]),m(t,"rootPublicKey",32))]))}var hc=new TextEncoder().encode("calimero.device.scope.v1");async function Er(t){return k(hc,[m(t.account,"account",32),m(t.device,"device",32),R(t.scopeEpoch),R(t.keyEpoch),...t.applications.map((e,n)=>m(e,`applications[${n}]`,32))])}async function ni(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=m(e.publicKey,"signer.publicKey",32),r=await F(y(n)),o=t.applications??[],i=t.scopeEpoch??0;if(!Number.isInteger(i)||i<0||i>4294967295)throw new Error(`scopeEpoch must be a u32, got ${i}`);let s=0,a=await Er({account:r,device:t.device,applications:o,scopeEpoch:i,keyEpoch:s}),c=await e.sign(a);if(c.length!==64)throw new Error(`signer returned ${c.length} bytes, expected a 64-byte Ed25519 signature`);return y(f(new Uint8Array([Te]),n,R(0),m(r,"account",32),m(t.device,"device",32),R(o.length),...o.map((u,d)=>m(u,`applications[${d}]`,32)),R(i),R(s),c))}var kr=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"];var yc=new TextEncoder().encode("calimero.mdma.account-link.v1\0"),wc=new TextEncoder().encode("calimero.mdma.account-login.v1\0"),De=256,ri=De/32,Ir=(De+ri)/11;async function oi(){let t=crypto.getRandomValues(new Uint8Array(De/8));return ui(y(t),await pi(t))}async function ii(t){let e=di(t);return ui(y(await gi(e)),e.join(" "))}async function Pr(t){return m(t,"secret",32),{secret:t,publicKey:y(await re(t)),accountId:await Yt(t)}}async function si(){let t=crypto.getRandomValues(new Uint8Array(De/8)),e=await pi(t);return{...await ci(t),phrase:e}}async function ai(t){return ci(await gi(di(t)))}async function ci(t){let e=await Pe(y(t),"rootSecret");return t.fill(0),{publicKey:e.publicKey,accountId:await F(e.publicKey),signer:e}}async function Y(t){let e=typeof t=="string"?await Pe(t,"rootSecret"):t;return li(e)}async function Xt(t,e){return li(await I(t,e,"rootSecret"))}async function li(t){return{signer:t,publicKey:t.publicKey,accountId:await F(t.publicKey)}}async function ct(t){if(!t.nonce)throw new Error("nonce is required to sign an account link");let n=await(await I(t.rootSecret,t.signer,"rootSecret")).sign(f(yc,new TextEncoder().encode(t.nonce)));return hi(n)}async function Zt(t){if(!t.nonce)throw new Error("nonce is required to sign an account login");let n=await(await I(t.rootSecret,t.signer,"rootSecret")).sign(f(wc,new TextEncoder().encode(t.nonce)));return hi(n)}async function ui(t,e){return{...await Pr(t),phrase:e}}function di(t){let e=t.normalize("NFKD").toLowerCase().trim().split(/\s+/),n=e[0]===""?0:e.length;if(n!==Ir)throw new Error(`recovery phrase must be ${Ir} words, got ${n}`);return e}async function pi(t){let e=fi(t)+await mi(t),n=[];for(let r=0;r<Ir;r+=1){let o=Number.parseInt(e.slice(r*11,r*11+11),2);n.push(kr[o])}return n.join(" ")}async function gi(t){let e="";for(let r of t){let o=kr.indexOf(r);if(o<0)throw new Error(`"${r}" is not a word in the recovery phrase list`);e+=o.toString(2).padStart(11,"0")}let n=new Uint8Array(De/8);for(let r=0;r<n.length;r+=1)n[r]=Number.parseInt(e.slice(r*8,r*8+8),2);if(e.slice(De)!==await mi(n))throw new Error("recovery phrase checksum failed \u2014 check for a mistyped or transposed word");return n}async function mi(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return fi(e).slice(0,ri)}function fi(t){let e="";for(let n of t)e+=n.toString(2).padStart(8,"0");return e}function hi(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var bc=new TextEncoder().encode("calimero.tee-attest.key-binding.v1"),en=new TextEncoder().encode("MOCK_TDX_QUOTE_V1"),Ac=568;function xc(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}function Tr(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r+=1)n|=t[r]^e[r];return n===0}function vc(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}function Rc(t,e){if(typeof t!="string"||!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);let n=new Uint8Array(32);for(let r=0;r<32;r+=1)n[r]=Number.parseInt(t.slice(r*2,r*2+2),16);return n}async function tn(t){let e=await crypto.subtle.digest("SHA-256",xc(bc,new Uint8Array(32),t));return new Uint8Array(e)}function Dr(t){let e=t.length>=en.length&&Tr(t.subarray(0,en.length),en),n=e?en.length:Ac;if(t.length<n+64)throw new Error(`the quote is too short to carry report data (${t.length} bytes)`);return{reportData:t.slice(n,n+64),mock:e}}async function nn(t){let e=crypto.getRandomValues(new Uint8Array(32)),n=`${t.relayUrl.replace(/\/+$/,"")}/admin-api/tee/attest`,r=JSON.stringify({nonce:y(e),bindNodeKey:!0,...t.verify?.includeCollateral?{includeCollateral:!0}:{}}),o={method:"POST",headers:{"Content-Type":"application/json"},body:r},i=t.fetch?await t.fetch(n,o):await globalThis.fetch(n,o);if(!i.ok){let p=await i.text().catch(()=>"");throw new Error(`the relay would not attest (HTTP ${i.status})${p?`: ${p}`:""}`)}let s=await i.json(),a=s.data??s;if(typeof a.quoteB64!="string")throw new Error("the relay returned no quote");let c=Rc(a.boundPublicKey,"boundPublicKey"),u=vc(a.quoteB64),{reportData:d,mock:l}=Dr(u);if(l){if(!t.allowMock)throw new Error("the relay answered with a MOCK quote, which proves nothing about the hardware")}else if(t.verify){if(!await t.verify({quoteB64:a.quoteB64,nonce:y(e),reportDataSuffix:y(await tn(c)),...a.collateral?{collateral:a.collateral}:{}}))throw new Error("the relay's quote did not verify: not a trusted image, or not bound to this request")}else if(t.verifyQuote)await t.verifyQuote(u);else throw new Error("a real TDX quote needs a verify (or verifyQuote) to check its signature and measurements");if(!Tr(d.subarray(0,32),e))throw new Error("the quote does not carry our nonce: it was not made for this request");if(!Tr(d.subarray(32,64),await tn(c)))throw new Error("the quote does not bind the key the relay named: refusing it");return{nodeKey:y(c),mock:l}}var Cc="Noise_NK_25519_AESGCM_SHA256",Nr=32,Sc=16,Ec=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Or=class t{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(Cc),n=new Uint8Array(32);return n.set(e),new t(n)}async mixHash(e){this.h=await kc(f(this.h,e))}async mixKey(e){let[n,r]=await wi(this.ck,e);this.ck=n,this.k=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:yi(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(n),n}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let n=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:yi(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),n}split(){return wi(this.ck,new Uint8Array)}};async function bi(t,e,n){let r=await Or.initialize();await r.mixHash(e),await r.mixHash(t);let o=await Ne(n);return await r.mixHash(o.publicKey),await r.mixKey(await lt(o.privateKey,t)),{message1:f(o.publicKey,await r.encryptAndHash(new Uint8Array)),async finish(s){if(s.length<Nr+Sc)throw new Error("Noise: message 2 is too short");let a=s.slice(0,Nr);return await r.mixHash(a),await r.mixKey(await lt(o.privateKey,a)),{payload:await r.decryptAndHash(s.slice(Nr)),split:await r.split()}}}}async function Ne(t){if(!t){let r;try{r=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"])}catch(i){throw new Error(`Sealed transport needs WebCrypto with X25519, which this runtime lacks (${i?.name??"no crypto.subtle"}). Current browsers and Node have it; in React Native, install react-native-quick-crypto as the global crypto.`)}let o=new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey));return{privateKey:r.privateKey,publicKey:o}}let e=await crypto.subtle.importKey("pkcs8",f(Ec,t),{name:"X25519"},!0,["deriveBits"]),n=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Ic(n.x)}}async function lt(t,e){let n=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:n},t,256))}function yi(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}async function kc(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}async function Ur(t,e){let n=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",n,e))}async function wi(t,e){let n=await Ur(t,e),r=await Ur(n,new Uint8Array([1])),o=await Ur(n,f(r,new Uint8Array([2])));return[r,o]}function Ic(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}var Ri="/sealed/v2/handshake",Ci="/sealed/v2",dt="application/vnd.calimero.sealed",_r=2,Pc=new TextEncoder().encode("calimero/sealed-http/v2"),ut=16,Tc=1+ut+8,Dc=0,Nc=1,Uc=2,Oc=1+64*1024+16,_c=1024,Mc=6e4,Kc="calimero.tee-attest.transport-key.v1",Gc=[101,204,205,304],Si=new TextEncoder,pt=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},Ue=class extends Error{constructor(n,r,o,i){super(o);this.status=n;this.code=r;this.retryAfterMs=i;this.name="SealedTransportError"}};async function Ei(t,e){let n=await crypto.subtle.digest("SHA-256",f(Si.encode(Kc),t,e));return new Uint8Array(n)}async function ki(t,e,n={}){if(n.applicationId===void 0!=(n.applicationHash===void 0))throw new Error("applicationId and applicationHash are given together or not at all");let r=y(crypto.getRandomValues(new Uint8Array(32))),o=await t.teeAttest({nonce:r,applicationId:n.applicationId,bindTransportKey:!0,...e.includeCollateral?{includeCollateral:!0}:{}});if(!o.transportPublicKey)throw new Error("The node did not report a transport key; it predates sealed transport");let i=m(o.transportPublicKey,"transportPublicKey",32),s=n.applicationHash?m(n.applicationHash,"applicationHash",32):new Uint8Array(32),a=y(await Ei(s,i));if(!await e({quoteB64:o.quoteB64,nonce:r,reportDataSuffix:a,collateral:o.collateral}))throw new Error("The attestation did not verify, so its transport key is not trusted");return i}function fe(t){let e=t.fetch??((o,i)=>fetch(o,i)),n=`${t.baseUrl.replace(/\/+$/,"")}/admin-api/tee/attest`,r={async teeAttest(o){let i=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)});if(!i.ok)throw new Error(`The node refused to attest: HTTP ${i.status}`);let s=await i.json();if(!s.data)throw new Error("The attestation response is malformed");return s.data}};return Ii({baseUrl:t.baseUrl,transportPublicKey:()=>ki(r,t.verify,{applicationId:t.applicationId,applicationHash:t.applicationHash}),fetch:e})}function Ii(t){let e=new URL(t.baseUrl),n=e.pathname.replace(/\/+$/,""),r=`${e.origin}${n}`,o=t.fetch??((l,p)=>fetch(l,p)),i=typeof t.transportPublicKey=="function"?t.transportPublicKey:void 0,s=i?Promise.resolve().then(i):Promise.resolve(t.transportPublicKey);s.catch(()=>{});let a,c=async()=>{try{return await xi(o,r,await Ai(s))}catch(l){if(!(l instanceof pt)||!i)throw l;return s=Promise.resolve().then(i),xi(o,r,await Ai(s))}},u=async()=>{let l=a??d(void 0),p=await l;if(Date.now()<p.renewAt)return[p,l];let x=d(l);return[await x,x]},d=l=>{if(a===l){let p=c();a=p,p.catch(()=>{a===p&&(a=void 0)})}return a};return async(l,p)=>{let x=new Request(l,p),v=new URL(x.url);if(v.origin!==e.origin||!v.pathname.startsWith(`${n}/`))throw new Error(`Refusing to send ${v.href} outside the sealed node at ${t.baseUrl}`);let P=[];x.headers.forEach((h,b)=>P.push([b,h]));let w={method:x.method,path:v.pathname.slice(n.length)+v.search,headers:P},E=new Uint8Array(await x.arrayBuffer()),T=async h=>{let{requestId:b,header:S,envelope:U}=await Lc(h,w,E),M=await o(`${r}${Ci}`,{method:"POST",headers:{"content-type":dt},body:U,signal:x.signal});if(M.headers.get("content-type")!==dt)throw await Ti(M);return Bc(M,h.responseKey,S,b)},[H,z]=await u();try{return await T(H)}catch(h){if(!(h instanceof Ue)||h.code!=="unknown_session")throw h;return T(await d(z))}}}async function Ai(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function xi(t,e,n){try{return await vi(t,e,n)}catch(r){if(!(r instanceof Ue)||r.code!=="busy")throw r;return await new Promise(o=>setTimeout(o,r.retryAfterMs??1e3)),vi(t,e,n)}}async function vi(t,e,n){let r=await bi(n,Pc),o=await t(`${e}${Ri}`,{method:"POST",headers:{"content-type":dt},body:f(new Uint8Array([_r]),n,r.message1)});if(o.headers.get("content-type")!==dt)throw await Ti(o);let i=await jc(o,_c);return $c(r,i)}async function $c(t,e){if(e[0]!==_r)throw new Error("The handshake reply is malformed");let n;try{n=await t.finish(e.slice(1))}catch{throw new Error("The handshake reply did not open: it did not come from the attested node")}let{payload:r,split:o}=n;if(r.length!==ut+4)throw new Error("The handshake reply is malformed");let i=r.slice(0,ut),s=new DataView(r.buffer,r.byteOffset).getUint32(ut,!1),[a,c]=await Promise.all([crypto.subtle.importKey("raw",o[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",o[1],"AES-GCM",!1,["decrypt"])]);return o[0].fill(0),o[1].fill(0),{requestKey:a,responseKey:c,nextRequestId:1,renewAt:Date.now()+s*1e3-Mc,header(u){let d=new Uint8Array(Tc);return d[0]=_r,d.set(i,1),new DataView(d.buffer).setBigUint64(1+ut,BigInt(u),!1),d}}}async function Lc(t,e,n){let r=t.nextRequestId;t.nextRequestId+=1;let o=t.header(r),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:Pi(r,0),additionalData:o},t.requestKey,Hc(e,n));return{requestId:r,header:o,envelope:f(o,new Uint8Array(i))}}function Pi(t,e){let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setBigUint64(0,BigInt(t),!1),r.setUint32(8,e,!1),n}function Hc(t,e){let n=Si.encode(JSON.stringify(t)),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,n.length,!1),f(r,n,e)}async function Bc(t,e,n,r){if(!t.body)throw new Error("The sealed response has no body");let o=qc(t.body.getReader()),i=0,s=async()=>{let d=await o.next();if(!d)return null;let l;try{l=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Pi(r,i),additionalData:n},e,d))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return i+=1,{kind:l[0],data:l.slice(1)}},a=await s();if(!a||a.kind!==Dc)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(Gc.includes(c.status))return await o.cancel(),new Response(null,{status:c.status,headers:c.headers});let u=new ReadableStream({async pull(d){try{let l=await s();l?l.kind===Nc?d.enqueue(l.data):l.kind===Uc?(d.close(),await o.cancel()):d.error(new Error("The sealed response is malformed")):d.error(new Error("The sealed response was cut short"))}catch(l){d.error(l)}},cancel(){return o.cancel()}});return new Response(u,{status:c.status,headers:c.headers})}function qc(t){let e=new Uint8Array,n=async r=>{for(;e.length<r;){let{done:o,value:i}=await t.read();if(o)return!1;e=f(e,i)}return!0};return{async next(){if(!await n(4))return null;let r=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(r>Oc)throw await t.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await n(4+r))return null;let o=e.slice(4,4+r);return e=e.slice(4+r),o},cancel:()=>t.cancel()}}async function jc(t,e){if(!t.body)return new Uint8Array;let n=t.body.getReader(),r=new Uint8Array;for(;;){let{done:o,value:i}=await n.read();if(o)return r;if(r=f(r,i),r.length>e)throw await n.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function Ti(t){let e,n=`Sealed request refused: HTTP ${t.status}`;try{let i=await t.json();e=i?.error?.code,i?.error?.message&&(n=`Sealed request refused: ${i.error.message}`)}catch{}if(e==="stale_transport_key")return new pt;let r=Number(t.headers.get("retry-after")),o=Number.isFinite(r)&&r>0?Math.min(r,5)*1e3:void 0;return new Ue(t.status,e,n,o)}var Fc=/^[0-9a-f]{96}$/,Vc=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function mt(t){let e=Oe(t.allowedMrtd??[],"allowedMrtd"),n=(t.allowedMeasurements??[]).map((a,c)=>{let u=`allowedMeasurements[${c}]`;return Vc.map(d=>Oe([a?.[d]??""],`${u}.${d}`)[0]).join()}),r=[Oe(t.allowedRtmr0??[],"allowedRtmr0"),Oe(t.allowedRtmr1??[],"allowedRtmr1"),Oe(t.allowedRtmr2??[],"allowedRtmr2"),Oe(t.allowedRtmr3??[],"allowedRtmr3")];if(t.allowedMeasurements!==void 0&&n.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(n.length===0){if(e.length===0)throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");if(r.slice(1).some(a=>a.length===0))throw new Error("allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too")}let o=t.allowedTcbStatuses??["UpToDate"],i=t.now??Date.now;return Object.assign(async({quoteB64:a,nonce:c,reportDataSuffix:u,collateral:d})=>{let l=Jc(a),p=d??await t.fetchCollateral?.(l);if(!p)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let x;try{x=t.dcapVerify(l,p,Math.floor(i()/1e3))}catch(E){throw new Error(`The quote did not verify: ${E?.message??String(E)}`)}if(x.status==="Revoked"||!o.includes(x.status))throw new Error(`The platform's TCB status is ${x.status}, which is not accepted`);let v=Wc(x.report);if(v.tdAttributes?.length!==8||(v.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let P=[v.mrTd,v.rtMr0,v.rtMr1,v.rtMr2,v.rtMr3].map(E=>y(E));if(n.length>0&&!n.includes(P.join()))throw new Error(`The measurements (MRTD ${P[0]}, RTMR0-3 ${P.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(P[0]))throw new Error(`MRTD ${P[0]} is not an image this verifier trusts`);if([v.rtMr0,v.rtMr1,v.rtMr2,v.rtMr3].forEach((E,T)=>{let H=r[T];if(H.length>0&&!H.includes(y(E)))throw new Error(`RTMR${T} ${y(E)} is not one this verifier trusts`)}),y(v.reportData)!==`${c}${u}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function Oe(t,e){return t.map(n=>{let r=n.trim().toLowerCase();if(!Fc.test(r))throw new Error(`${e} holds ${JSON.stringify(n)}, which is not a 48-byte hex measurement`);return r})}function Wc(t){let e=t.data;if(t.type==="td10"&&e)return e;if(t.type==="td15"&&e?.base)return e.base;throw new Error(`The quote is a ${t.type} quote, not a TDX one`)}function Jc(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}var zc=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],gt="locked-read-only";function Mr(t,{profile:e,allowDebugProfile:n=!1}){if(t.length===0)throw new Error("No release given, so no image would be trusted");let r,o=t.map((i,s)=>{let a=i?.tag??`releases[${s}]`;if(i?.role!==void 0&&i.role!=="node")throw new Error(`${a} lists the measurements of a ${i.role}, not of a node image`);let c=i?.profiles?.[e];if(!c){let d=Object.keys(i?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${d})`)}if(e!==gt&&!n)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(gt)}, or pass allowDebugProfile to test`);let u=(c.allowed_tcb_statuses??["uptodate"]).map(d=>Qc(d,a));return r=r===void 0?u:r.filter(d=>u.includes(d)),{mrtd:c.mrtd,rtmr0:c.rtmr0,rtmr1:c.rtmr1,rtmr2:c.rtmr2,rtmr3:c.rtmr3}});if(!r||r.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:o,allowedTcbStatuses:r}}function Qc(t,e){let n=zc.find(r=>r.toLowerCase()===String(t).toLowerCase());if(!n)throw new Error(`${e} accepts TCB status ${JSON.stringify(t)}, which this verifier does not know`);return n}var Di=[{uri:"https://fulcio.sigstore.dev",validFor:{start:"2021-03-07T03:20:29Z",end:"2022-12-31T23:59:59.999Z"},certChain:["MIIB+DCCAX6gAwIBAgITNVkDZoCiofPDsy7dfm6geLbuhzAKBggqhkjOPQQDAzAqMRUwEwYDVQQKEwxzaWdzdG9yZS5kZXYxETAPBgNVBAMTCHNpZ3N0b3JlMB4XDTIxMDMwNzAzMjAyOVoXDTMxMDIyMzAzMjAyOVowKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTB2MBAGByqGSM49AgEGBSuBBAAiA2IABLSyA7Ii5k+pNO8ZEWY0ylemWDowOkNa3kL+GZE5Z5GWehL9/A9bRNA3RbrsZ5i0JcastaRL7Sp5fp/jD5dxqc/UdTVnlvS16an+2Yfswe/QuLolRUCrcOE2+2iA5+tzd6NmMGQwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwHQYDVR0OBBYEFMjFHQBBmiQpMlEk6w2uSu1KBtPsMB8GA1UdIwQYMBaAFMjFHQBBmiQpMlEk6w2uSu1KBtPsMAoGCCqGSM49BAMDA2gAMGUCMH8liWJfMui6vXXBhjDgY4MwslmN/TJxVe/83WrFomwmNf056y1X48F9c4m3a3ozXAIxAKjRay5/aj/jsKKGIkmQatjI8uupHr/+CxFvaJWmpYqNkLDGRU+9orzh5hI2RrcuaQ=="]},{uri:"https://fulcio.sigstore.dev",validFor:{start:"2022-04-13T20:06:15Z"},certChain:["MIICGjCCAaGgAwIBAgIUALnViVfnU0brJasmRkHrn/UnfaQwCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMjA0MTMyMDA2MTVaFw0zMTEwMDUxMzU2NThaMDcxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjEeMBwGA1UEAxMVc2lnc3RvcmUtaW50ZXJtZWRpYXRlMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8RVS/ysH+NOvuDZyPIZtilgUF9NlarYpAd9HP1vBBH1U5CV77LSS7s0ZiH4nE7Hv7ptS6LvvR/STk798LVgMzLlJ4HeIfF3tHSaexLcYpSASr1kS0N/RgBJz/9jWCiXno3sweTAOBgNVHQ8BAf8EBAMCAQYwEwYDVR0lBAwwCgYIKwYBBQUHAwMwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQU39Ppz1YkEZb5qNjpKFWixi4YZD8wHwYDVR0jBBgwFoAUWMAeX5FFpWapesyQoZMi0CrFxfowCgYIKoZIzj0EAwMDZwAwZAIwPCsQK4DYiZYDPIaDi5HFKnfxXx6ASSVmERfsynYBiX2X6SJRnZU84/9DZdnFvvxmAjBOt6QpBlc4J/0DxvkTCqpclvziL6BCCPnjdlIB3Pu3BxsPmygUY7Ii2zbdCdliiow=","MIIB9zCCAXygAwIBAgIUALZNAPFdxHPwjeDloDwyYChAO/4wCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMTEwMDcxMzU2NTlaFw0zMTEwMDUxMzU2NThaMCoxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjERMA8GA1UEAxMIc2lnc3RvcmUwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT7XeFT4rb3PQGwS4IajtLk3/OlnpgangaBclYpsYBr5i+4ynB07ceb3LP0OIOZdxexX69c5iVuyJRQ+Hz05yi+UF3uBWAlHpiS5sh0+H2GHE7SXrk1EC5m1Tr19L9gg92jYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRYwB5fkUWlZql6zJChkyLQKsXF+jAfBgNVHSMEGDAWgBRYwB5fkUWlZql6zJChkyLQKsXF+jAKBggqhkjOPQQDAwNpADBmAjEAj1nHeXZp+13NWBNa+EDsDP8G1WWg1tCMWP/WHPqpaVo0jhsweNFZgSs0eE7wYI4qAjEA2WB9ot98sIkoF3vZYdd3/VtWB5b9TNMea7Ix/stJ5TfcLLeABLE4BNJOsQ4vnBHJ"]}],Ni=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var Yc="1.2.840.10045.2.1",Xc={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},Zc={"P-256":32,"P-384":48},el={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function Ui(t,e,n){if(e+2>n)throw new Error("it is truncated");let r=t[e];if((r&31)===31)throw new Error("it uses a tag this parser does not read");let o=t[e+1],i=e+2;if(o&128){let a=o&127;if(a===0||a>4||i+a>n)throw new Error("it has a length this parser does not read");o=0;for(let c=0;c<a;c+=1)o=o*256+t[i+c];i+=a}let s=i+o;if(s>n)throw new Error("it is truncated");return{tag:r,bytes:t,offset:e,start:i,end:s}}function Me(t){let e=Ui(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function K(t){let e=[];for(let n=t.start;n<t.end;){let r=Ui(t.bytes,n,t.end);e.push(r),n=r.end}return e}function O(t,e,n){if(!t||t.tag!==e)throw new Error(`${n} is not where it should be`);return t}function ae(t){return t.bytes.slice(t.start,t.end)}function rn(t){return t.bytes.slice(t.offset,t.end)}function _e(t){let e=ae(O(t,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let n=[],r=0;for(let s of e)r=r*128+(s&127),s&128||(n.push(r),r=0);let o=n.shift();return[...o<80?[Math.floor(o/40),o%40]:[2,o-80],...n].join(".")}function tl(t){let e=new TextDecoder().decode(ae(t)),n=t.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,r=t.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,o=n??r;if(!o)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let i=Number(o[1]);n&&(i+=i<50?2e3:1900);let[s,a,c,u,d]=o.slice(2).map(Number);return Date.UTC(i,s-1,a,c,u,d)}function Kr(t){try{let[e,n,r,...o]=K(O(Me(t),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let i=K(O(e,48,"The signed part")),s=i[0]?.tag===160?1:0,[a,c,u,d,l,p,...x]=i.slice(s);O(a,2,"The serial number");let v=_e(K(O(n,48,"The signature algorithm"))[0]);if(_e(K(O(c,48,"The signature algorithm"))[0])!==v)throw new Error("it names two different signature algorithms");let w=el[v];if(!w)throw new Error(`it is signed with ${v}, not ECDSA with SHA-256 or SHA-384`);let[E,T]=K(O(d,48,"The validity")).map(tl);if(T===void 0)throw new Error("its validity is incomplete");let[H,z]=K(O(p,48,"The public key"));O(z,3,"The public key");let[h,b]=K(O(H,48,"The key algorithm"));if(_e(h)!==Yc)throw new Error("its key is not an elliptic-curve key");let S=Xc[_e(b)];if(!S)throw new Error("its key is on a curve other than P-256 or P-384");let U=new Map,M=x.find(ee=>ee.tag===163);if(M){let[ee]=K(M);for(let te of K(O(ee,48,"The extensions"))){let Se=K(O(te,48,"An extension"));if(Se.length===3)O(Se[1],1,"An extension's critical flag");else if(Se.length!==2)throw new Error("it has a malformed extension");let cr=_e(Se[0]);if(U.has(cr))throw new Error(`it has extension ${cr} twice`);U.set(cr,ae(O(Se[Se.length-1],4,"An extension value")))}}let Q=ae(O(r,3,"The signature"));if(Q[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:rn(e),signatureHash:w,signature:Q.slice(1),issuer:rn(O(u,48,"The issuer")),subject:rn(O(l,48,"The subject")),notBefore:E,notAfter:T,spki:rn(p),curve:S,extensions:U}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function Oi(t){return K(O(Me(t),48,"The list")).map(_e)}function nl(t,e){let n=Zc[e],r=K(O(Me(t),48,"The signature"));if(r.length!==2)throw new Error("The signature is not an ECDSA signature");let o=new Uint8Array(n*2);return r.forEach((i,s)=>{let a=ae(O(i,2,"The signature"));if(a.length===0||a[0]&128)throw new Error("The signature is not an ECDSA signature");for(;a.length>1&&a[0]===0;)a=a.subarray(1);if(a.length>n)throw new Error("The signature is not an ECDSA signature");o.set(a,s*n+n-a.length)}),o}async function on(t,e,n,r,o){let i;try{i=nl(r,e)}catch{return!1}let s=await crypto.subtle.importKey("spki",t,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:n},s,i,o)}function V(t,e){let n=t.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(n)||n.length%4!==0)throw new Error(`${e} is not base64`);let r=atob(n),o=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)o[i]=r.charCodeAt(i);return o}function Gr(t,e){let n=[...t.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(n.length!==1||t.replace(n[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return V(n[0][1],e)}var rl="2.5.29.17",ol="2.5.29.37",il="1.3.6.1.5.5.7.3.3",sl="1.3.6.1.4.1.57264.1.8",al="1.3.6.1.4.1.57264.1.1",cl=134,ll=12,ul=48,dl=new TextEncoder,Ke=t=>new TextDecoder().decode(t);async function sn(t,e,n,r){let{base64Signature:o,cert:i,rekorBundle:s}=fl(e),a=s.Payload;if(r!==void 0&&r.trim()!==o.trim())throw new Error("The detached signature is not the one in the bundle");let c=V(o,"The bundle signature"),u=Gr(Ke(V(i,"The bundle certificate")),"The bundle certificate"),d=Kr(u),l=Ni.find(T=>T.logId===a.logID.toLowerCase());if(!l)throw new Error(`The bundle names Rekor log ${a.logID}, which the Sigstore trust root does not know`);let p=dl.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await on(V(l.publicKey,"The Rekor key"),"P-256","SHA-256",V(s.SignedEntryTimestamp,"The signed entry timestamp"),p))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let v=a.integratedTime*1e3;if(!Ki(v,l.validFor))throw new Error(`Rekor log ${l.baseUrl} was not in use at ${ft(v)}, when the entry says it was logged`);let P=hl(a.body),w=y(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(P.hash!==w)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!$r(V(P.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let E=Gr(Ke(V(P.publicKey,"The logged certificate")),"The logged certificate");if(!$r(E,u))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await on(d.spki,"P-256","SHA-256",c,t))throw new Error("The signature over the file does not verify with the bundle's certificate");return await pl(d,v),ml(d,n),{integratedTime:a.integratedTime}}async function pl(t,e){if(!Mi(t,e))throw new Error(`The signing certificate was valid ${ft(t.notBefore)} to ${ft(t.notAfter)}, not at ${ft(e)} when Rekor logged it`);let n=[];for(let r of Di){let o=r.certChain.map(s=>Kr(V(s,"A Fulcio certificate")));if(!await _i(t,o[0]))continue;let i=await gl(o,r.validFor,e);if(!i)return;n.push(`${r.uri} (valid from ${r.validFor.start}): ${i}`)}throw new Error(n.length>0?`The signing certificate's CA is not trusted at ${ft(e)}: ${n.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function gl(t,e,n){if(!Ki(n,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of t.entries()){if(!Mi(o,n))return`its certificate ${r} was not valid then`;let i=t[r+1]??o;if(!await _i(o,i))return`its certificate ${r} is not signed by the next`}}async function _i(t,e){return $r(t.issuer,e.subject)?on(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function ml(t,e){let n=t.extensions.get(rl);if(!n)throw new Error("The signing certificate names no identity");let r=K(O(Me(n),ul,"The subject alternative name")),o=r.filter(u=>u.tag===cl).map(u=>Ke(ae(u)));if(o.length!==1||r.length!==1||o[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(o.length===1?o[0]:o)}, not by ${e.identity}`);let i=t.extensions.get(sl),s=t.extensions.get(al),a=i?Ke(ae(O(Me(i),ll,"The OIDC issuer"))):s?Ke(s):void 0;if(a!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${a===void 0?"missing":JSON.stringify(a)}, not ${e.issuer}`);let c=t.extensions.get(ol);if(!c||!Oi(c).includes(il))throw new Error("The signing certificate is not for code signing")}function fl(t){let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let n=e,r=n?.rekorBundle?.Payload;if(!(typeof n?.base64Signature=="string"&&typeof n.cert=="string"&&typeof n.rekorBundle?.SignedEntryTimestamp=="string"&&typeof r?.body=="string"&&typeof r.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(r.logID)&&Number.isSafeInteger(r.integratedTime)&&r.integratedTime>=0&&Number.isSafeInteger(r.logIndex)&&r.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return n}function hl(t){let e;try{e=JSON.parse(Ke(V(t,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let n=e?.spec?.data?.hash,r=e?.spec?.signature;if(e?.kind!=="hashedrekord"||n?.algorithm!=="sha256"||typeof n.value!="string"||typeof r?.content!="string"||typeof r.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:n.value.toLowerCase(),signature:r.content,publicKey:r.publicKey.content}}function Mi(t,e){return t.notBefore<=e&&e<=t.notAfter}function Ki(t,e){return Date.parse(e.start)<=t&&(e.end===void 0||t<=Date.parse(e.end))}function ft(t){return new Date(t).toISOString()}function $r(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Lr=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-node-image-gcp.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),yl=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],an="https://cloud.calimero.network";async function $i(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await sn(r,e,{identity:n.identity??Lr.identity,issuer:n.issuer??Lr.issuer},n.signature);let o;try{o=JSON.parse(new TextDecoder().decode(r))}catch{throw new Error("The signed release is not JSON")}if(o?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(o?.role)} release, not a node one`);let i=Object.values(o.profiles??{}),s=a=>yl.every(c=>/^[0-9a-f]{96}$/i.test(String(a?.[c])));if(typeof o.tag!="string"||i.length===0||!i.every(s))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(n.expectedVersion!==void 0&&o.tag!==n.expectedVersion)throw new Error(`The signed release is ${o.tag}, not ${n.expectedVersion}`);return o}async function cn(t,e={}){let n=await(e.fetch??fetch)(t,{headers:{accept:"application/json"}});if(!n.ok)throw new Error(`Fetching the node release from ${t} failed: HTTP ${n.status}`);let r;try{r=(await n.json())?.data}catch{throw new Error(`${t} did not answer with JSON`)}if(typeof r?.version!="string"||typeof r.publishedMrtds!="string"||typeof r.bundle!="string")throw new Error(`${t} did not answer with a signed node release`);return{version:r.version,publishedMrtds:r.publishedMrtds,bundle:r.bundle}}function Li(t){let e=/^merotee-.+-(\d+)-(\d+)-(\d+)$/.exec(t);if(!e)throw new Error(`${JSON.stringify(t)} is not the image of a mero-tee node release`);return`${Number(e[1])}.${Number(e[2])}.${Number(e[3])}`}async function ln(t,e={}){let n=await Bi(t,e.fetch??fetch);if(n===void 0)throw new Error(`${Hi(t)} was refused unsealed: the node requires sealing and is too old to name its release before a session exists. Name the release it runs yourself (createSignedReleaseSealedFetch's \`releaseVersion\`), or upgrade the node`);return n}function Hi(t){return`${t.replace(/\/+$/,"")}/admin-api/tee/info`}async function Bi(t,e){let n=Hi(t),r=await e(n,{headers:{accept:"application/json"}});if(r.status===403&&await r.json().then(s=>s?.error?.code).catch(()=>{})==="sealed_required")return;if(!r.ok)throw new Error(`Fetching ${n} failed: HTTP ${r.status}`);let o;try{o=(await r.json())?.data?.osImage}catch{throw new Error(`${n} did not answer with JSON`)}if(typeof o!="string")throw new Error(`${n} did not name the node's image`);return Li(o)}function un(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${ht(e,"version")}`}async function qi(t){let e=ht(t.minReleaseVersion,"minReleaseVersion"),n=ht(t.release?.version,"The release version"),r=await $i(t.release.publishedMrtds,t.release.bundle,{expectedVersion:n,identity:t.identity,issuer:t.issuer});if(bl(n,e)<0)throw new Error(`Release ${n} is older than the minimum trusted, ${e}`);return Mr([r],{profile:t.profile,allowDebugProfile:t.allowDebugProfile})}function dn(t){return ht(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async n=>{let r=await qi({release:await t.release(),profile:t.profile,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer});return mt({dcapVerify:t.dcapVerify,fetchCollateral:t.fetchCollateral,now:t.now,...r})(n)},{includeCollateral:!0})}function wl(t){let{baseUrl:e,releaseSource:n,releaseVersion:r,applicationId:o,applicationHash:i,fetch:s,...a}=t;r!==void 0&&ht(r,"releaseVersion");let c=s??((d,l)=>fetch(d,l));return fe({baseUrl:e,verify:dn({...a,release:async()=>{let d=r===void 0?await ln(e,{fetch:c}):await Bi(e,c)??r;return typeof n=="function"?n({baseUrl:e,version:d,fetch:c}):cn(un(n??an,d),{fetch:c})}}),applicationId:o,applicationHash:i,fetch:c})}var ji=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ht(t,e){let n=typeof t=="string"?ji.exec(t):null,r=n?.[4];if(!n||r!==void 0&&r.split(".").some(o=>o===""))throw new Error(`${e} is ${JSON.stringify(t)}, not a release version like 2.3.87`);return t}function bl(t,e){let[n,r]=Gi(t),[o,i]=Gi(e);for(let c=0;c<3;c+=1)if(n[c]!==o[c])return n[c]<o[c]?-1:1;if(r===void 0||i===void 0)return r===i?0:r===void 0?1:-1;let s=r.split("."),a=i.split(".");for(let c=0;c<Math.max(s.length,a.length);c+=1){let[u,d]=[s[c],a[c]];if(u===void 0||d===void 0)return u===void 0?-1:1;let[l,p]=[/^\d+$/.test(u),/^\d+$/.test(d)],x=l&&p?Math.sign(Number(u)-Number(d)):l!==p?l?-1:1:u<d?-1:u>d?1:0;if(x!==0)return x}return 0}function Gi(t){let e=ji.exec(t);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var Al=new TextEncoder().encode("calimero.warrant.v2"),xl=new TextEncoder().encode("calimero.warrant.intent.v1"),Fi=64,Vi=256;async function Hr(t,e){let n=new TextEncoder().encode(JSON.stringify(e));return k(xl,[new TextEncoder().encode(t),n])}async function pn(t){let e=m(t.context,"context",32),n=m(t.authorAccount,"authorAccount",32),r=m(t.executor,"executor",32),o=m(t.executorKey,"executorKey",32),i=m(t.releaseBytecodeId,"releaseBytecodeId",32),s=Br(t.releaseVersion??""),a=ce(t.accountHeads,"accountHeads"),c=ce(t.governanceFloor,"governanceFloor"),u=await I(t.deviceSecret,t.signer,"deviceSecret"),d=m(u.publicKey,"signer.publicKey",32),l=new TextEncoder().encode(t.method),p=await Hr(t.method,t.argsJson),x=C(t.nonce),v=C(t.notAfter),P=await k(Al,[e,n,d,r,o,i,s,l,p,C(a.length),...a,C(c.length),...c,x,v]),w=yt(await u.sign(P));return y(f(e,n,d,r,o,i,R(s.length),s,R(l.length),l,p,R(a.length),...a,R(c.length),...c,x,v,w))}function yt(t){if(!(t instanceof Uint8Array)||t.length!==64){let e=t instanceof Uint8Array?`${t.length} bytes`:typeof t;throw new Error(`signer returned ${e}, expected a 64-byte Ed25519 signature`)}return t}function Br(t){let e=new TextEncoder().encode(t);return vl(e.length),e}function vl(t){if(t>Vi)throw new Error(`releaseVersion is ${t} bytes, over the ${Vi} a node accepts`)}function ce(t,e){let n=t??[];if(n.length>Fi)throw new Error(`${e} cites ${n.length} heads, over the ${Fi} a node accepts`);return n.map((r,o)=>m(r,`${e}[${o}]`,32))}var Rl=new TextEncoder().encode("calimero.context-creation-warrant.v1"),Cl=new TextEncoder().encode("calimero.context-creation.init.v1"),gn=256;async function qr(t){let e=new TextEncoder().encode(JSON.stringify(t));return k(Cl,[e])}async function Sl(t){return k(Rl,[t.group,t.seed,t.authorAccount,t.deviceKey,t.executor,t.executorKey,t.applicationId,new Uint8Array([t.serviceName===null?0:1]),t.serviceName??new Uint8Array(0),new Uint8Array([t.name===null?0:1]),t.name??new Uint8Array(0),t.initHash,C(t.accountHeads.length),...t.accountHeads,C(t.governanceFloor.length),...t.governanceFloor,C(t.nonce),C(t.notAfter)])}async function mn(t){let e=m(t.group,"group",32),n=t.seed===void 0?crypto.getRandomValues(new Uint8Array(32)):m(t.seed,"seed",32),r=m(t.authorAccount,"authorAccount",32),o=m(t.executor,"executor",32),i=m(t.executorKey,"executorKey",32),s=m(t.applicationId,"applicationId",32),a=Wi(t.serviceName,"serviceName"),c=Wi(t.name,"name"),u=ce(t.accountHeads,"accountHeads"),d=ce(t.governanceFloor,"governanceFloor"),l=await I(t.deviceSecret,t.signer,"deviceSecret"),p=m(l.publicKey,"signer.publicKey",32),x=await qr(t.initArgs),v=await Sl({group:e,seed:n,authorAccount:r,deviceKey:p,executor:o,executorKey:i,applicationId:s,serviceName:a,name:c,initHash:x,accountHeads:u,governanceFloor:d,nonce:t.nonce,notAfter:t.notAfter}),P=yt(await l.sign(v));return{warrant:y(f(e,n,r,p,o,i,s,Ji(a),Ji(c),x,R(u.length),...u,R(d.length),...d,C(t.nonce),C(t.notAfter),P)),seed:y(n)}}function zi(t){let e=t.trim();if(!/^[0-9a-fA-F]*$/.test(e)||e.length%2!==0)throw new Error("creation warrant must be an even number of hex characters");let n=new Uint8Array(e.length/2);for(let l=0;l<n.length;l+=1)n[l]=Number.parseInt(e.slice(l*2,l*2+2),16);let r=new DataView(n.buffer),o=0,i=(l,p)=>{if(o+l>n.length)throw new Error(`creation warrant ends inside ${p} (${n.length} bytes)`);let x=n.subarray(o,o+l);return o+=l,x},s=l=>r.getUint32(i(4,l).byteOffset,!0),a=l=>r.getBigUint64(i(8,l).byteOffset,!0),c=l=>{let p=i(1,l)[0];if(p===0)return null;if(p!==1)throw new Error(`${l} has option tag ${p}, expected 0 or 1`);let x=s(l);if(x>gn)throw new Error(`${l} is ${x} bytes, over the ${gn} a node accepts`);return new TextDecoder("utf-8",{fatal:!0}).decode(i(x,l))},u=l=>{let p=s(l);if(p>64)throw new Error(`${l} cites ${p} heads, over the 64 a node accepts`);return Array.from({length:p},()=>y(i(32,l)))},d={group:y(i(32,"group")),seed:y(i(32,"seed")),authorAccount:y(i(32,"authorAccount")),deviceKey:y(i(32,"deviceKey")),executor:y(i(32,"executor")),executorKey:y(i(32,"executorKey")),applicationId:y(i(32,"applicationId")),serviceName:c("serviceName"),name:c("name"),initHash:y(i(32,"initHash")),accountHeads:u("accountHeads"),governanceFloor:u("governanceFloor"),nonce:a("nonce"),notAfter:a("notAfter"),signature:y(i(64,"signature"))};if(o!==n.length)throw new Error(`creation warrant is ${n.length} bytes but its fields account for ${o}`);return d}function Wi(t,e){if(t===void 0)return null;let n=new TextEncoder().encode(t);if(n.length>gn)throw new Error(`${e} is ${n.length} UTF-8 bytes, over the ${gn} a node accepts`);return n}function Ji(t){return t===null?new Uint8Array([0]):f(new Uint8Array([1]),R(t.length),t)}var El=new TextEncoder().encode("calimero.governance-warrant.v1"),kl=new TextEncoder().encode("calimero.governance-warrant.op.v1"),Il={group:0,root:1};async function jr(t){return k(kl,[new Uint8Array([Fr(t.kind)]),t.bytes])}async function Pl(t){return k(El,[t.scope,new Uint8Array([Fr(t.kind)]),t.authorAccount,t.deviceKey,t.executor,t.executorKey,t.opHash,C(t.accountHeads.length),...t.accountHeads,C(t.governanceFloor.length),...t.governanceFloor,C(t.nonce),C(t.notAfter)])}async function wt(t){let e=m(t.scope,"scope",32),n=m(t.authorAccount,"authorAccount",32),r=m(t.executor,"executor",32),o=m(t.executorKey,"executorKey",32),i=ce(t.accountHeads,"accountHeads"),s=ce(t.governanceFloor,"governanceFloor"),a=Fr(t.op.kind),c=await I(t.deviceSecret,t.signer,"deviceSecret"),u=m(c.publicKey,"signer.publicKey",32),d=await jr(t.op),l=await Pl({scope:e,kind:t.op.kind,authorAccount:n,deviceKey:u,executor:r,executorKey:o,opHash:d,accountHeads:i,governanceFloor:s,nonce:t.nonce,notAfter:t.notAfter}),p=yt(await c.sign(l));return y(f(e,new Uint8Array([a]),n,u,r,o,d,R(i.length),...i,R(s.length),...s,C(t.nonce),C(t.notAfter),p))}function Qi(t){let e=t.trim();if(!/^[0-9a-fA-F]*$/.test(e)||e.length%2!==0)throw new Error("governance warrant must be an even number of hex characters");let n=new Uint8Array(e.length/2);for(let l=0;l<n.length;l+=1)n[l]=Number.parseInt(e.slice(l*2,l*2+2),16);let r=new DataView(n.buffer),o=0,i=(l,p)=>{if(o+l>n.length)throw new Error(`governance warrant ends inside ${p} (${n.length} bytes)`);let x=n.subarray(o,o+l);return o+=l,x},s=l=>r.getUint32(i(4,l).byteOffset,!0),a=l=>r.getBigUint64(i(8,l).byteOffset,!0),c=l=>{let p=s(l);if(p>64)throw new Error(`${l} cites ${p} heads, over the 64 a node accepts`);return Array.from({length:p},()=>y(i(32,l)))},u=()=>{let l=i(1,"kind")[0];if(l===0)return"group";if(l===1)return"root";throw new Error(`governance warrant has kind ${l}, expected 0 (group) or 1 (root)`)},d={scope:y(i(32,"scope")),kind:u(),authorAccount:y(i(32,"authorAccount")),deviceKey:y(i(32,"deviceKey")),executor:y(i(32,"executor")),executorKey:y(i(32,"executorKey")),opHash:y(i(32,"opHash")),accountHeads:c("accountHeads"),governanceFloor:c("governanceFloor"),nonce:a("nonce"),notAfter:a("notAfter"),signature:y(i(64,"signature"))};if(o!==n.length)throw new Error(`governance warrant is ${n.length} bytes but its fields account for ${o}`);return d}function Fr(t){let e=Il[t];if(e===void 0)throw new Error(`op kind must be 'group' or 'root', got ${String(t)}`);return e}var Tl={Admin:0,Member:1,ReadOnly:2},G={MemberAdded:1,MemberRemoved:2,MemberLeft:3,MemberRoleSet:4,MemberCapabilitySet:5,DefaultCapabilitiesSet:6,TargetApplicationSet:7,ContextDetached:9,SubgroupVisibilitySet:10,GroupMetadataSet:11,MemberMetadataSet:12,ContextMetadataSet:13,ContextCapabilityGranted:16,ContextCapabilityRevoked:17},bt={GroupCreated:0,GroupReparented:1,GroupDeleted:2,MemberJoinedOpen:7,NamespaceCreatedV2:9},Dl=new TextEncoder().encode("calimero.namespace.id.v1"),Wr=new Uint8Array(32),fn=R(0);function Xi(t){let e=Tl[t];if(e===void 0)throw new Error(`role must be Admin, Member or ReadOnly, got ${String(t)}`);return new Uint8Array([e])}function N(t){return new Uint8Array([t])}function Ge(t,e){return{kind:"group",bytes:f(N(G.MemberAdded),m(t,"member",32),Xi(e))}}function hn(t){return{kind:"group",bytes:f(N(G.MemberRemoved),m(t,"member",32),Wr,fn)}}function At(t){return{kind:"group",bytes:f(N(G.MemberLeft),m(t,"member",32),Wr,fn)}}function yn(t,e){return{kind:"group",bytes:f(N(G.MemberRoleSet),m(t,"member",32),Xi(e))}}var Nl=new TextEncoder().encode("calimero.subgroup.id.v1");async function Jr(t,e,n,r){return y(await k(Nl,[m(t,"admin",32),m(e,"parentId",32),new Uint8Array([n?1:0]),m(r,"salt",32)]))}function Yi(t,e){if(t.length===0)throw new Error(`${e} must not be empty`);let n=new TextEncoder().encode(t);return f(R(n.length),n)}function wn(t){return{kind:"group",bytes:f(N(G.TargetApplicationSet),Wr,m(t.applicationId,"applicationId",32),Yi(t.package,"package"),Yi(t.version,"version"))}}function $e(t){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`capabilities must be a u32 bit mask, got ${String(t)}`);if(ge(t,_.CAN_AUTHOR_ON_BEHALF))throw new Error("capabilities may not include CAN_AUTHOR_ON_BEHALF (512): a relay never carries a change to it");return{kind:"group",bytes:f(N(G.DefaultCapabilitiesSet),R(t))}}function zr(t){return{kind:"root",bytes:f(N(bt.GroupCreated),m(t.groupId,"groupId",32),m(t.parentId,"parentId",32),N(t.restricted?1:0),m(t.admin,"admin",32),m(t.salt,"salt",32))}}async function Le(t){let e=t.salt??y(crypto.getRandomValues(new Uint8Array(32))),n=await Jr(t.admin,t.parentId,t.restricted,e);return{groupId:n,salt:e,op:zr({...t,groupId:n,salt:e})}}function bn(t,e){return{kind:"root",bytes:f(N(bt.GroupReparented),m(t,"childGroupId",32),m(e,"newParentId",32))}}function An(t){return{kind:"root",bytes:f(N(bt.GroupDeleted),m(t,"rootGroupId",32),fn,fn)}}async function xn(t,e){return y(await k(Dl,[m(t,"founder",32),m(e,"salt",32)]))}function vn(t){let e=j(t.credential,"credential");if(e.length===0)throw new Error("credential must be the founder's AccountProof<DeviceCert>, got nothing");return{kind:"root",bytes:f(N(bt.NamespaceCreatedV2),m(t.founder,"founder",32),e,m(t.salt,"salt",32))}}function Vr(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}function Qr(t){return t===void 0?N(0):f(N(1),Vr(t))}function Yr(t={}){let e=new TextEncoder,n=Object.entries(t).map(([r,o])=>[e.encode(r),o,r]).sort(([r],[o])=>{for(let i=0;i<Math.min(r.length,o.length);i++)if(r[i]!==o[i])return r[i]-o[i];return r.length-o.length});return f(R(n.length),...n.flatMap(([,r,o])=>[Vr(o),Vr(r)]))}function Ul(t,e){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`${e} must be a u32 bit mask, got ${String(t)}`);if(ge(t,_.CAN_AUTHOR_ON_BEHALF))throw new Error(`${e} may not include CAN_AUTHOR_ON_BEHALF (512): a relay never carries a change to it`);return t}function Rn(t,e){return{kind:"group",bytes:f(N(G.MemberCapabilitySet),m(t,"member",32),R(Ul(e,"capabilities")))}}function Cn(t){return{kind:"group",bytes:f(N(G.ContextDetached),m(t,"contextId",32))}}function Sn(t){if(t!=="open"&&t!=="restricted")throw new Error(`mode must be open or restricted, got ${String(t)}`);return{kind:"group",bytes:f(N(G.SubgroupVisibilitySet),N(t==="open"?0:1))}}function He(t={}){return{kind:"group",bytes:f(N(G.GroupMetadataSet),Qr(t.name),Yr(t.data))}}function En(t,e={}){return{kind:"group",bytes:f(N(G.MemberMetadataSet),m(t,"member",32),Qr(e.name),Yr(e.data))}}function kn(t,e={}){return{kind:"group",bytes:f(N(G.ContextMetadataSet),m(t,"contextId",32),Qr(e.name),Yr(e.data))}}function Zi(t){if(!Number.isInteger(t)||t<1||t>255)throw new Error(`capability must be a non-zero u8, got ${String(t)}`);return N(t)}function es(t,e,n){return{kind:"group",bytes:f(N(G.ContextCapabilityGranted),m(t,"contextId",32),m(e,"member",32),Zi(n))}}function ts(t,e,n){return{kind:"group",bytes:f(N(G.ContextCapabilityRevoked),m(t,"contextId",32),m(e,"member",32),Zi(n))}}function In(t){return{kind:"root",bytes:f(N(bt.MemberJoinedOpen),m(t.member,"member",32),m(t.groupId,"groupId",32),j(t.credential,"credential"))}}var Pn=300,he=class extends Error{constructor(n,r,o){super(`relay refused the intent (HTTP ${o}): ${n}`);this.reason=n;this.retryable=r;this.status=o;this.name="IntentRefusedError"}},Ol=t=>new Promise(e=>setTimeout(e,t));function _l(t){let e=t?.get?.("Retry-After");if(!e)return null;let n=Number.parseInt(e,10);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);return Number.isFinite(r)?Math.max(0,r-Date.now()):null}var W=class{constructor(e){this.config=e,this.baseUrl=e.relayUrl.replace(/\/+$/,"");let n=e.fetch;this.fetchImpl=n?(r,o)=>n(r,o):(r,o)=>globalThis.fetch(r,o),this.timeoutMs=e.timeoutMs??1e4,this.rateLimitRetries=e.rateLimitRetries??3}get relayUrl(){return this.baseUrl}get authorAccount(){return this.config.authorAccount}get authorProof(){return this.config.authorProof}async authorSigner(){return I(this.config.deviceSecret,this.config.signer,"deviceSecret")}async describe(e){return(await this.json("GET",`/admin-api/contexts/${g(e)}/intents`)).data}async execute(e,n,r={}){let o=await this.describe(e),i=this.checkedExecutor(o),s=y(m(o.releaseBytecodeId??"","the relay's releaseBytecodeId",32)),a=o.releaseVersion??"";Br(a);let c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??Pn,l=await pn({context:e,authorAccount:this.config.authorAccount,executor:i.executorAccount,executorKey:i.executorKey,releaseBytecodeId:s,releaseVersion:a,method:n,argsJson:r,nonce:u,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(d),signer:c}),p=await this.json("POST",`/admin-api/contexts/${g(e)}/intents`,{method:n,argsJson:r,warrant:l,authorProof:this.config.authorProof});return{rootHash:p.data.rootHash,returns:p.data.returns??null}}async presenceIntent(e,n){await this.jsonOnce("POST",`/admin-api/contexts/${g(e)}/presence-intents`,n)}async describeCreation(e,n={}){let r=n.author?`?author=${encodeURIComponent(n.author)}`:"";return(await this.json("GET",`/admin-api/groups/${g(e)}/context-intents${r}`)).data}async createContext(e){let n=await this.describeCreation(e.groupId,{author:this.config.authorAccount});if(!n.canCreateOnBehalf)throw new he(`the relay (${n.executorAccount}) has no standing to act for members of group ${n.groupId}; an admin must admit it as a relay or grant it CAN_AUTHOR_ON_BEHALF (checked before signing \u2014 no nonce was spent)`,!1,403);if(n.authorMayCreate===!1)throw new he(`the author (${this.config.authorAccount}) may not create contexts in group ${n.groupId}; it needs CAN_CREATE_CONTEXT or admin (checked before signing \u2014 no nonce was spent)`,!1,403);let r=this.checkedExecutor(n),o=e.initArgs??{},i=await this.authorSigner(),s=await this.config.nonces.next(),a=this.config.ttlSeconds??Pn,{warrant:c}=await mn({group:e.groupId,seed:e.seed,authorAccount:this.config.authorAccount,executor:r.executorAccount,executorKey:r.executorKey,applicationId:e.applicationId,serviceName:e.serviceName,name:e.name,initArgs:o,nonce:s,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(a),signer:i}),u=await this.json("POST",`/admin-api/groups/${g(e.groupId)}/context-intents`,{warrant:c,authorProof:this.config.authorProof,initArgs:o});return{contextId:u.data.contextId,groupId:u.data.groupId,memberPublicKey:u.data.memberPublicKey}}async describeGovernance(e){return(await this.json("GET",`/admin-api/groups/${g(e)}/governance-intents`)).data}async govern(e){let n=await this.describeGovernance(e.groupId);if(!n.canActOnBehalf)throw new he(`the relay (${n.executorAccount}) has no standing to act for members of group ${n.groupId}; an admin must admit it as a relay or grant it CAN_AUTHOR_ON_BEHALF (checked before signing, no nonce was spent)`,!1,403);let r=this.checkedExecutor(n),o=await this.authorSigner(),i=await this.config.nonces.next(),s=this.config.ttlSeconds??Pn,a=await wt({scope:e.groupId,op:e.op,authorAccount:this.config.authorAccount,executor:r.executorAccount,executorKey:r.executorKey,nonce:i,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(s),signer:o});return{groupId:(await this.postGovernance(e.groupId,e.op,a)).groupId}}async foundNamespace(e){if(!e?.executor)throw new Error("foundNamespace needs the relay's account and signing key: pass executor (checked before signing, no nonce was spent)");let n=this.checkedExecutor(e.executor),r=e.salt?y(m(e.salt,"salt",32)):y(crypto.getRandomValues(new Uint8Array(32))),o=await xn(this.config.authorAccount,r),i=vn({founder:this.config.authorAccount,credential:this.config.authorProof,salt:r}),s=e.defaultCapabilities===void 0?void 0:$e(e.defaultCapabilities),a=e.application?wn(e.application):void 0,c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??Pn,l=await wt({scope:o,op:i,authorAccount:this.config.authorAccount,executor:n.executorAccount,executorKey:n.executorKey,nonce:u,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(d),signer:c}),p=await this.postGovernance(o,i,l),x={namespaceId:p.groupId,salt:r,teeEnabled:p.teeEnabled??!1,...p.teeError?{teeError:p.teeError}:{}},v=x,P=w=>w instanceof Error?w.message:String(w);if(a)try{await this.govern({groupId:x.namespaceId,op:a}),v={...v,applicationSet:!0}}catch(w){v={...v,applicationSet:!1,applicationError:P(w)}}if(s)try{await this.govern({groupId:x.namespaceId,op:s}),v={...v,defaultCapabilitiesSet:!0}}catch(w){v={...v,defaultCapabilitiesSet:!1,defaultCapabilitiesError:P(w)}}return v}async postGovernance(e,n,r){return(await this.json("POST",`/admin-api/groups/${g(e)}/governance-intents`,{warrant:r,authorProof:this.config.authorProof,op:y(n.bytes)})).data}checkedExecutor(e){let n={executorAccount:y(m(e.executorAccount??"","the relay's executorAccount",32)),executorKey:y(m(e.executorKey??"","the relay's executorKey",32))},r=this.config.executorAccount;if(r&&r.toLowerCase()!==n.executorAccount)throw new Error(`configured executorAccount ${r} is not the relay's account ${n.executorAccount}; a warrant naming it would be unspendable`);return n}async json(e,n,r){let o=250;for(let i=0;;i+=1)try{return await this.jsonOnce(e,n,r)}catch(s){if(!(s instanceof D&&s.status===429)||i>=this.rateLimitRetries)throw s;let c=_l(s.headers);await Ol(c??o),o*=2}}async jsonOnce(e,n,r){let o={Accept:"application/json"};r!==void 0&&(o["Content-Type"]="application/json");let i=new AbortController,s=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r===void 0?void 0:JSON.stringify(r),signal:i.signal})}catch(c){throw new D(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(!a.ok){let c=await a.text().catch(()=>"");if(a.status===400||a.status===403){let u=Ml(c);throw new he(u,/nonce/i.test(u),a.status)}throw new D(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(a.status!==204)return await a.json()}};function Ml(t){if(!t)return"no reason given";try{let e=JSON.parse(t);for(let n of[e.error,e.message])if(typeof n=="string"&&n)return n}catch{}return t}var ye=class{constructor(e,n=null){this.relay=e;this.observer=n;this.kind="relay"}get canSubscribe(){return this.observer!==null}get events(){return this.observer}get client(){return this.relay}async execute(e){let{returns:n}=await this.executeWithMetadata(e);return n}async executeWithMetadata(e){let n=await this.relay.execute(e.contextId,e.method,e.argsJson??{});return{returns:n.returns,transport:"relay",rootHash:n.rootHash}}async migrateMyEntries(e){return this.execute({contextId:e,method:"migrate_my_entries"})}async countMyPending(e){return this.execute({contextId:e,method:"count_my_pending"})}};var Kl=new TextEncoder().encode("calimero.auth.login.v1"),ns={webOrigin:0,codeSigningId:1,cli:2};function rs(t){let e=new TextEncoder;switch(t.kind){case"webOrigin":return e.encode(t.origin);case"codeSigningId":return e.encode(t.id);case"cli":return new Uint8Array(0)}}function Gl(t){return f(Uint8Array.from([ns[t.kind]]),rs(t))}function $l(t){let e=Uint8Array.from([ns[t.kind]]);if(t.kind==="cli")return e;let n=rs(t);return f(e,R(n.length),n)}async function Tn(t){let e=m(t.node,"node",32),n=m(t.challenge,"challenge",32),r=m(t.sessionKey,"sessionKey",32),o=await I(t.deviceSecret,t.signer,"deviceSecret"),i=m(o.publicKey,"signer.publicKey",32),s=C(t.issuedAt),a=C(t.expiresAt),c=await k(Kl,[e,Gl(t.audience),n,r,i,s,a]),u=await o.sign(c);return y(f(e,$l(t.audience),n,r,i,s,a,u))}var Ll=300;async function Xr(){let t=y(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:y(await re(t)),secret:t}}async function Be(t){let e=t.nodeUrl.replace(/\/+$/,""),n=t.timeoutMs??1e4,r=async(p,x)=>{let v=new AbortController,P=setTimeout(()=>v.abort(),n),w;try{let T={...x,signal:v.signal};w=t.fetch?await t.fetch(`${e}${p}`,T):await globalThis.fetch(`${e}${p}`,T)}catch(T){throw new D(0,T instanceof Error?T.name:"NetworkError",`${e}${p}`,new Headers,T instanceof Error?T.message:String(T))}finally{clearTimeout(P)}let E=await w.text().catch(()=>"");if(!w.ok)throw new D(w.status,w.statusText,`${e}${p}`,w.headers,E);return E?JSON.parse(E):{}},o=await r("/auth/challenge",{method:"GET",headers:{Accept:"application/json"}}),i=o.challenge??o.data?.challenge;if(!i)throw new Error("the node issued no challenge");let s=await Xr(),a=Math.floor(Date.now()/1e3),c=await Tn({node:t.node,audience:t.audience,challenge:i,sessionKey:s.publicKey,issuedAt:a,expiresAt:a+(t.ttlSeconds??Ll),signer:await I(t.deviceSecret,t.signer,"deviceSecret")}),u=await r("/auth/token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({auth_method:"account_proof",public_key:s.publicKey,client_name:t.clientName??e,timestamp:a,provider_data:{challenge:i,login_statement:c,account_proof:t.accountProof}})}),d=u.access_token??u.data?.access_token,l=u.refresh_token??u.data?.refresh_token;if(!d)throw new Error("the node minted no session");return{accessToken:d,refreshToken:l??"",sessionKey:s.publicKey,sessionSecret:s.secret}}var Hl=3e4;function je(){let t=globalThis.location?.origin;return t?{kind:"webOrigin",origin:t}:{kind:"cli"}}function Bl(t){try{let e=t.split(".");if(e.length!==3)return null;let n=e[1].replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4;)n+="=";let r=JSON.parse(atob(n));return typeof r.exp=="number"?r.exp*1e3:null}catch{return null}}var qe=class{constructor(e){this.session=null;this.sessionExpiresAt=null;this.pending=null;this.sseClient=null;this.wsClient=null;this.config=e}get nodeKey(){return this.config.nodeKey}async accessToken(){let e=Date.now();return this.session&&this.sessionExpiresAt!==null&&this.sessionExpiresAt-Hl>e?this.session.accessToken:(this.pending||(this.pending=this.loginNow().finally(()=>{this.pending=null})),(await this.pending).accessToken)}async loginNow(){let e=await Be({nodeUrl:this.config.nodeUrl,node:this.config.nodeKey,signer:await this.config.signer(),accountProof:this.config.accountProof,audience:this.config.audience,clientName:this.config.clientName,ttlSeconds:this.config.ttlSeconds,fetch:this.config.fetch,timeoutMs:this.config.timeoutMs});return this.session=e,this.sessionExpiresAt=Bl(e.accessToken),e}get events(){return this.sseClient||(this.sseClient=new B({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.sseClient}get ws(){return this.wsClient||(this.wsClient=new ie({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.wsClient}close(){this.sseClient?.close(),this.wsClient?.close()}};var os=new TextEncoder().encode("calimero/presence/1");async function is(t){let e=t===null?new Uint8Array([0]):f(new Uint8Array([1]),R(t.length),t);return new Uint8Array(await crypto.subtle.digest("SHA-256",e))}async function Zr(t){return f(os,m(t.contextId,"contextId",32),m(t.author,"author",32),C(t.seq),C(t.sentAtMs),await is(t.state))}var ql=2500,xt=class{constructor(e){this.timers=new Map;this.lastSeq=new Map;this.refused=new Set;this.generation=new Map;this.relay=e.relay,this.events=e.events,this.heartbeatMs=e.heartbeatMs??ql,this.now=e.now??Date.now}async set(e,n,r=se()){let o=this.bump(e);this.refused.delete(e);let i=n===null?null:new Uint8Array(r.encode(n));await this.send(e,i),!(i===null||this.refused.has(e))&&this.generation.get(e)===o&&this.timers.set(e,setInterval(()=>{this.send(e,i).catch(()=>{})},this.heartbeatMs))}subscribe(e,n,r=se()){return Jt(this.events(),e,n,r)}close(){for(let e of new Set([...this.timers.keys(),...this.generation.keys()]))this.bump(e)}bump(e){this.stop(e);let n=(this.generation.get(e)??0)+1;return this.generation.set(e,n),n}stop(e){let n=this.timers.get(e);n!==void 0&&clearInterval(n),this.timers.delete(e)}nextSeq(e){let n=Math.max(this.now(),(this.lastSeq.get(e)??0)+1);return this.lastSeq.set(e,n),n}async send(e,n){if(this.refused.has(e))return;let r=await this.relay.authorSigner(),o=this.nextSeq(e),i=this.now(),s=await Zr({contextId:e,author:r.publicKey,seq:BigInt(o),sentAtMs:BigInt(i),state:n}),a=y(await r.sign(s));try{await this.relay.presenceIntent(e,{state:n===null?null:y(n),seq:o,sentAtMs:i,signature:a,authorProof:this.relay.authorProof})}catch(c){let u=c.status;if(u===void 0||u===0||u===429||u>=500)return;throw this.refused.add(e),this.stop(e),c}}};function ss(t,e){return new Error(`this client was constructed with the relay transport, which has no ${t}: ${e}. Construct a node client (createMeroClient({ baseUrl })) for that surface \u2014 nothing here will silently connect to a node you did not choose.`)}function as(t){return new Error(`this relay-transport client cannot open ${t}: it was given no relay node key. A relay is an ordinary node and does serve /sse and /ws \u2014 but the login statement must be signed against the node's device signing key, learned out of band (never read from the node, and never derived from its peerId). Pass it as \`observe: { nodeKey }\`. For a cloud-hosted relay the cloud does not publish it yet \u2014 see mdma #312.`)}function jl(t,e,n){let r=e?.nodeKey;return r?new qe({nodeUrl:e?.nodeUrl??t.relayUrl,nodeKey:r,accountProof:e?.accountProof??t.authorProof,audience:e?.audience??je(),signer:e?.signer?async()=>e.signer:()=>t.authorSigner(),clientName:e?.clientName,ttlSeconds:e?.ttlSeconds,fetch:e?.fetch??n,timeoutMs:e?.timeoutMs}):null}var we=class{constructor(e){this.relayObserver=null;this.relayAdmin=null;this.proofAuthorizer=null;this.relayUrl=null;this.proofEvents=null;this.relayFetch=void 0;this.relayPresence=null;if(e.transport==="relay"){this.transport="relay",this.nodeClient=null;let o=e.fetch;this.relayFetch=o;let i=e.relay instanceof W?e.relay:new W({...e.relay,fetch:e.relay.fetch??o});if(this.relayObserver=jl(i,e.observe,o),this.rpcTransport=new ye(i,this.relayObserver),this.relayUrl=i.relayUrl,e.proof&&(this.proofAuthorizer=gr(e.proof)),e.session){let s=e.session;this.relayAdmin=Bo({baseUrl:i.relayUrl,getAuthToken:typeof s=="string"?async()=>s:s,fetch:o})}else if(this.proofAuthorizer){let s=this.proofAuthorizer;this.relayAdmin=qt(ot({fetch:(a,c)=>o?o(a,c):globalThis.fetch(a,c),baseUrl:i.relayUrl,authorizeRequest:s}),{baseUrl:i.relayUrl})}return}this.transport="node";let{transport:n,...r}=e;this.nodeClient=new Fe(r),this.rpcTransport=this.nodeClient.rpc}get rpc(){return this.rpcTransport}get canSubscribe(){return this.rpcTransport.canSubscribe||this.proofAuthorizer!==null}get node(){if(!this.nodeClient)throw ss("node connection","it holds a signing key and a relay URL, not a node");return this.nodeClient}get relay(){if(!(this.rpcTransport instanceof ye))throw new Error("this client was constructed with the node transport and has no relay");return this.rpcTransport.client}get admin(){if(this.nodeClient)return this.nodeClient.admin;if(this.relayAdmin)return this.relayAdmin;throw new Error("this relay-transport client has no admin surface because it was given neither a `proof` nor a `session`. A warrant authorises one intent and is not a credential for reading. The caller-scoped reads (getContexts, listNamespaces) want one of the other two: pass `proof: { credential, deviceSecret }` \u2014 the device cert you already hold, which needs no login and no node key \u2014 or a `session` minted with `login()`. Context STATE reads work through execute/query either way.")}get auth(){return this.node.auth}get events(){if(this.nodeClient)return this.nodeClient.events;if(this.relayObserver)return this.relayObserver.events;if(this.proofAuthorizer&&this.relayUrl)return this.proofEvents??(this.proofEvents=new B({baseUrl:this.relayUrl,authorize:this.proofAuthorizer,fetch:this.relayFetch})),this.proofEvents;throw as("SSE events")}get ws(){if(this.nodeClient)return this.nodeClient.ws;if(this.relayObserver)return this.relayObserver.ws;throw this.proofAuthorizer?new Error("this client authenticates with a request proof, which cannot open a WebSocket from a browser: `WebSocket` cannot set the X-Calimero-Proof header, and core's guard reads the proof from a header only (the ?token= query parameter is the session equivalent and has no proof counterpart). Use `client.events` \u2014 SSE is fetch-based, carries the header, and is the recommended transport anyway."):as("WebSocket events")}get ephemeral(){return this.nodeClient?this.nodeClient.ephemeral:(this.relayPresence??(this.relayPresence=new xt({relay:this.relay,events:()=>this.events})),this.relayPresence)}get cloud(){if(!this.nodeClient)throw ss("bundled cloud client","a relay client is built from a cloud connection rather than owning one \u2014 reach it through the `cloud` field that `connectCloud` returns, or construct a `CloudClient` directly");return this.nodeClient.cloud}close(){this.nodeClient?.close(),this.relayObserver?.close(),this.proofEvents?.close()}};function Dn(t){return new we(t)}var no="calimero.delegated.connection",ro="calimero.delegated.credential";function oo(){if(typeof sessionStorage>"u")return null;try{let t=sessionStorage.getItem(no);return t?JSON.parse(t):null}catch{return null}}function ls(t){try{sessionStorage.setItem(no,JSON.stringify(t))}catch{}}function us(){try{sessionStorage.removeItem(no)}catch{}}function ds(){let t=oo();if(t){let{account:e,credential:n,deviceSecret:r}=t;return{account:e,credential:n,deviceSecret:r}}if(typeof sessionStorage>"u")return null;try{let e=sessionStorage.getItem(ro);if(!e)return null;let n=JSON.parse(e);return!n.account||!n.credential||!n.deviceSecret?null:n}catch{return null}}function ps(t){try{sessionStorage.setItem(ro,JSON.stringify(t))}catch{}}function gs(){try{sessionStorage.removeItem(ro)}catch{}}function io(t){let e=Un(t);return{next:async()=>{let n=0n;try{n=ms(t)}catch{n=0n}try{localStorage.setItem(e,String(n+1n))}catch{}return n}}}function Un(t){return`calimero.nonce.${t}`}function ms(t){let e=localStorage.getItem(Un(t));if(e!==null)return BigInt(e);let n=`${Un(t)}.`,r=0n;for(let o=0;o<localStorage.length;o++){let i=localStorage.key(o);if(!i?.startsWith(n))continue;let s=BigInt(localStorage.getItem(i)??"0");s>r&&(r=s)}return r}function _n(t,e,n){try{ms(t)<=n&&localStorage.setItem(Un(t),String(n+1n))}catch{}}var fs="calimero.delegated.relay-node-key.";function X(t){return t.replace(/\/+$/,"")}function so(t,e){localStorage.setItem(fs+X(t),e.trim().toLowerCase())}function Mn(t){try{let e=localStorage.getItem(fs+X(t));return e&&/^[0-9a-f]{64}$/.test(e)?e:null}catch{return null}}function ao(t){try{let{hostname:e}=new URL(t);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch{return!1}}var Fl="locked-read-only",Vl="2.3.99",eo;function Wl(t){let e=t,n=typeof e.verify=="function"?e.verify:e.default?.verify;if(typeof n!="function")throw new TypeError("@phala/dcap-qvl loaded without a verify function");return n}var Ve=class extends Error{constructor(n,r){super(`${n}: ${r instanceof Error?r.message:String(r)}`);this.step=n;this.cause=r;this.name="RelayKeyTransportError"}};async function cs(t,e){try{return await e()}catch(n){throw n instanceof Ve?n:new Ve(t,n)}}function Jl(t){return async(e,n)=>{let r;try{r=await globalThis.fetch(e,n)}catch(o){throw t.failure=o,new Ve(`reaching ${String(e)}`,o)}return r.ok||(t.failure??(t.failure=new Error(`${String(e)} answered HTTP ${r.status}`))),r}}function hs(t,e){return Object.assign(async r=>{let o=await cs("loading the quote verifier",()=>(eo??(eo=import("@phala/dcap-qvl").then(i=>Wl(i),i=>{throw eo=void 0,i})),eo));return dn({dcapVerify:o,release:()=>cs("fetching the release the relay runs",async()=>cn(un(an,await ln(t,{fetch:e})))),profile:Fl,minReleaseVersion:Vl})(r)},{includeCollateral:!0})}async function We(t,e={}){let n=e.fresh?null:Mn(t);if(n)return{kind:"learned",nodeKey:n};let r={failure:null},o=Jl(r);try{let i=ao(t),{nodeKey:s}=await nn({relayUrl:t,allowMock:i,fetch:o,...i?{}:{verify:hs(t,o)}});return so(t,s),{kind:"learned",nodeKey:s}}catch(i){return i instanceof Ve||r.failure?{kind:"unavailable",error:i}:{kind:"refused",error:i}}}async function Kn(t){let e=await We(t);return e.kind==="learned"?e.nodeKey:(console.warn("[mero-js] could not learn the relay node key from its attestation",e.error),null)}var On=[1e3,2e3,5e3,1e4,3e4];function zl(t,e){return new Promise(n=>{if(e?.aborted)return n();let r=setTimeout(o,t);function o(){clearTimeout(r),e?.removeEventListener("abort",o),n()}e?.addEventListener("abort",o)})}async function ys(t,e={}){let{signal:n}=e;for(let r=0;!n?.aborted;r+=1){let o=await We(t);if(o.kind==="learned")return o.nodeKey;if(o.kind==="refused")return console.warn("[mero-js] refusing the relay's attestation; its node key stays unknown",o.error),null;let i=On[Math.min(r,On.length-1)];console.warn(`[mero-js] could not reach what proves the relay's node key; retrying in ${i/1e3} s`,o.error),await zl(i,n)}return null}function Ql(t){try{let e=JSON.parse(atob(t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")));return typeof e.exp=="number"?e.exp*1e3:null}catch{return null}}var to=new Map;function ws(){to.clear()}async function Yl(t){if(t.status!==403)return!1;try{return(await t.clone().json()).error?.code==="sealed_route_unguarded"}catch{return!1}}function Xl(t){return t.headers.has("authorization")||new URL(t.url).pathname.startsWith("/auth/")}function Zl(t){let e=(o,i)=>globalThis.fetch(o,i),n=fe({baseUrl:t,verify:hs(t,e),fetch:e}),r=!1;return async(o,i)=>{let s=new Request(o,i);if(r&&Xl(s))return e(s);let a=await n(s.clone());return await Yl(a)?(r||(r=!0,console.warn(`[mero-js] ${X(t)} cannot guard logged-in calls sealed (no forward_auth); they go over its TLS until it does`)),e(s)):a}}function Je(t){if(ao(t))return;let e=X(t),n=to.get(e);return n||(n=Zl(t),to.set(e,n)),n}function eu(t,e){let n=null,r=null;return async()=>{let o=n?Ql(n):null;return n&&(o===null||o-Date.now()>3e4)?n:(r||(r=Be({nodeUrl:t.relayUrl,fetch:Je(t.relayUrl),node:e,deviceSecret:t.deviceSecret,accountProof:t.credential,audience:je()}).then(i=>(n=i.accessToken,n)).catch(i=>{console.warn("[mero-js] relay login failed",i),n=null}).finally(()=>{r=null})),r)}}var Nn=new Map;function bs(){Nn.clear()}function tu(t){return typeof t=="object"&&t!==null&&t.status===409}function nu(t,e){let n=t.rpc,r=X(e),o=async i=>{let s=`${r}|${i.contextId}|${i.method}`;if(Nn.get(s)!=="write")try{let{returns:a}=await t.admin.queryContext(i.contextId,{method:i.method,argsJson:i.argsJson??{}});return Nn.set(s,"read"),{returns:a,transport:"relay"}}catch(a){tu(a)&&Nn.set(s,"write")}return n.executeWithMetadata(i)};return{get kind(){return n.kind},get canSubscribe(){return n.canSubscribe},execute:async i=>(await o(i)).returns,executeWithMetadata:o,migrateMyEntries:i=>n.migrateMyEntries(i),countMyPending:i=>n.countMyPending(i)}}function ru(t){return new B({baseUrl:t,authorize:async()=>({}),fetch:(e,n)=>new Promise((r,o)=>{let i=()=>o(Object.assign(new Error("the stream was closed before the relay was attested"),{name:"AbortError"}));if(n?.signal?.aborted)return i();n?.signal?.addEventListener("abort",i,{once:!0})})})}function ou(t,e){let n=e.session?nu(t,e.relayUrl):null,r=null;return new Proxy(t,{get(o,i){if(i==="rpc"&&n)return n;if(!e.attested){if(i==="canSubscribe")return!1;if(i==="events")return r??(r=ru(e.relayUrl));if(i==="close")return()=>{r?.close(),o.close()}}let s=Reflect.get(o,i,o);return typeof s=="function"?s.bind(o):s}})}function Gn(t,e){if(!t.relayUrl)return null;let n=Mn(t.relayUrl),r=Dn({transport:"relay",fetch:Je(t.relayUrl),relay:{relayUrl:t.relayUrl,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:io(t.relayUrl)},proof:{credential:t.credential,deviceSecret:t.deviceSecret},session:n?eu({...t,relayUrl:t.relayUrl},n):void 0,observe:n?{nodeKey:n}:void 0});return ou(r,{relayUrl:t.relayUrl,session:n!==null,attested:n!==null||ao(t.relayUrl)})}var As="calimero.delegated.relays.";function q(t){try{let e=localStorage.getItem(As+t),n=e?JSON.parse(e):{};return{namespaces:n.namespaces??{},contexts:n.contexts??{}}}catch{return{namespaces:{},contexts:{}}}}function co(t,e){try{localStorage.setItem(As+t,JSON.stringify(e))}catch{}}function be(t,e,n){let r=q(t),o=X(e);n.namespaceId&&(r.namespaces[n.namespaceId]=o),n.contextId&&(r.contexts[n.contextId]=o),co(t,r)}function xs(t,e){return q(t).contexts[e]??null}function $n(t,e){return e.executorAccount||!t?.executorAccount||!t.relayUrl||!e.relayUrl||X(t.relayUrl)!==X(e.relayUrl)?e:{...e,executorAccount:t.executorAccount}}function ze(t){let e=q(t.account),n=[t.relayUrl,...Object.values(e.namespaces),...Object.values(e.contexts)].filter(r=>typeof r=="string"&&r.length>0).map(X);return[...new Set(n)]}async function vs(t){let e=[],n=q(t.account);for(let r of ze(t))try{if(!await Kn(r))continue;let o=Gn({...t,relayUrl:r},null);if(!o)continue;let{contexts:i}=await o.admin.getContexts();for(let s of i??[])e.push({...s,relayUrl:r}),n.contexts[s.id]=r}catch(o){console.warn(`[mero-js] could not list contexts on ${r}`,o)}return co(t.account,n),e}async function Rs(t){var o,i;let e=[],n=new Set,r=q(t.account);for(let s of ze(t))try{if(!await Kn(s))continue;let a=Gn({...t,relayUrl:s},null);if(!a)continue;for(let c of await a.admin.listNamespaces())n.has(c.namespaceId)||(n.add(c.namespaceId),e.push({...c,relayUrl:s}),(o=r.namespaces)[i=c.namespaceId]??(o[i]=s))}catch(a){console.warn(`[mero-js] could not list namespaces on ${s}`,a)}return co(t.account,r),e}function Hn(t=1){let e=BigInt(t);if(e<1n)throw new Error("nonce sequence starts at 1");return{next(){let n=e;return e+=1n,Promise.resolve(n)},advanceTo(n){return n>e&&(e=n),Promise.resolve()}}}function vt(t,e){let n=e??globalThis.localStorage;if(!n)throw new Error("no localStorage in this runtime: pass a storage implementation, or use createMemoryNonceSource for a process that owns its whole sequence");let r=()=>{let o=n.getItem(t);if(o===null||o==="")return 0n;try{let i=BigInt(o);return i>0n?i:0n}catch{return 0n}};return{next(){let o=r()+1n;return n.setItem(t,o.toString()),Promise.resolve(o)},advanceTo(o){let i=o>0n?o-1n:0n;return i>r()&&n.setItem(t,i.toString()),Promise.resolve()}}}function iu(t){return{getWarrantNonce:(e,n)=>t.client.getWarrantNonceAsAuthor(e,t.authorProof)}}var Ln=class extends Error{constructor(n,r){super(`author device ${r} has spent every nonce in context ${n}; it must re-key to write again`);this.contextId=n;this.authorDeviceKey=r;this.name="WarrantNonceExhaustedError"}};function su(t){let e=Array.isArray(t.lookups)?t.lookups:[t.lookups];if(e.length===0)throw new Error("a recovering nonce source needs at least one node to ask");let n=t.local??Hn(1),r=t.onLookupFailure??"throw",o=null,i=null,s=async()=>{let a=await Promise.allSettled(e.map(d=>d.getWarrantNonce(t.contextId,t.authorDeviceKey))),c=null,u=!1;for(let d of a){if(d.status!=="fulfilled")continue;let l=d.value;if(l.kind==="exhausted"){u=!0;continue}(c===null||l.nextNonce>c)&&(c=l.nextNonce)}if(c===null&&u)throw new Ln(t.contextId,t.authorDeviceKey);if(c===null){let d=a.find(p=>p.status==="rejected"),l=d&&d.status==="rejected"?d.reason:void 0;if(r==="local"){o=0n;return}throw l instanceof Error?l:new Error(`no node could answer where the warrant-nonce sequence stands: ${String(l)}`)}o=c,await n.advanceTo?.(c)};return{async next(){o===null&&(i??(i=s().finally(()=>{i=null})),await i);let a=await n.next(),c=o!==null&&o>a?o:a;return o=c+1n,c},async advanceTo(a){(o===null||a>o)&&(o=a),await n.advanceTo?.(a)}}}async function Cs(t){if(!t.sessionToken&&!t.googleIdToken)throw new Error("connectCloud needs either a sessionToken or a googleIdToken");let e=await I(t.deviceSecret,t.signer,"deviceSecret"),n=new $({cloudBaseUrl:t.cloudBaseUrl,sessionToken:t.sessionToken,onSession:t.onSession,fetch:t.fetch,timeoutMs:t.timeoutMs});!t.sessionToken&&t.googleIdToken&&await n.signInWithGoogle(t.googleIdToken);let r=await n.getMyNamespaces(),o=cu(r,t.namespaceId),i=await n.getNamespaceRelays(o.namespaceId),s=lo(i);if(!s)throw new Error(lu(o,i));let a=new W({relayUrl:s.relayUrl,executorAccount:s.executorAccount,authorAccount:t.authorAccount,authorProof:t.authorProof,signer:e,nonces:t.nonces??uu(e.publicKey),ttlSeconds:t.ttlSeconds,fetch:t.seal?fe({baseUrl:s.relayUrl,verify:t.seal,fetch:t.fetch}):t.fetch,timeoutMs:t.timeoutMs});return{cloud:n,relay:a,namespaceId:o.namespaceId,namespace:o,relayInfo:s,execute:(c,u,d)=>a.execute(c,u,d),client:new we({transport:"relay",relay:a,observe:{nodeKey:t.relayNodeKey??s.nodeKey,audience:t.observeAudience,fetch:t.fetch,timeoutMs:t.timeoutMs}})}}async function au(t){let{root:e,authorAccount:n,...r}=t,o=await I(r.deviceSecret,r.signer,"deviceSecret"),i=await Y(e),a=await new $({cloudBaseUrl:t.cloudBaseUrl,onSession:t.onSession,fetch:t.fetch,timeoutMs:t.timeoutMs}).signInWithAccount(i.signer);return Cs({...r,deviceSecret:void 0,signer:o,sessionToken:a.sessionToken,authorAccount:n??i.accountId})}function cu(t,e){if(e){let n=t.find(r=>r.namespaceId===e);if(!n)throw new Error(`this account owns no namespace ${e}; it owns: ${t.map(r=>r.namespaceId).join(", ")||"(none)"}`);return n}if(t.length===0)throw new Error("this account owns no namespaces in the cloud: claim one first, then enable HA on it so a relay is assigned");if(t.length>1)throw new Error(`this account owns ${t.length} namespaces \u2014 pass namespaceId to say which: ${t.map(n=>n.namespaceId).join(", ")}`);return t[0]}function lu(t,e){if(e.length===0)return t.haStatus==="enabled"?`namespace ${t.namespaceId} has HA enabled but no relay has been assigned to it yet \u2014 retry shortly`:`namespace ${t.namespaceId} has no relays: enable HA on it in the cloud to have an attested node assigned`;let n=e.filter(o=>o.teeRole!==null&&o.teeRole!=="RelayTee");if(n.length===e.length)return`every node on namespace ${t.namespaceId} is a read-only TEE replica (ReadOnlyTee), which never relays delegated writes: an admin of the namespace must set its TEE admission policy with mode: 'relay' \u2014 AdminClient.setTeeAdmissionPolicy(namespaceId, { ..., mode: 'relay' }) \u2014 so fleet nodes are admitted as RelayTee`;let r=e.filter(o=>o.teeRole===null&&!o.authorshipReady);return r.length>0&&r.length+n.length===e.length?`every relay on namespace ${t.namespaceId} is waiting for the authorship grant: an admin of the namespace must grant CAN_AUTHOR_ON_BEHALF to ${r.map(o=>o.executorAccount??o.peerId).join(", ")||"the relay account"} \u2014 with AdminClient.grantAuthorship(namespaceId, account) for these relays, and AdminClient.openToDelegatedExecution(namespaceId) so relays assigned later need no further op`:`namespace ${t.namespaceId} has ${e.length} relay(s), but none is ready to relay yet (a URL, an executor account and a recent heartbeat) \u2014 retry shortly`}function uu(t){let e=`mero-js:warrant-nonce:${t}`;try{return vt(e)}catch{return Hn(1)}}var du=new TextEncoder().encode("calimero.mdma.routing-read.v1\0");async function Ss(t,e){m(e,"deviceSecret",32);let n=await ne(e),r=f(du,new TextEncoder().encode(t)),o=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,r));return pu(o)}async function Bn(t,e){return{"X-Calimero-Credential":e.credential,"X-Calimero-Nonce":t.nonce,"X-Calimero-Signature":await Ss(t.nonce,e.deviceSecret)}}function pu(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var Es="calimero.cloud.link.pending",uo="link_state";var po=/^[0-9a-f]{64}$/;function ks(t){try{let e=localStorage.getItem(Es),n=e?JSON.parse(e):{};return Object.fromEntries(Object.entries(n).filter(([,r])=>r&&typeof r.expiresAt=="number"&&r.expiresAt>t))}catch{return{}}}function Is(t){try{localStorage.setItem(Es,JSON.stringify(t))}catch{}}function qn(t,e){if(!po.test(t))throw new Error("accountId must be 64 lowercase hex characters");let n=new URL(e),r=Date.now(),o=ks(r),i=crypto.getRandomValues(new Uint8Array(16)),s=Array.from(i,a=>a.toString(16).padStart(2,"0")).join("");return o[s]={account:t,expiresAt:r+6e5},Is(Object.fromEntries(Object.entries(o).slice(-20))),n.searchParams.set(uo,s),n.toString()}function Qe(t){let e=new URLSearchParams(t).get(uo),n=ks(Date.now());if(!e||!Object.prototype.hasOwnProperty.call(n,e))return null;let r=n[e];return delete n[e],Is(n),r}function Ps(t){let e=new URLSearchParams(t);e.delete(uo);let n=e.toString();return n?`?${n}`:""}var gu="https://cloud.calimero.network";function Ts(t){let e=new URL(t.cloudWebUrl??gu);return e.searchParams.set("link-account",t.accountId),e.searchParams.set("callback-url",qn(t.accountId,t.returnTo)),e.toString()}function mu(t){throw window.location.assign(Ts(t)),new Error("redirecting to the cloud to authorise this link")}function fu(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Qe(t.search??""),go(),new Error(n==="denied"?"the account link was declined at the cloud":`the cloud refused this link: ${n}`);let r=e.get("grant"),o=e.get("account");if(!r||!o)return null;if(Qe(t.search??"")?.account!==o)throw go(),new Error("this account link answers a request this browser did not make - start the link again from here");return go(),{grant:r,account:o}}function go(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+Ps(location.search))}async function hu(t){let e=await Y(t.root);if(e.accountId!==t.account)throw new Error(`this grant is for account ${t.account}, but the root here derives ${e.accountId} \u2014 it was minted for a different account`);return new $({cloudBaseUrl:t.cloudBaseUrl,fetch:t.fetch}).linkAccountWithGrant({grant:t.grant,signer:e.signer})}var yu="enrol-device",wu="enrol-kem",bu="callback-url",Au="state";function Us(t){Ns(t.devicePublicKey,"devicePublicKey"),Ns(t.kemPublicKey,"kemPublicKey"),Su(t.returnTo),Cu(t.returnTo);let e=new URL(t.walletUrl);return e.searchParams.set(yu,t.devicePublicKey),e.searchParams.set(wu,t.kemPublicKey),e.searchParams.set(bu,t.returnTo),t.state&&e.searchParams.set(Au,t.state),e.toString()}function xu(t){throw window.location.assign(Us(t)),new Error("redirecting to the wallet to approve this device")}function vu(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Ds(),new Error(n==="denied"||n==="cancelled"?"the device was not approved at the wallet":`the wallet refused this enrolment: ${n}`);let r=e.get("credential"),o=e.get("account"),i=e.get("device");if(!r||!o||!i)return null;Ds();let s=e.get("state");return{credential:r,account:o,device:i,...s?{state:s}:{}}}function Ds(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+location.search)}async function Ru(t){if(t.expectState!==void 0&&t.expectState!==t.state)throw new Error("this enrolment answers a request this app did not make \u2014 the state it carries is not the one sent");let e=await Qt(t.credential);if(e.signPublicKey!==Ae(t.devicePublicKey))throw new Error(`this credential certifies device key ${e.signPublicKey}, but this app holds ${Ae(t.devicePublicKey)} \u2014 it would sign with a key the certificate does not cover`);if(t.kemPublicKey!==void 0&&e.kemPublicKey!==Ae(t.kemPublicKey))throw new Error(`this credential names delivery key ${e.kemPublicKey}, not the one this app asked about \u2014 group keys would be sealed to somebody else`);if(e.account!==Ae(t.account))throw new Error(`the wallet reported account ${Ae(t.account)}, but the credential names ${e.account}`);if(e.device!==Ae(t.device))throw new Error(`the wallet reported device ${Ae(t.device)}, but the credential names ${e.device}`);return{credential:t.credential,account:e.account,device:e.device,certificate:e}}function Ns(t,e){if(!/^[0-9a-f]{64}$/.test(t))throw new Error(`${e} must be 64 lowercase hex characters`)}function Ae(t){return t.trim().toLowerCase()}function Os(t,e){let n=e??(typeof window>"u"?void 0:window.location.origin);if(!n)return!1;try{return new URL(t).origin!==n}catch{return!1}}function Cu(t){Os(t)&&console.warn(`[calimero] enrolling a device but sending the credential to ${new URL(t).origin}, which is not this page's origin. Legitimate when deliberate; worth a second look otherwise.`)}function Su(t){let e;try{e=new URL(t)}catch{throw new Error(`returnTo must be an absolute URL, got ${t}`)}let n=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]"||e.hostname==="::1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new Error(`returnTo must be https:, or http: on localhost \u2014 got ${e.protocol}//${e.hostname}`)}function jn(t){if(!t)return null;let e=t.trim().toLowerCase(),n=e.startsWith("0x")?e.slice(2):e;return n.length>0?n:null}function ku(t,e){if(e.size===0)return!0;let n=jn(t.account);return n!==null&&e.has(n)}async function Fn(t){let e=t.cloud??new $({cloudBaseUrl:t.cloudBaseUrl,routingCredential:{credential:t.credential,deviceSecret:t.deviceSecret}}),n,r;try{let p=await e.getNamespaceRouting(t.namespaceId);n=p.nodes,r=p.servable}catch(p){return{ok:!1,step:"admitters-lookup",reason:`The cloud could not be asked which nodes serve namespace ${t.namespaceId}: ${p instanceof Error?p.message:String(p)}. Nothing is known about the invitation yet \u2014 this is the lookup failing, not the invitation.`}}if(n.length===0)return{ok:!1,step:"no-nodes",reason:"The cloud lists no nodes serving this namespace, so there is no hosted node to be admitted through. The namespace has no fleet assignment \u2014 whoever invited you is running their own node, and admission has to go through a node the cloud routes to."};let o=new Set((t.admitters??[]).map(jn).filter(p=>p!==null)),i=n.filter(p=>ku(p,o));if(i.length===0)return{ok:!1,step:"not-invited",reason:`${n.length} node${n.length===1?"":"s"} serve this namespace, but your invitation names none of them. The signed admitter list is a snapshot from when the invitation was minted, so a node assigned since is healthy and will still refuse the claim. Ask for a fresh invitation.`};let s=i.filter(p=>p.canAdmit),a=s.length>0?s:i,c=s.length===0||!r,u=a.filter(p=>typeof p.relayUrl=="string"&&p.relayUrl.length>0),[d]=u;if(d===void 0)return{ok:!1,step:"no-relay-url",reason:"A node your invitation names can admit you, but the cloud knows no address for it yet, so there would be nothing to connect through afterwards. Try again shortly."};let l=u.find(p=>p.canExecute)??u.find(p=>p.fresh)??d;return{ok:!0,relayUrl:l.relayUrl,admitUrl:l.admitUrl??`${l.relayUrl.replace(/\/+$/,"")}/admin-api/namespaces/${g(t.namespaceId)}/admit`,admitterAccount:l.account,peerId:l.peerId,writable:l.canExecute,stale:!l.fresh||c}}var Vn=1440*60,fo={Admin:0,Member:1,ReadOnly:2};function kt(t){let e=t.admitters??[];return f(mo(t.inviter_identity,"inviter_identity"),mo(t.group_id,"group_id"),C(t.expiration_timestamp),mo(t.secret_salt,"secret_salt"),new Uint8Array([t.invited_role]),R(e.length),...e.map((n,r)=>m(n,`admitters[${r}]`,32)))}async function ho(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",kt(t)))}function yo(t){return[...new Set(t.filter(n=>n.role==="Admin").map(n=>n.identity.toLowerCase()))].sort()}async function Wn(t){let e=await I(t.deviceSecret,t.signer,"deviceSecret"),n=m(e.publicKey,"signer.publicKey",32),r=m(t.groupId,"groupId",32);m(t.inviterAccount,"inviterAccount",32);let o=[...t.admitters??[]].map(p=>p.trim().toLowerCase());if(o.length===0){if(!t.members)throw new Error("name the admitters, or pass the group members to default them to its admins: an invitation with no admitters is claimable by broadcast");if(o=yo(t.members),o.length===0)throw new Error("the member list names no admin, so there is nobody to default the admitters to")}o.forEach((p,x)=>m(p,`admitters[${x}]`,32));let i=t.invitedRole??fo.Member;if(![0,1,2].includes(i))throw new Error(`invitedRole must be 0 (Admin), 1 (Member) or 2 (ReadOnly), got ${i}`);let s=t.now??Math.floor(Date.now()/1e3),a=Math.min(t.validForSecs??Vn,Vn);if(!Number.isInteger(a)||a<=0)throw new Error(`validForSecs must be a positive whole number, got ${t.validForSecs}`);let c=t.nonce??crypto.getRandomValues(new Uint8Array(32));if(c.length!==32)throw new Error(`nonce must be 32 bytes, got ${c.length}`);let u={inviter_identity:Array.from(n),group_id:Array.from(r),expiration_timestamp:s+a,secret_salt:Array.from(c),invited_role:i,admitters:o},d=await e.sign(await ho(u));if(d.length!==64)throw new Error(`signer returned ${d.length} bytes, expected a 64-byte Ed25519 signature`);let l={invitation:u,inviter_signature:y(d),inviter_account:t.inviterAccount.trim().toLowerCase()};return t.admitterAddrs?.length&&(l.admitter_addrs=[...t.admitterAddrs]),t.applicationId&&(l.application_id=Array.from(m(t.applicationId,"applicationId",32))),t.appKey&&(l.app_key=Array.from(m(t.appKey,"appKey",32))),l}function mo(t,e){if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return new Uint8Array(t)}var wo=25,Iu=new TextEncoder().encode("calimero.namespace.v1"),Pu=0,_s={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreatedV2:9,MemberJoinedViaTeeAttestation:10};function Ms(t,e){if(t==null)return new Uint8Array([0]);if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return f(new Uint8Array([1]),new Uint8Array(t))}function Ks(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}function Jn(t){let e=t.invitation,n=t.admitter_addrs??[];return f(kt(e),Ks(t.inviter_signature),t.inviter_account?f(new Uint8Array([1]),m(t.inviter_account,"inviter_account",32)):new Uint8Array([0]),R(n.length),...n.map(Ks),Ms(t.application_id,"application_id"),Ms(t.app_key,"app_key"))}async function zn(t){let e=t.parentOpHashes??[],n=m(t.credential,"credential",t.credential.length/2),r=BigInt(t.invitation.invitation.expiration_timestamp??0)!==0n,o=t.joinedAt??BigInt(Math.floor(Date.now()/1e3)),i=r?f(new Uint8Array([_s.MemberJoinedAt]),m(t.member,"member",32),Jn(t.invitation),C(o),n):f(new Uint8Array([_s.MemberJoined]),m(t.member,"member",32),Jn(t.invitation),n),s=f(new Uint8Array([Pu]),i),a=await I(t.deviceSecret,t.signer,"deviceSecret"),c=m(a.publicKey,"signer.publicKey",32),u=f(new Uint8Array([wo]),m(t.namespaceId,"namespaceId",32),R(e.length),...e.map((p,x)=>m(p,`parentOpHashes[${x}]`,32)),c,C(t.nonce),s),d=await a.sign(f(Iu,u)),l=new Uint8Array([0]);return y(f(u,d,l))}function Tu(t,e){let n=e?`: ${e}`:"";switch(t){case 400:return`The node refused the join as malformed (400)${n}. The signature covers the invitation exactly as sent, so an edited or re-serialised invitation fails here \u2014 as does a namespace id that is not the invitation's own group.`;case 403:return`The node refused to carry this join (403)${n}. Either it is not in the invitation's signed admitters list \u2014 being live and listed by the cloud is not the same thing \u2014 or the invitation itself was rejected as expired or not the inviter\u2019s to issue.`;case 409:return`That node holds no device of its own, so it cannot endorse anyone (409)${n}. Another admitter from the same invitation would work.`;default:return`The join was not published (HTTP ${t})${n}.`}}function Du(t){let e=vt(`calimero.delegated.joinnonce.${t}`);return()=>e.next()}function Gs(t){return t.replace(/\/+$/,"")}async function Qn(t){let{account:e,credential:n,deviceSecret:r}=t.credential,o;try{o=await zn({namespaceId:t.namespaceId,member:e,invitation:t.invitation,credential:n,deviceSecret:r,nonce:await(t.deps?.nonce??Du(e))()})}catch(l){return{ok:!1,step:"sign",reason:`The join op could not be signed, so nothing was sent: ${l instanceof Error?l.message:String(l)}`}}let i={invitation:t.invitation,signedOp:o},s=t.admitUrl??`${Gs(t.nodeUrl)}/admin-api/namespaces/${g(t.namespaceId)}/admit`,a=t.deps?.fetch??fetch,c;try{c=await a(s,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(i)})}catch(l){return{ok:!1,step:"admit",reason:`The admitter at ${t.nodeUrl} could not be reached: ${l instanceof Error?l.message:String(l)}. The invitation is untouched \u2014 this is the node being unreachable, not a refusal.`}}let u=await c.text();if(!c.ok)return{ok:!1,step:"admit",status:c.status,reason:Tu(c.status,u)};let d=!1;try{d=(u?JSON.parse(u):{}).data?.published===!0}catch{d=!1}return{ok:!0,published:d,session:{relayUrl:Gs(t.nodeUrl),account:e,credential:n,deviceSecret:r}}}async function Yn(t){let e=t.deps?.resolve??Fn,n=t.deps?.join??Qn,r=null,o=t.nodeUrl,i;if(!o){let a=await e({namespaceId:t.namespaceId,admitters:t.invitation.invitation.admitters,credential:t.credential.credential,deviceSecret:t.credential.deviceSecret,cloudBaseUrl:t.cloudBaseUrl});if(a.ok===!1)return a;r=a,o=a.relayUrl,i=a.admitUrl}let s=await n({nodeUrl:o,admitUrl:i,namespaceId:t.namespaceId,invitation:t.invitation,credential:t.credential,deps:{fetch:t.deps?.fetch,nonce:t.deps?.nonce}});return s.ok===!1?s:{ok:!0,published:s.published,relay:r,session:s.session}}async function $s(t,e,n,r){let i=await(r.bootstrap??Yn)({namespaceId:e,invitation:n,credential:{account:t.account,credential:t.credential,deviceSecret:t.deviceSecret},cloudBaseUrl:r.cloudBaseUrl});if(i.ok===!1)throw Object.assign(new Error(i.reason),{step:i.step,...i.status!==void 0?{status:i.status}:{}});return i.session.relayUrl&&be(t.account,i.session.relayUrl,{namespaceId:e}),r.onJoined($n(t,i.session)),{namespaceId:e}}function Ls(t){let e=new TextEncoder().encode(t),n=new Uint8Array(4+e.length);return new DataView(n.buffer).setUint32(0,e.length,!0),n.set(e,4),n}async function bo(t,e){let n=Ls(t),r=Ls(e),o=new Uint8Array(n.length+r.length);o.set(n,0),o.set(r,n.length);let i=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(i),s=>s.toString(16).padStart(2,"0")).join("")}function Nu(t,e){let[n,r]=[t,e].map(o=>o.split(/[.-]/).map(i=>Number.parseInt(i,10)||0));for(let o=0;o<Math.max(n.length,r.length);o++)if((n[o]??0)!==(r[o]??0))return(n[o]??0)>(r[o]??0);return!1}function It(t){return t.filter(e=>!e.yanked&&typeof e.appVersion=="string"&&e.appVersion.length>0).reduce((e,n)=>!e||Nu(n.appVersion,e.appVersion)?n:e,void 0)}async function Pt(t,e,n=globalThis.fetch){let r=`${t.replace(/\/+$/,"")}/api/v2/bundles?package=${encodeURIComponent(e)}`,o=await n(r,{headers:{Accept:"application/json"}});if(!o.ok)throw new Error(`the registry has no ${e} (HTTP ${o.status})`);let i=await o.json();return Array.isArray(i)?i:[]}async function Hs(t,e,n={}){let o=(await Pt(t,e,n.fetch)).filter(c=>!c.yanked),i=[...new Set(o.map(c=>c.signerId).filter(c=>typeof c=="string"&&c.length>0))];if(i.length>1)throw new Error(`the registry lists ${e} under more than one publisher (${i.join(", ")}): refusing to guess which application it is`);let s=It(o);if(!s)throw new Error(`the registry lists no version of ${e}`);let a=s.signerId;if(!a)throw new Error(`the registry names no publisher for ${e} ${s.appVersion}`);return{applicationId:await bo(e,a),signerId:a,version:s.appVersion}}function qs(t,e){return{next:async()=>Uu(t,e)}}function Uu(t,e){let n=`calimero.governance-nonce.${t}.${e}`,r=0n;try{r=BigInt(localStorage.getItem(n)??"0")}catch{}let o=[r+1n,BigInt(Date.now())].reduce((i,s)=>i>s?i:s);try{localStorage.setItem(n,String(o))}catch{}return o}function js(t,e){let n=q(t.account).namespaces[e]??t.relayUrl;if(!n)throw new Error("no relay is known for this namespace, so there is nowhere to send this");return n.replace(/\/+$/,"")}function Ou(t){return!t||t.length===0?{}:JSON.parse(new TextDecoder().decode(Uint8Array.from(t)))}function Zn(t,e,n,r){return new W({relayUrl:e,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:n,fetch:r??Je(e)})}async function Tt(t,e,n={}){let r=js(t,e.namespaceId),o=0n,i=await Zn(t,r,{next:async()=>o},n.fetch).createContext({groupId:e.groupId??e.namespaceId,applicationId:e.applicationId,serviceName:e.serviceName,seed:e.contextSeed,initArgs:Ou(e.initializationParams),name:e.name});return _n(r,i.contextId,o),be(t.account,r,{namespaceId:e.namespaceId,contextId:i.contextId}),{contextId:i.contextId}}async function ve(t,e,n={}){let r=js(t,e.namespaceId);return Zn(t,r,qs(r,e.group),n.fetch).govern({groupId:e.group,op:e.op})}async function Fs(t,e,n={}){let{groupId:r}=await ve(t,{namespaceId:e.namespaceId,group:e.namespaceId,op:(await Le({parentId:e.namespaceId,restricted:!0,admin:t.account})).op},n);for(let i of e.members)await ve(t,{namespaceId:e.namespaceId,group:r,op:Ge(i,"Member")},n);let{contextId:o}=await Tt(t,{...e,groupId:r},n);return{contextId:o,groupId:r}}async function er(t,e={},n={}){let o=ze(t).map(u=>u.replace(/\/+$/,""))[0];if(!o)throw new Error("no relay is known for this account, so there is nowhere to found a namespace");let i=await _u(t,o,n.fetch),s=BigInt(Date.now()),a=await Zn(t,o,{next:async()=>s++},n.fetch).foundNamespace({executor:i,...e.defaultCapabilities!==void 0?{defaultCapabilities:e.defaultCapabilities}:{},...e.application?{application:e.application}:{}});try{localStorage.setItem(`calimero.governance-nonce.${o}.${a.namespaceId}`,String(s))}catch{}if(be(t.account,o,{namespaceId:a.namespaceId}),e.application&&a.applicationSet!==!0)throw new Error(`founded ${a.namespaceId} but could not give it its application: ${a.applicationError??"unknown reason"}`);let c=a.teeEnabled?await Ku(t,a.namespaceId,a.salt,o,n):{haEnabled:!1,haError:`the relay did not attest the founding, so no fleet node could be admitted for HA${a.teeError?`: ${a.teeError}`:""}`};return{namespaceId:a.namespaceId,teeEnabled:a.teeEnabled,...c}}async function _u(t,e,n){let r=t.executorAccount&&t.relayUrl?.replace(/\/+$/,"")===e?t.executorAccount:null;if(r)return{executorAccount:r,executorKey:await Bs(e)};let o=Object.entries(q(t.account).namespaces).find(([,a])=>a.replace(/\/+$/,"")===e)?.[0];if(!o)throw new Error("the executor account of this relay is not known: join a namespace on it first, or connect with the relay's executor account (the cloud shows it beside the relay)");let i=await Bs(e),s=await Zn(t,e,qs(e,o),n).describeGovernance(o);if(s.executorKey?.toLowerCase()!==i)throw new Error(`the relay's discovery names signing key ${s.executorKey}, not the relay's node key ${i}: refusing to found through it`);return{executorAccount:s.executorAccount,executorKey:i}}async function Bs(t){let e=await We(t,{fresh:!0});if(e.kind==="learned")return e.nodeKey;throw new Error(e.kind==="unavailable"?"the relay's signing key could not be learned: its attestation did not answer, try again":"the relay's attestation was refused, so founding through it is not possible: it is not a signed locked-read-only release")}var tr="link this account to your cloud user in the wallet so the cloud can host this namespace on its fleet",Xn={account_not_linked:tr,account_linked_to_several_users:"this account is linked to more than one cloud user, so the cloud cannot tell whose plan hosts the namespace: unlink it from all but one in the wallet",ha_request_pending:"another namespace of this account is still waiting to be hosted; the cloud hosts one new namespace at a time without a cloud sign-in. Sign in to the cloud and turn off hosting for the waiting namespace, or wait until it is hosted",unknown_relay:"the cloud does not run the relay this namespace was founded on, so it cannot host it",relay_not_dialable:"the relay this namespace was founded on has not reported its address to the cloud yet; try enabling hosting again shortly"};function Mu(t){try{let e=JSON.parse(t.bodyText??""),n=e?.detail?.namespace_id??e?.namespace_id;return typeof n=="string"&&/^[0-9a-f]{64}$/i.test(n)?n.toLowerCase():null}catch{return null}}async function Ku(t,e,n,r,o){try{return await new $({cloudBaseUrl:o.cloudBaseUrl,fetch:o.fetch}).enableHaAsAccount({namespaceId:e,salt:n,accountId:t.account,credential:t.credential,deviceSecret:t.deviceSecret,relayUrl:r}),{haEnabled:!0}}catch(i){if(i instanceof xe)return{haEnabled:!1,haError:tr};if(i instanceof J&&Xn[i.code]){let s=i.code==="ha_request_pending"?Mu(i):null,a=Xn[i.code];return{haEnabled:!1,haError:s?`${a} (waiting: ${s})`:a}}return{haEnabled:!1,haError:i instanceof Error?i.message:String(i)}}}async function Ye(t,e,n=globalThis.fetch){let r=It(await Pt(t,e,n));if(!r)throw new Error(`the registry lists no version of ${e}`);return r.appVersion}var Vs="calimero.delegated.group-namespace.",Ao=new Map;function Ws(t){let e={};try{e=JSON.parse(localStorage.getItem(Vs+t)??"{}")}catch{}return{...e,...Ao.get(t)}}function Dt(t,e,n){Ao.set(t,{...Ao.get(t),[e]:n});try{let r=Ws(t);r[e]=n,localStorage.setItem(Vs+t,JSON.stringify(r))}catch{}}function Nt(t,e){return q(t.account).namespaces[e]?e:Ws(t.account)[e]}function Js(t,e){let n=Nt(t,e);if(!n)throw new Error(`the namespace of group ${e} is not known to this account: it can manage only groups in namespaces it joined or subgroups it created`);return n}async function nr(t,e,n){return ve(t,{namespaceId:Js(t,e),group:e,op:n})}async function rr(t,e,n){let r=Js(t,e);return ve(t,{namespaceId:r,group:r,op:n})}var Re=class extends Error{constructor(n){super(`${n} is not available for an account: it needs a node`);this.method=n;this.name="NotForAccountError"}},Xe=class extends Error{constructor(n){super(`${n} needs a relay, and this account has none yet: join from an invitation first`);this.method=n;this.name="NoRelayError"}},Ze=class extends Error{constructor(n,r){super(r==="not-hosted"?`nobody could claim an invitation to ${n} yet: the cloud lists no node holding the namespace, so an invitee with no node of their own has no relay to be admitted through.`:`nobody could claim an invitation to ${n}: the cloud routes to none of the relays or admins it would name as admitters`);this.namespaceId=n;this.reason=r;this.name="InvitationNotClaimableError"}},zs={listNamespaces:async()=>[],listNamespacesForApplication:async()=>[],getContexts:async()=>({contexts:[]})},Gu=new Set(["upgradeGroup","retryGroupUpgrade","abortMigration","installApplication","installDevApplication","uninstallApplication","generateContextIdentity","deleteContext","leaveContext","createContextAlias","createApplicationAlias","createDeviceAlias","deleteContextAlias","deleteApplicationAlias","deleteDeviceAlias","lookupContextAlias","lookupApplicationAlias","lookupDeviceAlias","listContextAliases","listApplicationAliases","listDeviceAliases","deleteNamespace","createGroupInvitation","joinGroup","setTeeAdmissionPolicy","getTeeAdmissionPolicy","deleteBlob","listAccountDevices","revokeAccountDevice"]);function $u(t){if(!(t instanceof Error))return!1;let e=t.status;return(e===void 0||e===409)&&/signer [0-9a-f]+ is a direct member/i.test(t.message)}function Qs(t,e={}){let{session:n,read:r,app:o}=t,i=e.govern?.group??nr,s=e.govern?.root??rr,a=e.createContext??Tt,c=e.found??er,u=e.latestVersion??Ye,d=e.signInvitation??Wn,l=e.join,p=e.routing;async function x(h,b){if(!l)throw new Re("joinNamespace without a join handler");return l(h,b.invitation)}let v=()=>{if(r===null)throw new Xe("this call");return r};async function P(h){if(Nt(n,h))return;let b=await v().getGroupInfo(h);Dt(n.account,h,b.namespaceId??h)}let w=async(h,b,S)=>(await P(b),i(h,b,S)),E=async(h,b,S)=>(await P(b),s(h,b,S));async function T(h){try{return await E(n,h,In({member:n.account,groupId:h,credential:n.credential})),!0}catch(b){if($u(b))return!1;throw b}}async function H(h,b){let S=b??String(await v().getContextGroup(h)),{members:U}=await v().listGroupMembers(S);return U.some(M=>M.identity.toLowerCase()===n.account.toLowerCase())}let z={async listNamespacesForApplication(h){return(await v().listNamespaces()).filter(b=>b.targetApplicationId===h)},async getNodeIdentity(){return{accountId:n.account,deviceId:null,publicKey:"",deviceCertified:!0}},async createNamespace(h){if(!o.packageName)throw new Re("createNamespace without a packageName");let b=o.packageVersion??await u(o.registryUrl??"https://apps.calimero.network",o.packageName),{namespaceId:S,haEnabled:U,haError:M}=await c(n,{defaultCapabilities:231,application:{applicationId:h.applicationId,package:o.packageName,version:b}});return h.name&&await w(n,S,He({name:h.name})),{namespaceId:S,haEnabled:U,...M!==void 0?{haError:M}:{}}},async createGroupInNamespace(h,b={}){let{op:S}=await Le({parentId:h,restricted:b.visibility==="restricted",admin:n.account}),{groupId:U}=await E(n,h,S);return Dt(n.account,U,h),b.groupName&&await w(n,U,He({name:b.groupName})),{groupId:U}},async addGroupMembers(h,b){for(let S of b.members)await w(n,h,Ge(S.identity,S.role??"Member"))},async removeGroupMembers(h,b){for(let S of b.members)await w(n,h,hn(S))},async setGroupMetadata(h,b){await w(n,h,He(b))},async setMemberMetadata(h,b,S){await w(n,h,En(b,S))},async setContextMetadata(h,b,S){await w(n,h,kn(b,S))},async setDefaultCapabilities(h,b){await w(n,h,$e(b.defaultCapabilities))},async setSubgroupVisibility(h,b){await w(n,h,Sn(b.subgroupVisibility==="open"?"open":"restricted"))},async setMemberCapabilities(h,b,S){await w(n,h,Rn(b,S.capabilities))},async deleteGroup(h){return await E(n,h,An(h)),{isDeleted:!0}},async reparentGroup(h,b){return await E(n,h,bn(h,b.newParentId)),{reparented:!0}},async leaveGroup(h){await w(n,h,At(n.account))},async leaveNamespace(h){await w(n,h,At(n.account))},async getContextIdentitiesOwned(h){return{identities:await H(h)?[n.account]:[]}},async joinContext(h){return await T(String(await v().getContextGroup(h))),{contextId:h,memberPublicKey:n.account}},async createContext(h){let S=(await v().getGroupInfo(h.groupId)).namespaceId??h.groupId,{contextId:U}=await a(n,{namespaceId:S,groupId:h.groupId,applicationId:h.applicationId,serviceName:h.serviceName,contextSeed:h.contextSeed,name:h.name,initializationParams:h.initializationParams});return{contextId:U,memberPublicKey:n.account,groupId:h.groupId}},async createNamespaceInvitation(h){let[{members:b},S]=await Promise.all([v().listGroupMembers(h),v().getGroupInfo(h)]),U=b.filter(Q=>Q.role==="RelayTee").map(Q=>Q.identity.toLowerCase());if(p){let Q=new Set(U.length>0?U:b.filter(te=>te.role==="Admin").map(te=>te.identity.toLowerCase())),ee=null;try{ee=(await p(h)).nodes}catch{}if(ee!==null){if(ee.length===0)throw new Ze(h,"not-hosted");if(!ee.some(te=>te.account!==null&&Q.has(te.account.toLowerCase())))throw new Ze(h,"no-named-node")}}return{invitation:await d({groupId:h,inviterAccount:n.account,deviceSecret:n.deviceSecret,...U.length>0?{admitters:U}:{},members:b,applicationId:S.targetApplicationId,appKey:S.appKey})}},async syncGroup(h){return{groupId:h,synced:!0}},async syncContext(){},joinNamespace:x,async updateMemberRole(h,b,S){await w(n,h,yn(b,S.role))},async joinSubgroupInheritance(h){return{groupId:h,memberPublicKey:n.account,wasInherited:await T(h)}},async detachContextFromGroup(h,b){await w(n,h,Cn(b))}};return r===null?new Proxy({},{get(h,b){if(typeof b=="string")return b==="getNodeIdentity"?z.getNodeIdentity:b==="joinNamespace"?x:b in zs?zs[b]:async()=>{throw new Xe(b)}}}):new Proxy(r,{get(h,b,S){return typeof b=="string"&&b in z?z[b]:typeof b=="string"&&Gu.has(b)?async()=>{throw new Re(b)}:Reflect.get(h,b,S)}})}function Ys(t,e={}){let{admin:n,app:r}=t,o=e.latestVersion??Ye;async function i(a){let{apps:c}=await n.listApplications();if(c.some(l=>l.id===a))return;if(!r.packageName)throw new Error(`application ${a} is not installed on this node, and no packageName is set to install it`);let u=r.packageVersion??await o(r.registryUrl??"https://apps.calimero.network",r.packageName),{applicationId:d}=await n.installApplication({package:r.packageName,version:u});if(d!==a)throw new Error(`installed ${r.packageName}@${u} as ${d}, not ${a}`)}let s={async createNamespace(a){return await i(a.applicationId),n.createNamespace(a)}};return new Proxy(n,{get(a,c,u){return typeof c=="string"&&c in s?s[c]:Reflect.get(a,c,u)}})}var Lu="https://manager.cloud.calimero.network";function xo(t,e){return typeof t.can_execute=="boolean"?t.can_execute:e}function vo(t){return typeof t.tee_role=="string"&&t.tee_role!==""?t.tee_role:null}function lo(t){return t.find(e=>e.canExecute&&e.relayUrl!==null&&e.executorAccount!==null)??null}function Hu(t){let e=t.join;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(typeof n.state!="string")return null;let r=Array.isArray(n.refusals)?n.refusals.filter(o=>!!o&&typeof o=="object").map(o=>({peer:String(o.peer??""),reason:String(o.reason??"")})):[];return{state:n.state,attempts:typeof n.attempts=="number"?n.attempts:0,refusals:r,error:typeof n.error=="string"?n.error:null,reportedAt:typeof n.reported_at=="string"?n.reported_at:null}}function Bu(t){return typeof t=="string"&&po.test(t)?t:null}var J=class extends D{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.code=n;this.name="AccountHaRefusedError"}},xe=class extends J{constructor(){super(...arguments);this.name="AccountNotLinkedError"}};xe.CODE="account_not_linked";var Rt=class extends J{constructor(){super(...arguments);this.name="AccountLinkedToSeveralUsersError"}};Rt.CODE="account_linked_to_several_users";var Ct=class extends J{constructor(){super(...arguments);this.name="HaRequestPendingError"}};Ct.CODE="ha_request_pending";var St=class extends J{constructor(){super(...arguments);this.name="UnknownRelayError"}};St.CODE="unknown_relay";var Et=class extends J{constructor(){super(...arguments);this.name="RelayNotDialableError"}};Et.CODE="relay_not_dialable";var Xs={409:[xe,Rt,Ct],422:[St,Et]};function qu(t){if(t)try{let e=JSON.parse(t);if(typeof e?.error=="string")return e.error;if(typeof e?.detail=="string")return e.detail;let n=e?.detail?.error;if(typeof n=="string")return n}catch{}}var ju="x-mdma-session-refresh",Fu="x-mdma-session-expires",$=class{constructor(e={}){this.session=null;this.baseUrl=(e.cloudBaseUrl||Lu).replace(/\/+$/,""),this.onSession=e.onSession;let n=e.fetch;this.fetchImpl=n?(r,o)=>n(r,o):(r,o)=>globalThis.fetch(r,o),this.timeoutMs=e.timeoutMs??1e4,this.routingCredential=e.routingCredential,e.sessionToken&&(this.session={sessionToken:e.sessionToken,expiresAt:0,user:{email:""}})}getSession(){return this.session}isSignedIn(){return this.session!==null}async signInWithGoogle(e){let n=await this.request("POST","/api/auth/google",{body:{id_token:e},anonymous:!0});return this.adoptSession(n)}async signInWithAccount(e){let{signer:n,publicKey:r}=await Y(e),{nonce:o}=await this.getAccountLoginChallenge();return this.submitAccountLogin({rootPublicKey:r,nonce:o,signature:await Zt({signer:n,nonce:o})})}async getAccountLoginChallenge(){let e=await this.request("GET","/api/auth/account/challenge",{anonymous:!0});return{nonce:e.nonce,expiresAtMs:e.expires_at_ms}}async submitAccountLogin(e){let n=await this.request("POST","/api/auth/account",{body:{root_public_key:e.rootPublicKey,nonce:e.nonce,signature:e.signature},anonymous:!0});return this.adoptSession(n)}async refreshSession(){let e=await this.request("POST","/api/auth/refresh");return this.adoptSession(e)}async signOut(){try{this.session&&await this.request("POST","/api/auth/logout",{parse:"none"})}finally{this.session=null,this.notifySession(null)}}async getMyNamespaces(){return(await this.request("GET","/api/cloud/me/namespaces")).map(n=>({namespaceId:String(n.namespace_id??n.group_id??""),groupId:String(n.group_id??n.namespace_id??""),haStatus:String(n.ha_status??"none"),haEnabledAt:n.ha_enabled_at??null,contexts:Array.isArray(n.contexts)?n.contexts:[],fleetReplicas:n.fleet_replicas}))}async getNamespaceRelays(e){return((await this.request("GET",`/api/cloud/me/namespaces/${g(e)}/relays`)).relays??[]).map(r=>{let o=r.relay_url??null,i=r.executor_account??null,s=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),relayUrl:o,executorAccount:i,nodeKey:r.node_key??r.node_public_key??null,status:String(r.status??""),authorshipReady:s,teeRole:vo(r),canExecute:xo(r,s&&o!==null&&i!==null),lastSeenAt:r.last_seen_at??null,confirmedAt:r.confirmed_at??null,admission:typeof r.admission=="string"?r.admission:null,admissionHint:typeof r.admission_hint=="string"?r.admission_hint:null,join:Hu(r)}})}async findExecutingRelay(e){let n=await this.getNamespaceRelays(e);return lo(n)}async getNamespaceRouting(e){let n=await this.request("GET",`/api/cloud/namespaces/${g(e)}/admitters`,{anonymous:!0,headers:await this.routingProof(e)});return{namespaceId:String(n.namespace_id??e),nodes:(n.admitters??[]).map(r=>{let o=r.account??null,i=r.relay_url??null,s=r.fresh===!0,a=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),account:o,relayUrl:i,admitUrl:r.admit_url??null,status:String(r.status??""),fresh:s,canAdmit:r.can_admit===!0,authorshipReady:a,teeRole:vo(r),canExecute:xo(r,a&&i!==null&&o!==null&&s)}}),servable:n.servable===!0,writable:n.writable===!0}}async getRoutingChallenge(e){let n=await this.request("GET",`/api/cloud/namespaces/${g(e)}/challenge`,{anonymous:!0});return{namespaceId:String(n.namespace_id??e),nonce:String(n.nonce??""),expiresAtMs:Number(n.expires_at_ms??0)}}async routingProof(e){if(!this.routingCredential)return;let n=await this.getRoutingChallenge(e);return Bn(n,this.routingCredential)}async getAccountRelaysChallenge(e){let n=await this.request("GET",`/api/cloud/accounts/${g(e)}/challenge`,{anonymous:!0});return{accountId:String(n.account_id??e),nonce:String(n.nonce??""),expiresAtMs:Number(n.expires_at_ms??0)}}async getAccountRelays(e){if(!this.routingCredential)throw new Error("getAccountRelays needs a routingCredential: construct the client with the device certificate and its signing secret, since this read is proven by the device, not by a session.");let n=await this.getAccountRelaysChallenge(e);return((await this.request("GET",`/api/cloud/accounts/${g(e)}/relays`,{anonymous:!0,headers:await Bn(n,this.routingCredential)})).relays??[]).map(o=>({peerId:String(o.peer_id??""),relayUrl:o.relay_url??null,fresh:o.fresh===!0,executorAccount:Bu(o.executor_account),assigned:o.assigned===!0}))}async findAdmitter(e,n){let{nodes:r}=await this.getNamespaceRouting(e),o=n&&n.length>0?new Set(n.map(i=>i.toLowerCase())):null;return r.find(i=>i.canAdmit&&(o===null||i.account!==null&&o.has(i.account.toLowerCase())))??null}async getMyMachines(){return((await this.request("GET","/api/cloud/me/machines")).machines??[]).map(n=>{let r=n.relay_url??null,o=n.executor_account??null,i=(Array.isArray(n.namespaces)?n.namespaces:[]).map(s=>{let a=s;return{namespaceId:String(a.namespace_id??""),status:String(a.status??""),authorshipReady:a.authorship_ready===!0,teeRole:vo(a),fresh:a.fresh===!0,confirmedAt:a.confirmed_at??null,lastSeenAt:a.last_seen_at??null}});return{peerId:String(n.peer_id??""),relayUrl:r,executorAccount:o,canExecute:xo(n,r!==null&&o!==null&&i.some(s=>s.authorshipReady)),namespaces:i}})}async claimNamespace(e,n){await this.request("POST","/api/cloud/namespaces/claim",{body:{namespace_id:e,ownership_proof:n}})}async enableNamespaceHa(e,n={}){let r=n.admitterAddrs===void 0?{}:{admitter_addrs:[...n.admitterAddrs]};return this.request("POST",`/api/cloud/namespaces/${g(e)}/enable-ha`,{body:r})}async enableFoundedNamespaceHa(e,n){return this.request("POST",`/api/cloud/me/namespaces/${g(e)}/enable-ha`,{body:{groups:[],ownership_proof:n}})}async enableHaAsAccount(e){let n=await Rr({namespaceId:e.namespaceId,accountId:e.accountId,salt:e.salt,credential:e.credential,deviceSecret:e.deviceSecret,signer:e.signer,ttlMs:e.ttlMs,relayUrl:e.relayUrl}),r=e.accountId.toLowerCase(),o=e.namespaceId.toLowerCase();try{return await this.request("POST",`/api/cloud/accounts/${g(r)}/namespaces/${g(o)}/enable-ha`,{body:{ownership_proof:n},anonymous:!0})}catch(i){if(i instanceof D&&Xs[i.status]){let s=qu(i.bodyText),a=Xs[i.status].find(c=>c.CODE===s);if(a&&s)throw new a(s,i.status,i.statusText,i.url,i.headers,i.bodyText)}throw i}}async disableNamespaceHa(e){return this.request("POST",`/api/cloud/namespaces/${g(e)}/disable-ha`,{body:{}})}async getMyNode(){return(await this.request("GET","/api/cloud/me/node")).node??null}enableHA(e){let n=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&n.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/enable-ha?${n.toString()}`)}disableHA(e){let n=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&n.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/disable-ha?${n.toString()}`)}async linkAccount(e){let{signer:n,publicKey:r,accountId:o}=await Y(e),{nonce:i}=await this.getAccountLinkChallenge();return this.submitAccountLink({accountId:o,rootPublicKey:r,nonce:i,signature:await ct({signer:n,nonce:i})})}async getAccountLinkChallenge(){let e=await this.request("GET","/api/cloud/me/accounts/challenge");return{nonce:e.nonce,expiresAtMs:e.expires_at_ms??null}}async submitAccountLink(e){let n=await this.request("POST","/api/cloud/me/accounts",{body:{account_id:e.accountId,root_public_key:e.rootPublicKey,nonce:e.nonce,signature:e.signature}});return{accountId:String(n.account_id??e.accountId),linkedAt:n.linked_at??null,alreadyLinked:n.already_linked===!0}}static accountLinkHandoff(e){let n=e.portalUrl.replace(/\/+$/,""),r=new URLSearchParams({"link-account":e.accountId,"callback-url":qn(e.accountId,e.callbackUrl)});return{url:`${n}/?${r.toString()}`,accountId:e.accountId}}static readAccountLinkCallback(e){let n=e??(typeof window>"u"?"":window.location.href);if(!n)return{};let r,o;try{({hash:r,search:o}=new URL(n))}catch{return{}}let i=new URLSearchParams(r.replace(/^#/,"")),s=i.get("grant"),a=i.get("account"),c=i.get("error"),u={};return c&&Qe(o),s&&Qe(o)?.account!==a?{error:"unexpected_callback"}:(s&&(u.grant=s),a&&(u.accountId=a),c&&(u.error=c),u)}async linkAccountWithGrant(e){let{signer:n,publicKey:r,accountId:o}=await Xt(e.rootSecret,e.signer),i=await this.request("POST","/api/cloud/accounts/link",{body:{grant:e.grant,root_public_key:r,signature:await ct({signer:n,nonce:e.grant})},anonymous:!0});return{accountId:String(i.account_id??o),linkedAt:i.linked_at??null,alreadyLinked:i.already_linked===!0}}async getMyAccounts(){let e=await this.request("GET","/api/cloud/me/accounts");return{accounts:(e.accounts??[]).map(n=>({accountId:String(n.account_id??""),linkedAt:n.linked_at??null,hasRecoveryEnvelope:n.has_recovery_envelope===!0})),limit:e.limit??null}}adoptSession(e){return this.session={sessionToken:e.session_token,expiresAt:e.expires_at,user:e.user},this.notifySession(this.session),this.session}async notifySession(e){try{await this.onSession?.(e)}catch{}}async request(e,n,r={}){if(!r.anonymous&&!this.session)throw new Error("Not signed in to Calimero Cloud: call signInWithGoogle() or construct the client with a sessionToken");let o={...r.headers,Accept:"application/json"};r.body!==void 0&&(o["Content-Type"]="application/json"),!r.anonymous&&this.session&&(o.Authorization=`Bearer ${this.session.sessionToken}`);let i=new AbortController,s=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r.body===void 0?void 0:JSON.stringify(r.body),signal:i.signal})}catch(c){throw new D(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(this.adoptRollingRefresh(a),!a.ok){let c=await a.text().catch(()=>{});throw new D(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(!(r.parse==="none"||a.status===204))return await a.json()}adoptRollingRefresh(e){let n=e.headers.get(ju);if(!n||!this.session)return;let r=e.headers.get(Fu),o=Number(r);this.session={sessionToken:n,expiresAt:Number.isFinite(o)&&o>0?o:this.session.expiresAt,user:this.session.user},this.notifySession(this.session)}};function Eu(t){let e=t&&typeof t=="object"?t.data??t:void 0;if(!e||typeof e!="object")return[];let n=e.localPeerId,r=e.externalAddrs;if(typeof n!="string"||!n||!Array.isArray(r))return[];let o=`/p2p/${n}`,i=[];for(let s of r){if(typeof s!="string")continue;let a=s.trim();if(!a.startsWith("/"))continue;let c=a.endsWith(o)?a:`${a}${o}`;i.includes(c)||i.push(c)}return i}function Vu(t){if(t)return typeof t=="function"?t:Ft(t)}var Wu="mero-js:token-refresh";function Ju(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function zu(t){try{let{origin:e,pathname:n}=new URL(t);return e==="null"?t:e+n.replace(/\/+$/,"")}catch{return t}}function Ro(t,e){try{let n=t.split(".");if(n.length===3){let r=n[1].replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4;)r+="=";let o=JSON.parse(atob(r));if(typeof o.exp=="number")return o.exp*1e3}}catch{}return e}var Fe=class{constructor(e){this.tokenData=null;this.refreshPromise=null;this.storeHoldsTokens=!1;this.tokenGeneration=0;this.onStorage=()=>{this.signedOutElsewhere()&&this.dropLocalTokens()};this.rpcClient=null;this.sseClient=null;this.wsClient=null;this.wsWarned=!1;this.config={timeoutMs:1e4,...e},this.tokenStore=e.tokenStore??null,this.nodeKey=zu(e.baseUrl),this.tokenData=this.readStoredTokens(),this.tokenStore&&(this.storeHoldsTokens=this.tokenData!==null,typeof window<"u"&&window.addEventListener("storage",this.onStorage));let n=typeof window<"u"&&"__TAURI_INTERNALS__"in window,r=Vu(this.config.requestProof);this.httpClient=Ie({baseUrl:this.config.baseUrl,fetch:this.config.fetch,getProof:r,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",refreshToken:async()=>(await this.performTokenRefresh()).access_token,onTokenRefresh:async o=>{this.tokenData&&(this.tokenData.access_token=o,this.persistTokens())},onAuthRevoked:async()=>{this.clearToken();try{await this.config.onAuthRevoked?.()}catch{}},timeoutMs:this.config.timeoutMs,credentials:this.config.requestCredentials??(n?"omit":void 0)}),this.authClient=Ko(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs}),this.adminClient=qt(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs})}get auth(){return this.authClient}get admin(){return this.adminClient}get rpc(){return this.rpcClient||(this.rpcClient=new st({httpClient:this.httpClient})),this.rpcClient}get events(){return this.sseClient||(this.sseClient=new B({baseUrl:this.config.baseUrl,fetch:this.config.fetch,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.sseClient}get ephemeral(){return this.ephemeralClient||(this.ephemeralClient=new at({httpClient:this.httpClient,sse:this.events})),this.ephemeralClient}get cloud(){return this.cloudClient||(this.cloudClient=new $(this.config.cloud??{})),this.cloudClient}get ws(){return this.wsWarned||(this.wsWarned=!0,console.warn("[mero-js] WsClient is experimental. Use mero.events (SSE) for production.")),this.wsClient||(this.wsClient=new ie({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.wsClient}async authenticate(e){let n=e||this.config.credentials;if(!n)throw new Error("No credentials provided for authentication");try{let r={auth_method:"user_password",public_key:n.username,client_name:"mero-js-sdk",permissions:["admin"],timestamp:Math.floor(Date.now()/1e3),provider_data:{username:n.username,password:n.password}},o=await this.authClient.generateTokens(r),i=o.data.access_token;return this.tokenData={access_token:i,refresh_token:o.data.refresh_token,expires_at:Ro(i,Date.now()+36e5)},this.persistTokens(),this.tokenData}catch(r){throw new Error(`Authentication failed: ${r instanceof Error?r.message:"Unknown error"}`)}}persistTokens(){!this.tokenStore||!this.tokenData||(this.tokenStore.setTokens({...this.tokenData,node_origin:this.nodeKey}),this.storeHoldsTokens=this.tokenStore.getTokens()!==null)}readStoredTokens(){let e=this.tokenStore?.getTokens();return!e||e.node_origin!==this.nodeKey?null:{access_token:e.access_token,refresh_token:e.refresh_token,expires_at:e.expires_at}}signedOutElsewhere(){return this.storeHoldsTokens&&!this.tokenStore?.getTokens()}dropLocalTokens(){this.tokenGeneration++,this.refreshPromise=null,this.tokenData=null,this.storeHoldsTokens=!1}async getValidToken(){return this.tokenData}async performTokenRefresh(){if(this.refreshPromise)return this.refreshPromise;let e=this.tokenData?.access_token,n=this.withRefreshLock(()=>this.performTokenRefreshLocked(e));this.refreshPromise=n;try{return await n}finally{this.refreshPromise===n&&(this.refreshPromise=null)}}withRefreshLock(e){if(this.tokenStore?.withLock)return this.tokenStore.withLock(e);let n=Ju();return n?n.request(Wu,e):e()}async performTokenRefreshLocked(e){if(this.signedOutElsewhere())throw this.dropLocalTokens(),new Error("Signed out in another tab");let n=this.readStoredTokens();if(n?.refresh_token&&(this.storeHoldsTokens=!0,this.tokenData=n,e&&n.access_token!==e))return n;if(!this.tokenData?.refresh_token)throw new Error("No refresh token available");let r=this.tokenGeneration,o=this.tokenData.access_token,i=this.tokenStore?.getTokens()?.access_token===o;try{let s=await this.authClient.refreshToken({access_token:this.tokenData.access_token,refresh_token:this.tokenData.refresh_token});if(r!==this.tokenGeneration)throw new Error("Signed out during token refresh");if(i&&this.tokenStore?.getTokens()?.access_token!==o)throw this.tokenData=this.tokenStore?.getTokens()??null,this.storeHoldsTokens=this.tokenData!==null,new Error("Signed out during token refresh");let a=s.data.access_token;return this.tokenData={access_token:a,refresh_token:s.data.refresh_token,expires_at:Ro(a,Date.now()+36e5)},this.persistTokens(),this.tokenData}catch(s){throw new Error(`Token refresh failed: ${s instanceof Error?s.message:"Unknown error"}`)}}clearToken(){this.dropLocalTokens(),this.tokenStore?.clear()}isAuthenticated(){return this.tokenData!==null}setTokenData(e){let n=e.expires_at||Ro(e.access_token,Date.now()+36e5);this.tokenData={...e,expires_at:n},this.persistTokens()}getTokenData(){return this.tokenData}close(){typeof window<"u"&&window.removeEventListener("storage",this.onStorage),this.sseClient?.close(),this.wsClient?.close()}static parseAuthCallback(e){return br(e)}static buildAuthLoginUrl(e,n){return Ar(e,n)}};function Qu(t){return new Fe(t)}var Co=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},Yu="mero-tokens",So=class{constructor(e=Yu){this.key=e}getTokens(){try{if(typeof localStorage>"u")return null;let e=localStorage.getItem(this.key);if(!e)return null;let n=JSON.parse(e);return n&&n.access_token&&n.refresh_token?{access_token:n.access_token,refresh_token:n.refresh_token,expires_at:typeof n.expires_at=="number"?n.expires_at:Date.now()+36e5,...typeof n.node_origin=="string"&&{node_origin:n.node_origin}}:null}catch{return null}}setTokens(e){try{if(typeof localStorage>"u")return;localStorage.setItem(this.key,JSON.stringify(e))}catch{}}clear(){try{if(typeof localStorage>"u")return;localStorage.removeItem(this.key)}catch{}}};var Xu=new TextEncoder().encode("calimero.account.owner-op.v1"),Zu=new TextEncoder().encode("calimero.account.owner-op.body.v1"),ed=new TextEncoder().encode("calimero.account.genesis.v1"),td=2,Eo={transferOwnership:0,adminChanged:1,groupDelete:2,teeAdmissionPolicy:3,teeAuthoringPolicy:4,teeReleaseAdmissionPolicy:5},et={GroupDelete:14,TransferOwnership:21,TeeAuthoringPolicySet:33,TeeAdmissionPolicySetV2:37,TeeReleaseAdmissionPolicySetV2:38,RootGuarded:42},ea={AdminChanged:3,RootGuarded:12},nd={replica:0,relay:1},rd=new TextEncoder;function L(t){return new Uint8Array([t])}function ta(t){let e=rd.encode(t);return f(R(e.length),e)}function Z(t){return f(R(t.length),...t.map(ta))}function na(t){return L(t?1:0)}function ra(t){let e=nd[t??"replica"];if(e===void 0)throw new Error(`mode must be replica or relay, got ${String(t)}`);return L(e)}function oa(t){return{kind:"transferOwnership",plane:"group",bytes:f(L(et.TransferOwnership),m(t,"newOwner",32))}}function ia(){return{kind:"groupDelete",plane:"group",bytes:L(et.GroupDelete)}}function sa(t){return{kind:"adminChanged",plane:"root",bytes:f(L(ea.AdminChanged),m(t,"newAdmin",32))}}function aa(t){return{kind:"teeAuthoringPolicy",plane:"group",bytes:f(L(et.TeeAuthoringPolicySet),Z(t))}}function ca(t){return{kind:"teeAdmissionPolicy",plane:"group",bytes:f(L(et.TeeAdmissionPolicySetV2),Z(t.allowedMrtd),Z(t.allowedRtmr0),Z(t.allowedRtmr1),Z(t.allowedRtmr2),Z(t.allowedRtmr3),Z(t.allowedTcbStatuses),na(t.acceptMock),ra(t.mode))}}function la(t){let e=t.minReleaseVersion===void 0?L(0):f(L(1),ta(t.minReleaseVersion));return{kind:"teeReleaseAdmissionPolicy",plane:"group",bytes:f(L(et.TeeReleaseAdmissionPolicySetV2),Z(t.allowedProfiles),e,Z(t.allowedTcbStatuses),na(t.acceptMock),ra(t.mode))}}async function ko(t){return k(Zu,[t])}async function Io(t){return k(Xu,[m(t.account,"account",32),m(t.namespaceId,"namespaceId",32),m(t.groupId,"groupId",32),L(ua(t.kind)),t.opDigest,C(t.counter),R(t.keyEpoch)])}function ua(t){let e=Eo[t];if(e===void 0)throw new Error(`unknown owner-op kind ${String(t)}`);return e}var Zs=132;async function da(t){let e=await re(t.rootSecret),n=f(L(td),e),r=y(await k(ed,[n])),o=t.keyEpoch??0,i=(t.chain??[]).map((d,l)=>{let p=j(d,`chain[${l}]`);if(p.length!==Zs)throw new Error(`chain[${l}] must be a ${Zs}-byte RootKeyHandoff, got ${p.length}`);return p});if(o>i.length)throw new Error(`keyEpoch ${o} needs ${o} handoffs in chain, got ${i.length}`);let s=await ko(t.op.bytes),a=await Io({account:r,namespaceId:t.namespaceId,groupId:t.groupId,kind:t.op.kind,opDigest:s,counter:t.counter,keyEpoch:o}),c=await ne(t.rootSecret),u=new Uint8Array(await crypto.subtle.sign("Ed25519",c,a));return y(f(n,R(i.length),...i,m(r,"account",32),m(t.namespaceId,"namespaceId",32),m(t.groupId,"groupId",32),L(ua(t.op.kind)),s,C(t.counter),R(o),u))}function pa(t,e){let n=t.plane==="group"?et.RootGuarded:ea.RootGuarded;return f(L(n),t.bytes,j(e,"rootProof"))}var ga=[2428,2429,2528,2529],od="localhost",id=2e3;function ma(t){return`http://${od}:${t}`}function fa(t,e){let n=t.endsWith("/")?t:`${t}/`;return new URL(e,n).toString()}async function ha(t,e={}){let{timeoutMs:n=id,signal:r}=e;if(r?.aborted)return!1;let o=new AbortController,i=()=>o.abort(),s=r;s&&s.addEventListener("abort",i,{once:!0});let a=setTimeout(()=>o.abort(),n);try{let c=fa(t,"admin-api/health"),u=await fetch(c,{method:"GET",signal:o.signal});if(!u.ok)return!1;try{let d=await u.json(),l=d?.data?.status!==void 0?d?.data?.status:d?.status;return l===void 0?!0:typeof l=="string"&&l.toLowerCase()==="alive"}catch{return!0}}catch{return!1}finally{clearTimeout(a),s&&s.removeEventListener("abort",i)}}async function sd(t={}){let{ports:e=ga,timeoutMs:n,signal:r}=t;return(await Promise.all(e.map(async i=>{let s=ma(i);return await ha(s,{timeoutMs:n,signal:r})?s:null}))).filter(i=>i!==null)}function or(t,e){return(t<<e|t>>>32-e)>>>0}function le(t,e,n,r,o){t[e]=t[e]+t[n]>>>0,t[o]=or(t[o]^t[e],16),t[r]=t[r]+t[o]>>>0,t[n]=or(t[n]^t[r],12),t[e]=t[e]+t[n]>>>0,t[o]=or(t[o]^t[e],8),t[r]=t[r]+t[o]>>>0,t[n]=or(t[n]^t[r],7)}function ya(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function Aa(t,e,n){let r=new Uint32Array(16);r[0]=1634760805,r[1]=857760878,r[2]=2036477234,r[3]=1797285236;for(let s=0;s<8;s+=1)r[4+s]=ya(t,s*4);r[12]=e>>>0;for(let s=0;s<3;s+=1)r[13+s]=ya(n,s*4);let o=r.slice();for(let s=0;s<10;s+=1)le(o,0,4,8,12),le(o,1,5,9,13),le(o,2,6,10,14),le(o,3,7,11,15),le(o,0,5,10,15),le(o,1,6,11,12),le(o,2,7,8,13),le(o,3,4,9,14);let i=new Uint8Array(64);for(let s=0;s<16;s+=1){let a=o[s]+r[s]>>>0;i[s*4]=a&255,i[s*4+1]=a>>>8&255,i[s*4+2]=a>>>16&255,i[s*4+3]=a>>>24&255}return i}function ad(t,e,n,r){let o=new Uint8Array(r.length);for(let i=0,s=e;i<r.length;i+=64,s+=1){let a=Aa(t,s,n),c=Math.min(i+64,r.length);for(let u=i;u<c;u+=1)o[u]=r[u]^a[u-i]}return o}function Po(t){let e=0n;for(let n=t.length-1;n>=0;n-=1)e=e<<8n|BigInt(t[n]);return e}var cd=(1n<<130n)-5n;function ld(t,e){let n=Po(t.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,r=Po(t.subarray(16,32)),o=0n;for(let a=0;a<e.length;a+=16){let c=e.subarray(a,Math.min(a+16,e.length)),u=Po(c)+(1n<<BigInt(8*c.length));o=(o+u)*n%cd}let i=o+r&(1n<<128n)-1n,s=new Uint8Array(16);for(let a=0;a<16;a+=1)s[a]=Number(i&0xffn),i>>=8n;return s}function wa(t){return new Uint8Array((16-t%16)%16)}function ba(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function ud(t,e){let n=[t,wa(t.length),e,wa(e.length),ba(t.length),ba(e.length)],r=new Uint8Array(n.reduce((i,s)=>i+s.length,0)),o=0;for(let i of n)r.set(i,o),o+=i.length;return r}function dd(t,e){if(t.length!==32)throw new Error("ChaCha20-Poly1305 needs a 32-byte key");if(e.length!==12)throw new Error("ChaCha20-Poly1305 needs a 12-byte nonce")}function xa(t,e,n,r=new Uint8Array(0)){dd(t,e);let o=Aa(t,0,e).subarray(0,32),i=ad(t,1,e,n),s=ld(o,ud(r,i)),a=new Uint8Array(i.length+16);return a.set(i),a.set(s,i.length),a}var Ra=32,pd=1,gd=3,md=2,fd=32,hd=32,yd=12,tt=t=>new TextEncoder().encode(t),Ot=t=>new Uint8Array([t>>8&255,t&255]),va=f(tt("KEM"),Ot(Ra)),Ut=f(tt("HPKE"),Ot(Ra),Ot(pd),Ot(gd));async function Ca(t,e){let n=t.length===0?new Uint8Array(32):t,r=await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",r,e))}async function wd(t,e,n){let r=new Uint8Array(n),o=new Uint8Array(0);for(let i=1,s=0;s<n;i+=1)o=await Ca(t,f(o,e,new Uint8Array([i]))),r.set(o.subarray(0,Math.min(o.length,n-s)),s),s+=o.length;return r}function ir(t,e,n,r){return Ca(e,f(tt("HPKE-v1"),t,tt(n),r))}function To(t,e,n,r,o){return wd(e,f(Ot(o),tt("HPKE-v1"),t,tt(n),r),o)}async function bd(t,e){let n=await ir(va,new Uint8Array(0),"eae_prk",t);return To(va,n,"shared_secret",e,fd)}async function Ad(t,e){let n=new Uint8Array(0),r=await ir(Ut,n,"psk_id_hash",n),o=await ir(Ut,n,"info_hash",e),i=f(new Uint8Array([md]),r,o),s=await ir(Ut,t,"secret",n);return{key:await To(Ut,s,"key",i,hd),nonce:await To(Ut,s,"base_nonce",i,yd)}}async function Sa(t,e,n,r,o=new Uint8Array(0),i){if(t.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let s=await Ne(i),a=await Ne(e),c=f(await lt(s.privateKey,t),await lt(a.privateKey,t)),u=await bd(c,f(s.publicKey,t,a.publicKey)),{key:d,nonce:l}=await Ad(u,n);return{enc:s.publicKey,ciphertext:xa(d,l,r,o)}}var Ia="mero-agent-gate/attest/v3",Pa="mero-agent-gate/provision/v2",xd=/^[a-z0-9][a-z0-9-]{0,62}$/,vd=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,Ea=64,ka=64*1024,ue=class extends Error{constructor(n,r,o){super(n);this.status=r;this.code=o;this.name="AgentGateError"}};function Ta(t){if(!xd.test(t))throw new Error(`Agent id ${JSON.stringify(t)} must match [a-z0-9][a-z0-9-]{0,62}`)}function _t(t){return new TextEncoder().encode(t)}function Da(t){let e=_t(t);return f(new Uint8Array([e.length]),e)}function Ce(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}function sr(t,e,n){let r;try{r=Uint8Array.from(atob(t.trim()),o=>o.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(n!==void 0&&r.length!==n)throw new Error(`${e} is not ${n} bytes`);return r}async function Na(t,e,n,r){let o=new Uint8Array(32),i=f(_t(Ia),t,Da(e),n??o,r??o);return new Uint8Array(await crypto.subtle.digest("SHA-256",i))}function Ua(t,e){return f(_t(Pa),t,Da(e))}async function Rd(){let t=crypto.getRandomValues(new Uint8Array(32));return{secret:t,publicKey:await ar(t)}}async function ar(t){if(t.length!==32)throw new Error("An owner key is 32 bytes");return Ce((await Ne(t)).publicKey)}function Oa(t,e){return`${t.replace(/\/+$/,"")}${e}`}async function _a(t,e,n){let r=await t(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}),o=await r.text(),i;try{i=o?JSON.parse(o):void 0}catch{}if(!r.ok){let s=i;throw new ue(`The gate answered ${r.status}${s?.error?` ${s.error}`:""}: ${s?.details??o.slice(0,200)}`,r.status,s?.error)}return i}async function Do(t){let e=t.agentId??"";e&&Ta(e);let n=crypto.getRandomValues(new Uint8Array(32)),r=await _a(t.fetch??fetch,Oa(t.gateUrl,"/attest"),{nonceB64:Ce(n),...e?{agentId:e}:{}});if((r?.agentId??"")!==e)throw new Error(`Asked about agent ${JSON.stringify(e)}, the gate answered for ${JSON.stringify(r?.agentId)}`);let o=sr(r.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),i=r.signingPublicKeyB64?sr(r.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,s=r.ownerPublicKeyB64?sr(r.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!i!=!s)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let a=await Na(o,e,i,s);return await t.verifier({quoteB64:r.quoteB64,nonce:y(n),reportDataSuffix:y(a)}),{agentId:e,provisioningPublicKey:Ce(o),...i?{signingPublicKey:Ce(i)}:{},...s?{ownerPublicKey:Ce(s)}:{}}}async function Ma(t,e){let n=await ar(e);if(t.ownerPublicKey&&t.ownerPublicKey!==n)throw new ue(`This agent is claimed by another key (${t.ownerPublicKey}); it is not yours. Send it nothing and do not authorize its signing key`,void 0,"not_yours");return n}function Cd(t){let e=Object.keys(t);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>Ea)throw new Error(`At most ${Ea} secrets at once`);for(let n of e){if(!vd.test(n))throw new Error(`Secret name ${JSON.stringify(n)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);if(typeof t[n]!="string")throw new Error(`Secret ${n} is not a string`);if(_t(t[n]).length>ka)throw new Error(`Secret ${n} is over ${ka} bytes`)}}async function Ka(t,e,n,r,o,i){if(!r.agentId)throw new Error("This quote names no agent; attest with the agent id");let s=await Ma(r,o),a=sr(r.provisioningPublicKey,"provisioningPublicKey",32),c=await Sa(a,o,Ua(a,r.agentId),_t(JSON.stringify(i)));return _a(t,Oa(e,n),{agentId:r.agentId,provisioningPublicKeyB64:r.provisioningPublicKey,senderPublicKeyB64:s,encappedKeyB64:Ce(c.enc),ciphertextB64:Ce(c.ciphertext)})}async function Sd(t){Cd(t.secrets);let e=t.fetch??fetch,n=await Ka(e,t.gateUrl,"/provision",t.agent,t.ownerSecret,{secrets:t.secrets}),r=await Do({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e}),o=await ar(t.ownerSecret);if(r.ownerPublicKey!==o||!r.signingPublicKey)throw new ue("The gate accepted the secrets, but its quote does not name your key as owner");if(t.agent.signingPublicKey&&t.agent.signingPublicKey!==r.signingPublicKey)throw new ue("The agent's signing key changed while provisioning");return{agentId:r.agentId,provisioningPublicKey:r.provisioningPublicKey,signingPublicKey:r.signingPublicKey,ownerPublicKey:o,written:n?.written??[],claimed:n?.claimed===!0}}async function Ed(t){if(!t.agent.ownerPublicKey)throw new Error("This agent is not claimed; there is nothing to release");let e=t.fetch??fetch;if(await Ka(e,t.gateUrl,"/release",t.agent,t.ownerSecret,{release:!0}),(await Do({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e})).ownerPublicKey)throw new ue("The gate says it released the agent, but its quote still names an owner")}var No=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),kd=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function Id(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await sn(r,e,{identity:n.identity??No.identity,issuer:n.issuer??No.issuer});let o;try{o=JSON.parse(new TextDecoder().decode(r))}catch{throw new Error("The signed agent policy is not JSON")}if(o?.role!=="agent")throw new Error(`The signed file is a ${JSON.stringify(o?.role)} policy, not an agent one`);let i=n.profile??gt;if(o.profile!==i)throw new Error(`The signed agent policy is for the ${JSON.stringify(o.profile)} profile, not ${i}`);if(n.expectedVersion!==void 0&&o.version!==n.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(o.version)}, not ${n.expectedVersion}`);return Ga(o),o}function Ga(t){for(let e of kd)if(!Array.isArray(t?.[e])||t[e].length===0)throw new Error(`The agent policy's ${e} is empty, so no agent would be accepted`)}var Pd=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function Td(t){let e=Pd.find(n=>n.toLowerCase()===t.trim().toLowerCase());if(!e)throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(t)}`);return e}var Mt=t=>t.trim().replace(/^0x/i,"");function Dd(t,e){return Ga(t),mt({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:t.allowed_tcb_statuses.map(Td),allowedMrtd:t.allowed_mrtd.map(Mt),allowedRtmr0:t.allowed_rtmr0.map(Mt),allowedRtmr1:t.allowed_rtmr1.map(Mt),allowedRtmr2:t.allowed_rtmr2.map(Mt),allowedRtmr3:t.allowed_rtmr3.map(Mt)})}export{Xo as ACCOUNT_HA_AUDIENCE,Yo as ACCOUNT_OWNERSHIP_AUDIENCE,Ia as AGENT_ATTEST_DOMAIN,Pa as AGENT_PROVISION_INFO_DOMAIN,J as AccountHaRefusedError,Rt as AccountLinkedToSeveralUsersError,xe as AccountNotLinkedError,me as AdminApiClient,ue as AgentGateError,pe as AuthApiClient,oe as AuthRevokedError,_ as CAPABILITIES,lp as CAPABILITY_PRESETS,$ as CloudClient,ga as DEFAULT_LOCAL_NODE_PORTS,an as DEFAULT_RELEASE_MIRROR,at as EphemeralClient,Ri as HANDSHAKE_PATH,tr as HA_ACCOUNT_NOT_LINKED_MESSAGE,Xn as HA_REFUSAL_MESSAGES,D as HTTPError,Ct as HaRequestPendingError,fo as INVITED_ROLE,he as IntentRefusedError,Ze as InvitationNotClaimableError,No as KMS_RELEASE_SIGNER,So as LocalStorageTokenStore,Vn as MAX_INVITATION_VALIDITY_SECS,Co as MemoryTokenStore,we as MeroClient,Fe as MeroJs,Lr as NODE_RELEASE_SIGNER,Xe as NoRelayError,Re as NotForAccountError,Eo as OWNER_OP_KIND,os as PRESENCE_DOMAIN,gt as PRODUCTION_PROFILE,On as RELAY_NODE_KEY_RETRY_MS,ke as REQUEST_PROOF_HEADER,W as RelayClient,Et as RelayNotDialableError,qe as RelayObserver,xt as RelayPresenceClient,ye as RelayTransport,st as RpcClient,Vt as RpcError,dt as SEALED_CONTENT_TYPE,Ci as SEALED_PATH,wo as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,Ue as SealedTransportError,B as SseClient,pt as StaleTransportKeyError,St as UnknownRelayError,Ln as WarrantNonceExhaustedError,Bt as WarrantNonceRouteUnavailableError,rt as WebHttpClient,ie as WsClient,Yt as accountForRoot,F as accountForRootPublicKey,ii as accountRootFromPhrase,Pr as accountRootFromSecret,ai as accountRootSignerFromPhrase,sa as adminChangedOp,Eu as admitterAddrsFromNetworkStatus,Na as agentKeyBinding,Dd as agentQuoteVerifier,bo as applicationIdForBundle,We as attemptRelayNodeKey,Do as attestAgent,tn as attestKeyBinding,nn as attestRelayNodeKey,iu as authorNonceLookup,mu as beginCloudLink,xu as beginDeviceEnrolment,Yn as bootstrapFromInvitation,Ar as buildAuthLoginUrl,Gn as buildDelegatedClient,Os as callbackIsForeign,jt as callerProof,up as capMask,dp as capNames,$n as carryExecutorAccount,Ma as checkOwner,yr as classifyError,gs as clearDelegatedCredential,us as clearDelegatedSession,Ts as cloudLinkUrl,un as cloudNodeReleaseUrl,lr as combineSignals,tc as compareSemver,hu as completeCloudLink,Ru as completeDeviceEnrolment,Cs as connectCloud,au as connectCloudWithAccount,es as contextCapabilityGrantedOp,ts as contextCapabilityRevokedOp,Cn as contextDetachedOp,kn as contextMetadataSetOp,Qs as createAccountAdmin,si as createAccountRootSigner,Bo as createAdminApiClient,qt as createAdminApiClientFromHttpClient,fe as createAttestedSealedFetch,ap as createAuthApiClient,Ko as createAuthApiClientFromHttpClient,Pp as createBrowserAdminApiClient,ip as createBrowserAuthApiClient,Ie as createBrowserHttpClient,Tt as createDelegatedContext,Fs as createDelegatedPrivateContext,ot as createHttpClient,vt as createLocalStorageNonceSource,Hn as createMemoryNonceSource,Dn as createMeroClient,Qu as createMeroJs,Ys as createNodeAdmin,Tp as createNodeAdminApiClient,sp as createNodeAuthApiClient,Lt as createNodeHttpClient,gr as createProofAuthorizer,Ft as createProofSigner,mt as createQuoteVerifier,su as createRecoveringNonceSource,Ja as createRetryableMethod,Ii as createSealedFetch,wl as createSignedReleaseSealedFetch,dn as createSignedReleaseVerifier,ur as createTimeoutSignal,mr as createUniversalHttpClient,Jr as createdSubgroupId,qr as creationInitHash,yo as defaultAdmitters,je as defaultAudience,$e as defaultCapabilitiesSetOp,ve as delegatedGovernance,zt as deviceCertPayload,Us as deviceEnrolmentUrl,Er as deviceScopePayload,sd as discoverLocalNodes,kt as encodeGroupInvitation,Jn as encodeSignedInvitation,ki as fetchAttestedTransportKey,cn as fetchNodeRelease,ln as fetchNodeReleaseVersion,Pt as fetchRegistryBundles,bs as forgetMethodKinds,ws as forgetRelaySealing,er as foundDelegatedNamespace,xn as foundedNamespaceId,oi as generateAccountRoot,Rd as generateOwnerKey,Xr as generateSessionKey,nr as governGroup,rr as governRoot,jr as governanceOpHash,zr as groupCreatedOp,ia as groupDeleteOp,An as groupDeletedOp,ho as groupInvitationHash,He as groupMetadataSetOp,bn as groupReparentedOp,ge as hasCap,Cp as hexEncodeUtf8,Hr as intentHash,Xa as isSettled,$s as joinAsAccount,Qn as joinWithNode,se as jsonCodec,ze as knownRelays,Ye as latestPublishedVersion,ys as learnRelayNodeKey,vs as listDelegatedContexts,Rs as listDelegatedNamespaces,ma as localNodeUrl,Be as login,_n as markContextNonceSpent,Ge as memberAddedOp,Rn as memberCapabilitySetOp,In as memberJoinedOpenOp,At as memberLeftOp,En as memberMetadataSetOp,hn as memberRemovedOp,yn as memberRoleSetOp,Cr as mintDeviceId,vn as namespaceCreatedOp,Nt as namespaceOfGroup,fa as nodeEndpoint,Li as nodeReleaseVersionFromImage,jn as normaliseAccount,ko as ownerOpDigest,Io as ownerOpSigningPayload,ar as ownerPublicKey,br as parseAuthCallback,zi as parseCreationWarrant,Sr as parseDeviceCredential,Qi as parseGovernanceWarrant,$o as parseWarrantNonce,io as persistedNonces,so as pinRelayNodeKey,Zr as presenceStatementBytes,ha as probeNodeHealth,Sd as provisionAgent,Ua as provisionInfo,fu as readCloudLinkCallback,ds as readDelegatedCredential,oo as readDelegatedSession,vu as readEnrolmentCallback,Mn as readPinnedRelayNodeKey,q as readRelayMap,Go as redeemInvitation,xs as relayForContext,Je as relayTransportFetch,Ed as releaseAgent,Dt as rememberGroupNamespace,be as rememberRelay,Dr as reportDataOf,nt as requestBodyHash,Hs as resolveApplicationIdFromRegistry,Fn as resolveRelayFromInvitation,Kn as resolveRelayNodeKey,Y as resolveRoot,Xt as resolveRootPair,pa as rootGuardedOpBytes,Bn as routingProofHeaders,ps as saveDelegatedCredential,ls as saveDelegatedSession,It as selectLatestBundle,hp as shouldRetain,Rr as signAccountHaClaim,ct as signAccountLink,Zt as signAccountLogin,dc as signAccountOwnershipClaim,mn as signCreationWarrant,ti as signDeviceCert,ni as signDeviceScope,wt as signGovernanceWarrant,Wn as signGroupInvitation,Tn as signLoginStatement,zn as signMemberJoinOp,da as signOwnerOpProof,Kt as signRequest,pr as signRequestProof,Ss as signRoutingChallenge,pn as signWarrant,de as signedPath,Vo as signerFromCryptoKey,Pe as signerFromSecret,is as stateHash,Le as subgroupCreation,Sn as subgroupVisibilitySetOp,Jt as subscribePresence,wn as targetApplicationSetOp,ca as teeAdmissionPolicyOp,aa as teeAuthoringPolicyOp,la as teeReleaseAdmissionPolicyOp,oa as transferOwnershipOp,Ei as transportKeyBinding,qi as trustSignedRelease,Mr as trustedMeasurementsFromReleases,Ta as validateAgentId,Qt as verifyDeviceCredential,Id as verifySignedAgentPolicy,$i as verifySignedNodeRelease,fr as withCap,Ht as withRetry,pp as withoutCap};
|
|
1
|
+
function dr(t){let e=t.filter(Boolean);if(e.length===0)return;let n=AbortSignal;if(typeof n.any=="function")try{return n.any(e)}catch{}let r=new AbortController,o=i=>{r.abort(i.target.reason);for(let s of e)s.removeEventListener("abort",o)};for(let i of e){if(i.aborted)return AbortSignal.abort(i.reason);i.addEventListener("abort",o,{once:!0})}return r.signal}function pr(t){if(typeof AbortSignal.timeout=="function")return AbortSignal.timeout(t);let e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("Timeout","TimeoutError"))},t),e.signal}var Mo=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function R(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),e}function y(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function m(t,e,n){let r=t.trim();if(!/^[0-9a-fA-F]*$/.test(r)||r.length!==n*2)throw new Error(`${e} must be ${n*2} hex characters, got ${r.length}`);let o=new Uint8Array(n);for(let i=0;i<n;i+=1)o[i]=Number.parseInt(r.slice(i*2,i*2+2),16);return o}function j(t,e){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2!==0)throw new Error(`${e} must be an even number of hex characters`);let r=new Uint8Array(n.length/2);for(let o=0;o<r.length;o+=1)r[o]=Number.parseInt(n.slice(o*2,o*2+2),16);return r}function C(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function f(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}async function E(t,e){let n=[C(t.length),t];for(let r of e)n.push(C(r.length),r);return new Uint8Array(await crypto.subtle.digest("SHA-256",f(...n)))}async function ne(t){let e=m(t,"deviceSecret",32),n=f(Mo,e);try{return await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!1,["sign"])}catch(r){let o=r instanceof Error?`: ${r.message}`:"";throw new Error("this runtime has no WebCrypto Ed25519, so a warrant cannot be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it; otherwise mint the warrant with `merod account warrant`"+o)}}async function Ko(t,e,n){let r=await crypto.subtle.importKey("raw",m(t,"publicKey",32),{name:"Ed25519"},!1,["verify"]);return crypto.subtle.verify({name:"Ed25519"},r,e,n)}async function re(t){let e=m(t,"deviceSecret",32),n=f(Mo,e),r=await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),i=(await crypto.subtle.exportKey("jwk",r)).x;return Uint8Array.from(atob(i.replace(/-/g,"+").replace(/_/g,"/")),s=>s.charCodeAt(0))}var gr=new TextEncoder().encode("calimero.auth.request.v2"),Fa=new TextEncoder().encode("calimero.auth.request.body.v1");function Go(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}async function rt(t=new Uint8Array(0)){let e=typeof t=="string"?new TextEncoder().encode(t):t;return E(Fa,[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 E(gr,[i.encode(t.method),i.encode(t.path),n,r,o]),a=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},e,s));return y(f(Go(t.method),Go(t.path),n,r,o,a))}var ke=t=>new TextEncoder().encode(t),Ee="X-Calimero-Proof",Va=300;async function mr(t){let{method:e,path:n,credential:r}=t;if(!e)throw new Error("signRequestProof needs the method the request will use");if(!n.startsWith("/"))throw new Error(`signRequestProof needs a path, got ${JSON.stringify(n)}`);let o=await rt(t.body),i=Math.floor(t.now??Date.now()/1e3),s=i+(t.validForSeconds??Va),a=await E(gr,[ke(e),ke(n),o,C(i),C(s)]),c=await Wa(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=Ja(r,"credential");return y(f(d,new Uint8Array([0]),u))}async function Wa(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 m(n,e,n.length/2)}function fr(t){if(!t.credential)throw new Error("a proof authorizer needs the `credential` from signDeviceCert");if(!t.deviceSecret&&!t.signer)throw new Error("a proof authorizer needs either `deviceSecret` or `signer`");return async({method:e,path:n,body:r})=>{let o=await mr({method:e,path:n,body:r,credential:t.credential,deviceSecret:t.deviceSecret,signer:t.signer,validForSeconds:t.validForSeconds});return{[Ee]:o}}}function de(t){let e=new URL(t,globalThis.location?.href??"http://localhost");return e.pathname+e.search}var za=new Set(["token_reuse","token_revoked"]);function Qa(t){if(t)try{let e=JSON.parse(t),n=e?.error;if(typeof n=="string"&&n.trim()!=="")return n;let r=n?.message;if(typeof r=="string"&&r.trim()!=="")return r;let o=e?.detail;if(typeof o=="string"&&o.trim()!=="")return o}catch{}}var D=class extends Error{constructor(n,r,o,i,s){let a=Qa(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 D{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.reason=n;this.name="AuthRevokedError";this.message=`Authentication revoked (${n}): HTTP ${r} ${o}`}};function $o(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function Ya(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()===Ee.toLowerCase())}function Ht(t,e){if(t.type==="opaqueredirect"||t.status>=300&&t.status<400)throw new D(0,"Redirect Not Followed",e,t.headers,`the node answered with a redirect; a request carrying ${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=Ya(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=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 k=await this.getBodyText(b),T=new D(b.status,b.statusText,s,b.headers,k),H=b.headers.get("x-auth-error");if((b.status===401||b.status===403)&&H&&za.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 D||b instanceof Error&&b.message.includes("onTokenRefresh")?b:new D(0,"Network Error",s,new Headers,b instanceof Error?b.message:"Unknown error")}}buildUrl(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;let n=this.transport.baseUrl;return e.startsWith("/")?`${n.endsWith("/")?n.slice(0,-1):n}${e}`:`${n.endsWith("/")?n:`${n}/`}${e}`}createAbortSignal(e){let n=[];this.transport.defaultAbortSignal&&n.push(this.transport.defaultAbortSignal),e?.signal&&n.push(e.signal);let r=e?.timeoutMs||this.transport.timeoutMs;return r&&n.push(pr(r)),n.length>0?dr(n):void 0}async buildHeaders(e){let n={...this.transport.defaultHeaders};if(this.transport.getAuthToken)try{let r=await this.transport.getAuthToken();r&&r.trim()!==""&&(n.Authorization=`Bearer ${r}`)}catch{}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 hr(t){return typeof window<"u"?Ie(t):Bt(t)}function Xa(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,!Xa(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 ec(t,e={}){return async(...n)=>qt(()=>t(...n),e)}function g(t){if(t===""||t==="."||t==="..")throw new TypeError(`invalid request path segment: ${JSON.stringify(t)}`);return encodeURIComponent(t)}var pe=class{constructor(e){this.httpClient=e}async getHealth(){let e=await this.httpClient.get("/auth/health");if(!e.data)throw new Error("Health response data is null");return e.data}async getIdentity(){let e=await this.httpClient.get("/admin/identity");if(!e.data)throw new Error("Identity response data is null");return e.data}async getProviders(){let e=await this.httpClient.get("/auth/providers");if(!e.data)throw new Error("Providers response data is null");return e.data}async getLoginPage(){return this.httpClient.get("/auth/login",{parse:"text"})}async generateTokens(e){return this.httpClient.post("/auth/token",e)}async refreshToken(e){return this.httpClient.post("/auth/refresh",e)}async generateMockTokens(e){return this.httpClient.post("/auth/mock-token",e)}async validateToken(e){try{let n=await this.validateTokenGet(e);return{valid:n.status===200,headers:n.headers,status:n.status}}catch{return{valid:!1,headers:{},status:401}}}async validateTokenGet(e){let n=await this.httpClient.head("/auth/validate",{headers:{Authorization:`Bearer ${e}`}});return{status:n.status,headers:n.headers}}async revokeTokens(e){let n=await this.httpClient.post("/admin/revoke",e);if(!n.data)throw new Error("Revoke tokens response data is null");return n.data}async listRootKeys(){let e=await this.httpClient.get("/admin/keys");if(!e.data)throw new Error("Root keys response data is null");return e.data}async createRootKey(e){let n=await this.httpClient.post("/admin/keys",e);if(!n.data)throw new Error("Create root key response data is null");return n.data}async deleteRootKey(e){return this.httpClient.delete(`/admin/keys/${g(e)}`)}async listClientKeys(){let e=await this.httpClient.get("/admin/keys/clients");if(!e.data)throw new Error("Client keys response data is null");return e.data}async generateClientKey(e){return this.httpClient.post("/admin/client-key",e)}async deleteClientKey(e,n){return this.httpClient.delete(`/admin/keys/${g(e)}/clients/${g(n)}`)}async getKeyPermissions(e){return this.httpClient.get(`/admin/keys/${g(e)}/permissions`)}async updateKeyPermissions(e,n){return this.httpClient.put(`/admin/keys/${g(e)}/permissions`,{add:n.add,remove:n.remove})}};var 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 dp(t){let e=new st;return new pe(e)}function pp(t){let e=new st;return new pe(e)}function gp(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},fp={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 hp(...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 yp(t){return Object.keys(_).filter(e=>ge(t,_[e]))}function ge(t,e){let n=e>>>0;return(t&n)>>>0===n}function yr(t,e){return(t|e)>>>0}function bp(t,e){return(t&~e)>>>0}var tc={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 nc(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 rc(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 br(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 wr(t){let e=rc(t),n;return e!==void 0?n=nc(e):t instanceof TypeError?n="unreachable":n="unknown",{kind:n,status:e,retryable:tc[n],message:br(t)}}function oc(t){return t.status!=="failed"||!t.retryable}function vp(t){return!oc(t)}function ic(t){let e=t.toLowerCase();return e.includes("invitation has expired")||e.includes("invitation expired")||/\binvitation for group .+? expired at \d+/.test(e)?"expired":e.includes("malformed")||e.includes("does not match namespace_id")||e.includes("invalid invitation")||/\binvitation for group .+? is invalid:/.test(e)?"invalid":null}function sc(t,e){let{kind:n,status:r}=wr(t),o=ic(e);return r===401?{reason:"signed-out",retryable:!0}:r===400?{reason:o??"invalid",retryable:!1}:r===410?{reason:"expired",retryable:!1}:r===403?{reason:"refused",retryable:!1}:r===409?{reason:o??"refused",retryable:!1}:n==="unavailable"?{reason:"no-one-online",retryable:!0}:n==="unreachable"?{reason:"node-unreachable",retryable:!0}:o?{reason:o,retryable:!1}:{reason:"unknown",retryable:!0}}async function 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=br(i,"Could not join. Check the invitation."),{reason:c,retryable:u}=sc(i,a);return{status:"failed",namespaceId:n,message:a,reason:c,retryable:u}}var jt=class extends Error{constructor(n,r){super(`this node does not serve warrant-nonce discovery (404 on ${n}); it predates the route, so a client must fall back to its own nonce counter`);this.path=n;this.cause=r;this.name="WarrantNonceRouteUnavailableError"}};function Ar(t,e,n){let r=e[n];if(r==null)return;let o=new RegExp(`"${n}"\\s*:\\s*(\\d+)`).exec(t);if(o)return BigInt(o[1]);if(typeof r=="string"&&/^\d+$/.test(r))return BigInt(r);throw new Error(`warrant-nonce response field \`${n}\` is not a u64: ${JSON.stringify(r)}`)}function Bo(t){let n=JSON.parse(t)?.data;if(!n||typeof n!="object")throw new Error(`warrant-nonce response had no \`data\`: ${t.slice(0,200)}`);let r={contextId:String(n.contextId??""),authorDeviceKey:String(n.authorDeviceKey??""),seen:n.seen===!0,highWaterNonce:Ar(t,n,"highWaterNonce"),windowWidth:Ar(t,n,"windowWidth")??0n},o=Ar(t,n,"nextNonce");return o===void 0?{...r,kind:"exhausted",seen:!0,highWaterNonce:r.highWaterNonce??0xffffffffffffffffn}:{...r,kind:"open",nextNonce:o}}function A(t){return t?.data}function ac(t,e){let[n,r]=qo(t),[o,i]=qo(e),s=n.split("."),a=o.split("."),c=Math.max(s.length,a.length);for(let p=0;p<c;p++){let x=jo(s[p]??"0",a[p]??"0");if(x!==0)return x}if(r===void 0&&i===void 0)return 0;if(r===void 0)return 1;if(i===void 0)return-1;let u=r.split("."),d=i.split("."),l=Math.max(u.length,d.length);for(let p=0;p<l;p++){if(p>=u.length)return-1;if(p>=d.length)return 1;let x=jo(u[p],d[p]);if(x!==0)return x}return 0}function qo(t){let e=t.split("+",1)[0],n=e.indexOf("-");return n===-1?[e,void 0]:[e.slice(0,n),e.slice(n+1)]}function jo(t,e){let n=/^\d+$/.test(t),r=/^\d+$/.test(e);if(n&&r){let o=Number(t)-Number(e);return o<0?-1:o>0?1:0}return n?-1:r?1:t<e?-1:t>e?1:0}async function cc(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 cc(r.toString(),"versions",n)).json();return(Array.isArray(i)?i:[]).map(s=>s.appVersion).filter(s=>typeof s=="string").sort((s,a)=>ac(a,s))}async installDevApplication(e){return A(await this.httpClient.post("/admin-api/install-dev-application",e))}async uninstallApplication(e){return A(await this.httpClient.delete(`/admin-api/applications/${g(e)}`))}async listApplications(){return A(await this.httpClient.get("/admin-api/applications"))}async getApplication(e){return A(await this.httpClient.get(`/admin-api/applications/${g(e)}`))}async listApplicationVersions(e){return A(await this.httpClient.get(`/admin-api/applications/${g(e)}/versions`))}async getApplicationAbi(e,n){let r=n?`?service_name=${encodeURIComponent(n)}`:"";return A(await this.httpClient.get(`/admin-api/applications/${g(e)}/abi${r}`))}async listPackages(){let e=await this.httpClient.get("/admin-api/packages");return e?.data??e}async listPackageVersions(e){let n=await this.httpClient.get(`/admin-api/packages/${g(e)}/versions`);return n?.data??n}async getLatestPackageVersion(e){return this.httpClient.get(`/admin-api/packages/${g(e)}/latest`)}async createContext(e){let n={...e,initializationParams:e.initializationParams??[]};return A(await this.httpClient.post("/admin-api/contexts",n))}async deleteContext(e){return A(await this.httpClient.delete(`/admin-api/contexts/${g(e)}`))}async getContexts(){return A(await this.httpClient.get("/admin-api/contexts"))}async getContext(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}`))}async getContextsForApplication(e){return A(await this.httpClient.get(`/admin-api/contexts/for-application/${g(e)}`))}async generateContextIdentity(){return A(await this.httpClient.post("/admin-api/identity/context",{}))}async getContextIdentities(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/identities`))}async getContextIdentitiesOwned(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/identities-owned`))}async joinContext(e){return A(await this.httpClient.post(`/admin-api/contexts/${g(e)}/join`,{}))}async getContextGroup(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/group`))}async getContextStorage(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/storage`))}async syncContext(e){let n=e?`/admin-api/contexts/sync/${g(e)}`:"/admin-api/contexts/sync";await this.httpClient.post(n,{})}async resyncContext(e,n={}){return await this.httpClient.post(`/admin-api/contexts/${g(e)}/resync`,n)??{contextId:e,resyncStarted:!0}}async inviteSpecializedNode(e){return A(await this.httpClient.post("/admin-api/contexts/invite-specialized-node",e))}async updateContextApplication(e,n){await this.httpClient.post(`/admin-api/contexts/${g(e)}/application`,n)}async getContextsWithExecutorsForApplication(e){let n=await this.httpClient.get(`/admin-api/contexts/with-executors/for-application/${g(e)}`);return Array.isArray(n)?n:n?.contexts??n?.data??[]}async uploadBlob(e){let n=new URLSearchParams;e.hash&&n.set("hash",e.hash),e.contextId&&n.set("context_id",e.contextId);let r=n.toString(),o=r?`/admin-api/blobs?${r}`:"/admin-api/blobs",i=A(await this.httpClient.request(o,{method:"PUT",body:e.data,headers:{"Content-Type":"application/octet-stream"}}));return{blobId:i.blob_id,size:i.size}}async deleteBlob(e){let n=await this.httpClient.delete(`/admin-api/blobs/${g(e)}`);return{blobId:n.blob_id,deleted:n.deleted}}async listBlobs(){return{blobs:A(await this.httpClient.get("/admin-api/blobs")).blobs.map(n=>({blobId:n.blob_id,size:n.size}))}}blobPath(e,n){if(!n?.contextId)return`/admin-api/blobs/${g(e)}`;let r=new URLSearchParams({context_id:n.contextId});return`/admin-api/blobs/${g(e)}?${r.toString()}`}async getBlob(e,n){return this.httpClient.get(this.blobPath(e,n),{parse:"arrayBuffer"})}async getBlobInfo(e,n){let{headers:r}=await this.httpClient.head(this.blobPath(e,n)),o=Number(r["content-length"]);return{blobId:r["x-blob-id"]??e,size:Number.isFinite(o)?o:0,hash:r["x-blob-hash"],mimeType:r["x-blob-mime-type"],source:r["x-blob-source"]}}async createContextAlias(e){return A(await this.httpClient.post("/admin-api/alias/create/context",{alias:e.alias,contextId:e.contextId}))}async createApplicationAlias(e){return A(await this.httpClient.post("/admin-api/alias/create/application",{alias:e.alias,applicationId:e.applicationId}))}async lookupContextAlias(e){return A(await this.httpClient.post(`/admin-api/alias/lookup/context/${g(e)}`,{}))}async lookupApplicationAlias(e){return A(await this.httpClient.post(`/admin-api/alias/lookup/application/${g(e)}`,{}))}async deleteContextAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/context/${g(e)}`,{}))}async deleteApplicationAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/application/${g(e)}`,{}))}async listContextAliases(){return A(await this.httpClient.get("/admin-api/alias/list/context"))}async listApplicationAliases(){return A(await this.httpClient.get("/admin-api/alias/list/application"))}async createDeviceAlias(e){return A(await this.httpClient.post("/admin-api/alias/create/device",{alias:e.alias,deviceId:e.deviceId}))}async lookupDeviceAlias(e){return A(await this.httpClient.post(`/admin-api/alias/lookup/device/${g(e)}`,{}))}async deleteDeviceAlias(e){return A(await this.httpClient.post(`/admin-api/alias/delete/device/${g(e)}`,{}))}async listDeviceAliases(){return A(await this.httpClient.get("/admin-api/alias/list/device"))}async listNamespaces(){return A(await this.httpClient.get("/admin-api/namespaces"))}async getNamespace(e){return A(await this.httpClient.get(`/admin-api/namespaces/${g(e)}`))}async getNodeIdentity(){return A(await this.httpClient.get("/admin-api/identity"))}async getNamespaceIdentity(e){let n=await this.getNodeIdentity();return{namespaceId:e,publicKey:n.publicKey,account:n.accountId}}async performIntent(e,n){return A(await this.httpClient.post(`/admin-api/contexts/${g(e)}/intents`,n))}async queryContext(e,n){return A(await this.httpClient.post(`/admin-api/contexts/${g(e)}/query`,n))}async getIntentRelay(e){return A(await this.httpClient.get(`/admin-api/contexts/${g(e)}/intents`))}async listNamespacesForApplication(e){return A(await this.httpClient.get(`/admin-api/namespaces/for-application/${g(e)}`))}async createNamespace(e){return A(await this.httpClient.post("/admin-api/namespaces",e))}async deleteNamespace(e){return A(await this.httpClient.request(`/admin-api/namespaces/${g(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async createNamespaceInvitation(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/invite`,n??{}))}async admitJoin(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/admit`,n,{timeoutMs:65e3}))}async joinNamespace(e,n){let r=A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/join`,n,{timeoutMs:65e3}));return r&&r.namespaceId===void 0&&r.groupId!==void 0?{...r,namespaceId:r.groupId}:r}async redeemInvitation(e,n,r={}){let{groupName:o,teamName:i}=r;return Ho({namespaceId:e,invitation:n,teamName:i},{join:async()=>{await this.joinNamespace(e,o===void 0?{invitation:n}:{invitation:n,groupName:o})},memberships:async()=>(await this.listNamespaces()??[]).map(s=>s.namespaceId)})}async createGroupInNamespace(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/groups`,n??{}))}async listNamespaceGroups(e){return A(await this.httpClient.get(`/admin-api/namespaces/${g(e)}/groups`))}async initAccountPairing(e){return A(await this.httpClient.post("/admin-api/account/pair-init",e))}async completeAccountPairing(e){return A(await this.httpClient.post("/admin-api/account/pair-complete",e))}async relinkAccountDevice(e,n){return A(await this.httpClient.post(`/admin-api/account/devices/${g(e)}/relink`,n??{}))}async rescopeAccountDevice(e,n){return A(await this.httpClient.put(`/admin-api/account/devices/${g(e)}/scope`,n))}async signWithAccountRoot(e){return A(await this.httpClient.post("/admin-api/account/sign-with-root",e))}async labelAccountDevice(e,n){return A(await this.httpClient.put(`/admin-api/account/devices/${g(e)}/label`,n))}async listAccountDevices(){return(await this.httpClient.get("/admin-api/account/devices")).devices}async listAccountApplications(){return(await this.httpClient.get("/admin-api/account/applications")).applications}async revokeAccountDevice(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/account/revoke`,n))}async linkAccountDevice(e,n){return A(await this.httpClient.post(`/admin-api/namespaces/${g(e)}/account/link-device`,n))}async getGroupInfo(e){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}`))}async getDefaultCapabilities(e){return(await this.getGroupInfo(e)).defaultCapabilities}async getSubgroupVisibility(e){return(await this.getGroupInfo(e)).subgroupVisibility}async deleteGroup(e){return A(await this.httpClient.request(`/admin-api/groups/${g(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async listGroupMembers(e){let n=await this.httpClient.get(`/admin-api/groups/${g(e)}/members`);if(!Array.isArray(n?.members)){let r=String(e).replace(/[\r\n\t\s]/g,"").slice(0,64);throw new Error(`Invalid listGroupMembers response for group ${r}: missing or non-array \`members\` field`)}return n}async listGroupMemberDevices(e,n){let r=new URLSearchParams;n?.offset!==void 0&&r.set("offset",String(n.offset)),n?.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${g(e)}/member-devices`;return(await this.httpClient.get(o?`${i}?${o}`:i)).members}async getWarrantNonce(e,n){let r=`/admin-api/contexts/${g(e)}/warrant-nonce/${g(n)}`,o;try{o=await this.httpClient.get(r,{parse:"text"})}catch(i){throw i instanceof D&&i.status===404?new jt(r,i):i}return Bo(o)}async getWarrantNonceAsAuthor(e,n){let r=`/admin-api/contexts/${g(e)}/warrant-nonce`,o;try{o=await this.httpClient.post(r,{authorProof:n},{parse:"text"})}catch(i){throw i instanceof D&&i.status===404?new jt(r,i):i}return Bo(o)}async listMemberDevices(e,n={}){let r=new URLSearchParams;n.offset!==void 0&&r.set("offset",String(n.offset)),n.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${g(e)}/member-devices${o?`?${o}`:""}`;return this.httpClient.get(i)}async sealToAccount(e,n,r){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/accounts/${g(n)}/seal`,r))}async listGroupContexts(e){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}/contexts`))}async addGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${g(e)}/members`,n)}async removeGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${g(e)}/members/remove`,n)}async updateMemberRole(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/members/${g(n)}/role`,r)}async getMemberCapabilities(e,n){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}/members/${g(n)}/capabilities`))}async setMemberCapabilities(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/members/${g(n)}/capabilities`,r)}async setDefaultCapabilities(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/settings/default-capabilities`,n)}async openToDelegatedExecution(e){let n=await this.getDefaultCapabilities(e);if(ge(n,_.CAN_AUTHOR_ON_BEHALF))return{changed:!1,defaultCapabilities:n};let r=yr(n,_.CAN_AUTHOR_ON_BEHALF);return await this.setDefaultCapabilities(e,{defaultCapabilities:r}),{changed:!0,defaultCapabilities:r}}async grantAuthorship(e,n){let{capabilities:r}=await this.getMemberCapabilities(e,n);if(ge(r,_.CAN_AUTHOR_ON_BEHALF))return{changed:!1,capabilities:r};let o=yr(r,_.CAN_AUTHOR_ON_BEHALF);return await this.setMemberCapabilities(e,n,{capabilities:o}),{changed:!0,capabilities:o}}async setSubgroupVisibility(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/settings/subgroup-visibility`,n)}async setTeeAdmissionPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/settings/tee-admission-policy`,n)}async getTeeAdmissionPolicy(e){let n=await this.httpClient.get(`/admin-api/groups/${g(e)}/settings/tee-admission-policy`);return n.data??n}async setTeeAuthoringPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/settings/tee-authoring-policy`,n)}async disableTeeAuthoringPolicy(e,n={}){let r=`/admin-api/groups/${g(e)}/settings/tee-authoring-policy`;if(n.rootProof===void 0){await this.httpClient.delete(r);return}await this.httpClient.request(r,{method:"DELETE",body:JSON.stringify({rootProof:n.rootProof}),headers:{"Content-Type":"application/json"}})}async transferOwnership(e,n){await this.httpClient.post(`/admin-api/groups/${g(e)}/transfer-ownership`,n)}async changeNamespaceAdmin(e,n){await this.httpClient.post(`/admin-api/namespaces/${g(e)}/admin`,n)}async ownerDeleteGroup(e,n={}){await this.httpClient.post(`/admin-api/groups/${g(e)}/owner-delete`,n)}async setGroupMetadata(e,n){await this.httpClient.put(`/admin-api/groups/${g(e)}/metadata`,n)}async getGroupMetadata(e){return(await this.httpClient.get(`/admin-api/groups/${g(e)}/metadata`))?.data??null}async setMemberMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/members/${g(n)}/metadata`,r)}async getMemberMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${g(e)}/members/${g(n)}/metadata`))?.data??null}async setContextMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/contexts/${g(n)}/metadata`,r)}async getContextMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${g(e)}/contexts/${g(n)}/metadata`))?.data??null}async syncGroup(e){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/sync`,{}))}async upgradeGroup(e,n){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/upgrade`,n))}async getGroupUpgradeStatus(e){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}/upgrade/status`))}async getMigrationStatus(e){return this.httpClient.get(`/admin-api/groups/${g(e)}/migration-status`)}async listNamespaceRevokedDevices(e){return this.httpClient.get(`/admin-api/namespaces/${g(e)}/revoked-devices`)}async getCascadeStatus(e){return A(await this.httpClient.get(`/admin-api/groups/${g(e)}/cascade-status`))}async retryGroupUpgrade(e){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/upgrade/retry`,{}))}async reparentGroup(e,n){let r=await this.httpClient.post(`/admin-api/groups/${g(e)}/reparent`,n);return r?.data??r}async listSubgroups(e){let n=await this.httpClient.get(`/admin-api/groups/${g(e)}/subgroups`);return n.subgroups??n.data??[]}async detachContextFromGroup(e,n){await this.httpClient.post(`/admin-api/groups/${g(e)}/contexts/${g(n)}/remove`,{})}async createGroupInvitation(e,n){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/invite`,n??{}))}async joinGroup(e){return A(await this.httpClient.post("/admin-api/groups/join",e))}async joinSubgroupInheritance(e){return A(await this.httpClient.post(`/admin-api/groups/${g(e)}/join-via-inheritance`,{}))}async getTeeInfo(){return A(await this.httpClient.get("/admin-api/tee/info"))}async teeAttest(e){return A(await this.httpClient.post("/admin-api/tee/attest",e))}async teeVerifyQuote(e){return A(await this.httpClient.post("/admin-api/tee/verify-quote",e))}async getPeersCount(){return this.httpClient.get("/admin-api/peers")}async getNetworkStatus(){return this.httpClient.get("/admin-api/network/status")}async getUsage(){return this.httpClient.get("/admin-api/usage")}async createGroup(e){return A(await this.httpClient.post("/admin-api/groups",e))}async leaveGroup(e){await this.httpClient.post(`/admin-api/groups/${g(e)}/leave`,{})}async leaveContext(e){await this.httpClient.post(`/admin-api/contexts/${g(e)}/leave`,{})}async leaveNamespace(e){await this.httpClient.post(`/admin-api/namespaces/${g(e)}/leave`,{})}async issueOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${g(e)}/issue-ownership-proof`,n)}async issueNamespaceOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${g(e)}/issue-namespace-ownership-proof`,n)}async setMemberAutoFollow(e,n,r){await this.httpClient.put(`/admin-api/groups/${g(e)}/members/${g(n)}/auto-follow`,r)}async abortMigration(e){return this.httpClient.post(`/admin-api/groups/${g(e)}/migration/abort`,{})}};function Tp(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 Mp(t){return new me(Bt(t))}function Fo(t){return new me(hr(t))}function Ft(t,e){return new me(t)}var Vo="calimero.cloud.link.pending",xr="link_state";var vr=/^[0-9a-f]{64}$/;function Wo(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=Wo(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=Wo(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 Vt(t,e){if(!vr.test(t))throw new Error("accountId must be 64 lowercase hex characters");let n=new URL(e);return n.searchParams.set(xr,at(Vo,{account:t})),n.toString()}function Te(t){return Pe(Vo,new URLSearchParams(t).get(xr))}function zo(t){let e=new URLSearchParams(t);e.delete(xr);let n=e.toString();return n?`?${n}`:""}var Qo="calimero.auth.login.pending",Yo="auth_state";function Rr(t,e={}){try{let n=t.indexOf("#");if(n===-1)return null;let r=t.substring(n+1),o=new URLSearchParams(r),i=o.get("access_token");return i?!e.allowUnsolicited&&!Pe(Qo,lc(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 lc(t,e){let n=t.indexOf("?");return n===-1||n>e?null:new URLSearchParams(t.substring(n+1,e)).get(Yo)}function Cr(t,e){let n=new URL(e.callbackUrl);n.searchParams.set(Yo,at(Qo,{}));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 uc(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 $t({method:r.method,path:r.path,body:uc(r.body),issuedAt:o,expiresAt:o+e,signerSecret:t.signerSecret})})}}var zt=class extends Error{constructor(e,n,r,o){super(n),this.name="RpcError",this.code=e,this.data=r,this.type=o}};async function Sr(t,e,n){let r=await t.post("/jsonrpc",{jsonrpc:"2.0",id:1,method:e,params:n});if(r.error){let o=r.error;throw new zt(o.code??-1,o.message??o.type??"RPC error",o.data,o.type)}return r.result}var ct=class{constructor(e){this.kind="node";this.canSubscribe=!0;this.httpClient=e.httpClient}async execute(e){let n=await Sr(this.httpClient,"execute",{contextId:e.contextId,method:e.method,argsJson:e.argsJson??{}});return n&&"output"in n?n.output:n}async executeWithMetadata(e){return{returns:await this.execute(e),transport:"node"}}async migrateMyEntries(e){return this.execute({contextId:e,method:"migrate_my_entries"})}async countMyPending(e){return this.execute({contextId:e,method:"count_my_pending"})}};var dc=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function Xo(t){return t.type!==void 0&&dc.has(t.type)}var pc=new Set(["token_reuse","token_revoked"]),gc=new Set([401,403]),mc=1e4;function Zo(t){let e=t.headers.get("x-auth-error");return!e||!gc.has(t.status)?null:pc.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=>{Xo(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 D(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")),mc);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 D(d.status,d.statusText,`${this.baseUrl}/sse/subscription`,d.headers,p)}return null}catch(i){return i instanceof Error?i:new Error(`SSE ${e} failed`)}finally{clearTimeout(o)}}forceReconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.sessionId=null,this.connect()}scheduleReconnect(){this.closed||(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.forceReconnect()},this.reconnectDelayMs))}close(){this.closed=!0,this.abortController&&(this.abortController.abort(),this.abortController=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.sessionId=null,this.subscribedContextIds.clear(),this.subscribedGroupIds.clear()}};var 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 lt=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,n,r=se()){await Sr(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 fc=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function ei(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=m(t,e,32),r=f(fc,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 ei(s)}return ni(o,i)}async function ti(t,e){if(t.type!=="private")throw new Error(`signerFromCryptoKey needs the private half of the pair, got a ${t.type} key`);if(!t.usages.includes("sign"))throw new Error("this CryptoKey cannot sign: generate it with usages ['sign', 'verify']");let n;if(typeof e=="string")m(e,"publicKey",32),n=e.trim().toLowerCase();else try{n=y(new Uint8Array(await crypto.subtle.exportKey("raw",e)))}catch(r){let o=r instanceof Error?`: ${r.message}`:"";throw new Error("could not read the public half of this key pair; pass the public key as 64 hex instead"+o)}return ni(t,n)}function ni(t,e){return{publicKey:e,async sign(n){try{return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},t,n))}catch(r){throw ei(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 hc=new TextEncoder().encode("calimero.mdma.account-ownership-claim.v1\0"),yc=6e4,ri=5*6e4,oi=1024,si="mdma:enable-ha-namespace",ai="mdma:enable-ha-namespace-as-account";function ii(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var kr=(t,e)=>{if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);return t.toLowerCase()};async function ci(t,e,n,r){if(r!==void 0&&!(r.length>0&&r.length<=oi))throw new Error(`relayUrl must be a non-empty string of at most ${oi} characters`);let o=t.ttlMs??yc;if(!(o>0&&o<=ri))throw new Error(`ttlMs must be in (0, ${ri}]`);let i=kr(t.namespaceId,"namespaceId"),s=kr(t.accountId,"accountId"),a=kr(t.salt,"salt"),c=await I(t.deviceSecret,t.signer,"deviceSecret"),u=(t.now??Date.now)(),d=Array.from(crypto.getRandomValues(new Uint8Array(16)),x=>x.toString(16).padStart(2,"0")).join(""),l=new TextEncoder().encode(JSON.stringify({v:1,audience:e,group_id:i,account_id:s,salt:a,...n===void 0?{}:{subject:n},nonce:d,issued_at_ms:u,expires_at_ms:u+o,...r===void 0?{}:{relay_url:r}})),p=await c.sign(f(hc,l));return{kind:"account",credential:t.credential,signed_payload:ii(l),signature:ii(p)}}async function bc(t){if(!t.subject)throw new Error("subject must be the cloud login email");return ci(t,si,t.subject)}async function Er(t){return ci(t,ai,void 0,t.relayUrl)}var wc=new TextEncoder().encode("calimero.device.cert.v1"),Ac=new TextEncoder().encode("calimero.account.genesis.v1"),xc=new TextEncoder().encode("calimero.device.id.v1"),Ne=2,vc=237;async function Ir(t,e){if(e.length!==16)throw new Error(`nonce must be 16 bytes, got ${e.length}`);let n=m(t,"account",32),r=await E(xc,[n,e]);return y(f(e,r.subarray(0,16)))}async function Xt(t){return E(wc,[m(t.account,"account",32),m(t.device,"device",32),m(t.signPublicKey,"signPublicKey",32),m(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch)])}function li(t){return f(new Uint8Array([Ne]),t.rootPublicKey,R(0),m(t.account,"account",32),m(t.device,"device",32),m(t.signPublicKey,"signPublicKey",32),m(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch),t.signature)}async function ui(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=m(e.publicKey,"signer.publicKey",32),r=await F(e.publicKey),o=0,i=await Xt({account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch}),s=await e.sign(i),a=li({rootPublicKey:n,account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch,signature:s});return y(a)}function Pr(t){let e=m(t,"credential",vc);if(e[0]!==Ne)throw new Error(`this credential has account genesis version ${e[0]}, not ${Ne} \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=Pr(t),n=await F(e.rootPublicKey);if(n!==e.account)throw new Error(`this credential names account ${e.account}, but its root key derives ${n} \u2014 the certificate was re-pointed at another account`);let r=m(e.device,"device",32).subarray(0,16);if(await Ir(e.account,r)!==e.device)throw new Error(`this credential names device ${e.device}, which was not minted for account ${e.account}; core refuses it`);if(!await Ko(e.rootPublicKey,m(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(Ac,[f(new Uint8Array([Ne]),m(t,"rootPublicKey",32))]))}var Rc=new TextEncoder().encode("calimero.device.scope.v1");async function Tr(t){return E(Rc,[m(t.account,"account",32),m(t.device,"device",32),R(t.scopeEpoch),R(t.keyEpoch),...t.applications.map((e,n)=>m(e,`applications[${n}]`,32))])}async function di(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=m(e.publicKey,"signer.publicKey",32),r=await F(y(n)),o=t.applications??[],i=t.scopeEpoch??0;if(!Number.isInteger(i)||i<0||i>4294967295)throw new Error(`scopeEpoch must be a u32, got ${i}`);let s=0,a=await Tr({account:r,device:t.device,applications:o,scopeEpoch:i,keyEpoch:s}),c=await e.sign(a);if(c.length!==64)throw new Error(`signer returned ${c.length} bytes, expected a 64-byte Ed25519 signature`);return y(f(new Uint8Array([Ne]),n,R(0),m(r,"account",32),m(t.device,"device",32),R(o.length),...o.map((u,d)=>m(u,`applications[${d}]`,32)),R(i),R(s),c))}var Dr=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"];var Cc=new TextEncoder().encode("calimero.mdma.account-link.v1\0"),Sc=new TextEncoder().encode("calimero.mdma.account-login.v1\0"),Ue=256,pi=Ue/32,Nr=(Ue+pi)/11;async function gi(){let t=crypto.getRandomValues(new Uint8Array(Ue/8));return wi(y(t),await xi(t))}async function mi(t){let e=Ai(t);return wi(y(await vi(e)),e.join(" "))}async function Ur(t){return m(t,"secret",32),{secret:t,publicKey:y(await re(t)),accountId:await en(t)}}async function fi(){let t=crypto.getRandomValues(new Uint8Array(Ue/8)),e=await xi(t);return{...await yi(t),phrase:e}}async function hi(t){return yi(await vi(Ai(t)))}async function yi(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 bi(e)}async function tn(t,e){return bi(await I(t,e,"rootSecret"))}async function bi(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(Cc,new TextEncoder().encode(t.nonce)));return Si(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(Sc,new TextEncoder().encode(t.nonce)));return Si(n)}async function wi(t,e){return{...await Ur(t),phrase:e}}function Ai(t){let e=t.normalize("NFKD").toLowerCase().trim().split(/\s+/),n=e[0]===""?0:e.length;if(n!==Nr)throw new Error(`recovery phrase must be ${Nr} words, got ${n}`);return e}async function xi(t){let e=Ci(t)+await Ri(t),n=[];for(let r=0;r<Nr;r+=1){let o=Number.parseInt(e.slice(r*11,r*11+11),2);n.push(Dr[o])}return n.join(" ")}async function vi(t){let e="";for(let r of t){let o=Dr.indexOf(r);if(o<0)throw new Error(`"${r}" is not a word in the recovery phrase list`);e+=o.toString(2).padStart(11,"0")}let n=new Uint8Array(Ue/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(Ue)!==await Ri(n))throw new Error("recovery phrase checksum failed \u2014 check for a mistyped or transposed word");return n}async function Ri(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return Ci(e).slice(0,pi)}function Ci(t){let e="";for(let n of t)e+=n.toString(2).padStart(8,"0");return e}function Si(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var kc=new TextEncoder().encode("calimero.tee-attest.key-binding.v1"),rn=new TextEncoder().encode("MOCK_TDX_QUOTE_V1"),Ec=568;function Ic(...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 Pc(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 Tc(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",Ic(kc,new Uint8Array(32),t));return new Uint8Array(e)}function _r(t){let e=t.length>=rn.length&&Or(t.subarray(0,rn.length),rn),n=e?rn.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 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=Tc(a.boundPublicKey,"boundPublicKey"),u=Pc(a.quoteB64),{reportData:d,mock:l}=_r(u);if(l){if(!t.allowMock)throw new Error("the relay answered with a MOCK quote, which proves nothing about the hardware")}else if(t.verify){if(!await t.verify({quoteB64:a.quoteB64,nonce:y(e),reportDataSuffix:y(await 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 Dc="Noise_NK_25519_AESGCM_SHA256",Mr=32,Nc=16,Uc=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(Dc),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 Ei(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:ki(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:ki(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),n}split(){return Ei(this.ck,new Uint8Array)}};async function Ii(t,e,n){let r=await Gr.initialize();await r.mixHash(e),await r.mixHash(t);let o=await Oe(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<Mr+Nc)throw new Error("Noise: message 2 is too short");let a=s.slice(0,Mr);return await r.mixHash(a),await r.mixKey(await dt(o.privateKey,a)),{payload:await r.decryptAndHash(s.slice(Mr)),split:await r.split()}}}}async function Oe(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:_c(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 ki(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 Kr(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 Ei(t,e){let n=await Kr(t,e),r=await Kr(n,new Uint8Array([1])),o=await Kr(n,f(r,new Uint8Array([2])));return[r,o]}function _c(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 Ni="/sealed/v2/handshake",Ui="/sealed/v2",gt="application/vnd.calimero.sealed",$r=2,Mc=new TextEncoder().encode("calimero/sealed-http/v2"),pt=16,Kc=1+pt+8,Gc=0,$c=1,Lc=2,Hc=1+64*1024+16,Bc=1024,qc=6e4,jc="calimero.tee-attest.transport-key.v1",Fc=[101,204,205,304],Oi=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 _i(t,e){let n=await crypto.subtle.digest("SHA-256",f(Oi.encode(jc),t,e));return new Uint8Array(n)}async function Mi(t,e,n={}){if(n.applicationId===void 0!=(n.applicationHash===void 0))throw new Error("applicationId and applicationHash are given together or not at all");let r=y(crypto.getRandomValues(new Uint8Array(32))),o=await t.teeAttest({nonce:r,applicationId:n.applicationId,bindTransportKey:!0,...e.includeCollateral?{includeCollateral:!0}:{}});if(!o.transportPublicKey)throw new Error("The node did not report a transport key; it predates sealed transport");let i=m(o.transportPublicKey,"transportPublicKey",32),s=n.applicationHash?m(n.applicationHash,"applicationHash",32):new Uint8Array(32),a=y(await _i(s,i));if(!await e({quoteB64:o.quoteB64,nonce:r,reportDataSuffix:a,collateral:o.collateral}))throw new Error("The attestation did not verify, so its transport key is not trusted");return i}function 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 Ki({baseUrl:t.baseUrl,transportPublicKey:()=>Mi(r,t.verify,{applicationId:t.applicationId,applicationHash:t.applicationHash}),fetch:e})}function Ki(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 Ti(o,r,await Pi(s))}catch(l){if(!(l instanceof mt)||!i)throw l;return s=Promise.resolve().then(i),Ti(o,r,await Pi(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 Wc(h,b,k),M=await o(`${r}${Ui}`,{method:"POST",headers:{"content-type":gt},body:U,signal:x.signal});if(M.headers.get("content-type")!==gt)throw await $i(M);return zc(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 Pi(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function Ti(t,e,n){try{return await Di(t,e,n)}catch(r){if(!(r instanceof _e)||r.code!=="busy")throw r;return await new Promise(o=>setTimeout(o,r.retryAfterMs??1e3)),Di(t,e,n)}}async function Di(t,e,n){let r=await Ii(n,Mc),o=await t(`${e}${Ni}`,{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 Yc(o,Bc);return Vc(r,i)}async function Vc(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-qc,header(u){let d=new Uint8Array(Kc);return d[0]=$r,d.set(i,1),new DataView(d.buffer).setBigUint64(1+pt,BigInt(u),!1),d}}}async function Wc(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,Jc(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 Jc(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 zc(t,e,n,r){if(!t.body)throw new Error("The sealed response has no body");let o=Qc(t.body.getReader()),i=0,s=async()=>{let d=await o.next();if(!d)return null;let l;try{l=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv: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!==Gc)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(Fc.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===$c?d.enqueue(l.data):l.kind===Lc?(d.close(),await o.cancel()):d.error(new Error("The sealed response is malformed")):d.error(new Error("The sealed response was cut short"))}catch(l){d.error(l)}},cancel(){return o.cancel()}});return new Response(u,{status:c.status,headers:c.headers})}function Qc(t){let e=new Uint8Array,n=async r=>{for(;e.length<r;){let{done:o,value:i}=await t.read();if(o)return!1;e=f(e,i)}return!0};return{async next(){if(!await n(4))return null;let r=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(r>Hc)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 Yc(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 Xc=/^[0-9a-f]{96}$/,Zc=["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 Zc.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=tl(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=el(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(!Xc.test(r))throw new Error(`${e} holds ${JSON.stringify(n)}, which is not a 48-byte hex measurement`);return r})}function el(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 tl(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 nl=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],ft="locked-read-only";function Lr(t,{profile:e,allowDebugProfile:n=!1}){if(t.length===0)throw new Error("No release given, so no image would be trusted");let r,o=t.map((i,s)=>{let a=i?.tag??`releases[${s}]`;if(i?.role!==void 0&&i.role!=="node")throw new Error(`${a} lists the measurements of a ${i.role}, not of a node image`);let c=i?.profiles?.[e];if(!c){let d=Object.keys(i?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${d})`)}if(e!==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=>rl(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 rl(t,e){let n=nl.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 Li=[{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"]}],Hi=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var ol="1.2.840.10045.2.1",il={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},sl={"P-256":32,"P-384":48},al={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function Bi(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 Ge(t){let e=Bi(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function K(t){let e=[];for(let n=t.start;n<t.end;){let r=Bi(t.bytes,n,t.end);e.push(r),n=r.end}return e}function O(t,e,n){if(!t||t.tag!==e)throw new Error(`${n} is not where it should be`);return t}function ae(t){return t.bytes.slice(t.start,t.end)}function an(t){return t.bytes.slice(t.offset,t.end)}function Ke(t){let e=ae(O(t,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let n=[],r=0;for(let s of e)r=r*128+(s&127),s&128||(n.push(r),r=0);let o=n.shift();return[...o<80?[Math.floor(o/40),o%40]:[2,o-80],...n].join(".")}function cl(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 Hr(t){try{let[e,n,r,...o]=K(O(Ge(t),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let i=K(O(e,48,"The signed part")),s=i[0]?.tag===160?1:0,[a,c,u,d,l,p,...x]=i.slice(s);O(a,2,"The serial number");let v=Ke(K(O(n,48,"The signature algorithm"))[0]);if(Ke(K(O(c,48,"The signature algorithm"))[0])!==v)throw new Error("it names two different signature algorithms");let b=al[v];if(!b)throw new Error(`it is signed with ${v}, not ECDSA with SHA-256 or SHA-384`);let[k,T]=K(O(d,48,"The validity")).map(cl);if(T===void 0)throw new Error("its validity is incomplete");let[H,z]=K(O(p,48,"The public key"));O(z,3,"The public key");let[h,w]=K(O(H,48,"The key algorithm"));if(Ke(h)!==ol)throw new Error("its key is not an elliptic-curve key");let S=il[Ke(w)];if(!S)throw new Error("its key is on a curve other than P-256 or P-384");let U=new Map,M=x.find(ee=>ee.tag===163);if(M){let[ee]=K(M);for(let te of K(O(ee,48,"The extensions"))){let Se=K(O(te,48,"An extension"));if(Se.length===3)O(Se[1],1,"An extension's critical flag");else if(Se.length!==2)throw new Error("it has a malformed extension");let ur=Ke(Se[0]);if(U.has(ur))throw new Error(`it has extension ${ur} twice`);U.set(ur,ae(O(Se[Se.length-1],4,"An extension value")))}}let Q=ae(O(r,3,"The signature"));if(Q[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:an(e),signatureHash:b,signature:Q.slice(1),issuer:an(O(u,48,"The issuer")),subject:an(O(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 qi(t){return K(O(Ge(t),48,"The list")).map(Ke)}function ll(t,e){let n=sl[e],r=K(O(Ge(t),48,"The signature"));if(r.length!==2)throw new Error("The signature is not an ECDSA signature");let o=new Uint8Array(n*2);return r.forEach((i,s)=>{let a=ae(O(i,2,"The signature"));if(a.length===0||a[0]&128)throw new Error("The signature is not an ECDSA signature");for(;a.length>1&&a[0]===0;)a=a.subarray(1);if(a.length>n)throw new Error("The signature is not an ECDSA signature");o.set(a,s*n+n-a.length)}),o}async function cn(t,e,n,r,o){let i;try{i=ll(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 Br(t,e){let n=[...t.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(n.length!==1||t.replace(n[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return V(n[0][1],e)}var ul="2.5.29.17",dl="2.5.29.37",pl="1.3.6.1.5.5.7.3.3",gl="1.3.6.1.4.1.57264.1.8",ml="1.3.6.1.4.1.57264.1.1",fl=134,hl=12,yl=48,bl=new TextEncoder,$e=t=>new TextDecoder().decode(t);async function ln(t,e,n,r){let{base64Signature:o,cert:i,rekorBundle:s}=vl(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=Br($e(V(i,"The bundle certificate")),"The bundle certificate"),d=Hr(u),l=Hi.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=bl.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(!Vi(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=Rl(a.body),b=y(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(P.hash!==b)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!qr(V(P.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let k=Br($e(V(P.publicKey,"The logged certificate")),"The logged certificate");if(!qr(k,u))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await 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 wl(d,v),xl(d,n),{integratedTime:a.integratedTime}}async function wl(t,e){if(!Fi(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 Li){let o=r.certChain.map(s=>Hr(V(s,"A Fulcio certificate")));if(!await ji(t,o[0]))continue;let i=await Al(o,r.validFor,e);if(!i)return;n.push(`${r.uri} (valid from ${r.validFor.start}): ${i}`)}throw new Error(n.length>0?`The signing certificate's CA is not trusted at ${yt(e)}: ${n.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function Al(t,e,n){if(!Vi(n,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of t.entries()){if(!Fi(o,n))return`its certificate ${r} was not valid then`;let i=t[r+1]??o;if(!await ji(o,i))return`its certificate ${r} is not signed by the next`}}async function ji(t,e){return qr(t.issuer,e.subject)?cn(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function xl(t,e){let n=t.extensions.get(ul);if(!n)throw new Error("The signing certificate names no identity");let r=K(O(Ge(n),yl,"The subject alternative name")),o=r.filter(u=>u.tag===fl).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(gl),s=t.extensions.get(ml),a=i?$e(ae(O(Ge(i),hl,"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(dl);if(!c||!qi(c).includes(pl))throw new Error("The signing certificate is not for code signing")}function vl(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 Rl(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 Fi(t,e){return t.notBefore<=e&&e<=t.notAfter}function Vi(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 qr(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var jr=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-node-image-gcp.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),Cl=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],un="https://cloud.calimero.network";async function Ji(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await ln(r,e,{identity:n.identity??jr.identity,issuer:n.issuer??jr.issuer},n.signature);let o;try{o=JSON.parse(new TextDecoder().decode(r))}catch{throw new Error("The signed release is not JSON")}if(o?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(o?.role)} release, not a node one`);let i=Object.values(o.profiles??{}),s=a=>Cl.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 zi(t){let e=/^merotee-.+-(\d+)-(\d+)-(\d+)$/.exec(t);if(!e)throw new Error(`${JSON.stringify(t)} is not the image of a mero-tee node release`);return`${Number(e[1])}.${Number(e[2])}.${Number(e[3])}`}async function pn(t,e={}){let n=await Yi(t,e.fetch??fetch);if(n===void 0)throw new Error(`${Qi(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 Qi(t){return`${t.replace(/\/+$/,"")}/admin-api/tee/info`}async function Yi(t,e){let n=Qi(t),r=await e(n,{headers:{accept:"application/json"}});if(r.status===403&&await r.json().then(s=>s?.error?.code).catch(()=>{})==="sealed_required")return;if(!r.ok)throw new Error(`Fetching ${n} failed: HTTP ${r.status}`);let o;try{o=(await r.json())?.data?.osImage}catch{throw new Error(`${n} did not answer with JSON`)}if(typeof o!="string")throw new Error(`${n} did not name the node's image`);return zi(o)}function gn(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${bt(e,"version")}`}async function Xi(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(kl(n,e)<0)throw new Error(`Release ${n} is older than the minimum trusted, ${e}`);return Lr([r],{profile:t.profile,allowDebugProfile:t.allowDebugProfile})}function mn(t){return bt(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async n=>{let r=await Xi({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 Sl(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:mn({...a,release:async()=>{let d=r===void 0?await pn(e,{fetch:c}):await Yi(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 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 kl(t,e){let[n,r]=Wi(t),[o,i]=Wi(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 Wi(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"),Il=new TextEncoder().encode("calimero.warrant.intent.v1"),es=64,ts=256;async function Fr(t,e){let n=new TextEncoder().encode(JSON.stringify(e));return E(Il,[new TextEncoder().encode(t),n])}async function fn(t){let e=m(t.context,"context",32),n=m(t.authorAccount,"authorAccount",32),r=m(t.executor,"executor",32),o=m(t.executorKey,"executorKey",32),i=m(t.releaseBytecodeId,"releaseBytecodeId",32),s=Vr(t.releaseVersion??""),a=ce(t.accountHeads,"accountHeads"),c=ce(t.governanceFloor,"governanceFloor"),u=await I(t.deviceSecret,t.signer,"deviceSecret"),d=m(u.publicKey,"signer.publicKey",32),l=new TextEncoder().encode(t.method),p=await Fr(t.method,t.argsJson),x=C(t.nonce),v=C(t.notAfter),P=await E(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 Vr(t){let e=new TextEncoder().encode(t);return Pl(e.length),e}function Pl(t){if(t>ts)throw new Error(`releaseVersion is ${t} bytes, over the ${ts} a node accepts`)}function ce(t,e){let n=t??[];if(n.length>es)throw new Error(`${e} cites ${n.length} heads, over the ${es} a node accepts`);return n.map((r,o)=>m(r,`${e}[${o}]`,32))}var Tl=new TextEncoder().encode("calimero.context-creation-warrant.v1"),Dl=new TextEncoder().encode("calimero.context-creation.init.v1"),hn=256;async function Wr(t){let e=new TextEncoder().encode(JSON.stringify(t));return E(Dl,[e])}async function Nl(t){return E(Tl,[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=m(t.group,"group",32),n=t.seed===void 0?crypto.getRandomValues(new Uint8Array(32)):m(t.seed,"seed",32),r=m(t.authorAccount,"authorAccount",32),o=m(t.executor,"executor",32),i=m(t.executorKey,"executorKey",32),s=m(t.applicationId,"applicationId",32),a=ns(t.serviceName,"serviceName"),c=ns(t.name,"name"),u=ce(t.accountHeads,"accountHeads"),d=ce(t.governanceFloor,"governanceFloor"),l=await I(t.deviceSecret,t.signer,"deviceSecret"),p=m(l.publicKey,"signer.publicKey",32),x=await Wr(t.initArgs),v=await Nl({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,rs(a),rs(c),x,R(u.length),...u,R(d.length),...d,C(t.nonce),C(t.notAfter),P)),seed:y(n)}}function os(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 ns(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 rs(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"),_l={group:0,root:1};async function Jr(t){return E(Ol,[new Uint8Array([zr(t.kind)]),t.bytes])}async function Ml(t){return E(Ul,[t.scope,new Uint8Array([zr(t.kind)]),t.authorAccount,t.deviceKey,t.executor,t.executorKey,t.opHash,C(t.accountHeads.length),...t.accountHeads,C(t.governanceFloor.length),...t.governanceFloor,C(t.nonce),C(t.notAfter)])}async function At(t){let e=m(t.scope,"scope",32),n=m(t.authorAccount,"authorAccount",32),r=m(t.executor,"executor",32),o=m(t.executorKey,"executorKey",32),i=ce(t.accountHeads,"accountHeads"),s=ce(t.governanceFloor,"governanceFloor"),a=zr(t.op.kind),c=await I(t.deviceSecret,t.signer,"deviceSecret"),u=m(c.publicKey,"signer.publicKey",32),d=await Jr(t.op),l=await Ml({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 is(t){let e=t.trim();if(!/^[0-9a-fA-F]*$/.test(e)||e.length%2!==0)throw new Error("governance warrant must be an even number of hex characters");let n=new Uint8Array(e.length/2);for(let l=0;l<n.length;l+=1)n[l]=Number.parseInt(e.slice(l*2,l*2+2),16);let r=new DataView(n.buffer),o=0,i=(l,p)=>{if(o+l>n.length)throw new Error(`governance warrant ends inside ${p} (${n.length} bytes)`);let x=n.subarray(o,o+l);return o+=l,x},s=l=>r.getUint32(i(4,l).byteOffset,!0),a=l=>r.getBigUint64(i(8,l).byteOffset,!0),c=l=>{let p=s(l);if(p>64)throw new Error(`${l} cites ${p} heads, over the 64 a node accepts`);return Array.from({length:p},()=>y(i(32,l)))},u=()=>{let l=i(1,"kind")[0];if(l===0)return"group";if(l===1)return"root";throw new Error(`governance warrant has kind ${l}, expected 0 (group) or 1 (root)`)},d={scope:y(i(32,"scope")),kind:u(),authorAccount:y(i(32,"authorAccount")),deviceKey:y(i(32,"deviceKey")),executor:y(i(32,"executor")),executorKey:y(i(32,"executorKey")),opHash:y(i(32,"opHash")),accountHeads:c("accountHeads"),governanceFloor:c("governanceFloor"),nonce:a("nonce"),notAfter:a("notAfter"),signature:y(i(64,"signature"))};if(o!==n.length)throw new Error(`governance warrant is ${n.length} bytes but its fields account for ${o}`);return d}function zr(t){let e=_l[t];if(e===void 0)throw new Error(`op kind must be 'group' or 'root', got ${String(t)}`);return e}var Kl={Admin:0,Member:1,ReadOnly:2},G={MemberAdded:1,MemberRemoved:2,MemberLeft:3,MemberRoleSet:4,MemberCapabilitySet:5,DefaultCapabilitiesSet:6,TargetApplicationSet:7,ContextDetached:9,SubgroupVisibilitySet:10,GroupMetadataSet:11,MemberMetadataSet:12,ContextMetadataSet:13,ContextCapabilityGranted:16,ContextCapabilityRevoked:17},xt={GroupCreated:0,GroupReparented:1,GroupDeleted:2,MemberJoinedOpen:7,NamespaceCreatedV2:9},Gl=new TextEncoder().encode("calimero.namespace.id.v1"),Yr=new Uint8Array(32),bn=R(0);function as(t){let e=Kl[t];if(e===void 0)throw new Error(`role must be Admin, Member or ReadOnly, got ${String(t)}`);return new Uint8Array([e])}function N(t){return new Uint8Array([t])}function Le(t,e){return{kind:"group",bytes:f(N(G.MemberAdded),m(t,"member",32),as(e))}}function wn(t){return{kind:"group",bytes:f(N(G.MemberRemoved),m(t,"member",32),Yr,bn)}}function vt(t){return{kind:"group",bytes:f(N(G.MemberLeft),m(t,"member",32),Yr,bn)}}function An(t,e){return{kind:"group",bytes:f(N(G.MemberRoleSet),m(t,"member",32),as(e))}}var $l=new TextEncoder().encode("calimero.subgroup.id.v1");async function Xr(t,e,n,r){return y(await E($l,[m(t,"admin",32),m(e,"parentId",32),new Uint8Array([n?1:0]),m(r,"salt",32)]))}function ss(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(N(G.TargetApplicationSet),Yr,m(t.applicationId,"applicationId",32),ss(t.package,"package"),ss(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(N(G.DefaultCapabilitiesSet),R(t))}}function Zr(t){return{kind:"root",bytes:f(N(xt.GroupCreated),m(t.groupId,"groupId",32),m(t.parentId,"parentId",32),N(t.restricted?1:0),m(t.admin,"admin",32),m(t.salt,"salt",32))}}async function Be(t){let e=t.salt??y(crypto.getRandomValues(new Uint8Array(32))),n=await Xr(t.admin,t.parentId,t.restricted,e);return{groupId:n,salt:e,op:Zr({...t,groupId:n,salt:e})}}function vn(t,e){return{kind:"root",bytes:f(N(xt.GroupReparented),m(t,"childGroupId",32),m(e,"newParentId",32))}}function Rn(t){return{kind:"root",bytes:f(N(xt.GroupDeleted),m(t,"rootGroupId",32),bn,bn)}}async function Cn(t,e){return y(await E(Gl,[m(t,"founder",32),m(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(N(xt.NamespaceCreatedV2),m(t.founder,"founder",32),e,m(t.salt,"salt",32))}}function Qr(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}function eo(t){return t===void 0?N(0):f(N(1),Qr(t))}function to(t={}){let e=new TextEncoder,n=Object.entries(t).map(([r,o])=>[e.encode(r),o,r]).sort(([r],[o])=>{for(let i=0;i<Math.min(r.length,o.length);i++)if(r[i]!==o[i])return r[i]-o[i];return r.length-o.length});return f(R(n.length),...n.flatMap(([,r,o])=>[Qr(o),Qr(r)]))}function Ll(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(N(G.MemberCapabilitySet),m(t,"member",32),R(Ll(e,"capabilities")))}}function En(t){return{kind:"group",bytes:f(N(G.ContextDetached),m(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(N(G.SubgroupVisibilitySet),N(t==="open"?0:1))}}function qe(t={}){return{kind:"group",bytes:f(N(G.GroupMetadataSet),eo(t.name),to(t.data))}}function Pn(t,e={}){return{kind:"group",bytes:f(N(G.MemberMetadataSet),m(t,"member",32),eo(e.name),to(e.data))}}function Tn(t,e={}){return{kind:"group",bytes:f(N(G.ContextMetadataSet),m(t,"contextId",32),eo(e.name),to(e.data))}}function cs(t){if(!Number.isInteger(t)||t<1||t>255)throw new Error(`capability must be a non-zero u8, got ${String(t)}`);return N(t)}function ls(t,e,n){return{kind:"group",bytes:f(N(G.ContextCapabilityGranted),m(t,"contextId",32),m(e,"member",32),cs(n))}}function us(t,e,n){return{kind:"group",bytes:f(N(G.ContextCapabilityRevoked),m(t,"contextId",32),m(e,"member",32),cs(n))}}function Dn(t){return{kind:"root",bytes:f(N(xt.MemberJoinedOpen),m(t.member,"member",32),m(t.groupId,"groupId",32),j(t.credential,"credential"))}}var Nn=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"}},Hl=t=>new Promise(e=>setTimeout(e,t));function Bl(t){let e=t?.get?.("Retry-After");if(!e)return null;let n=Number.parseInt(e,10);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);return Number.isFinite(r)?Math.max(0,r-Date.now()):null}var W=class{constructor(e){this.config=e,this.baseUrl=e.relayUrl.replace(/\/+$/,"");let n=e.fetch;this.fetchImpl=n?(r,o)=>n(r,o):(r,o)=>globalThis.fetch(r,o),this.timeoutMs=e.timeoutMs??1e4,this.rateLimitRetries=e.rateLimitRetries??3}get relayUrl(){return this.baseUrl}get authorAccount(){return this.config.authorAccount}get authorProof(){return this.config.authorProof}async authorSigner(){return I(this.config.deviceSecret,this.config.signer,"deviceSecret")}async describe(e){return(await this.json("GET",`/admin-api/contexts/${g(e)}/intents`)).data}async execute(e,n,r={}){let o=await this.describe(e),i=this.checkedExecutor(o),s=y(m(o.releaseBytecodeId??"","the relay's releaseBytecodeId",32)),a=o.releaseVersion??"";Vr(a);let c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??Nn,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/${g(e)}/intents`,{method:n,argsJson:r,warrant:l,authorProof:this.config.authorProof});return{rootHash:p.data.rootHash,returns:p.data.returns??null}}async presenceIntent(e,n){await this.jsonOnce("POST",`/admin-api/contexts/${g(e)}/presence-intents`,n)}async describeCreation(e,n={}){let r=n.author?`?author=${encodeURIComponent(n.author)}`:"";return(await this.json("GET",`/admin-api/groups/${g(e)}/context-intents${r}`)).data}async createContext(e){let n=await this.describeCreation(e.groupId,{author:this.config.authorAccount});if(!n.canCreateOnBehalf)throw new he(`the relay (${n.executorAccount}) has no standing to act for members of group ${n.groupId}; an admin must admit it as a relay or grant it CAN_AUTHOR_ON_BEHALF (checked before signing \u2014 no nonce was spent)`,!1,403);if(n.authorMayCreate===!1)throw new he(`the author (${this.config.authorAccount}) may not create contexts in group ${n.groupId}; it needs CAN_CREATE_CONTEXT or admin (checked before signing \u2014 no nonce was spent)`,!1,403);let r=this.checkedExecutor(n),o=e.initArgs??{},i=await this.authorSigner(),s=await this.config.nonces.next(),a=this.config.ttlSeconds??Nn,{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/${g(e.groupId)}/context-intents`,{warrant:c,authorProof:this.config.authorProof,initArgs:o});return{contextId:u.data.contextId,groupId:u.data.groupId,memberPublicKey:u.data.memberPublicKey}}async describeGovernance(e){return(await this.json("GET",`/admin-api/groups/${g(e)}/governance-intents`)).data}async govern(e){let n=await this.describeGovernance(e.groupId);if(!n.canActOnBehalf)throw new he(`the relay (${n.executorAccount}) has no standing to act for members of group ${n.groupId}; an admin must admit it as a relay or grant it CAN_AUTHOR_ON_BEHALF (checked before signing, no nonce was spent)`,!1,403);let r=this.checkedExecutor(n),o=await this.authorSigner(),i=await this.config.nonces.next(),s=this.config.ttlSeconds??Nn,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(m(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??Nn,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/${g(e)}/governance-intents`,{warrant:r,authorProof:this.config.authorProof,op:y(n.bytes)})).data}checkedExecutor(e){let n={executorAccount:y(m(e.executorAccount??"","the relay's executorAccount",32)),executorKey:y(m(e.executorKey??"","the relay's executorKey",32))},r=this.config.executorAccount;if(r&&r.toLowerCase()!==n.executorAccount)throw new Error(`configured executorAccount ${r} is not the relay's account ${n.executorAccount}; a warrant naming it would be unspendable`);return n}async json(e,n,r){let o=250;for(let i=0;;i+=1)try{return await this.jsonOnce(e,n,r)}catch(s){if(!(s instanceof D&&s.status===429)||i>=this.rateLimitRetries)throw s;let c=Bl(s.headers);await Hl(c??o),o*=2}}async jsonOnce(e,n,r){let o={Accept:"application/json"};r!==void 0&&(o["Content-Type"]="application/json");let i=new AbortController,s=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r===void 0?void 0:JSON.stringify(r),signal:i.signal})}catch(c){throw new D(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(!a.ok){let c=await a.text().catch(()=>"");if(a.status===400||a.status===403){let u=ql(c);throw new he(u,/nonce/i.test(u),a.status)}throw new D(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(a.status!==204)return await a.json()}};function ql(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 jl=new TextEncoder().encode("calimero.auth.login.v1"),ds={webOrigin:0,codeSigningId:1,cli:2};function ps(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 Fl(t){return f(Uint8Array.from([ds[t.kind]]),ps(t))}function Vl(t){let e=Uint8Array.from([ds[t.kind]]);if(t.kind==="cli")return e;let n=ps(t);return f(e,R(n.length),n)}async function Un(t){let e=m(t.node,"node",32),n=m(t.challenge,"challenge",32),r=m(t.sessionKey,"sessionKey",32),o=await I(t.deviceSecret,t.signer,"deviceSecret"),i=m(o.publicKey,"signer.publicKey",32),s=C(t.issuedAt),a=C(t.expiresAt),c=await E(jl,[e,Fl(t.audience),n,r,i,s,a]),u=await o.sign(c);return y(f(e,Vl(t.audience),n,r,i,s,a,u))}var Wl=300;async function no(){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 D(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 D(b.status,b.statusText,`${e}${p}`,b.headers,k);return k?JSON.parse(k):{}},o=await r("/auth/challenge",{method:"GET",headers:{Accept:"application/json"}}),i=o.challenge??o.data?.challenge;if(!i)throw new Error("the node issued no challenge");let s=await no(),a=Math.floor(Date.now()/1e3),c=await Un({node:t.node,audience:t.audience,challenge:i,sessionKey:s.publicKey,issuedAt:a,expiresAt:a+(t.ttlSeconds??Wl),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 Jl=3e4;function Ve(){let t=globalThis.location?.origin;return t?{kind:"webOrigin",origin:t}:{kind:"cli"}}function zl(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-Jl>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=zl(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 gs=new TextEncoder().encode("calimero/presence/1");async function ms(t){let e=t===null?new Uint8Array([0]):f(new Uint8Array([1]),R(t.length),t);return new Uint8Array(await crypto.subtle.digest("SHA-256",e))}async function ro(t){return f(gs,m(t.contextId,"contextId",32),m(t.author,"author",32),C(t.seq),C(t.sentAtMs),await ms(t.state))}var Ql=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??Ql,this.now=e.now??Date.now}async set(e,n,r=se()){let o=this.bump(e);this.refused.delete(e);let i=n===null?null:new Uint8Array(r.encode(n));await this.send(e,i),!(i===null||this.refused.has(e))&&this.generation.get(e)===o&&this.timers.set(e,setInterval(()=>{this.send(e,i).catch(()=>{})},this.heartbeatMs))}subscribe(e,n,r=se()){return 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 ro({contextId:e,author:r.publicKey,seq:BigInt(o),sentAtMs:BigInt(i),state:n}),a=y(await r.sign(s));try{await this.relay.presenceIntent(e,{state:n===null?null:y(n),seq:o,sentAtMs:i,signature:a,authorProof:this.relay.authorProof})}catch(c){let u=c.status;if(u===void 0||u===0||u===429||u>=500)return;throw this.refused.add(e),this.stop(e),c}}};function fs(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 hs(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 Yl(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=Yl(i,e.observe,o),this.rpcTransport=new ye(i,this.relayObserver),this.relayUrl=i.relayUrl,e.proof&&(this.proofAuthorizer=fr(e.proof)),e.session){let s=e.session;this.relayAdmin=Fo({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 fs("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 hs("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."):hs("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 fs("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 so="calimero.delegated.connection",ao="calimero.delegated.credential";function co(){if(typeof sessionStorage>"u")return null;try{let t=sessionStorage.getItem(so);return t?JSON.parse(t):null}catch{return null}}function bs(t){try{sessionStorage.setItem(so,JSON.stringify(t))}catch{}}function ws(){try{sessionStorage.removeItem(so)}catch{}}function As(){let t=co();if(t){let{account:e,credential:n,deviceSecret:r}=t;return{account:e,credential:n,deviceSecret:r}}if(typeof sessionStorage>"u")return null;try{let e=sessionStorage.getItem(ao);if(!e)return null;let n=JSON.parse(e);return!n.account||!n.credential||!n.deviceSecret?null:n}catch{return null}}function xs(t){try{sessionStorage.setItem(ao,JSON.stringify(t))}catch{}}function vs(){try{sessionStorage.removeItem(ao)}catch{}}function lo(t){let e=Mn(t);return{next:async()=>{let n=0n;try{n=Rs(t)}catch{n=0n}try{localStorage.setItem(e,String(n+1n))}catch{}return n}}}function Mn(t){return`calimero.nonce.${t}`}function Rs(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 Gn(t,e,n){try{Rs(t)<=n&&localStorage.setItem(Mn(t),String(n+1n))}catch{}}var Cs="calimero.delegated.relay-node-key.";function X(t){return t.replace(/\/+$/,"")}function uo(t,e){localStorage.setItem(Cs+X(t),e.trim().toLowerCase())}function $n(t){try{let e=localStorage.getItem(Cs+X(t));return e&&/^[0-9a-f]{64}$/.test(e)?e:null}catch{return null}}function po(t){try{let{hostname:e}=new URL(t);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch{return!1}}var Xl="locked-read-only",Zl="2.3.99",oo;function eu(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 ys(t,e){try{return await e()}catch(n){throw n instanceof Je?n:new Je(t,n)}}function tu(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 Ss(t,e){return Object.assign(async r=>{let o=await ys("loading the quote verifier",()=>(oo??(oo=import("@phala/dcap-qvl").then(i=>eu(i),i=>{throw oo=void 0,i})),oo));return mn({dcapVerify:o,release:()=>ys("fetching the release the relay runs",async()=>dn(gn(un,await pn(t,{fetch:e})))),profile:Xl,minReleaseVersion:Zl})(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=tu(r);try{let i=po(t),{nodeKey:s}=await sn({relayUrl:t,allowMock:i,fetch:o,...i?{}:{verify:Ss(t,o)}});return uo(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 Kn=[1e3,2e3,5e3,1e4,3e4];function nu(t,e){return new Promise(n=>{if(e?.aborted)return n();let r=setTimeout(o,t);function o(){clearTimeout(r),e?.removeEventListener("abort",o),n()}e?.addEventListener("abort",o)})}async function ks(t,e={}){let{signal:n}=e;for(let r=0;!n?.aborted;r+=1){let o=await 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=Kn[Math.min(r,Kn.length-1)];console.warn(`[mero-js] could not reach what proves the relay's node key; retrying in ${i/1e3} s`,o.error),await nu(i,n)}return null}function ru(t){try{let e=JSON.parse(atob(t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")));return typeof e.exp=="number"?e.exp*1e3:null}catch{return null}}var io=new Map;function Es(){io.clear()}async function ou(t){if(t.status!==403)return!1;try{return(await t.clone().json()).error?.code==="sealed_route_unguarded"}catch{return!1}}function iu(t){return t.headers.has("authorization")||new URL(t.url).pathname.startsWith("/auth/")}function su(t){let e=(o,i)=>globalThis.fetch(o,i),n=fe({baseUrl:t,verify:Ss(t,e),fetch:e}),r=!1;return async(o,i)=>{let s=new Request(o,i);if(r&&iu(s))return e(s);let a=await n(s.clone());return await ou(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(po(t))return;let e=X(t),n=io.get(e);return n||(n=su(t),io.set(e,n)),n}function au(t,e){let n=null,r=null;return async()=>{let o=n?ru(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 Is(){_n.clear()}function cu(t){return typeof t=="object"&&t!==null&&t.status===409}function lu(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){cu(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 uu(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 du(t,e){let n=e.session?lu(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=uu(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=On({transport:"relay",fetch:Qe(t.relayUrl),relay:{relayUrl:t.relayUrl,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:lo(t.relayUrl)},proof:{credential:t.credential,deviceSecret:t.deviceSecret},session:n?au({...t,relayUrl:t.relayUrl},n):void 0,observe:n?{nodeKey:n}:void 0});return du(r,{relayUrl:t.relayUrl,session:n!==null,attested:n!==null||po(t.relayUrl)})}var Ps="calimero.delegated.relays.";function q(t){try{let e=localStorage.getItem(Ps+t),n=e?JSON.parse(e):{};return{namespaces:n.namespaces??{},contexts:n.contexts??{}}}catch{return{namespaces:{},contexts:{}}}}function go(t,e){try{localStorage.setItem(Ps+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),go(t,r)}function Ts(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 Ds(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 go(t.account,n),e}async function Ns(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 go(t.account,r),e}function jn(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()}}}function pu(t){return{getWarrantNonce:(e,n)=>t.client.getWarrantNonceAsAuthor(e,t.authorProof)}}var qn=class extends Error{constructor(n,r){super(`author device ${r} has spent every nonce in context ${n}; it must re-key to write again`);this.contextId=n;this.authorDeviceKey=r;this.name="WarrantNonceExhaustedError"}};function gu(t){let e=Array.isArray(t.lookups)?t.lookups:[t.lookups];if(e.length===0)throw new Error("a recovering nonce source needs at least one node to ask");let n=t.local??jn(1),r=t.onLookupFailure??"throw",o=null,i=null,s=async()=>{let a=await Promise.allSettled(e.map(d=>d.getWarrantNonce(t.contextId,t.authorDeviceKey))),c=null,u=!1;for(let d of a){if(d.status!=="fulfilled")continue;let l=d.value;if(l.kind==="exhausted"){u=!0;continue}(c===null||l.nextNonce>c)&&(c=l.nextNonce)}if(c===null&&u)throw new qn(t.contextId,t.authorDeviceKey);if(c===null){let d=a.find(p=>p.status==="rejected"),l=d&&d.status==="rejected"?d.reason:void 0;if(r==="local"){o=0n;return}throw l instanceof Error?l:new Error(`no node could answer where the warrant-nonce sequence stands: ${String(l)}`)}o=c,await n.advanceTo?.(c)};return{async next(){o===null&&(i??(i=s().finally(()=>{i=null})),await i);let a=await n.next(),c=o!==null&&o>a?o:a;return o=c+1n,c},async advanceTo(a){(o===null||a>o)&&(o=a),await n.advanceTo?.(a)}}}async function 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=fu(r,t.namespaceId),i=await n.getNamespaceRelays(o.namespaceId),s=mo(i);if(!s)throw new Error(hu(o,i));let a=new W({relayUrl:s.relayUrl,executorAccount:s.executorAccount,authorAccount:t.authorAccount,authorProof:t.authorProof,signer:e,nonces:t.nonces??yu(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 mu(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 fu(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 hu(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 yu(t){let e=`mero-js:warrant-nonce:${t}`;try{return Ct(e)}catch{return jn(1)}}var bu=new TextEncoder().encode("calimero.mdma.routing-read.v1\0");async function Os(t,e){m(e,"deviceSecret",32);let n=await ne(e),r=f(bu,new TextEncoder().encode(t)),o=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,r));return wu(o)}async function Fn(t,e){return{"X-Calimero-Credential":e.credential,"X-Calimero-Nonce":t.nonce,"X-Calimero-Signature":await Os(t.nonce,e.deviceSecret)}}function wu(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var Au="https://cloud.calimero.network";function _s(t){let e=new URL(t.cloudWebUrl??Au);return e.searchParams.set("link-account",t.accountId),e.searchParams.set("callback-url",Vt(t.accountId,t.returnTo)),e.toString()}function xu(t){throw window.location.assign(_s(t)),new Error("redirecting to the cloud to authorise this link")}function vu(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Te(t.search??""),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;if(Te(t.search??"")?.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}}function fo(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+zo(location.search))}async function Ru(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 Cu="enrol-device",Su="enrol-kem",ku="callback-url",Gs="state",ho="calimero.device.enrol.pending";function $s(t){Ks(t.devicePublicKey,"devicePublicKey"),Ks(t.kemPublicKey,"kemPublicKey"),Du(t.returnTo),Tu(t.returnTo);let e=new URL(t.walletUrl);return e.searchParams.set(Cu,t.devicePublicKey),e.searchParams.set(Su,t.kemPublicKey),e.searchParams.set(ku,t.returnTo),e.searchParams.set(Gs,at(ho,{})),e.toString()}function Eu(t){throw window.location.assign($s(t)),new Error("redirecting to the wallet to approve this device")}function Iu(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Pe(ho,e.get(Gs)),Ms(),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;Ms();let s=e.get("state");return{credential:r,account:o,device:i,...s?{state:s}:{}}}function Ms(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+location.search)}async function Pu(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 Ks(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 Ls(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 Tu(t){Ls(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 Du(t){let e;try{e=new URL(t)}catch{throw new Error(`returnTo must be an absolute URL, got ${t}`)}let n=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]"||e.hostname==="::1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new Error(`returnTo must be https:, or http: on localhost \u2014 got ${e.protocol}//${e.hostname}`)}function Vn(t){if(!t)return null;let e=t.trim().toLowerCase(),n=e.startsWith("0x")?e.slice(2):e;return n.length>0?n:null}function Uu(t,e){if(e.size===0)return!0;let n=Vn(t.account);return n!==null&&e.has(n)}async function Wn(t){let e=t.cloud??new $({cloudBaseUrl:t.cloudBaseUrl,routingCredential:{credential:t.credential,deviceSecret:t.deviceSecret}}),n,r;try{let p=await e.getNamespaceRouting(t.namespaceId);n=p.nodes,r=p.servable}catch(p){return{ok:!1,step:"admitters-lookup",reason:`The cloud could not be asked which nodes serve namespace ${t.namespaceId}: ${p instanceof Error?p.message:String(p)}. Nothing is known about the invitation yet \u2014 this is the lookup failing, not the invitation.`}}if(n.length===0)return{ok:!1,step:"no-nodes",reason:"The cloud lists no nodes serving this namespace, so there is no hosted node to be admitted through. The namespace has no fleet assignment \u2014 whoever invited you is running their own node, and admission has to go through a node the cloud routes to."};let o=new Set((t.admitters??[]).map(Vn).filter(p=>p!==null)),i=n.filter(p=>Uu(p,o));if(i.length===0)return{ok:!1,step:"not-invited",reason:`${n.length} node${n.length===1?"":"s"} serve this namespace, but your invitation names none of them. The signed admitter list is a snapshot from when the invitation was minted, so a node assigned since is healthy and will still refuse the claim. Ask for a fresh invitation.`};let s=i.filter(p=>p.canAdmit),a=s.length>0?s:i,c=s.length===0||!r,u=a.filter(p=>typeof p.relayUrl=="string"&&p.relayUrl.length>0),[d]=u;if(d===void 0)return{ok:!1,step:"no-relay-url",reason:"A node your invitation names can admit you, but the cloud knows no address for it yet, so there would be nothing to connect through afterwards. Try again shortly."};let l=u.find(p=>p.canExecute)??u.find(p=>p.fresh)??d;return{ok:!0,relayUrl:l.relayUrl,admitUrl:l.admitUrl??`${l.relayUrl.replace(/\/+$/,"")}/admin-api/namespaces/${g(t.namespaceId)}/admit`,admitterAccount:l.account,peerId:l.peerId,writable:l.canExecute,stale:!l.fresh||c}}var Jn=1440*60,bo={Admin:0,Member:1,ReadOnly:2};function Pt(t){let e=t.admitters??[];return f(yo(t.inviter_identity,"inviter_identity"),yo(t.group_id,"group_id"),C(t.expiration_timestamp),yo(t.secret_salt,"secret_salt"),new Uint8Array([t.invited_role]),R(e.length),...e.map((n,r)=>m(n,`admitters[${r}]`,32)))}async function wo(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",Pt(t)))}function Ao(t){return[...new Set(t.filter(n=>n.role==="Admin").map(n=>n.identity.toLowerCase()))].sort()}async function zn(t){let e=await I(t.deviceSecret,t.signer,"deviceSecret"),n=m(e.publicKey,"signer.publicKey",32),r=m(t.groupId,"groupId",32);m(t.inviterAccount,"inviterAccount",32);let o=[...t.admitters??[]].map(p=>p.trim().toLowerCase());if(o.length===0){if(!t.members)throw new Error("name the admitters, or pass the group members to default them to its admins: an invitation with no admitters is claimable by broadcast");if(o=Ao(t.members),o.length===0)throw new Error("the member list names no admin, so there is nobody to default the admitters to")}o.forEach((p,x)=>m(p,`admitters[${x}]`,32));let i=t.invitedRole??bo.Member;if(![0,1,2].includes(i))throw new Error(`invitedRole must be 0 (Admin), 1 (Member) or 2 (ReadOnly), got ${i}`);let s=t.now??Math.floor(Date.now()/1e3),a=Math.min(t.validForSecs??Jn,Jn);if(!Number.isInteger(a)||a<=0)throw new Error(`validForSecs must be a positive whole number, got ${t.validForSecs}`);let c=t.nonce??crypto.getRandomValues(new Uint8Array(32));if(c.length!==32)throw new Error(`nonce must be 32 bytes, got ${c.length}`);let u={inviter_identity:Array.from(n),group_id:Array.from(r),expiration_timestamp:s+a,secret_salt:Array.from(c),invited_role:i,admitters:o},d=await e.sign(await wo(u));if(d.length!==64)throw new Error(`signer returned ${d.length} bytes, expected a 64-byte Ed25519 signature`);let l={invitation:u,inviter_signature:y(d),inviter_account:t.inviterAccount.trim().toLowerCase()};return t.admitterAddrs?.length&&(l.admitter_addrs=[...t.admitterAddrs]),t.applicationId&&(l.application_id=Array.from(m(t.applicationId,"applicationId",32))),t.appKey&&(l.app_key=Array.from(m(t.appKey,"appKey",32))),l}function yo(t,e){if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return new Uint8Array(t)}var xo=25,Ou=new TextEncoder().encode("calimero.namespace.v1"),_u=0,Hs={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreatedV2:9,MemberJoinedViaTeeAttestation:10};function Bs(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 qs(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}function Qn(t){let e=t.invitation,n=t.admitter_addrs??[];return f(Pt(e),qs(t.inviter_signature),t.inviter_account?f(new Uint8Array([1]),m(t.inviter_account,"inviter_account",32)):new Uint8Array([0]),R(n.length),...n.map(qs),Bs(t.application_id,"application_id"),Bs(t.app_key,"app_key"))}async function Yn(t){let e=t.parentOpHashes??[],n=m(t.credential,"credential",t.credential.length/2),r=BigInt(t.invitation.invitation.expiration_timestamp??0)!==0n,o=t.joinedAt??BigInt(Math.floor(Date.now()/1e3)),i=r?f(new Uint8Array([Hs.MemberJoinedAt]),m(t.member,"member",32),Qn(t.invitation),C(o),n):f(new Uint8Array([Hs.MemberJoined]),m(t.member,"member",32),Qn(t.invitation),n),s=f(new Uint8Array([_u]),i),a=await I(t.deviceSecret,t.signer,"deviceSecret"),c=m(a.publicKey,"signer.publicKey",32),u=f(new Uint8Array([xo]),m(t.namespaceId,"namespaceId",32),R(e.length),...e.map((p,x)=>m(p,`parentOpHashes[${x}]`,32)),c,C(t.nonce),s),d=await a.sign(f(Ou,u)),l=new Uint8Array([0]);return y(f(u,d,l))}function Mu(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 Ku(t){let e=Ct(`calimero.delegated.joinnonce.${t}`);return()=>e.next()}function js(t){return t.replace(/\/+$/,"")}async function Xn(t){let{account:e,credential:n,deviceSecret:r}=t.credential,o;try{o=await Yn({namespaceId:t.namespaceId,member:e,invitation:t.invitation,credential:n,deviceSecret:r,nonce:await(t.deps?.nonce??Ku(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??`${js(t.nodeUrl)}/admin-api/namespaces/${g(t.namespaceId)}/admit`,a=t.deps?.fetch??fetch,c;try{c=await a(s,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(i)})}catch(l){return{ok:!1,step:"admit",reason:`The admitter at ${t.nodeUrl} could not be reached: ${l instanceof Error?l.message:String(l)}. The invitation is untouched \u2014 this is the node being unreachable, not a refusal.`}}let u=await c.text();if(!c.ok)return{ok:!1,step:"admit",status:c.status,reason:Mu(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:js(t.nodeUrl),account:e,credential:n,deviceSecret:r}}}async function Zn(t){let e=t.deps?.resolve??Wn,n=t.deps?.join??Xn,r=null,o=t.nodeUrl,i;if(!o){let a=await e({namespaceId:t.namespaceId,admitters:t.invitation.invitation.admitters,credential:t.credential.credential,deviceSecret:t.credential.deviceSecret,cloudBaseUrl:t.cloudBaseUrl});if(a.ok===!1)return a;r=a,o=a.relayUrl,i=a.admitUrl}let s=await n({nodeUrl:o,admitUrl:i,namespaceId:t.namespaceId,invitation:t.invitation,credential:t.credential,deps:{fetch:t.deps?.fetch,nonce:t.deps?.nonce}});return s.ok===!1?s:{ok:!0,published:s.published,relay:r,session:s.session}}async function Fs(t,e,n,r){let i=await(r.bootstrap??Zn)({namespaceId:e,invitation:n,credential:{account:t.account,credential:t.credential,deviceSecret:t.deviceSecret},cloudBaseUrl:r.cloudBaseUrl});if(i.ok===!1)throw Object.assign(new Error(i.reason),{step:i.step,...i.status!==void 0?{status:i.status}:{}});return i.session.relayUrl&&we(t.account,i.session.relayUrl,{namespaceId:e}),r.onJoined(Bn(t,i.session)),{namespaceId:e}}function Vs(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=Vs(t),r=Vs(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 Gu(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||Gu(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 Ws(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 vo(e,a),signerId:a,version:s.appVersion}}function zs(t,e){return{next:async()=>$u(t,e)}}function $u(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 Qs(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 Lu(t){return!t||t.length===0?{}:JSON.parse(new TextDecoder().decode(Uint8Array.from(t)))}function tr(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 Nt(t,e,n={}){let r=Qs(t,e.namespaceId),o=0n,i=await tr(t,r,{next:async()=>o},n.fetch).createContext({groupId:e.groupId??e.namespaceId,applicationId:e.applicationId,serviceName:e.serviceName,seed:e.contextSeed,initArgs:Lu(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=Qs(t,e.namespaceId);return tr(t,r,zs(r,e.group),n.fetch).govern({groupId:e.group,op:e.op})}async function Ys(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 Nt(t,{...e,groupId:r},n);return{contextId:o,groupId:r}}async function nr(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 Hu(t,o,n.fetch),s=BigInt(Date.now()),a=await tr(t,o,{next:async()=>s++},n.fetch).foundNamespace({executor:i,...e.defaultCapabilities!==void 0?{defaultCapabilities:e.defaultCapabilities}:{},...e.application?{application:e.application}:{}});try{localStorage.setItem(`calimero.governance-nonce.${o}.${a.namespaceId}`,String(s))}catch{}if(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 qu(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 Hu(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 tr(t,e,zs(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 rr="link this account to your cloud user in the wallet so the cloud can host this namespace on its fleet",er={account_not_linked:rr,account_linked_to_several_users:"this account is linked to more than one cloud user, so the cloud cannot tell whose plan hosts the namespace: unlink it from all but one in the wallet",ha_request_pending:"another namespace of this account is still waiting to be hosted; the cloud hosts one new namespace at a time without a cloud sign-in. Sign in to the cloud and turn off hosting for the waiting namespace, or wait until it is hosted",unknown_relay:"the cloud does not run the relay this namespace was founded on, so it cannot host it",relay_not_dialable:"the relay this namespace was founded on has not reported its address to the cloud yet; try enabling hosting again shortly"};function Bu(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 qu(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:rr};if(i instanceof J&&er[i.code]){let s=i.code==="ha_request_pending"?Bu(i):null,a=er[i.code];return{haEnabled:!1,haError:s?`${a} (waiting: ${s})`:a}}return{haEnabled:!1,haError:i instanceof Error?i.message:String(i)}}}async function 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 Xs="calimero.delegated.group-namespace.",Ro=new Map;function Zs(t){let e={};try{e=JSON.parse(localStorage.getItem(Xs+t)??"{}")}catch{}return{...e,...Ro.get(t)}}function Ut(t,e,n){Ro.set(t,{...Ro.get(t),[e]:n});try{let r=Zs(t);r[e]=n,localStorage.setItem(Xs+t,JSON.stringify(r))}catch{}}function Ot(t,e){return q(t.account).namespaces[e]?e:Zs(t.account)[e]}function ea(t,e){let n=Ot(t,e);if(!n)throw new Error(`the namespace of group ${e} is not known to this account: it can manage only groups in namespaces it joined or subgroups it created`);return n}async function or(t,e,n){return ve(t,{namespaceId:ea(t,e),group:e,op:n})}async function ir(t,e,n){let r=ea(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"}},ta={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 Fu(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 na(t,e={}){let{session:n,read:r,app:o}=t,i=e.govern?.group??or,s=e.govern?.root??ir,a=e.createContext??Nt,c=e.found??nr,u=e.latestVersion??Xe,d=e.signInvitation??zn,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(Ot(n,h))return;let w=await v().getGroupInfo(h);Ut(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(Fu(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 Ut(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,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,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 ta?ta[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 ra(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 Vu="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 Wu(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 Ju(t){return typeof t=="string"&&vr.test(t)?t:null}var J=class extends D{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.code=n;this.name="AccountHaRefusedError"}},xe=class extends J{constructor(){super(...arguments);this.name="AccountNotLinkedError"}};xe.CODE="account_not_linked";var St=class extends J{constructor(){super(...arguments);this.name="AccountLinkedToSeveralUsersError"}};St.CODE="account_linked_to_several_users";var kt=class extends J{constructor(){super(...arguments);this.name="HaRequestPendingError"}};kt.CODE="ha_request_pending";var Et=class extends J{constructor(){super(...arguments);this.name="UnknownRelayError"}};Et.CODE="unknown_relay";var It=class extends J{constructor(){super(...arguments);this.name="RelayNotDialableError"}};It.CODE="relay_not_dialable";var oa={409:[xe,St,kt],422:[Et,It]};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 Qu="x-mdma-session-refresh",Yu="x-mdma-session-expires",$=class{constructor(e={}){this.session=null;this.baseUrl=(e.cloudBaseUrl||Vu).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/${g(e)}/relays`)).relays??[]).map(r=>{let o=r.relay_url??null,i=r.executor_account??null,s=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),relayUrl:o,executorAccount:i,nodeKey:r.node_key??r.node_public_key??null,status:String(r.status??""),authorshipReady:s,teeRole:So(r),canExecute:Co(r,s&&o!==null&&i!==null),lastSeenAt:r.last_seen_at??null,confirmedAt:r.confirmed_at??null,admission:typeof r.admission=="string"?r.admission:null,admissionHint:typeof r.admission_hint=="string"?r.admission_hint:null,join:Wu(r)}})}async findExecutingRelay(e){let n=await this.getNamespaceRelays(e);return mo(n)}async getNamespaceRouting(e){let n=await this.request("GET",`/api/cloud/namespaces/${g(e)}/admitters`,{anonymous:!0,headers:await this.routingProof(e)});return{namespaceId:String(n.namespace_id??e),nodes:(n.admitters??[]).map(r=>{let o=r.account??null,i=r.relay_url??null,s=r.fresh===!0,a=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),account:o,relayUrl:i,admitUrl:r.admit_url??null,status:String(r.status??""),fresh:s,canAdmit:r.can_admit===!0,authorshipReady:a,teeRole:So(r),canExecute:Co(r,a&&i!==null&&o!==null&&s)}}),servable:n.servable===!0,writable:n.writable===!0}}async getRoutingChallenge(e){let n=await this.request("GET",`/api/cloud/namespaces/${g(e)}/challenge`,{anonymous:!0});return{namespaceId:String(n.namespace_id??e),nonce:String(n.nonce??""),expiresAtMs:Number(n.expires_at_ms??0)}}async routingProof(e){if(!this.routingCredential)return;let n=await this.getRoutingChallenge(e);return Fn(n,this.routingCredential)}async getAccountRelaysChallenge(e){let n=await this.request("GET",`/api/cloud/accounts/${g(e)}/challenge`,{anonymous:!0});return{accountId:String(n.account_id??e),nonce:String(n.nonce??""),expiresAtMs:Number(n.expires_at_ms??0)}}async getAccountRelays(e){if(!this.routingCredential)throw new Error("getAccountRelays needs a routingCredential: construct the client with the device certificate and its signing secret, since this read is proven by the device, not by a session.");let n=await this.getAccountRelaysChallenge(e);return((await this.request("GET",`/api/cloud/accounts/${g(e)}/relays`,{anonymous:!0,headers:await Fn(n,this.routingCredential)})).relays??[]).map(o=>({peerId:String(o.peer_id??""),relayUrl:o.relay_url??null,fresh:o.fresh===!0,executorAccount:Ju(o.executor_account),assigned:o.assigned===!0}))}async findAdmitter(e,n){let{nodes:r}=await this.getNamespaceRouting(e),o=n&&n.length>0?new Set(n.map(i=>i.toLowerCase())):null;return r.find(i=>i.canAdmit&&(o===null||i.account!==null&&o.has(i.account.toLowerCase())))??null}async getMyMachines(){return((await this.request("GET","/api/cloud/me/machines")).machines??[]).map(n=>{let r=n.relay_url??null,o=n.executor_account??null,i=(Array.isArray(n.namespaces)?n.namespaces:[]).map(s=>{let a=s;return{namespaceId:String(a.namespace_id??""),status:String(a.status??""),authorshipReady:a.authorship_ready===!0,teeRole:So(a),fresh:a.fresh===!0,confirmedAt:a.confirmed_at??null,lastSeenAt:a.last_seen_at??null}});return{peerId:String(n.peer_id??""),relayUrl:r,executorAccount:o,canExecute:Co(n,r!==null&&o!==null&&i.some(s=>s.authorshipReady)),namespaces:i}})}async claimNamespace(e,n){await this.request("POST","/api/cloud/namespaces/claim",{body:{namespace_id:e,ownership_proof:n}})}async enableNamespaceHa(e,n={}){let r=n.admitterAddrs===void 0?{}:{admitter_addrs:[...n.admitterAddrs]};return this.request("POST",`/api/cloud/namespaces/${g(e)}/enable-ha`,{body:r})}async enableFoundedNamespaceHa(e,n){return this.request("POST",`/api/cloud/me/namespaces/${g(e)}/enable-ha`,{body:{groups:[],ownership_proof:n}})}async enableHaAsAccount(e){let n=await Er({namespaceId:e.namespaceId,accountId:e.accountId,salt:e.salt,credential:e.credential,deviceSecret:e.deviceSecret,signer:e.signer,ttlMs:e.ttlMs,relayUrl:e.relayUrl}),r=e.accountId.toLowerCase(),o=e.namespaceId.toLowerCase();try{return await this.request("POST",`/api/cloud/accounts/${g(r)}/namespaces/${g(o)}/enable-ha`,{body:{ownership_proof:n},anonymous:!0})}catch(i){if(i instanceof D&&oa[i.status]){let s=zu(i.bodyText),a=oa[i.status].find(c=>c.CODE===s);if(a&&s)throw new a(s,i.status,i.statusText,i.url,i.headers,i.bodyText)}throw i}}async disableNamespaceHa(e){return this.request("POST",`/api/cloud/namespaces/${g(e)}/disable-ha`,{body:{}})}async getMyNode(){return(await this.request("GET","/api/cloud/me/node")).node??null}enableHA(e){let n=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&n.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/enable-ha?${n.toString()}`)}disableHA(e){let n=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&n.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/disable-ha?${n.toString()}`)}async linkAccount(e){let{signer:n,publicKey:r,accountId:o}=await Y(e),{nonce:i}=await this.getAccountLinkChallenge();return this.submitAccountLink({accountId:o,rootPublicKey:r,nonce:i,signature:await 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":Vt(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 tn(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 D(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(this.adoptRollingRefresh(a),!a.ok){let c=await a.text().catch(()=>{});throw new D(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(!(r.parse==="none"||a.status===204))return await a.json()}adoptRollingRefresh(e){let n=e.headers.get(Qu);if(!n||!this.session)return;let r=e.headers.get(Yu),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 Nu(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 Xu(t){if(t)return typeof t=="function"?t:Jt(t)}var Zu="mero-js:token-refresh";function ed(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function td(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=td(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=Xu(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 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: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=ed();return n?n.request(Zu,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 Rr(e,n)}static buildAuthLoginUrl(e,n){return Cr(e,n)}};function nd(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}},rd="mero-tokens",Io=class{constructor(e=rd){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 od=new TextEncoder().encode("calimero.account.owner-op.v1"),id=new TextEncoder().encode("calimero.account.owner-op.body.v1"),sd=new TextEncoder().encode("calimero.account.genesis.v1"),ad=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},sa={AdminChanged:3,RootGuarded:12},cd={replica:0,relay:1},ld=new TextEncoder;function L(t){return new Uint8Array([t])}function aa(t){let e=ld.encode(t);return f(R(e.length),e)}function Z(t){return f(R(t.length),...t.map(aa))}function ca(t){return L(t?1:0)}function la(t){let e=cd[t??"replica"];if(e===void 0)throw new Error(`mode must be replica or relay, got ${String(t)}`);return L(e)}function ua(t){return{kind:"transferOwnership",plane:"group",bytes:f(L(tt.TransferOwnership),m(t,"newOwner",32))}}function da(){return{kind:"groupDelete",plane:"group",bytes:L(tt.GroupDelete)}}function pa(t){return{kind:"adminChanged",plane:"root",bytes:f(L(sa.AdminChanged),m(t,"newAdmin",32))}}function ga(t){return{kind:"teeAuthoringPolicy",plane:"group",bytes:f(L(tt.TeeAuthoringPolicySet),Z(t))}}function ma(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),ca(t.acceptMock),la(t.mode))}}function fa(t){let e=t.minReleaseVersion===void 0?L(0):f(L(1),aa(t.minReleaseVersion));return{kind:"teeReleaseAdmissionPolicy",plane:"group",bytes:f(L(tt.TeeReleaseAdmissionPolicySetV2),Z(t.allowedProfiles),e,Z(t.allowedTcbStatuses),ca(t.acceptMock),la(t.mode))}}async function To(t){return E(id,[t])}async function Do(t){return E(od,[m(t.account,"account",32),m(t.namespaceId,"namespaceId",32),m(t.groupId,"groupId",32),L(ha(t.kind)),t.opDigest,C(t.counter),R(t.keyEpoch)])}function ha(t){let e=Po[t];if(e===void 0)throw new Error(`unknown owner-op kind ${String(t)}`);return e}var ia=132;async function ya(t){let e=await re(t.rootSecret),n=f(L(ad),e),r=y(await E(sd,[n])),o=t.keyEpoch??0,i=(t.chain??[]).map((d,l)=>{let p=j(d,`chain[${l}]`);if(p.length!==ia)throw new Error(`chain[${l}] must be a ${ia}-byte RootKeyHandoff, got ${p.length}`);return p});if(o>i.length)throw new Error(`keyEpoch ${o} needs ${o} handoffs in chain, got ${i.length}`);let s=await To(t.op.bytes),a=await Do({account:r,namespaceId:t.namespaceId,groupId:t.groupId,kind:t.op.kind,opDigest:s,counter:t.counter,keyEpoch:o}),c=await ne(t.rootSecret),u=new Uint8Array(await crypto.subtle.sign("Ed25519",c,a));return y(f(n,R(i.length),...i,m(r,"account",32),m(t.namespaceId,"namespaceId",32),m(t.groupId,"groupId",32),L(ha(t.op.kind)),s,C(t.counter),R(o),u))}function ba(t,e){let n=t.plane==="group"?tt.RootGuarded:sa.RootGuarded;return f(L(n),t.bytes,j(e,"rootProof"))}var wa=[2428,2429,2528,2529],ud="localhost",dd=2e3;function Aa(t){return`http://${ud}:${t}`}function xa(t,e){let n=t.endsWith("/")?t:`${t}/`;return new URL(e,n).toString()}async function va(t,e={}){let{timeoutMs:n=dd,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=xa(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 pd(t={}){let{ports:e=wa,timeoutMs:n,signal:r}=t;return(await Promise.all(e.map(async i=>{let s=Aa(i);return await va(s,{timeoutMs:n,signal:r})?s:null}))).filter(i=>i!==null)}function sr(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]=sr(t[o]^t[e],16),t[r]=t[r]+t[o]>>>0,t[n]=sr(t[n]^t[r],12),t[e]=t[e]+t[n]>>>0,t[o]=sr(t[o]^t[e],8),t[r]=t[r]+t[o]>>>0,t[n]=sr(t[n]^t[r],7)}function Ra(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function ka(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]=Ra(t,s*4);r[12]=e>>>0;for(let s=0;s<3;s+=1)r[13+s]=Ra(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 gd(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=ka(t,s,n),c=Math.min(i+64,r.length);for(let u=i;u<c;u+=1)o[u]=r[u]^a[u-i]}return o}function No(t){let e=0n;for(let n=t.length-1;n>=0;n-=1)e=e<<8n|BigInt(t[n]);return e}var md=(1n<<130n)-5n;function fd(t,e){let n=No(t.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,r=No(t.subarray(16,32)),o=0n;for(let a=0;a<e.length;a+=16){let c=e.subarray(a,Math.min(a+16,e.length)),u=No(c)+(1n<<BigInt(8*c.length));o=(o+u)*n%md}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 Ca(t){return new Uint8Array((16-t%16)%16)}function Sa(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function hd(t,e){let n=[t,Ca(t.length),e,Ca(e.length),Sa(t.length),Sa(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 yd(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 Ea(t,e,n,r=new Uint8Array(0)){yd(t,e);let o=ka(t,0,e).subarray(0,32),i=gd(t,1,e,n),s=fd(o,hd(r,i)),a=new Uint8Array(i.length+16);return a.set(i),a.set(s,i.length),a}var Pa=32,bd=1,wd=3,Ad=2,xd=32,vd=32,Rd=12,nt=t=>new TextEncoder().encode(t),Mt=t=>new Uint8Array([t>>8&255,t&255]),Ia=f(nt("KEM"),Mt(Pa)),_t=f(nt("HPKE"),Mt(Pa),Mt(bd),Mt(wd));async function Ta(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 Cd(t,e,n){let r=new Uint8Array(n),o=new Uint8Array(0);for(let i=1,s=0;s<n;i+=1)o=await Ta(t,f(o,e,new Uint8Array([i]))),r.set(o.subarray(0,Math.min(o.length,n-s)),s),s+=o.length;return r}function ar(t,e,n,r){return Ta(e,f(nt("HPKE-v1"),t,nt(n),r))}function Uo(t,e,n,r,o){return Cd(e,f(Mt(o),nt("HPKE-v1"),t,nt(n),r),o)}async function Sd(t,e){let n=await ar(Ia,new Uint8Array(0),"eae_prk",t);return Uo(Ia,n,"shared_secret",e,xd)}async function kd(t,e){let n=new Uint8Array(0),r=await ar(_t,n,"psk_id_hash",n),o=await ar(_t,n,"info_hash",e),i=f(new Uint8Array([Ad]),r,o),s=await ar(_t,t,"secret",n);return{key:await Uo(_t,s,"key",i,vd),nonce:await Uo(_t,s,"base_nonce",i,Rd)}}async function Da(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 Oe(i),a=await Oe(e),c=f(await dt(s.privateKey,t),await dt(a.privateKey,t)),u=await Sd(c,f(s.publicKey,t,a.publicKey)),{key:d,nonce:l}=await kd(u,n);return{enc:s.publicKey,ciphertext:Ea(d,l,r,o)}}var Oa="mero-agent-gate/attest/v3",_a="mero-agent-gate/provision/v2",Ed=/^[a-z0-9][a-z0-9-]{0,62}$/,Id=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,Na=64,Ua=64*1024,ue=class extends Error{constructor(n,r,o){super(n);this.status=r;this.code=o;this.name="AgentGateError"}};function Ma(t){if(!Ed.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 Ka(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 cr(t,e,n){let r;try{r=Uint8Array.from(atob(t.trim()),o=>o.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(n!==void 0&&r.length!==n)throw new Error(`${e} is not ${n} bytes`);return r}async function Ga(t,e,n,r){let o=new Uint8Array(32),i=f(Kt(Oa),t,Ka(e),n??o,r??o);return new Uint8Array(await crypto.subtle.digest("SHA-256",i))}function $a(t,e){return f(Kt(_a),t,Ka(e))}async function Pd(){let t=crypto.getRandomValues(new Uint8Array(32));return{secret:t,publicKey:await lr(t)}}async function lr(t){if(t.length!==32)throw new Error("An owner key is 32 bytes");return Ce((await Oe(t)).publicKey)}function La(t,e){return`${t.replace(/\/+$/,"")}${e}`}async function Ha(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 Oo(t){let e=t.agentId??"";e&&Ma(e);let n=crypto.getRandomValues(new Uint8Array(32)),r=await Ha(t.fetch??fetch,La(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=cr(r.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),i=r.signingPublicKeyB64?cr(r.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,s=r.ownerPublicKeyB64?cr(r.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!i!=!s)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let a=await 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 Ba(t,e){let n=await lr(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 Td(t){let e=Object.keys(t);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>Na)throw new Error(`At most ${Na} secrets at once`);for(let n of e){if(!Id.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 qa(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 Ba(r,o),a=cr(r.provisioningPublicKey,"provisioningPublicKey",32),c=await Da(a,o,$a(a,r.agentId),Kt(JSON.stringify(i)));return Ha(t,La(e,n),{agentId:r.agentId,provisioningPublicKeyB64:r.provisioningPublicKey,senderPublicKeyB64:s,encappedKeyB64:Ce(c.enc),ciphertextB64:Ce(c.ciphertext)})}async function Dd(t){Td(t.secrets);let e=t.fetch??fetch,n=await qa(e,t.gateUrl,"/provision",t.agent,t.ownerSecret,{secrets:t.secrets}),r=await Oo({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e}),o=await lr(t.ownerSecret);if(r.ownerPublicKey!==o||!r.signingPublicKey)throw new 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 Nd(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 qa(e,t.gateUrl,"/release",t.agent,t.ownerSecret,{release:!0}),(await Oo({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"}),Ud=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function Od(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??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 ja(o),o}function ja(t){for(let e of Ud)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 Md(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 Gt=t=>t.trim().replace(/^0x/i,"");function Kd(t,e){return ja(t),ht({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:t.allowed_tcb_statuses.map(Md),allowedMrtd:t.allowed_mrtd.map(Gt),allowedRtmr0:t.allowed_rtmr0.map(Gt),allowedRtmr1:t.allowed_rtmr1.map(Gt),allowedRtmr2:t.allowed_rtmr2.map(Gt),allowedRtmr3:t.allowed_rtmr3.map(Gt)})}export{ai as ACCOUNT_HA_AUDIENCE,si as ACCOUNT_OWNERSHIP_AUDIENCE,Oa as AGENT_ATTEST_DOMAIN,_a 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,fp as CAPABILITY_PRESETS,$ as CloudClient,wa as DEFAULT_LOCAL_NODE_PORTS,un as DEFAULT_RELEASE_MIRROR,lt as EphemeralClient,Ni as HANDSHAKE_PATH,rr as HA_ACCOUNT_NOT_LINKED_MESSAGE,er as HA_REFUSAL_MESSAGES,D as HTTPError,kt as HaRequestPendingError,bo as INVITED_ROLE,he as IntentRefusedError,et as InvitationNotClaimableError,_o as KMS_RELEASE_SIGNER,Io as LocalStorageTokenStore,Jn as MAX_INVITATION_VALIDITY_SECS,Eo as MemoryTokenStore,be as MeroClient,We as MeroJs,jr as NODE_RELEASE_SIGNER,Ze as NoRelayError,Re as NotForAccountError,Po as OWNER_OP_KIND,gs as PRESENCE_DOMAIN,ft as PRODUCTION_PROFILE,Kn as RELAY_NODE_KEY_RETRY_MS,Ee as REQUEST_PROOF_HEADER,W as RelayClient,It as RelayNotDialableError,Fe as RelayObserver,Rt as RelayPresenceClient,ye as RelayTransport,ct as RpcClient,zt as RpcError,gt as SEALED_CONTENT_TYPE,Ui as SEALED_PATH,xo as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,_e as SealedTransportError,B as SseClient,mt as StaleTransportKeyError,Et as UnknownRelayError,qn as WarrantNonceExhaustedError,jt as WarrantNonceRouteUnavailableError,ot as WebHttpClient,ie as WsClient,en as accountForRoot,F as accountForRootPublicKey,mi as accountRootFromPhrase,Ur as accountRootFromSecret,hi as accountRootSignerFromPhrase,pa as adminChangedOp,Nu as admitterAddrsFromNetworkStatus,Ga as agentKeyBinding,Kd as agentQuoteVerifier,vo as applicationIdForBundle,ze as attemptRelayNodeKey,Oo as attestAgent,on as attestKeyBinding,sn as attestRelayNodeKey,pu as authorNonceLookup,xu as beginCloudLink,Eu as beginDeviceEnrolment,Zn as bootstrapFromInvitation,Cr as buildAuthLoginUrl,Hn as buildDelegatedClient,Ls as callbackIsForeign,Wt as callerProof,hp as capMask,yp as capNames,Bn as carryExecutorAccount,Ba as checkOwner,wr as classifyError,vs as clearDelegatedCredential,ws as clearDelegatedSession,_s as cloudLinkUrl,gn as cloudNodeReleaseUrl,dr as combineSignals,ac as compareSemver,Ru as completeCloudLink,Pu as completeDeviceEnrolment,Us as connectCloud,mu as connectCloudWithAccount,ls as contextCapabilityGrantedOp,us as contextCapabilityRevokedOp,En as contextDetachedOp,Tn as contextMetadataSetOp,na as createAccountAdmin,fi as createAccountRootSigner,Fo as createAdminApiClient,Ft as createAdminApiClientFromHttpClient,fe as createAttestedSealedFetch,gp as createAuthApiClient,Lo as createAuthApiClientFromHttpClient,_p as createBrowserAdminApiClient,dp as createBrowserAuthApiClient,Ie as createBrowserHttpClient,Nt as createDelegatedContext,Ys as createDelegatedPrivateContext,it as createHttpClient,Ct as createLocalStorageNonceSource,jn as createMemoryNonceSource,On as createMeroClient,nd as createMeroJs,ra as createNodeAdmin,Mp as createNodeAdminApiClient,pp as createNodeAuthApiClient,Bt as createNodeHttpClient,fr as createProofAuthorizer,Jt as createProofSigner,ht as createQuoteVerifier,gu as createRecoveringNonceSource,ec as createRetryableMethod,Ki as createSealedFetch,Sl as createSignedReleaseSealedFetch,mn as createSignedReleaseVerifier,pr as createTimeoutSignal,hr as createUniversalHttpClient,Xr as createdSubgroupId,Wr as creationInitHash,Ao as defaultAdmitters,Ve as defaultAudience,He as defaultCapabilitiesSetOp,ve as delegatedGovernance,Xt as deviceCertPayload,$s as deviceEnrolmentUrl,Tr as deviceScopePayload,pd as discoverLocalNodes,Pt as encodeGroupInvitation,Qn as encodeSignedInvitation,Mi as fetchAttestedTransportKey,dn as fetchNodeRelease,pn as fetchNodeReleaseVersion,Dt as fetchRegistryBundles,Is as forgetMethodKinds,Es as forgetRelaySealing,nr as foundDelegatedNamespace,Cn as foundedNamespaceId,gi as generateAccountRoot,Pd as generateOwnerKey,no as generateSessionKey,or as governGroup,ir as governRoot,Jr as governanceOpHash,Zr as groupCreatedOp,da as groupDeleteOp,Rn as groupDeletedOp,wo as groupInvitationHash,qe as groupMetadataSetOp,vn as groupReparentedOp,ge as hasCap,Tp as hexEncodeUtf8,Fr as intentHash,oc as isSettled,Fs as joinAsAccount,Xn as joinWithNode,se as jsonCodec,Ye as knownRelays,Xe as latestPublishedVersion,ks as learnRelayNodeKey,Ds as listDelegatedContexts,Ns as listDelegatedNamespaces,Aa as localNodeUrl,je as login,Gn as markContextNonceSpent,Le as memberAddedOp,kn as memberCapabilitySetOp,Dn as memberJoinedOpenOp,vt as memberLeftOp,Pn as memberMetadataSetOp,wn as memberRemovedOp,An as memberRoleSetOp,Ir as mintDeviceId,Sn as namespaceCreatedOp,Ot as namespaceOfGroup,xa as nodeEndpoint,zi as nodeReleaseVersionFromImage,Vn as normaliseAccount,To as ownerOpDigest,Do as ownerOpSigningPayload,lr as ownerPublicKey,Rr as parseAuthCallback,os as parseCreationWarrant,Pr as parseDeviceCredential,is as parseGovernanceWarrant,Bo as parseWarrantNonce,lo as persistedNonces,uo as pinRelayNodeKey,ro as presenceStatementBytes,va as probeNodeHealth,Dd as provisionAgent,$a as provisionInfo,vu as readCloudLinkCallback,As as readDelegatedCredential,co as readDelegatedSession,Iu as readEnrolmentCallback,$n as readPinnedRelayNodeKey,q as readRelayMap,Ho as redeemInvitation,Ts as relayForContext,Qe as relayTransportFetch,Nd as releaseAgent,Ut as rememberGroupNamespace,we as rememberRelay,_r as reportDataOf,rt as requestBodyHash,Ws as resolveApplicationIdFromRegistry,Wn as resolveRelayFromInvitation,Ln as resolveRelayNodeKey,Y as resolveRoot,tn as resolveRootPair,ba as rootGuardedOpBytes,Fn as routingProofHeaders,xs as saveDelegatedCredential,bs as saveDelegatedSession,Tt as selectLatestBundle,vp as shouldRetain,Er as signAccountHaClaim,ut as signAccountLink,nn as signAccountLogin,bc as signAccountOwnershipClaim,yn as signCreationWarrant,ui as signDeviceCert,di as signDeviceScope,At as signGovernanceWarrant,zn as signGroupInvitation,Un as signLoginStatement,Yn as signMemberJoinOp,ya as signOwnerOpProof,$t as signRequest,mr as signRequestProof,Os as signRoutingChallenge,fn as signWarrant,de as signedPath,ti as signerFromCryptoKey,De as signerFromSecret,ms as stateHash,Be as subgroupCreation,In as subgroupVisibilitySetOp,Yt as subscribePresence,xn as targetApplicationSetOp,ma as teeAdmissionPolicyOp,ga as teeAuthoringPolicyOp,fa as teeReleaseAdmissionPolicyOp,ua as transferOwnershipOp,_i as transportKeyBinding,Xi as trustSignedRelease,Lr as trustedMeasurementsFromReleases,Ma as validateAgentId,Zt as verifyDeviceCredential,Od as verifySignedAgentPolicy,Ji as verifySignedNodeRelease,yr as withCap,qt as withRetry,bp as withoutCap};
|
|
3
3
|
//# sourceMappingURL=index.browser.mjs.map
|