@calimero-network/mero-js 27.4.0 → 28.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The Calimero Cloud node directory: which nodes of a cluster take traffic now,
3
+ * and in what order this client tries them.
4
+ *
5
+ * `GET {directory}/{cluster}` (no auth) answers
6
+ * `{ cluster, nodes: [{ id, url, zone, weight }], refreshAfterSeconds }`. The
7
+ * directory is not trusted for security: it only picks which nodes to try.
8
+ * Every node is attested under the caller's own policy before anything is sent
9
+ * to it, so a bad list can only make connecting fail.
10
+ */
11
+ /** The Calimero Cloud control plane's public node directory. */
12
+ export declare const DEFAULT_DIRECTORY = "https://manager.cloud.calimero.network/api/v2/directory";
13
+ /** Why {@link DirectoryError} was thrown. */
14
+ export type DirectoryFailure = 'unreachable' | 'not-found' | 'bad-response' | 'empty';
15
+ /**
16
+ * The directory could not name a node to try: it could not be reached or
17
+ * answered an error (`unreachable`), does not know the cluster (`not-found`,
18
+ * a 404), answered something that is not a listing (`bad-response`), or listed
19
+ * no usable node (`empty`).
20
+ */
21
+ export declare class DirectoryError extends Error {
22
+ readonly cluster: string;
23
+ readonly reason: DirectoryFailure;
24
+ readonly status?: number;
25
+ readonly cause?: unknown;
26
+ constructor(cluster: string, reason: DirectoryFailure, message: string, status?: number, cause?: unknown);
27
+ }
28
+ /** One usable node of a listing. */
29
+ export interface DirectoryNode {
30
+ url: string;
31
+ zone?: string;
32
+ weight: number;
33
+ }
34
+ export interface DirectoryListing {
35
+ nodes: DirectoryNode[];
36
+ refreshAfterSeconds: number;
37
+ }
38
+ /** The URL of `cluster`'s listing in `directory`. */
39
+ export declare function directoryUrl(directory: string, cluster: string): string;
40
+ /**
41
+ * Read `cluster`'s listing, keeping only the entries with an http(s) URL and a
42
+ * positive integer weight (the first of a repeated URL).
43
+ */
44
+ export declare function readDirectory(directory: string, cluster: string, fetcher: typeof fetch): Promise<DirectoryListing>;
45
+ /**
46
+ * The order to try `nodes` in: those in `zone` first (when given), each group
47
+ * in weighted-random order, a node's weight its relative chance to come next.
48
+ * `random` answers in [0, 1), as `Math.random` does.
49
+ */
50
+ export declare function orderNodes(nodes: DirectoryNode[], zone: string | undefined, random: () => number): string[];
@@ -0,0 +1,115 @@
1
+ /**
2
+ * The Calimero Cloud node directory: which nodes of a cluster take traffic now,
3
+ * and in what order this client tries them.
4
+ *
5
+ * `GET {directory}/{cluster}` (no auth) answers
6
+ * `{ cluster, nodes: [{ id, url, zone, weight }], refreshAfterSeconds }`. The
7
+ * directory is not trusted for security: it only picks which nodes to try.
8
+ * Every node is attested under the caller's own policy before anything is sent
9
+ * to it, so a bad list can only make connecting fail.
10
+ */
11
+ /** The Calimero Cloud control plane's public node directory. */
12
+ export const DEFAULT_DIRECTORY = 'https://manager.cloud.calimero.network/api/v2/directory';
13
+ /** How long a listing stands when the directory does not say. */
14
+ const DEFAULT_REFRESH_SECONDS = 60;
15
+ /**
16
+ * The directory could not name a node to try: it could not be reached or
17
+ * answered an error (`unreachable`), does not know the cluster (`not-found`,
18
+ * a 404), answered something that is not a listing (`bad-response`), or listed
19
+ * no usable node (`empty`).
20
+ */
21
+ export class DirectoryError extends Error {
22
+ constructor(cluster, reason, message, status, cause) {
23
+ super(`directory for cluster ${cluster}: ${message}`);
24
+ this.cluster = cluster;
25
+ this.reason = reason;
26
+ this.status = status;
27
+ this.cause = cause;
28
+ this.name = 'DirectoryError';
29
+ }
30
+ }
31
+ /** The URL of `cluster`'s listing in `directory`. */
32
+ export function directoryUrl(directory, cluster) {
33
+ return `${directory.replace(/\/+$/, '')}/${encodeURIComponent(cluster)}`;
34
+ }
35
+ /**
36
+ * Read `cluster`'s listing, keeping only the entries with an http(s) URL and a
37
+ * positive integer weight (the first of a repeated URL).
38
+ */
39
+ export async function readDirectory(directory, cluster, fetcher) {
40
+ let response;
41
+ try {
42
+ response = await fetcher(directoryUrl(directory, cluster), { method: 'GET', headers: { accept: 'application/json' } });
43
+ }
44
+ catch (error) {
45
+ throw new DirectoryError(cluster, 'unreachable', `could not be reached: ${String(error)}`, undefined, error);
46
+ }
47
+ if (response.status === 404)
48
+ throw new DirectoryError(cluster, 'not-found', 'unknown cluster', 404);
49
+ if (!response.ok)
50
+ throw new DirectoryError(cluster, 'unreachable', `answered ${response.status}`, response.status);
51
+ let body;
52
+ try {
53
+ body = await response.json();
54
+ }
55
+ catch (error) {
56
+ throw new DirectoryError(cluster, 'bad-response', 'answered something other than JSON', response.status, error);
57
+ }
58
+ const listing = body;
59
+ if (!listing || typeof listing !== 'object' || !Array.isArray(listing.nodes)) {
60
+ throw new DirectoryError(cluster, 'bad-response', 'answered no node list', response.status);
61
+ }
62
+ const nodes = [];
63
+ const seen = new Set();
64
+ for (const entry of listing.nodes) {
65
+ const node = usable(entry);
66
+ if (node && !seen.has(node.url)) {
67
+ seen.add(node.url);
68
+ nodes.push(node);
69
+ }
70
+ }
71
+ if (nodes.length === 0)
72
+ throw new DirectoryError(cluster, 'empty', 'lists no usable node', response.status);
73
+ const after = listing.refreshAfterSeconds;
74
+ const refreshAfterSeconds = typeof after === 'number' && Number.isFinite(after) && after >= 1 ? after : DEFAULT_REFRESH_SECONDS;
75
+ return { nodes, refreshAfterSeconds };
76
+ }
77
+ function usable(entry) {
78
+ if (!entry || typeof entry !== 'object')
79
+ return undefined;
80
+ const { url, zone, weight } = entry;
81
+ if (typeof url !== 'string' || typeof weight !== 'number' || !Number.isInteger(weight) || weight < 1)
82
+ return undefined;
83
+ let parsed;
84
+ try {
85
+ parsed = new URL(url);
86
+ }
87
+ catch {
88
+ return undefined;
89
+ }
90
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:')
91
+ return undefined;
92
+ return { url: url.replace(/\/+$/, ''), zone: typeof zone === 'string' ? zone : undefined, weight };
93
+ }
94
+ /**
95
+ * The order to try `nodes` in: those in `zone` first (when given), each group
96
+ * in weighted-random order, a node's weight its relative chance to come next.
97
+ * `random` answers in [0, 1), as `Math.random` does.
98
+ */
99
+ export function orderNodes(nodes, zone, random) {
100
+ const near = zone === undefined ? [] : nodes.filter((node) => node.zone === zone);
101
+ const far = zone === undefined ? nodes : nodes.filter((node) => node.zone !== zone);
102
+ return [...weightedOrder(near, random), ...weightedOrder(far, random)];
103
+ }
104
+ function weightedOrder(nodes, random) {
105
+ const left = [...nodes];
106
+ const order = [];
107
+ while (left.length > 0) {
108
+ let roll = random() * left.reduce((sum, node) => sum + node.weight, 0);
109
+ let pick = 0;
110
+ while (pick < left.length - 1 && roll >= left[pick].weight)
111
+ roll -= left[pick++].weight;
112
+ order.push(left.splice(pick, 1)[0].url);
113
+ }
114
+ return order;
115
+ }
@@ -1,7 +1,9 @@
1
1
  export { CalimeroClient } from './client.js';
2
+ export { DEFAULT_DIRECTORY, DirectoryError } from './directory.js';
3
+ export type { DirectoryFailure } from './directory.js';
2
4
  export { AppError, ArgsTooLarge, CalimeroError, ConfirmCancelled, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, NotFound, ReleaseDeadlineError, TrapError, UnavailableError, WrongNode, errorFrom, } from './errors.js';
3
5
  export type { Committed } from './errors.js';
4
- export type { AppInfo, BlobInfo, CallResult, CalimeroClientOptions, CloudEvent, CalimeroSession, PackageInfo, PackageInstalled, CloudRetryOptions, OrgInfo, OrgUpgradeTarget, PresenceEntry, UpgradeRun, ViewResult, } from './client.js';
6
+ export type { AppInfo, BlobInfo, CallResult, CalimeroClientOptions, CalimeroConnectOptions, CloudEvent, CalimeroSession, PackageInfo, PackageInstalled, CloudRetryOptions, OrgInfo, OrgUpgradeTarget, PresenceEntry, UpgradeRun, ViewResult, } from './client.js';
5
7
  export { claimedRelease, fetchAttestedKey, freshCollateral, MOCK_QUOTE_HEADER } from './attestation.js';
6
8
  export type { AttestationDoc, CloudPolicy, CloudReleasePolicy } from './attestation.js';
7
9
  export { browserPasskey, b64url, fromB64url } from './passkey.js';
@@ -1,4 +1,5 @@
1
1
  export { CalimeroClient } from './client.js';
2
+ export { DEFAULT_DIRECTORY, DirectoryError } from './directory.js';
2
3
  export { AppError, ArgsTooLarge, CalimeroError, ConfirmCancelled, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, NotFound, ReleaseDeadlineError, TrapError, UnavailableError, WrongNode, errorFrom, } from './errors.js';
3
4
  export { claimedRelease, fetchAttestedKey, freshCollateral, MOCK_QUOTE_HEADER } from './attestation.js';
4
5
  export { browserPasskey, b64url, fromB64url } from './passkey.js';
@@ -1,9 +1,9 @@
1
- function R(r){return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}function pe(r,e,t){let n=r.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length!==t*2)throw new Error(`${e} must be ${t*2} hex characters, got ${n.length}`);let i=new Uint8Array(t);for(let s=0;s<t;s+=1)i[s]=Number.parseInt(n.slice(s*2,s*2+2),16);return i}function y(...r){let e=new Uint8Array(r.reduce((n,i)=>n+i.length,0)),t=0;for(let n of r)e.set(n,t),t+=n.length;return e}var yr="Noise_NK_25519_AESGCM_SHA256",_e=32,hr=16,mr=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Be=class r{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(yr),t=new Uint8Array(32);return t.set(e),new r(t)}async mixHash(e){this.h=await wr(y(this.h,e))}async mixKey(e){let[t,n]=await ut(this.ck,e);this.ck=t,this.k=await crypto.subtle.importKey("raw",n,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let t=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:lt(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(t),t}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let t=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:lt(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),t}split(){return ut(this.ck,new Uint8Array)}};async function dt(r,e,t){let n=await Be.initialize();await n.mixHash(e),await n.mixHash(r);let i=await F(t);return await n.mixHash(i.publicKey),await n.mixKey(await W(i.privateKey,r)),{message1:y(i.publicKey,await n.encryptAndHash(new Uint8Array)),async finish(o){if(o.length<_e+hr)throw new Error("Noise: message 2 is too short");let a=o.slice(0,_e);return await n.mixHash(a),await n.mixKey(await W(i.privateKey,a)),{payload:await n.decryptAndHash(o.slice(_e)),split:await n.split()}}}}async function F(r){if(!r){let n;try{n=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"])}catch(s){throw new Error(`Sealed transport needs WebCrypto with X25519, which this runtime lacks (${s?.name??"no crypto.subtle"}). Current browsers and Node have it; in React Native, install react-native-quick-crypto as the global crypto.`)}let i=new Uint8Array(await crypto.subtle.exportKey("raw",n.publicKey));return{privateKey:n.privateKey,publicKey:i}}let e=await crypto.subtle.importKey("pkcs8",y(mr,r),{name:"X25519"},!0,["deriveBits"]),t=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Ar(t.x)}}async function W(r,e){let t=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:t},r,256))}function lt(r){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(r),!1),e}async function wr(r){return new Uint8Array(await crypto.subtle.digest("SHA-256",r))}async function $e(r,e){let t=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",t,e))}async function ut(r,e){let t=await $e(r,e),n=await $e(t,new Uint8Array([1])),i=await $e(t,y(n,new Uint8Array([2])));return[n,i]}function Ar(r){let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(t,n=>n.charCodeAt(0))}var yt="/sealed/v2/handshake",ht="/sealed/v2",ee="application/vnd.calimero.sealed",Ke=2,br=new TextEncoder().encode("calimero/sealed-http/v2"),X=16,Er=1+X+8,Rr=0,Pr=1,Ur=2,xr=1+64*1024+16,Tr=1024,Sr=6e4,Cr="calimero.tee-attest.transport-key.v1",vr=[101,204,205,304],mt=new TextEncoder,te=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},S=class extends Error{constructor(t,n,i,s){super(i);this.status=t;this.code=n;this.retryAfterMs=s;this.name="SealedTransportError"}};async function Ve(r,e){let t=await crypto.subtle.digest("SHA-256",y(mt.encode(Cr),r,e));return new Uint8Array(t)}function Le(r){let e=new URL(r.baseUrl),t=e.pathname.replace(/\/+$/,""),n=`${e.origin}${t}`,i=r.fetch??((g,p)=>fetch(g,p)),s=typeof r.transportPublicKey=="function"?r.transportPublicKey:void 0,o=s?Promise.resolve().then(s):Promise.resolve(r.transportPublicKey);o.catch(()=>{});let a,c=async()=>{try{return await pt(i,n,await gt(o))}catch(g){if(!(g instanceof te)||!s)throw g;return o=Promise.resolve().then(s),pt(i,n,await gt(o))}},u=async()=>{let g=a??d(void 0),p=await g;if(Date.now()<p.renewAt)return[p,g];let h=d(g);return[await h,h]},d=g=>{if(a===g){let p=c();a=p,p.catch(()=>{a===p&&(a=void 0)})}return a};return async(g,p)=>{let h=new Request(g,p),f=new URL(h.url);if(f.origin!==e.origin||!f.pathname.startsWith(`${t}/`))throw new Error(`Refusing to send ${f.href} outside the sealed node at ${r.baseUrl}`);let b=[];h.headers.forEach((P,V)=>b.push([V,P]));let N={method:h.method,path:f.pathname.slice(t.length)+f.search,headers:b},E=new Uint8Array(await h.arrayBuffer()),x=p?.signal??(g instanceof Request?g.signal:void 0),D=async P=>{let{requestId:V,header:Z,envelope:ge}=await Ir(P,N,E),L=await i(`${n}${ht}`,{method:"POST",headers:{"content-type":ee},body:ge,signal:x});if(L.headers.get("content-type")!==ee)throw await At(L);return Nr(L,P.responseKey,Z,V)},[Oe,Ne]=await u();try{return await D(Oe)}catch(P){if(!(P instanceof S)||P.code!=="unknown_session")throw P;return D(await d(Ne))}}}async function gt(r){let e=await r;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function pt(r,e,t){try{return await ft(r,e,t)}catch(n){if(!(n instanceof S)||n.code!=="busy")throw n;return await new Promise(i=>setTimeout(i,n.retryAfterMs??1e3)),ft(r,e,t)}}async function ft(r,e,t){let n=await dt(t,br),i=await r(`${e}${yt}`,{method:"POST",headers:{"content-type":ee},body:y(new Uint8Array([Ke]),t,n.message1)});if(i.headers.get("content-type")!==ee)throw await At(i);let s=await Mr(i,Tr);return kr(n,s)}async function kr(r,e){if(e[0]!==Ke)throw new Error("The handshake reply is malformed");let t;try{t=await r.finish(e.slice(1))}catch{throw new Error("The handshake reply did not open: it did not come from the attested node")}let{payload:n,split:i}=t;if(n.length!==X+4)throw new Error("The handshake reply is malformed");let s=n.slice(0,X),o=new DataView(n.buffer,n.byteOffset).getUint32(X,!1),[a,c]=await Promise.all([crypto.subtle.importKey("raw",i[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",i[1],"AES-GCM",!1,["decrypt"])]);return i[0].fill(0),i[1].fill(0),{requestKey:a,responseKey:c,nextRequestId:1,renewAt:Date.now()+o*1e3-Sr,header(u){let d=new Uint8Array(Er);return d[0]=Ke,d.set(s,1),new DataView(d.buffer).setBigUint64(1+X,BigInt(u),!1),d}}}async function Ir(r,e,t){let n=r.nextRequestId;r.nextRequestId+=1;let i=r.header(n),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:wt(n,0),additionalData:i},r.requestKey,Or(e,t));return{requestId:n,header:i,envelope:y(i,new Uint8Array(s))}}function wt(r,e){let t=new Uint8Array(12),n=new DataView(t.buffer);return n.setBigUint64(0,BigInt(r),!1),n.setUint32(8,e,!1),t}function Or(r,e){let t=mt.encode(JSON.stringify(r)),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t.length,!1),y(n,t,e)}async function Nr(r,e,t,n){if(!r.body)throw new Error("The sealed response has no body");let i=Dr(r.body.getReader()),s=0,o=async()=>{let d=await i.next();if(!d)return null;let g;try{g=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:wt(n,s),additionalData:t},e,d))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return s+=1,{kind:g[0],data:g.slice(1)}},a=await o();if(!a||a.kind!==Rr)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(vr.includes(c.status))return await i.cancel(),new Response(null,{status:c.status,headers:c.headers});let u=new ReadableStream({async pull(d){try{let g=await o();g?g.kind===Pr?d.enqueue(g.data):g.kind===Ur?(d.close(),await i.cancel()):d.error(new Error("The sealed response is malformed")):d.error(new Error("The sealed response was cut short"))}catch(g){d.error(g)}},cancel(){return i.cancel()}});return new Response(u,{status:c.status,headers:c.headers})}function Dr(r){let e=new Uint8Array,t=async n=>{for(;e.length<n;){let{done:i,value:s}=await r.read();if(i)return!1;e=y(e,s)}return!0};return{async next(){if(!await t(4))return null;let n=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(n>xr)throw await r.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await t(4+n))return null;let i=e.slice(4,4+n);return e=e.slice(4+n),i},cancel:()=>r.cancel()}}async function Mr(r,e){if(!r.body)return new Uint8Array;let t=r.body.getReader(),n=new Uint8Array;for(;;){let{done:i,value:s}=await t.read();if(i)return n;if(n=y(n,s),n.length>e)throw await t.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function At(r){let e,t=`Sealed request refused: HTTP ${r.status}`;try{let s=await r.json();e=s?.error?.code,s?.error?.message&&(t=`Sealed request refused: ${s.error.message}`)}catch{}if(e==="stale_transport_key")return new te;let n=Number(r.headers.get("retry-after")),i=Number.isFinite(n)&&n>0?Math.min(n,5)*1e3:void 0;return new S(r.status,e,t,i)}var bt=[{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"]}],Et=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var _r="1.2.840.10045.2.1",$r={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},Br={"P-256":32,"P-384":48},Kr={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function Rt(r,e,t){if(e+2>t)throw new Error("it is truncated");let n=r[e];if((n&31)===31)throw new Error("it uses a tag this parser does not read");let i=r[e+1],s=e+2;if(i&128){let a=i&127;if(a===0||a>4||s+a>t)throw new Error("it has a length this parser does not read");i=0;for(let c=0;c<a;c+=1)i=i*256+r[s+c];s+=a}let o=s+i;if(o>t)throw new Error("it is truncated");return{tag:n,bytes:r,offset:e,start:s,end:o}}function j(r){let e=Rt(r,0,r.length);if(e.end!==r.length)throw new Error("it has trailing bytes");return e}function A(r){let e=[];for(let t=r.start;t<r.end;){let n=Rt(r.bytes,t,r.end);e.push(n),t=n.end}return e}function m(r,e,t){if(!r||r.tag!==e)throw new Error(`${t} is not where it should be`);return r}function C(r){return r.bytes.slice(r.start,r.end)}function fe(r){return r.bytes.slice(r.offset,r.end)}function G(r){let e=C(m(r,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let t=[],n=0;for(let o of e)n=n*128+(o&127),o&128||(t.push(n),n=0);let i=t.shift();return[...i<80?[Math.floor(i/40),i%40]:[2,i-80],...t].join(".")}function Vr(r){let e=new TextDecoder().decode(C(r)),t=r.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,n=r.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,i=t??n;if(!i)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let s=Number(i[1]);t&&(s+=s<50?2e3:1900);let[o,a,c,u,d]=i.slice(2).map(Number);return Date.UTC(s,o-1,a,c,u,d)}function He(r){try{let[e,t,n,...i]=A(m(j(r),48,"The certificate"));if(i.length>0)throw new Error("it has fields after its signature");let s=A(m(e,48,"The signed part")),o=s[0]?.tag===160?1:0,[a,c,u,d,g,p,...h]=s.slice(o);m(a,2,"The serial number");let f=G(A(m(t,48,"The signature algorithm"))[0]);if(G(A(m(c,48,"The signature algorithm"))[0])!==f)throw new Error("it names two different signature algorithms");let N=Kr[f];if(!N)throw new Error(`it is signed with ${f}, not ECDSA with SHA-256 or SHA-384`);let[E,x]=A(m(d,48,"The validity")).map(Vr);if(x===void 0)throw new Error("its validity is incomplete");let[D,Oe]=A(m(p,48,"The public key"));m(Oe,3,"The public key");let[Ne,P]=A(m(D,48,"The key algorithm"));if(G(Ne)!==_r)throw new Error("its key is not an elliptic-curve key");let V=$r[G(P)];if(!V)throw new Error("its key is on a curve other than P-256 or P-384");let Z=new Map,ge=h.find(De=>De.tag===163);if(ge){let[De]=A(ge);for(let fr of A(m(De,48,"The extensions"))){let H=A(m(fr,48,"An extension"));if(H.length===3)m(H[1],1,"An extension's critical flag");else if(H.length!==2)throw new Error("it has a malformed extension");let Me=G(H[0]);if(Z.has(Me))throw new Error(`it has extension ${Me} twice`);Z.set(Me,C(m(H[H.length-1],4,"An extension value")))}}let L=C(m(n,3,"The signature"));if(L[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:r,tbs:fe(e),signatureHash:N,signature:L.slice(1),issuer:fe(m(u,48,"The issuer")),subject:fe(m(g,48,"The subject")),notBefore:E,notAfter:x,spki:fe(p),curve:V,extensions:Z}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function Pt(r){return A(m(j(r),48,"The list")).map(G)}function Lr(r,e){let t=Br[e],n=A(m(j(r),48,"The signature"));if(n.length!==2)throw new Error("The signature is not an ECDSA signature");let i=new Uint8Array(t*2);return n.forEach((s,o)=>{let a=C(m(s,2,"The signature"));if(a.length===0||a[0]&128)throw new Error("The signature is not an ECDSA signature");for(;a.length>1&&a[0]===0;)a=a.subarray(1);if(a.length>t)throw new Error("The signature is not an ECDSA signature");i.set(a,o*t+t-a.length)}),i}async function ye(r,e,t,n,i){let s;try{s=Lr(n,e)}catch{return!1}let o=await crypto.subtle.importKey("spki",r,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:t},o,s,i)}function U(r,e){let t=r.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t)||t.length%4!==0)throw new Error(`${e} is not base64`);let n=atob(t),i=new Uint8Array(n.length);for(let s=0;s<n.length;s+=1)i[s]=n.charCodeAt(s);return i}function Fe(r,e){let t=[...r.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(t.length!==1||r.replace(t[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return U(t[0][1],e)}var Hr="2.5.29.17",Fr="2.5.29.37",Gr="1.3.6.1.5.5.7.3.3",jr="1.3.6.1.4.1.57264.1.8",qr="1.3.6.1.4.1.57264.1.1",Qr=134,Jr=12,Yr=48,zr=new TextEncoder,q=r=>new TextDecoder().decode(r);async function he(r,e,t,n){let{base64Signature:i,cert:s,rekorBundle:o}=en(e),a=o.Payload;if(n!==void 0&&n.trim()!==i.trim())throw new Error("The detached signature is not the one in the bundle");let c=U(i,"The bundle signature"),u=Fe(q(U(s,"The bundle certificate")),"The bundle certificate"),d=He(u),g=Et.find(x=>x.logId===a.logID.toLowerCase());if(!g)throw new Error(`The bundle names Rekor log ${a.logID}, which the Sigstore trust root does not know`);let p=zr.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await ye(U(g.publicKey,"The Rekor key"),"P-256","SHA-256",U(o.SignedEntryTimestamp,"The signed entry timestamp"),p))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let f=a.integratedTime*1e3;if(!Tt(f,g.validFor))throw new Error(`Rekor log ${g.baseUrl} was not in use at ${re(f)}, when the entry says it was logged`);let b=tn(a.body),N=R(new Uint8Array(await crypto.subtle.digest("SHA-256",r)));if(b.hash!==N)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!Ge(U(b.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let E=Fe(q(U(b.publicKey,"The logged certificate")),"The logged certificate");if(!Ge(E,u))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await ye(d.spki,"P-256","SHA-256",c,r))throw new Error("The signature over the file does not verify with the bundle's certificate");return await Zr(d,f),Xr(d,t),{integratedTime:a.integratedTime}}async function Zr(r,e){if(!xt(r,e))throw new Error(`The signing certificate was valid ${re(r.notBefore)} to ${re(r.notAfter)}, not at ${re(e)} when Rekor logged it`);let t=[];for(let n of bt){let i=n.certChain.map(o=>He(U(o,"A Fulcio certificate")));if(!await Ut(r,i[0]))continue;let s=await Wr(i,n.validFor,e);if(!s)return;t.push(`${n.uri} (valid from ${n.validFor.start}): ${s}`)}throw new Error(t.length>0?`The signing certificate's CA is not trusted at ${re(e)}: ${t.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function Wr(r,e,t){if(!Tt(t,e))return"the trust root says it was not issuing certificates then";for(let[n,i]of r.entries()){if(!xt(i,t))return`its certificate ${n} was not valid then`;let s=r[n+1]??i;if(!await Ut(i,s))return`its certificate ${n} is not signed by the next`}}async function Ut(r,e){return Ge(r.issuer,e.subject)?ye(e.spki,e.curve,r.signatureHash,r.signature,r.tbs):!1}function Xr(r,e){let t=r.extensions.get(Hr);if(!t)throw new Error("The signing certificate names no identity");let n=A(m(j(t),Yr,"The subject alternative name")),i=n.filter(u=>u.tag===Qr).map(u=>q(C(u)));if(i.length!==1||n.length!==1||i[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(i.length===1?i[0]:i)}, not by ${e.identity}`);let s=r.extensions.get(jr),o=r.extensions.get(qr),a=s?q(C(m(j(s),Jr,"The OIDC issuer"))):o?q(o):void 0;if(a!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${a===void 0?"missing":JSON.stringify(a)}, not ${e.issuer}`);let c=r.extensions.get(Fr);if(!c||!Pt(c).includes(Gr))throw new Error("The signing certificate is not for code signing")}function en(r){let e=r;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let t=e,n=t?.rekorBundle?.Payload;if(!(typeof t?.base64Signature=="string"&&typeof t.cert=="string"&&typeof t.rekorBundle?.SignedEntryTimestamp=="string"&&typeof n?.body=="string"&&typeof n.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(n.logID)&&Number.isSafeInteger(n.integratedTime)&&n.integratedTime>=0&&Number.isSafeInteger(n.logIndex)&&n.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return t}function tn(r){let e;try{e=JSON.parse(q(U(r,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let t=e?.spec?.data?.hash,n=e?.spec?.signature;if(e?.kind!=="hashedrekord"||t?.algorithm!=="sha256"||typeof t.value!="string"||typeof n?.content!="string"||typeof n.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:t.value.toLowerCase(),signature:n.content,publicKey:n.publicKey.content}}function xt(r,e){return r.notBefore<=e&&e<=r.notAfter}function Tt(r,e){return Date.parse(e.start)<=r&&(e.end===void 0||r<=Date.parse(e.end))}function re(r){return new Date(r).toISOString()}function Ge(r,e){return r.length===e.length&&r.every((t,n)=>t===e[n])}var rn=/^[0-9a-f]{96}$/,nn=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function _(r){let e=Q(r.allowedMrtd??[],"allowedMrtd"),t=(r.allowedMeasurements??[]).map((a,c)=>{let u=`allowedMeasurements[${c}]`;return nn.map(d=>Q([a?.[d]??""],`${u}.${d}`)[0]).join()}),n=[Q(r.allowedRtmr0??[],"allowedRtmr0"),Q(r.allowedRtmr1??[],"allowedRtmr1"),Q(r.allowedRtmr2??[],"allowedRtmr2"),Q(r.allowedRtmr3??[],"allowedRtmr3")];if(r.allowedMeasurements!==void 0&&t.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(t.length===0){if(e.length===0)throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");if(n.slice(1).some(a=>a.length===0))throw new Error("allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too")}let i=r.allowedTcbStatuses??["UpToDate"],s=r.now??Date.now;return Object.assign(async({quoteB64:a,nonce:c,reportDataSuffix:u,collateral:d})=>{let g=on(a),p=d??await r.fetchCollateral?.(g);if(!p)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let h;try{h=r.dcapVerify(g,p,Math.floor(s()/1e3))}catch(E){throw new Error(`The quote did not verify: ${E?.message??String(E)}`)}if(h.status==="Revoked"||!i.includes(h.status))throw new Error(`The platform's TCB status is ${h.status}, which is not accepted`);let f=sn(h.report);if(f.tdAttributes?.length!==8||(f.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let b=[f.mrTd,f.rtMr0,f.rtMr1,f.rtMr2,f.rtMr3].map(E=>R(E));if(t.length>0&&!t.includes(b.join()))throw new Error(`The measurements (MRTD ${b[0]}, RTMR0-3 ${b.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(b[0]))throw new Error(`MRTD ${b[0]} is not an image this verifier trusts`);if([f.rtMr0,f.rtMr1,f.rtMr2,f.rtMr3].forEach((E,x)=>{let D=n[x];if(D.length>0&&!D.includes(R(E)))throw new Error(`RTMR${x} ${R(E)} is not one this verifier trusts`)}),R(f.reportData)!==`${c}${u}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function Q(r,e){return r.map(t=>{let n=t.trim().toLowerCase();if(!rn.test(n))throw new Error(`${e} holds ${JSON.stringify(t)}, which is not a 48-byte hex measurement`);return n})}function sn(r){let e=r.data;if(r.type==="td10"&&e)return e;if(r.type==="td15"&&e?.base)return e.base;throw new Error(`The quote is a ${r.type} quote, not a TDX one`)}function on(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}var an=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],M="locked-read-only";function je(r,{profile:e,allowDebugProfile:t=!1}){if(r.length===0)throw new Error("No release given, so no image would be trusted");let n,i=r.map((s,o)=>{let a=s?.tag??`releases[${o}]`;if(s?.role!==void 0&&s.role!=="node")throw new Error(`${a} lists the measurements of a ${s.role}, not of a node image`);let c=s?.profiles?.[e];if(!c){let d=Object.keys(s?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${d})`)}if(e!==M&&!t)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(M)}, or pass allowDebugProfile to test`);let u=(c.allowed_tcb_statuses??["uptodate"]).map(d=>cn(d,a));return n=n===void 0?u:n.filter(d=>u.includes(d)),{mrtd:c.mrtd,rtmr0:c.rtmr0,rtmr1:c.rtmr1,rtmr2:c.rtmr2,rtmr3:c.rtmr3}});if(!n||n.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:i,allowedTcbStatuses:n}}function cn(r,e){let t=an.find(n=>n.toLowerCase()===String(r).toLowerCase());if(!t)throw new Error(`${e} accepts TCB status ${JSON.stringify(r)}, which this verifier does not know`);return t}var qe=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"}),ln=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],me="https://cloud.calimero.network",Qe=`${me}/api/tee/pcs`;async function Ct(r,e,t={}){let n=typeof r=="string"?new TextEncoder().encode(r):r;await he(n,e,{identity:t.identity??qe.identity,issuer:t.issuer??qe.issuer},t.signature);let i;try{i=JSON.parse(new TextDecoder().decode(n))}catch{throw new Error("The signed release is not JSON")}if(i?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(i?.role)} release, not a node one`);let s=Object.values(i.profiles??{}),o=a=>ln.every(c=>/^[0-9a-f]{96}$/i.test(String(a?.[c])));if(typeof i.tag!="string"||s.length===0||!s.every(o))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(t.expectedVersion!==void 0&&i.tag!==t.expectedVersion)throw new Error(`The signed release is ${i.tag}, not ${t.expectedVersion}`);return i}async function Je(r,e={}){let t=await(e.fetch??fetch)(r,{headers:{accept:"application/json"}});if(!t.ok)throw new Error(`Fetching the node release from ${r} failed: HTTP ${t.status}`);let n;try{n=(await t.json())?.data}catch{throw new Error(`${r} did not answer with JSON`)}if(typeof n?.version!="string"||typeof n.publishedMrtds!="string"||typeof n.bundle!="string")throw new Error(`${r} did not answer with a signed node release`);return{version:n.version,publishedMrtds:n.publishedMrtds,bundle:n.bundle}}var vt="https://github.com/calimero-network/mero-tee/releases/download";async function Ye(r,e={}){let t=`mero-tee-v${v(r,"version")}`,n=`${(e.base??vt).replace(/\/+$/,"")}/${t}/published-mrtds.json`,i=async a=>{let c=await(e.fetch??fetch)(a);if(!c.ok)throw new Error(`Fetching ${a} failed: HTTP ${c.status}`);return c.text()},[s,o]=await Promise.all([i(n),i(`${n}.bundle.json`)]);return{version:r,publishedMrtds:s,bundle:o}}function ze(r,e){return`${r.replace(/\/+$/,"")}/api/tee/node-releases/${v(e,"version")}`}async function we(r){let e=v(r.minReleaseVersion,"minReleaseVersion"),t=v(r.release?.version,"The release version"),n=await Ct(r.release.publishedMrtds,r.release.bundle,{expectedVersion:t,identity:r.identity,issuer:r.issuer});if(ne(t,e)<0)throw new Error(`Release ${t} is older than the minimum trusted, ${e}`);return je([n],{profile:r.profile,allowDebugProfile:r.allowDebugProfile})}function un(r){return v(r.minReleaseVersion,"minReleaseVersion"),Object.assign(async t=>{let n=await we({release:await r.release(),profile:r.profile,allowDebugProfile:r.allowDebugProfile,minReleaseVersion:r.minReleaseVersion,identity:r.identity,issuer:r.issuer});return _({dcapVerify:r.dcapVerify,fetchCollateral:r.fetchCollateral,now:r.now,...n})(t)},{includeCollateral:!0})}var kt=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function v(r,e){let t=typeof r=="string"?kt.exec(r):null,n=t?.[4];if(!t||n!==void 0&&n.split(".").some(i=>i===""))throw new Error(`${e} is ${JSON.stringify(r)}, not a release version like 2.3.87`);return r}function ne(r,e){let[t,n]=St(r),[i,s]=St(e);for(let c=0;c<3;c+=1)if(t[c]!==i[c])return t[c]<i[c]?-1:1;if(n===void 0||s===void 0)return n===s?0:n===void 0?1:-1;let o=n.split("."),a=s.split(".");for(let c=0;c<Math.max(o.length,a.length);c+=1){let[u,d]=[o[c],a[c]];if(u===void 0||d===void 0)return u===void 0?-1:1;let[g,p]=[/^\d+$/.test(u),/^\d+$/.test(d)],h=g&&p?Math.sign(Number(u)-Number(d)):g!==p?g?-1:1:u<d?-1:u>d?1:0;if(h!==0)return h}return 0}function St(r){let e=kt.exec(r);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var Ot="MOCK_TDX_QUOTE_V1";function dn(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function Ze(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}var It;async function We(r){It??(It=import("@phala/dcap-qvl"));let e=await It,t=typeof e[r]=="function"?e[r]:e.default?.[r];if(typeof t!="function")throw new TypeError(`@phala/dcap-qvl loaded without ${r}`);return t}function Nt(r,e){let t=v(e,"minReleaseVersion"),n=String(r.release?.version??"").trim().replace(/^mero-tee-v/,"").replace(/^v/,""),i=v(n,"The release the node names");if(ne(i,t)<0)throw new Error(`mero-tee release ${i} is older than the minimum ${t}`);return i}async function gn(r,e,t){let n=e.releaseSource;return typeof n=="function"?n(r):n==="github"?Ye(r,{fetch:t}):Je(ze(n??me,r),{fetch:t})}function pn(r){let e=r.collateralSource??Qe;return e==="intel"?async t=>(await We("getCollateralFromPcs"))(t):async t=>(await We("getCollateral"))(e,t)}function Dt(r,e){let t=e.maxCollateralAgeDays;return t===void 0?r:async n=>{let i=await r(n),s;try{s=Date.parse(JSON.parse(i.tcb_info).issueDate??"")}catch{s=Number.NaN}if(!Number.isFinite(s))throw new Error("The quote's collateral names no TCB info issue date");let o=((e.now??Date.now)()-s)/864e5;if(o>t)throw new Error(`The quote's collateral was issued ${Math.floor(o)} days ago, more than the ${t} this client accepts`);return i}}async function fn(r,e,t,n){let i=Nt(r,t.minReleaseVersion),s=await we({release:await gn(i,t,n),profile:t.profile??M,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer}),o=Dt(t.fetchCollateral??pn(t),t);return _({dcapVerify:t.dcapVerify??await We("verify"),fetchCollateral:o,now:t.now,...s})(e)}async function Xe(r,e,t=(n,i)=>fetch(n,i)){let n=R(crypto.getRandomValues(new Uint8Array(32))),i=new URL(`${r.replace(/\/+$/,"")}/attestation`);i.searchParams.set("nonce",n),e.appHash&&i.searchParams.set("appHash",e.appHash);let s=await t(i.toString());if(!s.ok)throw new Error(`The node refused to attest: HTTP ${s.status}`);let o=await s.json(),a=pe(o.transportKey,"transportKey",32),c=e.appHash?pe(e.appHash,"appHash",32):new Uint8Array(32),u=await Ve(c,a),d=dn(o.quote),g=new TextEncoder().encode(Ot);if(Ze(d.slice(0,g.length),g)){if(!e.allowMock)throw new Error("mock quote refused: this client only trusts real TEEs");let f=d.slice(g.length,g.length+64);if(!Ze(f.slice(0,32),pe(n,"nonce",32))||!Ze(f.slice(32),u))throw new Error("the quote does not bind this transport key, app and nonce");return a}let p={quoteB64:o.quote,nonce:n,reportDataSuffix:R(u)},h;if(e.verifyQuote)h=await e.verifyQuote(p);else if(e.release)h=await fn(o,p,e.release,t);else throw new Error("real quote refused: this client trusts no TD image (set policy.release)");if(!h)throw new Error("The attestation did not verify, so its transport key is not trusted");return a}var w=class extends Error{constructor(t,n,i,s={}){super(`${t} ${n}: ${i}`);this.status=t;this.code=n;this.details=s;this.name="CalimeroError"}},J=class extends w{constructor(e,t={}){super(401,"UNAUTHENTICATED",e,t),this.name="LoginRequired"}},$=class extends w{constructor(e,t={}){super(421,"WRONG_NODE",e,t),this.name="WrongNode"}},Ae=class extends w{constructor(e,t={}){super(404,"NOT_FOUND",e,t),this.name="NotFound"}},Y=class extends w{constructor(e,t={}){super(412,"CONFIRM_REQUIRED",e,t),this.name="ConfirmRequired"}},ie=class extends Error{constructor(t){super("the passkey confirmation was cancelled");this.cause=t;this.name="ConfirmCancelled"}},be=class extends w{constructor(e,t={}){super(413,"ARGS_TOO_LARGE",e,t),this.name="ArgsTooLarge"}},Ee=class extends w{constructor(e,t={}){super(409,"IDEMPOTENCY_MISMATCH",e,t),this.name="IdempotencyMismatch"}},Re=class extends w{constructor(e,t={}){super(409,"RELEASE_DEADLINE",e,t),this.name="ReleaseDeadlineError",this.release=typeof t.release=="string"?t.release:"",this.after=typeof t.after=="string"?t.after:""}},Pe=class extends w{constructor(e,t={}){super(409,"CONSENT_STALE",e,t),this.name="ConsentStale"}},Ue=class extends w{constructor(e,t={}){super(422,"APP_ERROR",e,t),this.name="AppError";let{appCode:n,fields:i}=yn(t);this.appCode=n,this.fields=i}},xe=class extends w{constructor(e,t={}){super(422,"TRAP",e,t),this.name="TrapError",this.kind=typeof t.kind=="string"?t.kind:""}},B=class extends w{constructor(e,t,n={},i,s){super(503,e,t,n),this.name="UnavailableError",this.reason=e.toLowerCase(),this.committed=e==="TIMEOUT"||e==="MIGRATING"?!1:"unknown",this.retryAfter=i,this.cause=s}};function Te(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function yn(r){let e=typeof r.code=="string"?r:Te(r.error);return{appCode:typeof e.code=="string"?e.code:"",fields:{...Te(e.fields)}}}function hn(r,e){for(let t of[r.retryAfter,e==null?void 0:Number(e)])if(typeof t=="number"&&Number.isFinite(t)&&t>=0)return t}function Se(r,e,t){let n=Te(e),i=typeof n.error=="string"?n.error:"ERROR",s=typeof n.message=="string"?n.message:"",o=Te(n.details);if(r===503)return new B(i,s,o,hn(o,t));switch(`${r} ${i}`){case"401 UNAUTHENTICATED":return new J(s,o);case"421 WRONG_NODE":return new $(s,o);case"404 NOT_FOUND":return new Ae(s,o);case"409 IDEMPOTENCY_MISMATCH":return new Ee(s,o);case"409 RELEASE_DEADLINE":return new Re(s,o);case"409 CONSENT_STALE":return new Pe(s,o);case"412 CONFIRM_REQUIRED":return new Y(s,o);case"413 ARGS_TOO_LARGE":return new be(s,o);case"422 APP_ERROR":return new Ue(s,o);case"422 TRAP":return new xe(s,o);default:return new w(r,i,s,o)}}function T(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function k(r){let e=r.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((r.length+3)%4),t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n}var se=r=>r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);function Mt(r){let e=new Error(r);return e.name="NotAllowedError",e}function mn(){return{async create(r){let e=r,t=await navigator.credentials.create({publicKey:{challenge:se(k(e.challenge)),rp:e.rp,user:{...e.user,id:se(k(e.user.id))},pubKeyCredParams:e.pubKeyCredParams,excludeCredentials:(e.excludeCredentials??[]).map(i=>({type:i.type,id:se(k(i.id))})),authenticatorSelection:e.authenticatorSelection,attestation:"none",timeout:e.timeout}});if(!t)throw Mt("passkey creation was cancelled");let n=t.response;return{attestationObject:T(new Uint8Array(n.attestationObject)),clientDataJson:T(new Uint8Array(n.clientDataJSON))}},async get(r,e,t){let n=await navigator.credentials.get({publicKey:{challenge:se(r),rpId:e,userVerification:"preferred",allowCredentials:(t??[]).map(s=>({type:"public-key",id:se(k(s))}))}});if(!n)throw Mt("passkey sign-in was cancelled");let i=n.response;return{credentialId:T(new Uint8Array(n.rawId)),authenticatorData:T(new Uint8Array(i.authenticatorData)),clientDataJson:T(new Uint8Array(i.clientDataJSON)),signature:T(new Uint8Array(i.signature))}}}}var et=100;function ae(r={}){let e=new URLSearchParams;if(r.after!==void 0&&e.set("after",r.after),r.limit!==void 0){if(!Number.isInteger(r.limit)||r.limit<1||r.limit>et)throw new RangeError(`limit is 1 to ${et}`);e.set("limit",String(r.limit))}let t=e.toString();return t?`?${t}`:""}function oe(r,e){try{return ne(r,e)}catch{return r<e?-1:r>e?1:0}}function _t(r,e,t=Date.now()/1e3){if(r===null||r.length===0)return null;let n=r.reduce((s,o)=>oe(s,o)>=0?s:o),i=null;for(let s of e)s.afterSecs<=t&&oe(n,s.version)<0&&(i===null||oe(s.version,i.version)>0)&&(i=s);return i}function $t(r,e,t,n){return`calimero-publisher-binding/v1
1
+ function R(r){return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}function fe(r,e,t){let n=r.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length!==t*2)throw new Error(`${e} must be ${t*2} hex characters, got ${n.length}`);let i=new Uint8Array(t);for(let s=0;s<t;s+=1)i[s]=Number.parseInt(n.slice(s*2,s*2+2),16);return i}function y(...r){let e=new Uint8Array(r.reduce((n,i)=>n+i.length,0)),t=0;for(let n of r)e.set(n,t),t+=n.length;return e}var br="Noise_NK_25519_AESGCM_SHA256",$e=32,Er=16,Rr=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Ke=class r{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(br),t=new Uint8Array(32);return t.set(e),new r(t)}async mixHash(e){this.h=await Pr(y(this.h,e))}async mixKey(e){let[t,n]=await ft(this.ck,e);this.ck=t,this.k=await crypto.subtle.importKey("raw",n,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let t=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:pt(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(t),t}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let t=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:pt(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),t}split(){return ft(this.ck,new Uint8Array)}};async function yt(r,e,t){let n=await Ke.initialize();await n.mixHash(e),await n.mixHash(r);let i=await G(t);return await n.mixHash(i.publicKey),await n.mixKey(await X(i.privateKey,r)),{message1:y(i.publicKey,await n.encryptAndHash(new Uint8Array)),async finish(o){if(o.length<$e+Er)throw new Error("Noise: message 2 is too short");let a=o.slice(0,$e);return await n.mixHash(a),await n.mixKey(await X(i.privateKey,a)),{payload:await n.decryptAndHash(o.slice($e)),split:await n.split()}}}}async function G(r){if(!r){let n;try{n=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"])}catch(s){throw new Error(`Sealed transport needs WebCrypto with X25519, which this runtime lacks (${s?.name??"no crypto.subtle"}). Current browsers and Node have it; in React Native, install react-native-quick-crypto as the global crypto.`)}let i=new Uint8Array(await crypto.subtle.exportKey("raw",n.publicKey));return{privateKey:n.privateKey,publicKey:i}}let e=await crypto.subtle.importKey("pkcs8",y(Rr,r),{name:"X25519"},!0,["deriveBits"]),t=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Ur(t.x)}}async function X(r,e){let t=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:t},r,256))}function pt(r){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(r),!1),e}async function Pr(r){return new Uint8Array(await crypto.subtle.digest("SHA-256",r))}async function Be(r,e){let t=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",t,e))}async function ft(r,e){let t=await Be(r,e),n=await Be(t,new Uint8Array([1])),i=await Be(t,y(n,new Uint8Array([2])));return[n,i]}function Ur(r){let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(t,n=>n.charCodeAt(0))}var At="/sealed/v2/handshake",bt="/sealed/v2",te="application/vnd.calimero.sealed",Ve=2,xr=new TextEncoder().encode("calimero/sealed-http/v2"),ee=16,Tr=1+ee+8,Sr=0,Cr=1,vr=2,kr=1+64*1024+16,Ir=1024,Or=6e4,Dr="calimero.tee-attest.transport-key.v1",Nr=[101,204,205,304],Et=new TextEncoder,re=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},C=class extends Error{constructor(t,n,i,s){super(i);this.status=t;this.code=n;this.retryAfterMs=s;this.name="SealedTransportError"}};async function Le(r,e){let t=await crypto.subtle.digest("SHA-256",y(Et.encode(Dr),r,e));return new Uint8Array(t)}function He(r){let e=new URL(r.baseUrl),t=e.pathname.replace(/\/+$/,""),n=`${e.origin}${t}`,i=r.fetch??((g,p)=>fetch(g,p)),s=typeof r.transportPublicKey=="function"?r.transportPublicKey:void 0,o=s?Promise.resolve().then(s):Promise.resolve(r.transportPublicKey);o.catch(()=>{});let a,c=async()=>{try{return await mt(i,n,await ht(o))}catch(g){if(!(g instanceof re)||!s)throw g;return o=Promise.resolve().then(s),mt(i,n,await ht(o))}},l=async()=>{let g=a??u(void 0),p=await g;if(Date.now()<p.renewAt)return[p,g];let h=u(g);return[await h,h]},u=g=>{if(a===g){let p=c();a=p,p.catch(()=>{a===p&&(a=void 0)})}return a};return async(g,p)=>{let h=new Request(g,p),f=new URL(h.url);if(f.origin!==e.origin||!f.pathname.startsWith(`${t}/`))throw new Error(`Refusing to send ${f.href} outside the sealed node at ${r.baseUrl}`);let b=[];h.headers.forEach((P,L)=>b.push([L,P]));let N={method:h.method,path:f.pathname.slice(t.length)+f.search,headers:b},E=new Uint8Array(await h.arrayBuffer()),x=p?.signal??(g instanceof Request?g.signal:void 0),M=async P=>{let{requestId:L,header:W,envelope:pe}=await _r(P,N,E),H=await i(`${n}${bt}`,{method:"POST",headers:{"content-type":te},body:pe,signal:x});if(H.headers.get("content-type")!==te)throw await Pt(H);return Br(H,P.responseKey,W,L)},[De,Ne]=await l();try{return await M(De)}catch(P){if(!(P instanceof C)||P.code!=="unknown_session")throw P;return M(await u(Ne))}}}async function ht(r){let e=await r;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function mt(r,e,t){try{return await wt(r,e,t)}catch(n){if(!(n instanceof C)||n.code!=="busy")throw n;return await new Promise(i=>setTimeout(i,n.retryAfterMs??1e3)),wt(r,e,t)}}async function wt(r,e,t){let n=await yt(t,xr),i=await r(`${e}${At}`,{method:"POST",headers:{"content-type":te},body:y(new Uint8Array([Ve]),t,n.message1)});if(i.headers.get("content-type")!==te)throw await Pt(i);let s=await Vr(i,Ir);return Mr(n,s)}async function Mr(r,e){if(e[0]!==Ve)throw new Error("The handshake reply is malformed");let t;try{t=await r.finish(e.slice(1))}catch{throw new Error("The handshake reply did not open: it did not come from the attested node")}let{payload:n,split:i}=t;if(n.length!==ee+4)throw new Error("The handshake reply is malformed");let s=n.slice(0,ee),o=new DataView(n.buffer,n.byteOffset).getUint32(ee,!1),[a,c]=await Promise.all([crypto.subtle.importKey("raw",i[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",i[1],"AES-GCM",!1,["decrypt"])]);return i[0].fill(0),i[1].fill(0),{requestKey:a,responseKey:c,nextRequestId:1,renewAt:Date.now()+o*1e3-Or,header(l){let u=new Uint8Array(Tr);return u[0]=Ve,u.set(s,1),new DataView(u.buffer).setBigUint64(1+ee,BigInt(l),!1),u}}}async function _r(r,e,t){let n=r.nextRequestId;r.nextRequestId+=1;let i=r.header(n),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:Rt(n,0),additionalData:i},r.requestKey,$r(e,t));return{requestId:n,header:i,envelope:y(i,new Uint8Array(s))}}function Rt(r,e){let t=new Uint8Array(12),n=new DataView(t.buffer);return n.setBigUint64(0,BigInt(r),!1),n.setUint32(8,e,!1),t}function $r(r,e){let t=Et.encode(JSON.stringify(r)),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t.length,!1),y(n,t,e)}async function Br(r,e,t,n){if(!r.body)throw new Error("The sealed response has no body");let i=Kr(r.body.getReader()),s=0,o=async()=>{let u=await i.next();if(!u)return null;let g;try{g=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Rt(n,s),additionalData:t},e,u))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return s+=1,{kind:g[0],data:g.slice(1)}},a=await o();if(!a||a.kind!==Sr)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(Nr.includes(c.status))return await i.cancel(),new Response(null,{status:c.status,headers:c.headers});let l=new ReadableStream({async pull(u){try{let g=await o();g?g.kind===Cr?u.enqueue(g.data):g.kind===vr?(u.close(),await i.cancel()):u.error(new Error("The sealed response is malformed")):u.error(new Error("The sealed response was cut short"))}catch(g){u.error(g)}},cancel(){return i.cancel()}});return new Response(l,{status:c.status,headers:c.headers})}function Kr(r){let e=new Uint8Array,t=async n=>{for(;e.length<n;){let{done:i,value:s}=await r.read();if(i)return!1;e=y(e,s)}return!0};return{async next(){if(!await t(4))return null;let n=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(n>kr)throw await r.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await t(4+n))return null;let i=e.slice(4,4+n);return e=e.slice(4+n),i},cancel:()=>r.cancel()}}async function Vr(r,e){if(!r.body)return new Uint8Array;let t=r.body.getReader(),n=new Uint8Array;for(;;){let{done:i,value:s}=await t.read();if(i)return n;if(n=y(n,s),n.length>e)throw await t.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function Pt(r){let e,t=`Sealed request refused: HTTP ${r.status}`;try{let s=await r.json();e=s?.error?.code,s?.error?.message&&(t=`Sealed request refused: ${s.error.message}`)}catch{}if(e==="stale_transport_key")return new re;let n=Number(r.headers.get("retry-after")),i=Number.isFinite(n)&&n>0?Math.min(n,5)*1e3:void 0;return new C(r.status,e,t,i)}var Ut=[{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"]}],xt=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var Lr="1.2.840.10045.2.1",Hr={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},Fr={"P-256":32,"P-384":48},Gr={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function Tt(r,e,t){if(e+2>t)throw new Error("it is truncated");let n=r[e];if((n&31)===31)throw new Error("it uses a tag this parser does not read");let i=r[e+1],s=e+2;if(i&128){let a=i&127;if(a===0||a>4||s+a>t)throw new Error("it has a length this parser does not read");i=0;for(let c=0;c<a;c+=1)i=i*256+r[s+c];s+=a}let o=s+i;if(o>t)throw new Error("it is truncated");return{tag:n,bytes:r,offset:e,start:s,end:o}}function q(r){let e=Tt(r,0,r.length);if(e.end!==r.length)throw new Error("it has trailing bytes");return e}function A(r){let e=[];for(let t=r.start;t<r.end;){let n=Tt(r.bytes,t,r.end);e.push(n),t=n.end}return e}function m(r,e,t){if(!r||r.tag!==e)throw new Error(`${t} is not where it should be`);return r}function v(r){return r.bytes.slice(r.start,r.end)}function ye(r){return r.bytes.slice(r.offset,r.end)}function j(r){let e=v(m(r,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let t=[],n=0;for(let o of e)n=n*128+(o&127),o&128||(t.push(n),n=0);let i=t.shift();return[...i<80?[Math.floor(i/40),i%40]:[2,i-80],...t].join(".")}function jr(r){let e=new TextDecoder().decode(v(r)),t=r.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,n=r.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,i=t??n;if(!i)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let s=Number(i[1]);t&&(s+=s<50?2e3:1900);let[o,a,c,l,u]=i.slice(2).map(Number);return Date.UTC(s,o-1,a,c,l,u)}function Fe(r){try{let[e,t,n,...i]=A(m(q(r),48,"The certificate"));if(i.length>0)throw new Error("it has fields after its signature");let s=A(m(e,48,"The signed part")),o=s[0]?.tag===160?1:0,[a,c,l,u,g,p,...h]=s.slice(o);m(a,2,"The serial number");let f=j(A(m(t,48,"The signature algorithm"))[0]);if(j(A(m(c,48,"The signature algorithm"))[0])!==f)throw new Error("it names two different signature algorithms");let N=Gr[f];if(!N)throw new Error(`it is signed with ${f}, not ECDSA with SHA-256 or SHA-384`);let[E,x]=A(m(u,48,"The validity")).map(jr);if(x===void 0)throw new Error("its validity is incomplete");let[M,De]=A(m(p,48,"The public key"));m(De,3,"The public key");let[Ne,P]=A(m(M,48,"The key algorithm"));if(j(Ne)!==Lr)throw new Error("its key is not an elliptic-curve key");let L=Hr[j(P)];if(!L)throw new Error("its key is on a curve other than P-256 or P-384");let W=new Map,pe=h.find(Me=>Me.tag===163);if(pe){let[Me]=A(pe);for(let Ar of A(m(Me,48,"The extensions"))){let F=A(m(Ar,48,"An extension"));if(F.length===3)m(F[1],1,"An extension's critical flag");else if(F.length!==2)throw new Error("it has a malformed extension");let _e=j(F[0]);if(W.has(_e))throw new Error(`it has extension ${_e} twice`);W.set(_e,v(m(F[F.length-1],4,"An extension value")))}}let H=v(m(n,3,"The signature"));if(H[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:r,tbs:ye(e),signatureHash:N,signature:H.slice(1),issuer:ye(m(l,48,"The issuer")),subject:ye(m(g,48,"The subject")),notBefore:E,notAfter:x,spki:ye(p),curve:L,extensions:W}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function St(r){return A(m(q(r),48,"The list")).map(j)}function qr(r,e){let t=Fr[e],n=A(m(q(r),48,"The signature"));if(n.length!==2)throw new Error("The signature is not an ECDSA signature");let i=new Uint8Array(t*2);return n.forEach((s,o)=>{let a=v(m(s,2,"The signature"));if(a.length===0||a[0]&128)throw new Error("The signature is not an ECDSA signature");for(;a.length>1&&a[0]===0;)a=a.subarray(1);if(a.length>t)throw new Error("The signature is not an ECDSA signature");i.set(a,o*t+t-a.length)}),i}async function he(r,e,t,n,i){let s;try{s=qr(n,e)}catch{return!1}let o=await crypto.subtle.importKey("spki",r,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:t},o,s,i)}function U(r,e){let t=r.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t)||t.length%4!==0)throw new Error(`${e} is not base64`);let n=atob(t),i=new Uint8Array(n.length);for(let s=0;s<n.length;s+=1)i[s]=n.charCodeAt(s);return i}function Ge(r,e){let t=[...r.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(t.length!==1||r.replace(t[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return U(t[0][1],e)}var Qr="2.5.29.17",Jr="2.5.29.37",zr="1.3.6.1.5.5.7.3.3",Yr="1.3.6.1.4.1.57264.1.8",Zr="1.3.6.1.4.1.57264.1.1",Wr=134,Xr=12,en=48,tn=new TextEncoder,Q=r=>new TextDecoder().decode(r);async function me(r,e,t,n){let{base64Signature:i,cert:s,rekorBundle:o}=on(e),a=o.Payload;if(n!==void 0&&n.trim()!==i.trim())throw new Error("The detached signature is not the one in the bundle");let c=U(i,"The bundle signature"),l=Ge(Q(U(s,"The bundle certificate")),"The bundle certificate"),u=Fe(l),g=xt.find(x=>x.logId===a.logID.toLowerCase());if(!g)throw new Error(`The bundle names Rekor log ${a.logID}, which the Sigstore trust root does not know`);let p=tn.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await he(U(g.publicKey,"The Rekor key"),"P-256","SHA-256",U(o.SignedEntryTimestamp,"The signed entry timestamp"),p))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let f=a.integratedTime*1e3;if(!kt(f,g.validFor))throw new Error(`Rekor log ${g.baseUrl} was not in use at ${ne(f)}, when the entry says it was logged`);let b=an(a.body),N=R(new Uint8Array(await crypto.subtle.digest("SHA-256",r)));if(b.hash!==N)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!je(U(b.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let E=Ge(Q(U(b.publicKey,"The logged certificate")),"The logged certificate");if(!je(E,l))throw new Error("The bundle's certificate is not the one Rekor logged");if(u.curve!=="P-256"||!await he(u.spki,"P-256","SHA-256",c,r))throw new Error("The signature over the file does not verify with the bundle's certificate");return await rn(u,f),sn(u,t),{integratedTime:a.integratedTime}}async function rn(r,e){if(!vt(r,e))throw new Error(`The signing certificate was valid ${ne(r.notBefore)} to ${ne(r.notAfter)}, not at ${ne(e)} when Rekor logged it`);let t=[];for(let n of Ut){let i=n.certChain.map(o=>Fe(U(o,"A Fulcio certificate")));if(!await Ct(r,i[0]))continue;let s=await nn(i,n.validFor,e);if(!s)return;t.push(`${n.uri} (valid from ${n.validFor.start}): ${s}`)}throw new Error(t.length>0?`The signing certificate's CA is not trusted at ${ne(e)}: ${t.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function nn(r,e,t){if(!kt(t,e))return"the trust root says it was not issuing certificates then";for(let[n,i]of r.entries()){if(!vt(i,t))return`its certificate ${n} was not valid then`;let s=r[n+1]??i;if(!await Ct(i,s))return`its certificate ${n} is not signed by the next`}}async function Ct(r,e){return je(r.issuer,e.subject)?he(e.spki,e.curve,r.signatureHash,r.signature,r.tbs):!1}function sn(r,e){let t=r.extensions.get(Qr);if(!t)throw new Error("The signing certificate names no identity");let n=A(m(q(t),en,"The subject alternative name")),i=n.filter(l=>l.tag===Wr).map(l=>Q(v(l)));if(i.length!==1||n.length!==1||i[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(i.length===1?i[0]:i)}, not by ${e.identity}`);let s=r.extensions.get(Yr),o=r.extensions.get(Zr),a=s?Q(v(m(q(s),Xr,"The OIDC issuer"))):o?Q(o):void 0;if(a!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${a===void 0?"missing":JSON.stringify(a)}, not ${e.issuer}`);let c=r.extensions.get(Jr);if(!c||!St(c).includes(zr))throw new Error("The signing certificate is not for code signing")}function on(r){let e=r;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let t=e,n=t?.rekorBundle?.Payload;if(!(typeof t?.base64Signature=="string"&&typeof t.cert=="string"&&typeof t.rekorBundle?.SignedEntryTimestamp=="string"&&typeof n?.body=="string"&&typeof n.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(n.logID)&&Number.isSafeInteger(n.integratedTime)&&n.integratedTime>=0&&Number.isSafeInteger(n.logIndex)&&n.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return t}function an(r){let e;try{e=JSON.parse(Q(U(r,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let t=e?.spec?.data?.hash,n=e?.spec?.signature;if(e?.kind!=="hashedrekord"||t?.algorithm!=="sha256"||typeof t.value!="string"||typeof n?.content!="string"||typeof n.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:t.value.toLowerCase(),signature:n.content,publicKey:n.publicKey.content}}function vt(r,e){return r.notBefore<=e&&e<=r.notAfter}function kt(r,e){return Date.parse(e.start)<=r&&(e.end===void 0||r<=Date.parse(e.end))}function ne(r){return new Date(r).toISOString()}function je(r,e){return r.length===e.length&&r.every((t,n)=>t===e[n])}var cn=/^[0-9a-f]{96}$/,ln=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function $(r){let e=J(r.allowedMrtd??[],"allowedMrtd"),t=(r.allowedMeasurements??[]).map((a,c)=>{let l=`allowedMeasurements[${c}]`;return ln.map(u=>J([a?.[u]??""],`${l}.${u}`)[0]).join()}),n=[J(r.allowedRtmr0??[],"allowedRtmr0"),J(r.allowedRtmr1??[],"allowedRtmr1"),J(r.allowedRtmr2??[],"allowedRtmr2"),J(r.allowedRtmr3??[],"allowedRtmr3")];if(r.allowedMeasurements!==void 0&&t.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(t.length===0){if(e.length===0)throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");if(n.slice(1).some(a=>a.length===0))throw new Error("allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too")}let i=r.allowedTcbStatuses??["UpToDate"],s=r.now??Date.now;return Object.assign(async({quoteB64:a,nonce:c,reportDataSuffix:l,collateral:u})=>{let g=dn(a),p=u??await r.fetchCollateral?.(g);if(!p)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let h;try{h=r.dcapVerify(g,p,Math.floor(s()/1e3))}catch(E){throw new Error(`The quote did not verify: ${E?.message??String(E)}`)}if(h.status==="Revoked"||!i.includes(h.status))throw new Error(`The platform's TCB status is ${h.status}, which is not accepted`);let f=un(h.report);if(f.tdAttributes?.length!==8||(f.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let b=[f.mrTd,f.rtMr0,f.rtMr1,f.rtMr2,f.rtMr3].map(E=>R(E));if(t.length>0&&!t.includes(b.join()))throw new Error(`The measurements (MRTD ${b[0]}, RTMR0-3 ${b.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(b[0]))throw new Error(`MRTD ${b[0]} is not an image this verifier trusts`);if([f.rtMr0,f.rtMr1,f.rtMr2,f.rtMr3].forEach((E,x)=>{let M=n[x];if(M.length>0&&!M.includes(R(E)))throw new Error(`RTMR${x} ${R(E)} is not one this verifier trusts`)}),R(f.reportData)!==`${c}${l}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function J(r,e){return r.map(t=>{let n=t.trim().toLowerCase();if(!cn.test(n))throw new Error(`${e} holds ${JSON.stringify(t)}, which is not a 48-byte hex measurement`);return n})}function un(r){let e=r.data;if(r.type==="td10"&&e)return e;if(r.type==="td15"&&e?.base)return e.base;throw new Error(`The quote is a ${r.type} quote, not a TDX one`)}function dn(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}var gn=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],_="locked-read-only";function qe(r,{profile:e,allowDebugProfile:t=!1}){if(r.length===0)throw new Error("No release given, so no image would be trusted");let n,i=r.map((s,o)=>{let a=s?.tag??`releases[${o}]`;if(s?.role!==void 0&&s.role!=="node")throw new Error(`${a} lists the measurements of a ${s.role}, not of a node image`);let c=s?.profiles?.[e];if(!c){let u=Object.keys(s?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${u})`)}if(e!==_&&!t)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(_)}, or pass allowDebugProfile to test`);let l=(c.allowed_tcb_statuses??["uptodate"]).map(u=>pn(u,a));return n=n===void 0?l:n.filter(u=>l.includes(u)),{mrtd:c.mrtd,rtmr0:c.rtmr0,rtmr1:c.rtmr1,rtmr2:c.rtmr2,rtmr3:c.rtmr3}});if(!n||n.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:i,allowedTcbStatuses:n}}function pn(r,e){let t=gn.find(n=>n.toLowerCase()===String(r).toLowerCase());if(!t)throw new Error(`${e} accepts TCB status ${JSON.stringify(r)}, which this verifier does not know`);return t}var Qe=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"}),fn=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],we="https://cloud.calimero.network",Je=`${we}/api/tee/pcs`;async function Ot(r,e,t={}){let n=typeof r=="string"?new TextEncoder().encode(r):r;await me(n,e,{identity:t.identity??Qe.identity,issuer:t.issuer??Qe.issuer},t.signature);let i;try{i=JSON.parse(new TextDecoder().decode(n))}catch{throw new Error("The signed release is not JSON")}if(i?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(i?.role)} release, not a node one`);let s=Object.values(i.profiles??{}),o=a=>fn.every(c=>/^[0-9a-f]{96}$/i.test(String(a?.[c])));if(typeof i.tag!="string"||s.length===0||!s.every(o))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(t.expectedVersion!==void 0&&i.tag!==t.expectedVersion)throw new Error(`The signed release is ${i.tag}, not ${t.expectedVersion}`);return i}async function ze(r,e={}){let t=await(e.fetch??fetch)(r,{headers:{accept:"application/json"}});if(!t.ok)throw new Error(`Fetching the node release from ${r} failed: HTTP ${t.status}`);let n;try{n=(await t.json())?.data}catch{throw new Error(`${r} did not answer with JSON`)}if(typeof n?.version!="string"||typeof n.publishedMrtds!="string"||typeof n.bundle!="string")throw new Error(`${r} did not answer with a signed node release`);return{version:n.version,publishedMrtds:n.publishedMrtds,bundle:n.bundle}}var Dt="https://github.com/calimero-network/mero-tee/releases/download";async function Ye(r,e={}){let t=`mero-tee-v${k(r,"version")}`,n=`${(e.base??Dt).replace(/\/+$/,"")}/${t}/published-mrtds.json`,i=async a=>{let c=await(e.fetch??fetch)(a);if(!c.ok)throw new Error(`Fetching ${a} failed: HTTP ${c.status}`);return c.text()},[s,o]=await Promise.all([i(n),i(`${n}.bundle.json`)]);return{version:r,publishedMrtds:s,bundle:o}}function Ze(r,e){return`${r.replace(/\/+$/,"")}/api/tee/node-releases/${k(e,"version")}`}async function Ae(r){let e=k(r.minReleaseVersion,"minReleaseVersion"),t=k(r.release?.version,"The release version"),n=await Ot(r.release.publishedMrtds,r.release.bundle,{expectedVersion:t,identity:r.identity,issuer:r.issuer});if(ie(t,e)<0)throw new Error(`Release ${t} is older than the minimum trusted, ${e}`);return qe([n],{profile:r.profile,allowDebugProfile:r.allowDebugProfile})}function yn(r){return k(r.minReleaseVersion,"minReleaseVersion"),Object.assign(async t=>{let n=await Ae({release:await r.release(),profile:r.profile,allowDebugProfile:r.allowDebugProfile,minReleaseVersion:r.minReleaseVersion,identity:r.identity,issuer:r.issuer});return $({dcapVerify:r.dcapVerify,fetchCollateral:r.fetchCollateral,now:r.now,...n})(t)},{includeCollateral:!0})}var Nt=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function k(r,e){let t=typeof r=="string"?Nt.exec(r):null,n=t?.[4];if(!t||n!==void 0&&n.split(".").some(i=>i===""))throw new Error(`${e} is ${JSON.stringify(r)}, not a release version like 2.3.87`);return r}function ie(r,e){let[t,n]=It(r),[i,s]=It(e);for(let c=0;c<3;c+=1)if(t[c]!==i[c])return t[c]<i[c]?-1:1;if(n===void 0||s===void 0)return n===s?0:n===void 0?1:-1;let o=n.split("."),a=s.split(".");for(let c=0;c<Math.max(o.length,a.length);c+=1){let[l,u]=[o[c],a[c]];if(l===void 0||u===void 0)return l===void 0?-1:1;let[g,p]=[/^\d+$/.test(l),/^\d+$/.test(u)],h=g&&p?Math.sign(Number(l)-Number(u)):g!==p?g?-1:1:l<u?-1:l>u?1:0;if(h!==0)return h}return 0}function It(r){let e=Nt.exec(r);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var _t="MOCK_TDX_QUOTE_V1";function hn(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function We(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}var Mt;async function Xe(r){Mt??(Mt=import("@phala/dcap-qvl"));let e=await Mt,t=typeof e[r]=="function"?e[r]:e.default?.[r];if(typeof t!="function")throw new TypeError(`@phala/dcap-qvl loaded without ${r}`);return t}function $t(r,e){let t=k(e,"minReleaseVersion"),n=String(r.release?.version??"").trim().replace(/^mero-tee-v/,"").replace(/^v/,""),i=k(n,"The release the node names");if(ie(i,t)<0)throw new Error(`mero-tee release ${i} is older than the minimum ${t}`);return i}async function mn(r,e,t){let n=e.releaseSource;return typeof n=="function"?n(r):n==="github"?Ye(r,{fetch:t}):ze(Ze(n??we,r),{fetch:t})}function wn(r){let e=r.collateralSource??Je;return e==="intel"?async t=>(await Xe("getCollateralFromPcs"))(t):async t=>(await Xe("getCollateral"))(e,t)}function Bt(r,e){let t=e.maxCollateralAgeDays;return t===void 0?r:async n=>{let i=await r(n),s;try{s=Date.parse(JSON.parse(i.tcb_info).issueDate??"")}catch{s=Number.NaN}if(!Number.isFinite(s))throw new Error("The quote's collateral names no TCB info issue date");let o=((e.now??Date.now)()-s)/864e5;if(o>t)throw new Error(`The quote's collateral was issued ${Math.floor(o)} days ago, more than the ${t} this client accepts`);return i}}async function An(r,e,t,n){let i=$t(r,t.minReleaseVersion),s=await Ae({release:await mn(i,t,n),profile:t.profile??_,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer}),o=Bt(t.fetchCollateral??wn(t),t);return $({dcapVerify:t.dcapVerify??await Xe("verify"),fetchCollateral:o,now:t.now,...s})(e)}async function et(r,e,t=(n,i)=>fetch(n,i)){let n=R(crypto.getRandomValues(new Uint8Array(32))),i=new URL(`${r.replace(/\/+$/,"")}/attestation`);i.searchParams.set("nonce",n),e.appHash&&i.searchParams.set("appHash",e.appHash);let s=await t(i.toString());if(!s.ok)throw new Error(`The node refused to attest: HTTP ${s.status}`);let o=await s.json(),a=fe(o.transportKey,"transportKey",32),c=e.appHash?fe(e.appHash,"appHash",32):new Uint8Array(32),l=await Le(c,a),u=hn(o.quote),g=new TextEncoder().encode(_t);if(We(u.slice(0,g.length),g)){if(!e.allowMock)throw new Error("mock quote refused: this client only trusts real TEEs");let f=u.slice(g.length,g.length+64);if(!We(f.slice(0,32),fe(n,"nonce",32))||!We(f.slice(32),l))throw new Error("the quote does not bind this transport key, app and nonce");return a}let p={quoteB64:o.quote,nonce:n,reportDataSuffix:R(l)},h;if(e.verifyQuote)h=await e.verifyQuote(p);else if(e.release)h=await An(o,p,e.release,t);else throw new Error("real quote refused: this client trusts no TD image (set policy.release)");if(!h)throw new Error("The attestation did not verify, so its transport key is not trusted");return a}var tt="https://manager.cloud.calimero.network/api/v2/directory";var T=class extends Error{constructor(t,n,i,s,o){super(`directory for cluster ${t}: ${i}`);this.cluster=t;this.reason=n;this.status=s;this.cause=o;this.name="DirectoryError"}};function bn(r,e){return`${r.replace(/\/+$/,"")}/${encodeURIComponent(e)}`}async function rt(r,e,t){let n;try{n=await t(bn(r,e),{method:"GET",headers:{accept:"application/json"}})}catch(u){throw new T(e,"unreachable",`could not be reached: ${String(u)}`,void 0,u)}if(n.status===404)throw new T(e,"not-found","unknown cluster",404);if(!n.ok)throw new T(e,"unreachable",`answered ${n.status}`,n.status);let i;try{i=await n.json()}catch(u){throw new T(e,"bad-response","answered something other than JSON",n.status,u)}let s=i;if(!s||typeof s!="object"||!Array.isArray(s.nodes))throw new T(e,"bad-response","answered no node list",n.status);let o=[],a=new Set;for(let u of s.nodes){let g=En(u);g&&!a.has(g.url)&&(a.add(g.url),o.push(g))}if(o.length===0)throw new T(e,"empty","lists no usable node",n.status);let c=s.refreshAfterSeconds,l=typeof c=="number"&&Number.isFinite(c)&&c>=1?c:60;return{nodes:o,refreshAfterSeconds:l}}function En(r){if(!r||typeof r!="object")return;let{url:e,zone:t,weight:n}=r;if(typeof e!="string"||typeof n!="number"||!Number.isInteger(n)||n<1)return;let i;try{i=new URL(e)}catch{return}if(!(i.protocol!=="https:"&&i.protocol!=="http:"))return{url:e.replace(/\/+$/,""),zone:typeof t=="string"?t:void 0,weight:n}}function nt(r,e,t){let n=e===void 0?[]:r.filter(s=>s.zone===e),i=e===void 0?r:r.filter(s=>s.zone!==e);return[...Kt(n,t),...Kt(i,t)]}function Kt(r,e){let t=[...r],n=[];for(;t.length>0;){let i=e()*t.reduce((o,a)=>o+a.weight,0),s=0;for(;s<t.length-1&&i>=t[s].weight;)i-=t[s++].weight;n.push(t.splice(s,1)[0].url)}return n}var w=class extends Error{constructor(t,n,i,s={}){super(`${t} ${n}: ${i}`);this.status=t;this.code=n;this.details=s;this.name="CalimeroError"}},z=class extends w{constructor(e,t={}){super(401,"UNAUTHENTICATED",e,t),this.name="LoginRequired"}},B=class extends w{constructor(e,t={}){super(421,"WRONG_NODE",e,t),this.name="WrongNode"}},be=class extends w{constructor(e,t={}){super(404,"NOT_FOUND",e,t),this.name="NotFound"}},Y=class extends w{constructor(e,t={}){super(412,"CONFIRM_REQUIRED",e,t),this.name="ConfirmRequired"}},se=class extends Error{constructor(t){super("the passkey confirmation was cancelled");this.cause=t;this.name="ConfirmCancelled"}},Ee=class extends w{constructor(e,t={}){super(413,"ARGS_TOO_LARGE",e,t),this.name="ArgsTooLarge"}},Re=class extends w{constructor(e,t={}){super(409,"IDEMPOTENCY_MISMATCH",e,t),this.name="IdempotencyMismatch"}},Pe=class extends w{constructor(e,t={}){super(409,"RELEASE_DEADLINE",e,t),this.name="ReleaseDeadlineError",this.release=typeof t.release=="string"?t.release:"",this.after=typeof t.after=="string"?t.after:""}},Ue=class extends w{constructor(e,t={}){super(409,"CONSENT_STALE",e,t),this.name="ConsentStale"}},xe=class extends w{constructor(e,t={}){super(422,"APP_ERROR",e,t),this.name="AppError";let{appCode:n,fields:i}=Rn(t);this.appCode=n,this.fields=i}},Te=class extends w{constructor(e,t={}){super(422,"TRAP",e,t),this.name="TrapError",this.kind=typeof t.kind=="string"?t.kind:""}},K=class extends w{constructor(e,t,n={},i,s){super(503,e,t,n),this.name="UnavailableError",this.reason=e.toLowerCase(),this.committed=e==="TIMEOUT"||e==="MIGRATING"?!1:"unknown",this.retryAfter=i,this.cause=s}};function Se(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function Rn(r){let e=typeof r.code=="string"?r:Se(r.error);return{appCode:typeof e.code=="string"?e.code:"",fields:{...Se(e.fields)}}}function Pn(r,e){for(let t of[r.retryAfter,e==null?void 0:Number(e)])if(typeof t=="number"&&Number.isFinite(t)&&t>=0)return t}function Ce(r,e,t){let n=Se(e),i=typeof n.error=="string"?n.error:"ERROR",s=typeof n.message=="string"?n.message:"",o=Se(n.details);if(r===503)return new K(i,s,o,Pn(o,t));switch(`${r} ${i}`){case"401 UNAUTHENTICATED":return new z(s,o);case"421 WRONG_NODE":return new B(s,o);case"404 NOT_FOUND":return new be(s,o);case"409 IDEMPOTENCY_MISMATCH":return new Re(s,o);case"409 RELEASE_DEADLINE":return new Pe(s,o);case"409 CONSENT_STALE":return new Ue(s,o);case"412 CONFIRM_REQUIRED":return new Y(s,o);case"413 ARGS_TOO_LARGE":return new Ee(s,o);case"422 APP_ERROR":return new xe(s,o);case"422 TRAP":return new Te(s,o);default:return new w(r,i,s,o)}}function S(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function I(r){let e=r.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((r.length+3)%4),t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n}var oe=r=>r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);function Vt(r){let e=new Error(r);return e.name="NotAllowedError",e}function Un(){return{async create(r){let e=r,t=await navigator.credentials.create({publicKey:{challenge:oe(I(e.challenge)),rp:e.rp,user:{...e.user,id:oe(I(e.user.id))},pubKeyCredParams:e.pubKeyCredParams,excludeCredentials:(e.excludeCredentials??[]).map(i=>({type:i.type,id:oe(I(i.id))})),authenticatorSelection:e.authenticatorSelection,attestation:"none",timeout:e.timeout}});if(!t)throw Vt("passkey creation was cancelled");let n=t.response;return{attestationObject:S(new Uint8Array(n.attestationObject)),clientDataJson:S(new Uint8Array(n.clientDataJSON))}},async get(r,e,t){let n=await navigator.credentials.get({publicKey:{challenge:oe(r),rpId:e,userVerification:"preferred",allowCredentials:(t??[]).map(s=>({type:"public-key",id:oe(I(s))}))}});if(!n)throw Vt("passkey sign-in was cancelled");let i=n.response;return{credentialId:S(new Uint8Array(n.rawId)),authenticatorData:S(new Uint8Array(i.authenticatorData)),clientDataJson:S(new Uint8Array(i.clientDataJSON)),signature:S(new Uint8Array(i.signature))}}}}var it=100;function ce(r={}){let e=new URLSearchParams;if(r.after!==void 0&&e.set("after",r.after),r.limit!==void 0){if(!Number.isInteger(r.limit)||r.limit<1||r.limit>it)throw new RangeError(`limit is 1 to ${it}`);e.set("limit",String(r.limit))}let t=e.toString();return t?`?${t}`:""}function ae(r,e){try{return ie(r,e)}catch{return r<e?-1:r>e?1:0}}function Lt(r,e,t=Date.now()/1e3){if(r===null||r.length===0)return null;let n=r.reduce((s,o)=>ae(s,o)>=0?s:o),i=null;for(let s of e)s.afterSecs<=t&&ae(n,s.version)<0&&(i===null||ae(s.version,i.version)>0)&&(i=s);return i}function Ht(r,e,t,n){return`calimero-publisher-binding/v1
2
2
  ${r}
3
3
  ${e}
4
4
  ${t}
5
- ${n}`}function wn(r,e,t,n){return new TextEncoder().encode($t(r,e,t,n))}var An="0123456789ABCDEFGHJKMNPQRSTVWXYZ";async function tt(r){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r))),t=(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0,n="";for(let i=0;i<6;i++)i===3&&(n+="-"),n+=An[t>>>27-5*i&31];return n}function bn(r){let e=typeof r=="string"?new URL(r):r,t=e.searchParams.get("request_id"),n=e.searchParams.get("result");return!t||n!=="approved"&&n!=="declined"?null:{requestId:t,result:n}}var Bt="https://mero-tee.vercel.app";function Kt(r){return`https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(r)}`}function Vt(r){return`${Bt}/mero-tee?release_tag=${encodeURIComponent(`mero-tee-v${r}`)}`}function rt(r,e,t=Date.now()/1e3){let n=c=>e.deadlines.find(u=>u.version===c)??null,i=r.governance.releases==="owner",s=r.governance.appUpgrades==="owner",o=r.clusterReleases.filter(c=>!c.approved).sort((c,u)=>oe(u.release,c.release)).map(c=>({version:c.release,nodes:c.nodes,actionable:i,releaseNotesUrl:Kt(c.release),verifyUrl:Vt(c.release),deadline:n(c.release)})),a=[];for(let c of r.apps){let u=c.availableVersions??[];c.package===null||u.length===0||a.push({app:c.app,name:c.name??null,package:c.package.package,from:c.package.version,to:u[u.length-1],available:u,actionable:s})}return{scope:r.scope,governance:r.governance,approvedReleases:r.approvedReleases,releases:o,upgrades:a,stalledBy:_t(r.approvedReleases,e.deadlines,t),actionable:o.some(c=>c.actionable)||a.some(c=>c.actionable)}}function Lt(r,e,t,n={}){return{kind:"release",scope:r.kind==="org"?{org:r.org}:"account",subject:n.withdraw?{version:e,withdraw:!0}:{version:e},returnTo:t}}function En(r,e,t){return Lt(r,e,t,{withdraw:!0})}function Rn(r,e,t){return{kind:"upgrade",subject:{app:r,toVersion:e},returnTo:t}}function l(r){return encodeURIComponent(r)}function Pn(r){return r instanceof S&&r.status===413?Se(413,{error:"TOO_LARGE",message:r.message.replace(/^Sealed request refused: /,"")}):r}async function Ht(r){let e=await r.text().catch(()=>""),t={};try{t=e?JSON.parse(e):{}}catch{t={message:e}}return Se(r.status,t,r.headers.get("retry-after"))}async function*Un(r){let e=r.getReader(),t=new TextDecoder,n="";for(;;){let{value:i,done:s}=await e.read();if(s)return;n+=t.decode(i,{stream:!0});let o;for(;(o=n.indexOf(`
5
+ ${n}`}function xn(r,e,t,n){return new TextEncoder().encode(Ht(r,e,t,n))}var Tn="0123456789ABCDEFGHJKMNPQRSTVWXYZ";async function st(r){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r))),t=(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0,n="";for(let i=0;i<6;i++)i===3&&(n+="-"),n+=Tn[t>>>27-5*i&31];return n}function Sn(r){let e=typeof r=="string"?new URL(r):r,t=e.searchParams.get("request_id"),n=e.searchParams.get("result");return!t||n!=="approved"&&n!=="declined"?null:{requestId:t,result:n}}var Ft="https://mero-tee.vercel.app";function Gt(r){return`https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(r)}`}function jt(r){return`${Ft}/mero-tee?release_tag=${encodeURIComponent(`mero-tee-v${r}`)}`}function ot(r,e,t=Date.now()/1e3){let n=c=>e.deadlines.find(l=>l.version===c)??null,i=r.governance.releases==="owner",s=r.governance.appUpgrades==="owner",o=r.clusterReleases.filter(c=>!c.approved).sort((c,l)=>ae(l.release,c.release)).map(c=>({version:c.release,nodes:c.nodes,actionable:i,releaseNotesUrl:Gt(c.release),verifyUrl:jt(c.release),deadline:n(c.release)})),a=[];for(let c of r.apps){let l=c.availableVersions??[];c.package===null||l.length===0||a.push({app:c.app,name:c.name??null,package:c.package.package,from:c.package.version,to:l[l.length-1],available:l,actionable:s})}return{scope:r.scope,governance:r.governance,approvedReleases:r.approvedReleases,releases:o,upgrades:a,stalledBy:Lt(r.approvedReleases,e.deadlines,t),actionable:o.some(c=>c.actionable)||a.some(c=>c.actionable)}}function qt(r,e,t,n={}){return{kind:"release",scope:r.kind==="org"?{org:r.org}:"account",subject:n.withdraw?{version:e,withdraw:!0}:{version:e},returnTo:t}}function Cn(r,e,t){return qt(r,e,t,{withdraw:!0})}function vn(r,e,t){return{kind:"upgrade",subject:{app:r,toVersion:e},returnTo:t}}function d(r){return encodeURIComponent(r)}function kn(r){return r instanceof C&&r.status===413?Ce(413,{error:"TOO_LARGE",message:r.message.replace(/^Sealed request refused: /,"")}):r}async function Qt(r){let e=await r.text().catch(()=>""),t={};try{t=e?JSON.parse(e):{}}catch{t={message:e}}return Ce(r.status,t,r.headers.get("retry-after"))}async function*In(r){let e=r.getReader(),t=new TextDecoder,n="";for(;;){let{value:i,done:s}=await e.read();if(s)return;n+=t.decode(i,{stream:!0});let o;for(;(o=n.indexOf(`
6
6
 
7
- `))>=0;){let a=n.slice(0,o);n=n.slice(o+2);let c="",u="",d="";for(let p of a.split(`
8
- `))p.startsWith("id:")?c=p.slice(3).trim():p.startsWith("event:")?u=p.slice(6).trim():p.startsWith("data:")&&(d+=p.slice(5).trim());if(!u&&!d)continue;let g=d;try{g=JSON.parse(d)}catch{}yield{id:c,kind:u,data:g}}}}function Ft(r){return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}function Gt(){return`node:c-${T(crypto.getRandomValues(new Uint8Array(16)))}`}var xn={retries:6,baseDelayMs:200,maxDelayMs:2e3};function Tn(r,e){return Math.min(e.baseDelayMs*2**r,e.maxDelayMs)}function jt(r){return r==="auth/refresh"||r.startsWith("auth/passkey/")}var nt=class{constructor(e){this.at=0;this.channels=new Map;this.networkFailures=new WeakSet;let t=s=>s.replace(/\/+$/,"");this.nodeUrls=[...new Set([e.baseUrl,...e.nodes??[]].map(t))],this.policy=e.policy,this.retry={...xn,...e.retry};let n=e.fetch??((s,o)=>fetch(s,o)),i=async(s,o)=>{try{return await n(s,o)}catch(a){throw a instanceof TypeError&&this.networkFailures.add(a),a}};this.raw=i}get nodeUrl(){return this.nodeUrls[this.at]}channel(e){let t=this.channels.get(e);return t||(t=Le({baseUrl:e,transportPublicKey:()=>Xe(e,this.policy,this.raw),fetch:this.raw}),this.channels.set(e,t)),t}moveOn(e){return this.nodeUrls.length<2?!1:(this.at===e&&(this.at=(e+1)%this.nodeUrls.length),!0)}useApiKey(e){this.auth=e,this.current=void 0}useSession(e){this.auth=e.sessionToken,this.current=e}get session(){return this.current}async request(e,t,n,i,s="application/wasm",o){let a={};this.auth&&(a.authorization=`Bearer ${this.auth}`);let c;i?(a["content-type"]=s,c=i):n!==void 0&&(a["content-type"]="application/json",c=JSON.stringify(n));let u=this.nodeUrl;try{return await this.channel(u)(`${u}/${t}`,{method:e,headers:a,body:c,signal:o})}catch(d){throw Pn(d)}}async send(e,t,n,i,s,o){let a=!1,c=!1;for(;;){let[u,d]=[this.auth,this.at],g=await this.request(e,t,n,i,s,o);if(g.ok)return g;let p=await Ht(g);if(p instanceof $&&!c){if(c=!0,this.moveOn(d)&&!jt(t))continue}else if(p instanceof J&&!a&&this.mayRefresh(u,t)){a=!0,await this.renew(u);continue}throw p}}mayRefresh(e,t){return e!==void 0&&this.current!==void 0&&!jt(t)}async renew(e){this.auth===e&&await this.refresh()}async json(e,t,n,i,s){let a=await(await this.send(e,t,n,i,s)).text();return a?JSON.parse(a):{}}async retried(e,t,n,i=this.retry.retries){for(let s=0;;s++){let o;try{return await this.json(e,t,n)}catch(c){if(c instanceof B)o=c;else if(c instanceof TypeError&&this.networkFailures.has(c))o=new B("NETWORK",`the node could not be reached: ${c.message}`,{},void 0,c);else throw c}if(s>=i)throw o;let a=Tn(s,this.retry);await new Promise(c=>setTimeout(c,Math.max(a,(o.retryAfter??0)*1e3)))}}post(e,t={}){return this.json("POST",e,t)}get(e){return this.json("GET",e)}put(e,t={}){return this.json("PUT",e,t)}delete(e,t){return this.json("DELETE",e,t)}async signUp(e,t){let n=await this.post("auth/passkey/register/begin",{name:t}),i=await e.create(n.options),s=await this.post("auth/passkey/register/finish",{challengeId:n.challengeId,registration:i});return this.useSession(s),s}async signIn(e){let t=await this.post("auth/passkey/login/begin"),n=await e.get(k(t.options.challenge),t.options.rpId),i=await this.post("auth/passkey/login/finish",{challengeId:t.challengeId,assertion:n});return this.useSession(i),i}refresh(){if(!this.refreshing){let e=this.exchangeRefresh();this.refreshing=e;let t=()=>{this.refreshing===e&&(this.refreshing=void 0)};e.then(t,t)}return this.refreshing}async exchangeRefresh(){let e=this.current;if(!e)throw new Error("no session to refresh");let t;for(let n=1;t===void 0;n++)try{t=await this.post("auth/refresh",{refreshToken:e.refreshToken})}catch(i){if(!(i instanceof $)||n>=this.nodeUrls.length)throw i}return this.current===e&&this.useSession(t),t}async signOut(){await this.post("auth/logout"),this.auth=void 0,this.current=void 0}async signOutEverywhere(){await this.post("auth/logout-all"),this.auth=void 0,this.current=void 0}me(){return this.get("auth/me")}async addPasskey(e){let t=await this.post("auth/passkeys/add/begin"),n=await e.create(t.options),{credentialId:i}=await this.post("auth/passkeys/add/finish",{challengeId:t.challengeId,registration:n});return i}async removePasskey(e){await this.delete(`auth/passkeys/${l(e)}`)}async labelPasskey(e,t){await this.post(`auth/passkeys/${l(e)}`,{label:t})}usage(){return this.get("auth/usage")}async attestation(){let e=Ft(crypto.getRandomValues(new Uint8Array(32))),t=await this.raw(`${this.nodeUrl}/attestation?nonce=${e}`);if(!t.ok)throw await Ht(t);return await t.json()}async listApiKeys(){let{keys:e}=await this.get("auth/apikeys");return e}async revokeApiKey(e){await this.delete(`auth/apikeys/${l(e)}`)}createApiKey(e){return this.post("auth/apikeys",e)}async uploadBundle(e){let{hash:t}=await this.json("POST","bundles",void 0,e);return t}uploadBlob(e,t){return this.json("POST",`apps/${l(e)}/blobs`,void 0,t)}async downloadBlob(e,t){let n=await this.send("GET",`apps/${l(e)}/blobs/${l(t)}`);return new Uint8Array(await n.arrayBuffer())}async listBlobs(e){let{blobs:t}=await this.get(`apps/${l(e)}/blobs`);return t}blobInfo(e,t){return this.get(`apps/${l(e)}/blobs/${l(t)}/info`)}async deleteBlob(e,t){await this.delete(`apps/${l(e)}/blobs/${l(t)}`)}uploadPackage(e){return this.json("POST","packages",void 0,e,"application/octet-stream")}installPackage(e,t){return this.post("packages/install",{package:e,version:t})}async packages(){let{packages:e}=await this.get("packages");return e}package(e){return this.get(`packages/${l(e)}`)}uninstallPackage(e,t){return this.delete(t===void 0?`packages/${l(e)}`:`packages/${l(e)}/${l(t)}`)}async listApps(e={}){let t=new URLSearchParams;e.package&&t.set("package",e.package),e.bundle&&t.set("bundle",e.bundle);let n=t.toString(),{apps:i}=await this.get(n?`apps?${n}`:"apps");return i}getApp(e){return this.get(`apps/${l(e)}`)}async deleteApp(e){await this.delete(`apps/${l(e)}`)}async setAccess(e,t){await this.post(`apps/${l(e)}/access`,{access:t})}async setAppMetadata(e,t){await this.post(`apps/${l(e)}/metadata`,{metadata:t})}appStorage(e){return this.get(`apps/${l(e)}/storage`)}appAbi(e){return this.get(`apps/${l(e)}/abi`)}async transferApp(e,t,n){await this.postConfirmed(`apps/${l(e)}/transfer`,{to:t},n)}upgradeApp(e,t,n){let i=`apps/${l(e)}/upgrade`;return n?this.postConfirmed(i,t,n):this.post(i,t)}postConfirmed(e,t,n){return this.confirmed("POST",e,t,n)}deleteConfirmed(e,t,n={}){return this.confirmed("DELETE",e,n,t)}async confirmed(e,t,n,i,s=o=>this.json(e,t,o)){try{return await s(n)}catch(o){if(!(o instanceof Y))throw o;let a=o.details,c;try{c=await i.get(k(a.challenge),a.rpId,a.allowCredentials)}catch(u){let d=u?.name;throw d==="NotAllowedError"||d==="AbortError"?new ie(u):u}return s({...n,confirm:{challengeId:a.challengeId,assertion:c}})}}async createApp(e,t,n={}){let i=typeof t=="string"?{bundle:t}:t,{appId:s}=await this.post("apps",{name:e,...i,...n});return s}call(e,t,n={},i){let s=i??Gt();return this.retried("POST",`apps/${l(e)}/intents`,{method:t,args:n,idempotencyKey:s})}async callConfirmed(e,t,n,i,s){let o=`apps/${l(e)}/intents`,a=s??Gt();return this.confirmed("POST",o,{method:t,args:n,idempotencyKey:a},i,c=>this.retried("POST",o,c,c.confirm===void 0?this.retry.retries:0))}view(e,t,n={},i={}){return this.retried("POST",`apps/${l(e)}/views`,{method:t,args:n,consistency:i.stale?"stale":"strong",minIndex:i.minIndex??0})}events(e,t=0,n){return this.stream(`apps/${l(e)}/events?from=${t}`,n)}async*stream(e,t){let n=await this.send("GET",e,void 0,void 0,void 0,t);if(!n.body)throw new w(n.status,"EVENTS","the event stream has no body");yield*Un(n.body)}async publishPresence(e,t,n){await this.post(`apps/${l(e)}/presence`,{seq:t,state:n===null?null:Ft(n)})}async presence(e){let{present:t}=await this.get(`apps/${l(e)}/presence`);return t}presenceStream(e,t){return this.stream(`apps/${l(e)}/presence/stream`,t)}async setAlias(e,t){await this.put(`auth/aliases/${l(e)}`,{app:t})}async aliases(){let{aliases:e}=await this.get("auth/aliases");return e}async alias(e){let{appId:t}=await this.get(`auth/aliases/${l(e)}`);return t}async deleteAlias(e){await this.delete(`auth/aliases/${l(e)}`)}async createOrg(e){let{orgId:t}=await this.post("orgs",{name:e});return t}getOrg(e){return this.get(`orgs/${l(e)}`)}async deleteOrg(e,t){await this.deleteConfirmed(`orgs/${l(e)}`,t)}async setOrgMetadata(e,t){await this.post(`orgs/${l(e)}/metadata`,{metadata:t})}async setMemberMetadata(e,t,n){await this.post(`orgs/${l(e)}/members/${l(t)}/metadata`,{metadata:n})}upgradeOrg(e,t,n){return this.postConfirmed(`orgs/${l(e)}/upgrade`,{...t},n)}upgradeRun(e,t){return this.get(`orgs/${l(e)}/upgrades/${l(t)}`)}retryUpgradeRun(e,t,n){return this.postConfirmed(`orgs/${l(e)}/upgrades/${l(t)}/retry`,{},n)}async approveRelease(e,t,n,i=!0){let s=e===null?"auth/releases":`orgs/${l(e)}/releases`;return this.postConfirmed(s,{version:t,approved:i},n)}async approveOutbound(e,t,n,i={}){let s=e===null?"auth/outbound":`orgs/${l(e)}/outbound`;return this.postConfirmed(s,{package:t,prefixes:i.prefixes??"manifest",replace:i.replace??!1},n)}appsReport(e,t={}){let n=e===null?"auth/apps":`orgs/${l(e)}/apps`;return this.get(`${n}${ae(t)}`)}async appsReportAll(e){let t=await this.appsReport(e),n=[...t.apps],i=t.next;for(;i!==null;){let s=await this.appsReport(e,{after:i});n.push(...s.apps),i=s.next}return{...t,apps:n,next:null}}releaseRules(){return this.get("releases")}async pendingApprovals(e=null){let[t,n]=await Promise.all([this.appsReportAll(e),this.releaseRules()]);return rt(t,n)}requestConsent(e){return this.post("consent/requests",e)}async openConsentPage(e,t={}){let n=typeof t=="function"?{navigate:t}:t,i=n.navigate??(o=>{let a=globalThis.window;if(!a)throw new Error("no window to open the consent page in; pass `navigate`");a.location.assign(o)}),s=await this.requestConsent(e);if(s.code!==void 0){let o=await tt(s.requestId);if(s.code!==o)throw new w(200,"CONSENT_CODE_MISMATCH","the consent page code does not match the request",{requestId:s.requestId,code:s.code,expected:o})}return n.confirm&&!await n.confirm(s)||i(s.url),s}consentResult(e){return this.get(`consent/${l(e)}/result`)}async waitForConsent(e,t={}){let n=t.intervalMs??2e3;for(;;){let i=await this.consentResult(e);if(i.status!=="pending"||t.signal?.aborted||t.expiresAt!==void 0&&Date.now()/1e3>=t.expiresAt)return i;await new Promise(s=>setTimeout(s,n))}}publisherBinding(e){return this.get(`publishers/${l(e)}`)}bindPublisher(e,t,n){return this.postConfirmed(`orgs/${l(e)}/publishers`,{...t},n)}upgradePublished(e,t,n,i){return this.postConfirmed(`orgs/${l(e)}/packages/${l(t)}/upgrade`,{...n},i)}opsApps(e={}){return this.get(`ops/apps${ae(e)}`)}opsOrgs(e={}){return this.get(`ops/orgs${ae(e)}`)}async setReleaseDeadline(e,t){let n=typeof t=="string"?t:t.toISOString();await this.post(`ops/releases/${l(e)}/deadline`,{after:n})}async liftReleaseDeadline(e){await this.delete(`ops/releases/${l(e)}/deadline`)}async setMember(e,t,n){await this.post(`orgs/${l(e)}/members`,{account:t,role:n})}removeMember(e,t){return this.delete(`orgs/${l(e)}/members/${l(t)}`)}async setCapabilities(e,t,n={}){await this.post(`orgs/${l(e)}/capabilities`,{capabilities:t,...n})}async createTeam(e,t,n,i){let{teamId:s}=await this.post(`orgs/${l(e)}/teams`,{name:t,join:n,parent:i});return s}getTeam(e,t){return this.get(`orgs/${l(e)}/teams/${l(t)}`)}async updateTeam(e,t,n){await this.post(`orgs/${l(e)}/teams/${l(t)}`,n)}async deleteTeam(e,t){await this.delete(`orgs/${l(e)}/teams/${l(t)}`)}async setTeamMember(e,t,n,i={}){await this.post(`orgs/${l(e)}/teams/${l(t)}/members`,{account:n,...i})}async removeTeamMember(e,t,n){await this.delete(`orgs/${l(e)}/teams/${l(t)}/members/${l(n)}`)}async invite(e,t,n=[],i={}){let{token:s}=await this.post(`orgs/${l(e)}/invites`,{role:t,teams:n,...i});return s}redeemInvite(e){return this.post(`invites/${l(e)}/redeem`)}};var it={CREATE_APP:1,INVITE_MEMBERS:2,JOIN_OPEN_TEAMS:4,MANAGE_MEMBERS:8,MANAGE_APPLICATION:16,CREATE_TEAM:32,DELETE_TEAM:64,MANAGE_VISIBILITY:128,MANAGE_METADATA:256,APPROVE_RELEASES:1024},Sn=it.JOIN_OPEN_TEAMS;function Cn(...r){return r.reduce((e,t)=>e|it[t],0)}function Ce(r,e){return(r<<e|r>>>32-e)>>>0}function I(r,e,t,n,i){r[e]=r[e]+r[t]>>>0,r[i]=Ce(r[i]^r[e],16),r[n]=r[n]+r[i]>>>0,r[t]=Ce(r[t]^r[n],12),r[e]=r[e]+r[t]>>>0,r[i]=Ce(r[i]^r[e],8),r[n]=r[n]+r[i]>>>0,r[t]=Ce(r[t]^r[n],7)}function qt(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0}function Yt(r,e,t){let n=new Uint32Array(16);n[0]=1634760805,n[1]=857760878,n[2]=2036477234,n[3]=1797285236;for(let o=0;o<8;o+=1)n[4+o]=qt(r,o*4);n[12]=e>>>0;for(let o=0;o<3;o+=1)n[13+o]=qt(t,o*4);let i=n.slice();for(let o=0;o<10;o+=1)I(i,0,4,8,12),I(i,1,5,9,13),I(i,2,6,10,14),I(i,3,7,11,15),I(i,0,5,10,15),I(i,1,6,11,12),I(i,2,7,8,13),I(i,3,4,9,14);let s=new Uint8Array(64);for(let o=0;o<16;o+=1){let a=i[o]+n[o]>>>0;s[o*4]=a&255,s[o*4+1]=a>>>8&255,s[o*4+2]=a>>>16&255,s[o*4+3]=a>>>24&255}return s}function vn(r,e,t,n){let i=new Uint8Array(n.length);for(let s=0,o=e;s<n.length;s+=64,o+=1){let a=Yt(r,o,t),c=Math.min(s+64,n.length);for(let u=s;u<c;u+=1)i[u]=n[u]^a[u-s]}return i}function st(r){let e=0n;for(let t=r.length-1;t>=0;t-=1)e=e<<8n|BigInt(r[t]);return e}var kn=(1n<<130n)-5n;function In(r,e){let t=st(r.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,n=st(r.subarray(16,32)),i=0n;for(let a=0;a<e.length;a+=16){let c=e.subarray(a,Math.min(a+16,e.length)),u=st(c)+(1n<<BigInt(8*c.length));i=(i+u)*t%kn}let s=i+n&(1n<<128n)-1n,o=new Uint8Array(16);for(let a=0;a<16;a+=1)o[a]=Number(s&0xffn),s>>=8n;return o}function Qt(r){return new Uint8Array((16-r%16)%16)}function Jt(r){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(r),!0),e}function On(r,e){let t=[r,Qt(r.length),e,Qt(e.length),Jt(r.length),Jt(e.length)],n=new Uint8Array(t.reduce((s,o)=>s+o.length,0)),i=0;for(let s of t)n.set(s,i),i+=s.length;return n}function Nn(r,e){if(r.length!==32)throw new Error("ChaCha20-Poly1305 needs a 32-byte key");if(e.length!==12)throw new Error("ChaCha20-Poly1305 needs a 12-byte nonce")}function zt(r,e,t,n=new Uint8Array(0)){Nn(r,e);let i=Yt(r,0,e).subarray(0,32),s=vn(r,1,e,t),o=In(i,On(n,s)),a=new Uint8Array(s.length+16);return a.set(s),a.set(o,s.length),a}var Wt=32,Dn=1,Mn=3,_n=2,$n=32,Bn=32,Kn=12,z=r=>new TextEncoder().encode(r),le=r=>new Uint8Array([r>>8&255,r&255]),Zt=y(z("KEM"),le(Wt)),ce=y(z("HPKE"),le(Wt),le(Dn),le(Mn));async function Xt(r,e){let t=r.length===0?new Uint8Array(32):r,n=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",n,e))}async function Vn(r,e,t){let n=new Uint8Array(t),i=new Uint8Array(0);for(let s=1,o=0;o<t;s+=1)i=await Xt(r,y(i,e,new Uint8Array([s]))),n.set(i.subarray(0,Math.min(i.length,t-o)),o),o+=i.length;return n}function ve(r,e,t,n){return Xt(e,y(z("HPKE-v1"),r,z(t),n))}function ot(r,e,t,n,i){return Vn(e,y(le(i),z("HPKE-v1"),r,z(t),n),i)}async function Ln(r,e){let t=await ve(Zt,new Uint8Array(0),"eae_prk",r);return ot(Zt,t,"shared_secret",e,$n)}async function Hn(r,e){let t=new Uint8Array(0),n=await ve(ce,t,"psk_id_hash",t),i=await ve(ce,t,"info_hash",e),s=y(new Uint8Array([_n]),n,i),o=await ve(ce,r,"secret",t);return{key:await ot(ce,o,"key",s,Bn),nonce:await ot(ce,o,"base_nonce",s,Kn)}}async function er(r,e,t,n,i=new Uint8Array(0),s){if(r.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let o=await F(s),a=await F(e),c=y(await W(o.privateKey,r),await W(a.privateKey,r)),u=await Ln(c,y(o.publicKey,r,a.publicKey)),{key:d,nonce:g}=await Hn(u,t);return{enc:o.publicKey,ciphertext:zt(d,g,n,i)}}var nr="mero-agent-gate/attest/v3",ir="mero-agent-gate/provision/v2",Fn=/^[a-z0-9][a-z0-9-]{0,62}$/,Gn=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,tr=64,rr=64*1024,O=class extends Error{constructor(t,n,i){super(t);this.status=n;this.code=i;this.name="AgentGateError"}};function sr(r){if(!Fn.test(r))throw new Error(`Agent id ${JSON.stringify(r)} must match [a-z0-9][a-z0-9-]{0,62}`)}function ue(r){return new TextEncoder().encode(r)}function or(r){let e=ue(r);return y(new Uint8Array([e.length]),e)}function K(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}function ke(r,e,t){let n;try{n=Uint8Array.from(atob(r.trim()),i=>i.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(t!==void 0&&n.length!==t)throw new Error(`${e} is not ${t} bytes`);return n}async function ar(r,e,t,n){let i=new Uint8Array(32),s=y(ue(nr),r,or(e),t??i,n??i);return new Uint8Array(await crypto.subtle.digest("SHA-256",s))}function cr(r,e){return y(ue(ir),r,or(e))}async function jn(){let r=crypto.getRandomValues(new Uint8Array(32));return{secret:r,publicKey:await Ie(r)}}async function Ie(r){if(r.length!==32)throw new Error("An owner key is 32 bytes");return K((await F(r)).publicKey)}function lr(r,e){return`${r.replace(/\/+$/,"")}${e}`}async function ur(r,e,t){let n=await r(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),i=await n.text(),s;try{s=i?JSON.parse(i):void 0}catch{}if(!n.ok){let o=s;throw new O(`The gate answered ${n.status}${o?.error?` ${o.error}`:""}: ${o?.details??i.slice(0,200)}`,n.status,o?.error)}return s}async function at(r){let e=r.agentId??"";e&&sr(e);let t=crypto.getRandomValues(new Uint8Array(32)),n=await ur(r.fetch??fetch,lr(r.gateUrl,"/attest"),{nonceB64:K(t),...e?{agentId:e}:{}});if((n?.agentId??"")!==e)throw new Error(`Asked about agent ${JSON.stringify(e)}, the gate answered for ${JSON.stringify(n?.agentId)}`);let i=ke(n.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),s=n.signingPublicKeyB64?ke(n.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,o=n.ownerPublicKeyB64?ke(n.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!s!=!o)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let a=await ar(i,e,s,o);return await r.verifier({quoteB64:n.quoteB64,nonce:R(t),reportDataSuffix:R(a)}),{agentId:e,provisioningPublicKey:K(i),...s?{signingPublicKey:K(s)}:{},...o?{ownerPublicKey:K(o)}:{}}}async function dr(r,e){let t=await Ie(e);if(r.ownerPublicKey&&r.ownerPublicKey!==t)throw new O(`This agent is claimed by another key (${r.ownerPublicKey}); it is not yours. Send it nothing and do not authorize its signing key`,void 0,"not_yours");return t}function qn(r){let e=Object.keys(r);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>tr)throw new Error(`At most ${tr} secrets at once`);for(let t of e){if(!Gn.test(t))throw new Error(`Secret name ${JSON.stringify(t)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);if(typeof r[t]!="string")throw new Error(`Secret ${t} is not a string`);if(ue(r[t]).length>rr)throw new Error(`Secret ${t} is over ${rr} bytes`)}}async function gr(r,e,t,n,i,s){if(!n.agentId)throw new Error("This quote names no agent; attest with the agent id");let o=await dr(n,i),a=ke(n.provisioningPublicKey,"provisioningPublicKey",32),c=await er(a,i,cr(a,n.agentId),ue(JSON.stringify(s)));return ur(r,lr(e,t),{agentId:n.agentId,provisioningPublicKeyB64:n.provisioningPublicKey,senderPublicKeyB64:o,encappedKeyB64:K(c.enc),ciphertextB64:K(c.ciphertext)})}async function Qn(r){qn(r.secrets);let e=r.fetch??fetch,t=await gr(e,r.gateUrl,"/provision",r.agent,r.ownerSecret,{secrets:r.secrets}),n=await at({gateUrl:r.gateUrl,agentId:r.agent.agentId,verifier:r.verifier,fetch:e}),i=await Ie(r.ownerSecret);if(n.ownerPublicKey!==i||!n.signingPublicKey)throw new O("The gate accepted the secrets, but its quote does not name your key as owner");if(r.agent.signingPublicKey&&r.agent.signingPublicKey!==n.signingPublicKey)throw new O("The agent's signing key changed while provisioning");return{agentId:n.agentId,provisioningPublicKey:n.provisioningPublicKey,signingPublicKey:n.signingPublicKey,ownerPublicKey:i,written:t?.written??[],claimed:t?.claimed===!0}}async function Jn(r){if(!r.agent.ownerPublicKey)throw new Error("This agent is not claimed; there is nothing to release");let e=r.fetch??fetch;if(await gr(e,r.gateUrl,"/release",r.agent,r.ownerSecret,{release:!0}),(await at({gateUrl:r.gateUrl,agentId:r.agent.agentId,verifier:r.verifier,fetch:e})).ownerPublicKey)throw new O("The gate says it released the agent, but its quote still names an owner")}var ct=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),Yn=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function zn(r,e,t={}){let n=typeof r=="string"?new TextEncoder().encode(r):r;await he(n,e,{identity:t.identity??ct.identity,issuer:t.issuer??ct.issuer});let i;try{i=JSON.parse(new TextDecoder().decode(n))}catch{throw new Error("The signed agent policy is not JSON")}let s=t.role??"agent";if(i?.role!==s)throw new Error(`The signed file is a ${JSON.stringify(i?.role)} policy, not an ${s} one`);let o=t.profile??M;if(i.profile!==o)throw new Error(`The signed agent policy is for the ${JSON.stringify(i.profile)} profile, not ${o}`);if(t.expectedVersion!==void 0&&i.version!==t.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(i.version)}, not ${t.expectedVersion}`);return pr(i),i}function pr(r){for(let e of Yn)if(!Array.isArray(r?.[e])||r[e].length===0)throw new Error(`The agent policy's ${e} is empty, so no agent would be accepted`)}var Zn=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function Wn(r){let e=Zn.find(t=>t.toLowerCase()===r.trim().toLowerCase());if(!e)throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(r)}`);return e}var de=r=>r.trim().replace(/^0x/i,"");function Xn(r,e){return pr(r),_({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:r.allowed_tcb_statuses.map(Wn),allowedMrtd:r.allowed_mrtd.map(de),allowedRtmr0:r.allowed_rtmr0.map(de),allowedRtmr1:r.allowed_rtmr1.map(de),allowedRtmr2:r.allowed_rtmr2.map(de),allowedRtmr3:r.allowed_rtmr3.map(de)})}export{nr as AGENT_ATTEST_DOMAIN,ir as AGENT_PROVISION_INFO_DOMAIN,O as AgentGateError,Ue as AppError,be as ArgsTooLarge,nt as CalimeroClient,w as CalimeroError,ie as ConfirmCancelled,Y as ConfirmRequired,Pe as ConsentStale,Qe as DEFAULT_COLLATERAL_MIRROR,Sn as DEFAULT_ORG_CAPABILITIES,me as DEFAULT_RELEASE_MIRROR,vt as GITHUB_RELEASES,yt as HANDSHAKE_PATH,Ee as IdempotencyMismatch,ct as KMS_RELEASE_SIGNER,J as LoginRequired,et as MAX_REPORT_PAGE,Ot as MOCK_QUOTE_HEADER,qe as NODE_RELEASE_SIGNER,Ae as NotFound,it as ORG_CAPABILITIES,M as PRODUCTION_PROFILE,Bt as RELEASE_VERIFIER,Re as ReleaseDeadlineError,ee as SEALED_CONTENT_TYPE,ht as SEALED_PATH,S as SealedTransportError,te as StaleTransportKeyError,xe as TrapError,B as UnavailableError,$ as WrongNode,ar as agentKeyBinding,Xn as agentQuoteVerifier,at as attestAgent,T as b64url,mn as browserPasskey,dr as checkOwner,Nt as claimedRelease,ze as cloudNodeReleaseUrl,oe as compareVersions,tt as confirmationCode,bn as consentReturn,_ as createQuoteVerifier,Le as createSealedFetch,un as createSignedReleaseVerifier,Se as errorFrom,Xe as fetchAttestedKey,Ye as fetchGithubNodeRelease,Je as fetchNodeRelease,Dt as freshCollateral,k as fromB64url,jn as generateOwnerKey,Cn as orgCapabilities,Ie as ownerPublicKey,ae as pageQuery,rt as pendingApprovalsFrom,Qn as provisionAgent,cr as provisionInfo,wn as publisherBindingBytes,$t as publisherBindingMessage,Jn as releaseAgent,Lt as releaseConsent,Kt as releaseNotesUrl,_t as stalledBy,Ve as transportKeyBinding,we as trustSignedRelease,je as trustedMeasurementsFromReleases,Rn as upgradeConsent,sr as validateAgentId,Vt as verifyReleaseUrl,zn as verifySignedAgentPolicy,Ct as verifySignedNodeRelease,En as withdrawConsent};
7
+ `))>=0;){let a=n.slice(0,o);n=n.slice(o+2);let c="",l="",u="";for(let p of a.split(`
8
+ `))p.startsWith("id:")?c=p.slice(3).trim():p.startsWith("event:")?l=p.slice(6).trim():p.startsWith("data:")&&(u+=p.slice(5).trim());if(!l&&!u)continue;let g=u;try{g=JSON.parse(u)}catch{}yield{id:c,kind:l,data:g}}}}function Jt(r){return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}function zt(){return`node:c-${S(crypto.getRandomValues(new Uint8Array(16)))}`}var On={retries:6,baseDelayMs:200,maxDelayMs:2e3};function Dn(r,e){return Math.min(e.baseDelayMs*2**r,e.maxDelayMs)}function Yt(r){return r==="auth/refresh"||r.startsWith("auth/passkey/")}var at=class r{constructor(e){this.at=0;this.channels=new Map;this.networkFailures=new WeakSet;let t=s=>s.replace(/\/+$/,"");this.nodeUrls=[...new Set([e.baseUrl,...e.nodes??[]].map(t))],this.policy=e.policy,this.retry={...On,...e.retry};let n=e.fetch??((s,o)=>fetch(s,o)),i=async(s,o)=>{try{return await n(s,o)}catch(a){throw a instanceof TypeError&&this.networkFailures.add(a),a}};this.raw=i}static async connect(e){let t=e.directory??tt,n=e.random??Math.random,i=e.fetch??((l,u)=>fetch(l,u)),s=await rt(t,e.cluster,i),[o,...a]=nt(s.nodes,e.zone,n),c=new r({baseUrl:o,nodes:a,policy:e.policy,fetch:e.fetch,retry:e.retry});return c.source={directory:t,cluster:e.cluster,zone:e.zone,random:n,due:Date.now()+s.refreshAfterSeconds*1e3},c}get nodeUrl(){return this.nodeUrls[this.at]}get nodes(){return[...this.nodeUrls]}channel(e){let t=this.channels.get(e);return t||(t=He({baseUrl:e,transportPublicKey:()=>et(e,this.policy,this.raw),fetch:this.raw}),this.channels.set(e,t)),t}moveOn(e){return this.nodeUrls.length<2?!1:(this.nodeUrl===e&&(this.at=(this.at+1)%this.nodeUrls.length),!0)}failOver(e,t){if(this.nodeUrl!==e&&!t.has(this.nodeUrl))return!0;let n=this.nodeUrls.length;for(let i=1;i<n;i++){let s=(this.at+i)%n;if(!t.has(this.nodeUrls[s]))return this.at=s,this.reread(),!0}return!1}reread(){let e=this.source;!e||e.reading||(e.reading=rt(e.directory,e.cluster,this.raw).then(t=>{let n=this.nodeUrl,i=nt(t.nodes,e.zone,e.random);this.nodeUrls=[n,...i.filter(s=>s!==n)],this.at=0,e.due=Date.now()+t.refreshAfterSeconds*1e3}).catch(()=>{}).finally(()=>{e.reading=void 0}))}useApiKey(e){this.auth=e,this.current=void 0}useSession(e){this.auth=e.sessionToken,this.current=e}get session(){return this.current}async request(e,t,n,i,s="application/wasm",o){let a={};this.auth&&(a.authorization=`Bearer ${this.auth}`);let c;i?(a["content-type"]=s,c=i):n!==void 0&&(a["content-type"]="application/json",c=JSON.stringify(n)),this.source&&Date.now()>=this.source.due&&this.reread();let l=this.nodeUrl;try{return await this.channel(l)(`${l}/${t}`,{method:e,headers:a,body:c,signal:o})}catch(u){throw kn(u)}}async send(e,t,n,i,s,o){let a=!1,c=!1;for(;;){let[l,u]=[this.auth,this.nodeUrl],g=await this.request(e,t,n,i,s,o);if(g.ok)return g;let p=await Qt(g);if(p instanceof B&&!c){if(c=!0,this.moveOn(u)&&!Yt(t))continue}else if(p instanceof z&&!a&&this.mayRefresh(l,t)){a=!0,await this.renew(l);continue}throw p}}mayRefresh(e,t){return e!==void 0&&this.current!==void 0&&!Yt(t)}async renew(e){this.auth===e&&await this.refresh()}async json(e,t,n,i,s){let a=await(await this.send(e,t,n,i,s)).text();return a?JSON.parse(a):{}}async retried(e,t,n,i=!1){let s=i?0:this.retry.retries,o=new Set;for(;;){let a,c=this.nodeUrl;for(let l=0;;l++){c=this.nodeUrl,o.add(c);try{return await this.json(e,t,n)}catch(g){if(g instanceof K)a=g;else if(g instanceof TypeError&&this.networkFailures.has(g))a=new K("NETWORK",`the node could not be reached: ${g.message}`,{},void 0,g);else throw g}if(l>=s)break;let u=Dn(l,this.retry);await new Promise(g=>setTimeout(g,Math.max(u,(a.retryAfter??0)*1e3)))}if(i||!this.failOver(c,o))throw a}}post(e,t={}){return this.json("POST",e,t)}get(e){return this.json("GET",e)}put(e,t={}){return this.json("PUT",e,t)}delete(e,t){return this.json("DELETE",e,t)}async signUp(e,t){let n=await this.post("auth/passkey/register/begin",{name:t}),i=await e.create(n.options),s=await this.post("auth/passkey/register/finish",{challengeId:n.challengeId,registration:i});return this.useSession(s),s}async signIn(e){let t=await this.post("auth/passkey/login/begin"),n=await e.get(I(t.options.challenge),t.options.rpId),i=await this.post("auth/passkey/login/finish",{challengeId:t.challengeId,assertion:n});return this.useSession(i),i}refresh(){if(!this.refreshing){let e=this.exchangeRefresh();this.refreshing=e;let t=()=>{this.refreshing===e&&(this.refreshing=void 0)};e.then(t,t)}return this.refreshing}async exchangeRefresh(){let e=this.current;if(!e)throw new Error("no session to refresh");let t;for(let n=1;t===void 0;n++)try{t=await this.post("auth/refresh",{refreshToken:e.refreshToken})}catch(i){if(!(i instanceof B)||n>=this.nodeUrls.length)throw i}return this.current===e&&this.useSession(t),t}async signOut(){await this.post("auth/logout"),this.auth=void 0,this.current=void 0}async signOutEverywhere(){await this.post("auth/logout-all"),this.auth=void 0,this.current=void 0}me(){return this.get("auth/me")}async addPasskey(e,t){let n=await this.post("auth/passkeys/add/begin"),i=await e.create(n.options),{credentialId:s}=await this.postConfirmed("auth/passkeys/add/finish",{challengeId:n.challengeId,registration:i},t);return s}async removePasskey(e,t){await this.deleteConfirmed(`auth/passkeys/${d(e)}`,t)}async labelPasskey(e,t){await this.post(`auth/passkeys/${d(e)}`,{label:t})}usage(){return this.get("auth/usage")}async attestation(){let e=Jt(crypto.getRandomValues(new Uint8Array(32))),t=await this.raw(`${this.nodeUrl}/attestation?nonce=${e}`);if(!t.ok)throw await Qt(t);return await t.json()}async listApiKeys(){let{keys:e}=await this.get("auth/apikeys");return e}async revokeApiKey(e){await this.delete(`auth/apikeys/${d(e)}`)}createApiKey(e,t){return this.postConfirmed("auth/apikeys",{...e},t)}async uploadBundle(e){let{hash:t}=await this.json("POST","bundles",void 0,e);return t}uploadBlob(e,t){return this.json("POST",`apps/${d(e)}/blobs`,void 0,t)}async downloadBlob(e,t){let n=await this.send("GET",`apps/${d(e)}/blobs/${d(t)}`);return new Uint8Array(await n.arrayBuffer())}async listBlobs(e){let{blobs:t}=await this.get(`apps/${d(e)}/blobs`);return t}blobInfo(e,t){return this.get(`apps/${d(e)}/blobs/${d(t)}/info`)}async deleteBlob(e,t){await this.delete(`apps/${d(e)}/blobs/${d(t)}`)}uploadPackage(e){return this.json("POST","packages",void 0,e,"application/octet-stream")}installPackage(e,t){return this.post("packages/install",{package:e,version:t})}async packages(){let{packages:e}=await this.get("packages");return e}package(e){return this.get(`packages/${d(e)}`)}uninstallPackage(e,t){return this.delete(t===void 0?`packages/${d(e)}`:`packages/${d(e)}/${d(t)}`)}async listApps(e={}){let t=new URLSearchParams;e.package&&t.set("package",e.package),e.bundle&&t.set("bundle",e.bundle);let n=t.toString(),{apps:i}=await this.get(n?`apps?${n}`:"apps");return i}getApp(e){return this.get(`apps/${d(e)}`)}async deleteApp(e){await this.delete(`apps/${d(e)}`)}async setAccess(e,t){await this.post(`apps/${d(e)}/access`,{access:t})}async setAppMetadata(e,t){await this.post(`apps/${d(e)}/metadata`,{metadata:t})}appStorage(e){return this.get(`apps/${d(e)}/storage`)}appAbi(e){return this.get(`apps/${d(e)}/abi`)}async transferApp(e,t,n){await this.postConfirmed(`apps/${d(e)}/transfer`,{to:t},n)}upgradeApp(e,t,n){let i=`apps/${d(e)}/upgrade`;return n?this.postConfirmed(i,t,n):this.post(i,t)}postConfirmed(e,t,n){return this.confirmed("POST",e,t,n)}deleteConfirmed(e,t,n={}){return this.confirmed("DELETE",e,n,t)}async confirmed(e,t,n,i,s=o=>this.json(e,t,o)){try{return await s(n)}catch(o){if(!(o instanceof Y)||!i)throw o;let a=o.details,c;try{c=await i.get(I(a.challenge),a.rpId,a.allowCredentials)}catch(l){let u=l?.name;throw u==="NotAllowedError"||u==="AbortError"?new se(l):l}return s({...n,confirm:{challengeId:a.challengeId,assertion:c}})}}async createApp(e,t,n={}){let i=typeof t=="string"?{bundle:t}:t,{appId:s}=await this.post("apps",{name:e,...i,...n});return s}call(e,t,n={},i){let s=i??zt();return this.retried("POST",`apps/${d(e)}/intents`,{method:t,args:n,idempotencyKey:s})}async callConfirmed(e,t,n,i,s){let o=`apps/${d(e)}/intents`,a=s??zt();return this.confirmed("POST",o,{method:t,args:n,idempotencyKey:a},i,c=>this.retried("POST",o,c,c.confirm!==void 0))}view(e,t,n={},i={}){return this.retried("POST",`apps/${d(e)}/views`,{method:t,args:n,consistency:i.stale?"stale":"strong",minIndex:i.minIndex??0})}events(e,t=0,n){return this.stream(`apps/${d(e)}/events?from=${t}`,n)}async*stream(e,t){let n=await this.send("GET",e,void 0,void 0,void 0,t);if(!n.body)throw new w(n.status,"EVENTS","the event stream has no body");yield*In(n.body)}async publishPresence(e,t,n){await this.post(`apps/${d(e)}/presence`,{seq:t,state:n===null?null:Jt(n)})}async presence(e){let{present:t}=await this.get(`apps/${d(e)}/presence`);return t}presenceStream(e,t){return this.stream(`apps/${d(e)}/presence/stream`,t)}async setAlias(e,t){await this.put(`auth/aliases/${d(e)}`,{app:t})}async aliases(){let{aliases:e}=await this.get("auth/aliases");return e}async alias(e){let{appId:t}=await this.get(`auth/aliases/${d(e)}`);return t}async deleteAlias(e){await this.delete(`auth/aliases/${d(e)}`)}async createOrg(e){let{orgId:t}=await this.post("orgs",{name:e});return t}getOrg(e){return this.get(`orgs/${d(e)}`)}async deleteOrg(e,t){await this.deleteConfirmed(`orgs/${d(e)}`,t)}async setOrgMetadata(e,t){await this.post(`orgs/${d(e)}/metadata`,{metadata:t})}async setMemberMetadata(e,t,n){await this.post(`orgs/${d(e)}/members/${d(t)}/metadata`,{metadata:n})}upgradeOrg(e,t,n){return this.postConfirmed(`orgs/${d(e)}/upgrade`,{...t},n)}upgradeRun(e,t){return this.get(`orgs/${d(e)}/upgrades/${d(t)}`)}retryUpgradeRun(e,t,n){return this.postConfirmed(`orgs/${d(e)}/upgrades/${d(t)}/retry`,{},n)}async approveRelease(e,t,n,i=!0){let s=e===null?"auth/releases":`orgs/${d(e)}/releases`;return this.postConfirmed(s,{version:t,approved:i},n)}async approveOutbound(e,t,n,i={}){let s=e===null?"auth/outbound":`orgs/${d(e)}/outbound`;return this.postConfirmed(s,{package:t,prefixes:i.prefixes??"manifest",replace:i.replace??!1},n)}appsReport(e,t={}){let n=e===null?"auth/apps":`orgs/${d(e)}/apps`;return this.get(`${n}${ce(t)}`)}async appsReportAll(e){let t=await this.appsReport(e),n=[...t.apps],i=t.next;for(;i!==null;){let s=await this.appsReport(e,{after:i});n.push(...s.apps),i=s.next}return{...t,apps:n,next:null}}releaseRules(){return this.get("releases")}async pendingApprovals(e=null){let[t,n]=await Promise.all([this.appsReportAll(e),this.releaseRules()]);return ot(t,n)}requestConsent(e){return this.post("consent/requests",e)}async openConsentPage(e,t={}){let n=typeof t=="function"?{navigate:t}:t,i=n.navigate??(o=>{let a=globalThis.window;if(!a)throw new Error("no window to open the consent page in; pass `navigate`");a.location.assign(o)}),s=await this.requestConsent(e);if(s.code!==void 0){let o=await st(s.requestId);if(s.code!==o)throw new w(200,"CONSENT_CODE_MISMATCH","the consent page code does not match the request",{requestId:s.requestId,code:s.code,expected:o})}return n.confirm&&!await n.confirm(s)||i(s.url),s}consentResult(e){return this.get(`consent/${d(e)}/result`)}async waitForConsent(e,t={}){let n=t.intervalMs??2e3;for(;;){let i=await this.consentResult(e);if(i.status!=="pending"||t.signal?.aborted||t.expiresAt!==void 0&&Date.now()/1e3>=t.expiresAt)return i;await new Promise(s=>setTimeout(s,n))}}publisherBinding(e){return this.get(`publishers/${d(e)}`)}bindPublisher(e,t,n){return this.postConfirmed(`orgs/${d(e)}/publishers`,{...t},n)}upgradePublished(e,t,n,i){return this.postConfirmed(`orgs/${d(e)}/packages/${d(t)}/upgrade`,{...n},i)}opsApps(e={}){return this.get(`ops/apps${ce(e)}`)}opsOrgs(e={}){return this.get(`ops/orgs${ce(e)}`)}async setReleaseDeadline(e,t){let n=typeof t=="string"?t:t.toISOString();await this.post(`ops/releases/${d(e)}/deadline`,{after:n})}async liftReleaseDeadline(e){await this.delete(`ops/releases/${d(e)}/deadline`)}async setMember(e,t,n,i){await this.postConfirmed(`orgs/${d(e)}/members`,{account:t,role:n},i)}removeMember(e,t,n){return this.deleteConfirmed(`orgs/${d(e)}/members/${d(t)}`,n)}async setCapabilities(e,t,n,i={}){await this.postConfirmed(`orgs/${d(e)}/capabilities`,{capabilities:t,...i},n)}async createTeam(e,t,n,i){let{teamId:s}=await this.post(`orgs/${d(e)}/teams`,{name:t,join:n,parent:i});return s}getTeam(e,t){return this.get(`orgs/${d(e)}/teams/${d(t)}`)}async updateTeam(e,t,n){await this.post(`orgs/${d(e)}/teams/${d(t)}`,n)}async deleteTeam(e,t){await this.delete(`orgs/${d(e)}/teams/${d(t)}`)}async setTeamMember(e,t,n,i,s={}){await this.postConfirmed(`orgs/${d(e)}/teams/${d(t)}/members`,{account:n,...s},i)}async removeTeamMember(e,t,n,i){await this.deleteConfirmed(`orgs/${d(e)}/teams/${d(t)}/members/${d(n)}`,i)}async invite(e,t,n,i=[],s={}){let{token:o}=await this.postConfirmed(`orgs/${d(e)}/invites`,{role:t,teams:i,...s},n);return o}redeemInvite(e){return this.post(`invites/${d(e)}/redeem`)}};var ct={CREATE_APP:1,INVITE_MEMBERS:2,JOIN_OPEN_TEAMS:4,MANAGE_MEMBERS:8,MANAGE_APPLICATION:16,CREATE_TEAM:32,DELETE_TEAM:64,MANAGE_VISIBILITY:128,MANAGE_METADATA:256,APPROVE_RELEASES:1024},Nn=ct.JOIN_OPEN_TEAMS;function Mn(...r){return r.reduce((e,t)=>e|ct[t],0)}function ve(r,e){return(r<<e|r>>>32-e)>>>0}function O(r,e,t,n,i){r[e]=r[e]+r[t]>>>0,r[i]=ve(r[i]^r[e],16),r[n]=r[n]+r[i]>>>0,r[t]=ve(r[t]^r[n],12),r[e]=r[e]+r[t]>>>0,r[i]=ve(r[i]^r[e],8),r[n]=r[n]+r[i]>>>0,r[t]=ve(r[t]^r[n],7)}function Zt(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0}function er(r,e,t){let n=new Uint32Array(16);n[0]=1634760805,n[1]=857760878,n[2]=2036477234,n[3]=1797285236;for(let o=0;o<8;o+=1)n[4+o]=Zt(r,o*4);n[12]=e>>>0;for(let o=0;o<3;o+=1)n[13+o]=Zt(t,o*4);let i=n.slice();for(let o=0;o<10;o+=1)O(i,0,4,8,12),O(i,1,5,9,13),O(i,2,6,10,14),O(i,3,7,11,15),O(i,0,5,10,15),O(i,1,6,11,12),O(i,2,7,8,13),O(i,3,4,9,14);let s=new Uint8Array(64);for(let o=0;o<16;o+=1){let a=i[o]+n[o]>>>0;s[o*4]=a&255,s[o*4+1]=a>>>8&255,s[o*4+2]=a>>>16&255,s[o*4+3]=a>>>24&255}return s}function _n(r,e,t,n){let i=new Uint8Array(n.length);for(let s=0,o=e;s<n.length;s+=64,o+=1){let a=er(r,o,t),c=Math.min(s+64,n.length);for(let l=s;l<c;l+=1)i[l]=n[l]^a[l-s]}return i}function lt(r){let e=0n;for(let t=r.length-1;t>=0;t-=1)e=e<<8n|BigInt(r[t]);return e}var $n=(1n<<130n)-5n;function Bn(r,e){let t=lt(r.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,n=lt(r.subarray(16,32)),i=0n;for(let a=0;a<e.length;a+=16){let c=e.subarray(a,Math.min(a+16,e.length)),l=lt(c)+(1n<<BigInt(8*c.length));i=(i+l)*t%$n}let s=i+n&(1n<<128n)-1n,o=new Uint8Array(16);for(let a=0;a<16;a+=1)o[a]=Number(s&0xffn),s>>=8n;return o}function Wt(r){return new Uint8Array((16-r%16)%16)}function Xt(r){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(r),!0),e}function Kn(r,e){let t=[r,Wt(r.length),e,Wt(e.length),Xt(r.length),Xt(e.length)],n=new Uint8Array(t.reduce((s,o)=>s+o.length,0)),i=0;for(let s of t)n.set(s,i),i+=s.length;return n}function Vn(r,e){if(r.length!==32)throw new Error("ChaCha20-Poly1305 needs a 32-byte key");if(e.length!==12)throw new Error("ChaCha20-Poly1305 needs a 12-byte nonce")}function tr(r,e,t,n=new Uint8Array(0)){Vn(r,e);let i=er(r,0,e).subarray(0,32),s=_n(r,1,e,t),o=Bn(i,Kn(n,s)),a=new Uint8Array(s.length+16);return a.set(s),a.set(o,s.length),a}var nr=32,Ln=1,Hn=3,Fn=2,Gn=32,jn=32,qn=12,Z=r=>new TextEncoder().encode(r),ue=r=>new Uint8Array([r>>8&255,r&255]),rr=y(Z("KEM"),ue(nr)),le=y(Z("HPKE"),ue(nr),ue(Ln),ue(Hn));async function ir(r,e){let t=r.length===0?new Uint8Array(32):r,n=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",n,e))}async function Qn(r,e,t){let n=new Uint8Array(t),i=new Uint8Array(0);for(let s=1,o=0;o<t;s+=1)i=await ir(r,y(i,e,new Uint8Array([s]))),n.set(i.subarray(0,Math.min(i.length,t-o)),o),o+=i.length;return n}function ke(r,e,t,n){return ir(e,y(Z("HPKE-v1"),r,Z(t),n))}function ut(r,e,t,n,i){return Qn(e,y(ue(i),Z("HPKE-v1"),r,Z(t),n),i)}async function Jn(r,e){let t=await ke(rr,new Uint8Array(0),"eae_prk",r);return ut(rr,t,"shared_secret",e,Gn)}async function zn(r,e){let t=new Uint8Array(0),n=await ke(le,t,"psk_id_hash",t),i=await ke(le,t,"info_hash",e),s=y(new Uint8Array([Fn]),n,i),o=await ke(le,r,"secret",t);return{key:await ut(le,o,"key",s,jn),nonce:await ut(le,o,"base_nonce",s,qn)}}async function sr(r,e,t,n,i=new Uint8Array(0),s){if(r.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let o=await G(s),a=await G(e),c=y(await X(o.privateKey,r),await X(a.privateKey,r)),l=await Jn(c,y(o.publicKey,r,a.publicKey)),{key:u,nonce:g}=await zn(l,t);return{enc:o.publicKey,ciphertext:tr(u,g,n,i)}}var cr="mero-agent-gate/attest/v3",lr="mero-agent-gate/provision/v2",Yn=/^[a-z0-9][a-z0-9-]{0,62}$/,Zn=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,or=64,ar=64*1024,D=class extends Error{constructor(t,n,i){super(t);this.status=n;this.code=i;this.name="AgentGateError"}};function ur(r){if(!Yn.test(r))throw new Error(`Agent id ${JSON.stringify(r)} must match [a-z0-9][a-z0-9-]{0,62}`)}function de(r){return new TextEncoder().encode(r)}function dr(r){let e=de(r);return y(new Uint8Array([e.length]),e)}function V(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}function Ie(r,e,t){let n;try{n=Uint8Array.from(atob(r.trim()),i=>i.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(t!==void 0&&n.length!==t)throw new Error(`${e} is not ${t} bytes`);return n}async function gr(r,e,t,n){let i=new Uint8Array(32),s=y(de(cr),r,dr(e),t??i,n??i);return new Uint8Array(await crypto.subtle.digest("SHA-256",s))}function pr(r,e){return y(de(lr),r,dr(e))}async function Wn(){let r=crypto.getRandomValues(new Uint8Array(32));return{secret:r,publicKey:await Oe(r)}}async function Oe(r){if(r.length!==32)throw new Error("An owner key is 32 bytes");return V((await G(r)).publicKey)}function fr(r,e){return`${r.replace(/\/+$/,"")}${e}`}async function yr(r,e,t){let n=await r(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),i=await n.text(),s;try{s=i?JSON.parse(i):void 0}catch{}if(!n.ok){let o=s;throw new D(`The gate answered ${n.status}${o?.error?` ${o.error}`:""}: ${o?.details??i.slice(0,200)}`,n.status,o?.error)}return s}async function dt(r){let e=r.agentId??"";e&&ur(e);let t=crypto.getRandomValues(new Uint8Array(32)),n=await yr(r.fetch??fetch,fr(r.gateUrl,"/attest"),{nonceB64:V(t),...e?{agentId:e}:{}});if((n?.agentId??"")!==e)throw new Error(`Asked about agent ${JSON.stringify(e)}, the gate answered for ${JSON.stringify(n?.agentId)}`);let i=Ie(n.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),s=n.signingPublicKeyB64?Ie(n.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,o=n.ownerPublicKeyB64?Ie(n.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!s!=!o)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let a=await gr(i,e,s,o);return await r.verifier({quoteB64:n.quoteB64,nonce:R(t),reportDataSuffix:R(a)}),{agentId:e,provisioningPublicKey:V(i),...s?{signingPublicKey:V(s)}:{},...o?{ownerPublicKey:V(o)}:{}}}async function hr(r,e){let t=await Oe(e);if(r.ownerPublicKey&&r.ownerPublicKey!==t)throw new D(`This agent is claimed by another key (${r.ownerPublicKey}); it is not yours. Send it nothing and do not authorize its signing key`,void 0,"not_yours");return t}function Xn(r){let e=Object.keys(r);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>or)throw new Error(`At most ${or} secrets at once`);for(let t of e){if(!Zn.test(t))throw new Error(`Secret name ${JSON.stringify(t)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);if(typeof r[t]!="string")throw new Error(`Secret ${t} is not a string`);if(de(r[t]).length>ar)throw new Error(`Secret ${t} is over ${ar} bytes`)}}async function mr(r,e,t,n,i,s){if(!n.agentId)throw new Error("This quote names no agent; attest with the agent id");let o=await hr(n,i),a=Ie(n.provisioningPublicKey,"provisioningPublicKey",32),c=await sr(a,i,pr(a,n.agentId),de(JSON.stringify(s)));return yr(r,fr(e,t),{agentId:n.agentId,provisioningPublicKeyB64:n.provisioningPublicKey,senderPublicKeyB64:o,encappedKeyB64:V(c.enc),ciphertextB64:V(c.ciphertext)})}async function ei(r){Xn(r.secrets);let e=r.fetch??fetch,t=await mr(e,r.gateUrl,"/provision",r.agent,r.ownerSecret,{secrets:r.secrets}),n=await dt({gateUrl:r.gateUrl,agentId:r.agent.agentId,verifier:r.verifier,fetch:e}),i=await Oe(r.ownerSecret);if(n.ownerPublicKey!==i||!n.signingPublicKey)throw new D("The gate accepted the secrets, but its quote does not name your key as owner");if(r.agent.signingPublicKey&&r.agent.signingPublicKey!==n.signingPublicKey)throw new D("The agent's signing key changed while provisioning");return{agentId:n.agentId,provisioningPublicKey:n.provisioningPublicKey,signingPublicKey:n.signingPublicKey,ownerPublicKey:i,written:t?.written??[],claimed:t?.claimed===!0}}async function ti(r){if(!r.agent.ownerPublicKey)throw new Error("This agent is not claimed; there is nothing to release");let e=r.fetch??fetch;if(await mr(e,r.gateUrl,"/release",r.agent,r.ownerSecret,{release:!0}),(await dt({gateUrl:r.gateUrl,agentId:r.agent.agentId,verifier:r.verifier,fetch:e})).ownerPublicKey)throw new D("The gate says it released the agent, but its quote still names an owner")}var gt=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),ri=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function ni(r,e,t={}){let n=typeof r=="string"?new TextEncoder().encode(r):r;await me(n,e,{identity:t.identity??gt.identity,issuer:t.issuer??gt.issuer});let i;try{i=JSON.parse(new TextDecoder().decode(n))}catch{throw new Error("The signed agent policy is not JSON")}let s=t.role??"agent";if(i?.role!==s)throw new Error(`The signed file is a ${JSON.stringify(i?.role)} policy, not an ${s} one`);let o=t.profile??_;if(i.profile!==o)throw new Error(`The signed agent policy is for the ${JSON.stringify(i.profile)} profile, not ${o}`);if(t.expectedVersion!==void 0&&i.version!==t.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(i.version)}, not ${t.expectedVersion}`);return wr(i),i}function wr(r){for(let e of ri)if(!Array.isArray(r?.[e])||r[e].length===0)throw new Error(`The agent policy's ${e} is empty, so no agent would be accepted`)}var ii=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function si(r){let e=ii.find(t=>t.toLowerCase()===r.trim().toLowerCase());if(!e)throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(r)}`);return e}var ge=r=>r.trim().replace(/^0x/i,"");function oi(r,e){return wr(r),$({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:r.allowed_tcb_statuses.map(si),allowedMrtd:r.allowed_mrtd.map(ge),allowedRtmr0:r.allowed_rtmr0.map(ge),allowedRtmr1:r.allowed_rtmr1.map(ge),allowedRtmr2:r.allowed_rtmr2.map(ge),allowedRtmr3:r.allowed_rtmr3.map(ge)})}export{cr as AGENT_ATTEST_DOMAIN,lr as AGENT_PROVISION_INFO_DOMAIN,D as AgentGateError,xe as AppError,Ee as ArgsTooLarge,at as CalimeroClient,w as CalimeroError,se as ConfirmCancelled,Y as ConfirmRequired,Ue as ConsentStale,Je as DEFAULT_COLLATERAL_MIRROR,tt as DEFAULT_DIRECTORY,Nn as DEFAULT_ORG_CAPABILITIES,we as DEFAULT_RELEASE_MIRROR,T as DirectoryError,Dt as GITHUB_RELEASES,At as HANDSHAKE_PATH,Re as IdempotencyMismatch,gt as KMS_RELEASE_SIGNER,z as LoginRequired,it as MAX_REPORT_PAGE,_t as MOCK_QUOTE_HEADER,Qe as NODE_RELEASE_SIGNER,be as NotFound,ct as ORG_CAPABILITIES,_ as PRODUCTION_PROFILE,Ft as RELEASE_VERIFIER,Pe as ReleaseDeadlineError,te as SEALED_CONTENT_TYPE,bt as SEALED_PATH,C as SealedTransportError,re as StaleTransportKeyError,Te as TrapError,K as UnavailableError,B as WrongNode,gr as agentKeyBinding,oi as agentQuoteVerifier,dt as attestAgent,S as b64url,Un as browserPasskey,hr as checkOwner,$t as claimedRelease,Ze as cloudNodeReleaseUrl,ae as compareVersions,st as confirmationCode,Sn as consentReturn,$ as createQuoteVerifier,He as createSealedFetch,yn as createSignedReleaseVerifier,Ce as errorFrom,et as fetchAttestedKey,Ye as fetchGithubNodeRelease,ze as fetchNodeRelease,Bt as freshCollateral,I as fromB64url,Wn as generateOwnerKey,Mn as orgCapabilities,Oe as ownerPublicKey,ce as pageQuery,ot as pendingApprovalsFrom,ei as provisionAgent,pr as provisionInfo,xn as publisherBindingBytes,Ht as publisherBindingMessage,ti as releaseAgent,qt as releaseConsent,Gt as releaseNotesUrl,Lt as stalledBy,Le as transportKeyBinding,Ae as trustSignedRelease,qe as trustedMeasurementsFromReleases,vn as upgradeConsent,ur as validateAgentId,jt as verifyReleaseUrl,ni as verifySignedAgentPolicy,Ot as verifySignedNodeRelease,Cn as withdrawConsent};
9
9
  //# sourceMappingURL=index.browser.mjs.map