@calimero-network/mero-js 29.2.0 → 29.3.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.
package/README.md CHANGED
@@ -97,7 +97,7 @@ Pinned measurements go through `policy.verifyQuote` (`createQuoteVerifier`).
97
97
 
98
98
  ## The API
99
99
 
100
- - **Credentials**: `signUp`, `signIn`, `refresh`, `signOut`, `signOutEverywhere`, `useSession`, `useApiKey`, `me`, `usage`, `addPasskey`, `labelPasskey`, `removePasskey`, `createApiKey`, `listApiKeys`, `revokeApiKey`. Adding or removing a passkey and creating an API key are approved with a passkey the account already has.
100
+ - **Credentials**: `signUp` (with an `invite`, on a cluster that takes new accounts by invite; `signUpPolicy` reads which), `signIn`, `refresh`, `signOut`, `signOutEverywhere`, `useSession`, `useApiKey`, `me`, `usage`, `addPasskey`, `labelPasskey`, `removePasskey`, `createApiKey`, `listApiKeys`, `revokeApiKey`. Adding or removing a passkey and creating an API key are approved with a passkey the account already has.
101
101
  - **Package origins**: `packageOrigins.list`, `packageOrigins.add`, `packageOrigins.remove`. A package's managers register the web origins of a frontend they host themselves (approved with a passkey); `signUp` and `signIn` on such a page send its origin, sign for that origin's relying-party id, and open a session bound to the package (`me()` answers its `app` and `origin`). An unregistered origin is refused with `OriginNotRegistered`.
102
102
  - **Packages**: `installPackage`, `uploadPackage`, `packages`, `package`, `uninstallPackage`; `uploadBundle` (raw WASM, development clusters only).
103
103
  - **Apps**: `createApp`, `listApps`, `getApp`, `deleteApp`, `setAccess`, `setAppMetadata`, `appStorage`, `appAbi`, `upgradeApp`, `transferApp`.
@@ -12,8 +12,8 @@
12
12
  import { type AttestationDoc, type CloudPolicy } from './attestation.js';
13
13
  import { type PasskeyProvider } from './passkey.js';
14
14
  import { type AppsReport, type ConsentRequest, type ConsentResult, type ConsentStarted, type OpenConsentOptions, type OpsAppsReport, type OpsOrgsReport, type PageOptions, type PendingApprovals, type PublisherBindingInfo, type PublisherProof, type ReleaseRules } from './approvals.js';
15
- export { AppError, ArgsTooLarge, BadOrigin, CalimeroError, ConfirmCancelled, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, NotFound, OriginNotRegistered, OriginTaken, QuotaExceeded, ReleaseDeadlineError, TrapError, UnavailableError, WrongNode, errorFrom, } from './errors.js';
16
- export type { Committed } from './errors.js';
15
+ export { AppError, ArgsTooLarge, BadOrigin, CalimeroError, ConfirmCancelled, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, NotFound, OriginNotRegistered, OriginTaken, QuotaExceeded, ReleaseDeadlineError, SignUpRefused, TrapError, UnavailableError, WrongNode, errorFrom, } from './errors.js';
16
+ export type { Committed, SignUpRefusal } from './errors.js';
17
17
  export interface CalimeroSession {
18
18
  accountId: string;
19
19
  sessionToken: string;
@@ -338,6 +338,30 @@ export interface PackageOrigins {
338
338
  export interface SignInOptions {
339
339
  origin?: string | null;
340
340
  }
341
+ /**
342
+ * {@link SignInOptions} for a sign-up, and the invite it is made with: an
343
+ * organization invite's token (the new account joins the organization at
344
+ * the invite's role) or a cluster sign-up invite's. A cluster whose policy
345
+ * is `invite` or `closed` ({@link CalimeroClient.signUpPolicy}) needs one.
346
+ */
347
+ export interface SignUpOptions extends SignInOptions {
348
+ invite?: string;
349
+ }
350
+ /**
351
+ * `GET /sign-up`: who may create an account on the cluster (core's sign-up
352
+ * policy, read without a session), so a page can say "invite only" before
353
+ * any passkey prompt.
354
+ */
355
+ export interface SignUpPolicy {
356
+ /** `open` (anyone), `invite` (an organization or sign-up invite), `closed` (a sign-up invite only). */
357
+ policy: 'open' | 'invite' | 'closed';
358
+ /** Whether an organization invite lets a new person sign up (and join it). */
359
+ orgInvites: boolean;
360
+ /** Whether a cluster sign-up invite does (always). */
361
+ signUpInvites: boolean;
362
+ /** Whether a sign-up without an invite is refused. */
363
+ inviteRequired: boolean;
364
+ }
341
365
  /**
342
366
  * How a call or a view is sent again while the node is unavailable (D70): with
343
367
  * the same key, after a backoff that starts at `baseDelayMs` and doubles up to
@@ -520,8 +544,15 @@ export declare class CalimeroClient {
520
544
  * origin's relying party (the confirmation's `rpId` is that origin's too)
521
545
  * and binds the session to the package the origin is registered for; an
522
546
  * unregistered origin is refused with {@link OriginNotRegistered}.
547
+ *
548
+ * `invite` ({@link SignUpOptions}) goes on both halves and on the retry,
549
+ * as the node judges it on each before it spends anything; a sign-up the
550
+ * cluster's policy refuses, or an unknown, expired or used invite, is
551
+ * {@link SignUpRefused} (from `begin`, before any passkey is made).
523
552
  */
524
- signUp(passkey: PasskeyProvider, name: string, options?: SignInOptions): Promise<CalimeroSession>;
553
+ signUp(passkey: PasskeyProvider, name: string, options?: SignUpOptions): Promise<CalimeroSession>;
554
+ /** Who may create an account on the cluster (`GET /sign-up`); needs no session. */
555
+ signUpPolicy(): Promise<SignUpPolicy>;
525
556
  /**
526
557
  * Sign in with an existing passkey. On a page whose origin is not the
527
558
  * cluster's ({@link SignInOptions}), the assertion is made for that
@@ -15,7 +15,7 @@ import { DEFAULT_DIRECTORY, orderNodes, readDirectory } from './directory.js';
15
15
  import { CalimeroError, ConfirmCancelled, ConfirmRequired, LoginRequired, OriginNotRegistered, UnavailableError, WrongNode, errorFrom, } from './errors.js';
16
16
  import { b64url, fromB64url } from './passkey.js';
17
17
  import { confirmationCode, pageQuery, pendingApprovalsFrom, } from './approvals.js';
18
- export { AppError, ArgsTooLarge, BadOrigin, CalimeroError, ConfirmCancelled, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, NotFound, OriginNotRegistered, OriginTaken, QuotaExceeded, ReleaseDeadlineError, TrapError, UnavailableError, WrongNode, errorFrom, } from './errors.js';
18
+ export { AppError, ArgsTooLarge, BadOrigin, CalimeroError, ConfirmCancelled, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, NotFound, OriginNotRegistered, OriginTaken, QuotaExceeded, ReleaseDeadlineError, SignUpRefused, TrapError, UnavailableError, WrongNode, errorFrom, } from './errors.js';
19
19
  /** A deployer's key, as `GET /deployers` lists it and `DELETE /deployers/{key}` takes it. */
20
20
  export function deployerKey(deployer) {
21
21
  return 'account' in deployer ? `account:${deployer.account}` : `org:${deployer.org}`;
@@ -462,15 +462,25 @@ export class CalimeroClient {
462
462
  * origin's relying party (the confirmation's `rpId` is that origin's too)
463
463
  * and binds the session to the package the origin is registered for; an
464
464
  * unregistered origin is refused with {@link OriginNotRegistered}.
465
+ *
466
+ * `invite` ({@link SignUpOptions}) goes on both halves and on the retry,
467
+ * as the node judges it on each before it spends anything; a sign-up the
468
+ * cluster's policy refuses, or an unknown, expired or used invite, is
469
+ * {@link SignUpRefused} (from `begin`, before any passkey is made).
465
470
  */
466
471
  async signUp(passkey, name, options = {}) {
467
472
  const origin = this.pageOrigin(options);
468
- const begin = await this.begin('auth/passkey/register/begin', origin === undefined ? { name } : { name, origin }, origin);
473
+ const invite = options.invite ? { invite: options.invite } : {};
474
+ const begin = await this.begin('auth/passkey/register/begin', origin === undefined ? { name, ...invite } : { name, origin, ...invite }, origin);
469
475
  const registration = await passkey.create(begin.options);
470
- const session = await this.postConfirmed('auth/passkey/register/finish', { challengeId: begin.challengeId, registration }, passkey);
476
+ const session = await this.postConfirmed('auth/passkey/register/finish', { challengeId: begin.challengeId, registration, ...invite }, passkey);
471
477
  this.useSession(session);
472
478
  return session;
473
479
  }
480
+ /** Who may create an account on the cluster (`GET /sign-up`); needs no session. */
481
+ signUpPolicy() {
482
+ return this.get('sign-up');
483
+ }
474
484
  /**
475
485
  * Sign in with an existing passkey. On a page whose origin is not the
476
486
  * cluster's ({@link SignInOptions}), the assertion is made for that
@@ -126,6 +126,26 @@ export declare class BadOrigin extends CalimeroError {
126
126
  export declare class OriginTaken extends CalimeroError {
127
127
  constructor(message: string, details?: Record<string, unknown>);
128
128
  }
129
+ /** Why a sign-up was refused ({@link SignUpRefused.reason}), read from what the node said. */
130
+ export type SignUpRefusal = 'invite-only' | 'closed' | 'unknown-invite' | 'expired-invite' | 'org-gone' | 'other';
131
+ /**
132
+ * `403 SIGN_UP_REFUSED`: the cluster's sign-up policy does not take this
133
+ * sign-up (core `SystemState::admits`), answered by `register/begin` before a
134
+ * passkey is made and by `register/finish` before its challenge is spent.
135
+ * `reason` says why, so a page can say "invite only" or "this invite has
136
+ * expired" instead of the node's sentence:
137
+ *
138
+ * - `invite-only`: the cluster takes new accounts with an invite only.
139
+ * - `closed`: only a cluster sign-up invite (the operator's or the owner's) admits.
140
+ * - `unknown-invite`: the invite is not one the cluster knows (mistyped, revoked,
141
+ * or used up: a spent invite is gone).
142
+ * - `expired-invite`: past its expiry, or no use left.
143
+ * - `org-gone`: the organization the invite was for was deleted.
144
+ */
145
+ export declare class SignUpRefused extends CalimeroError {
146
+ readonly reason: SignUpRefusal;
147
+ constructor(message: string, details?: Record<string, unknown>);
148
+ }
129
149
  /** `429 QUOTA_EXCEEDED`: the caller holds as many of something (origins, blobs, ...) as it may. */
130
150
  export declare class QuotaExceeded extends CalimeroError {
131
151
  constructor(message: string, details?: Record<string, unknown>);
@@ -165,6 +165,40 @@ export class OriginTaken extends CalimeroError {
165
165
  this.name = 'OriginTaken';
166
166
  }
167
167
  }
168
+ /**
169
+ * `403 SIGN_UP_REFUSED`: the cluster's sign-up policy does not take this
170
+ * sign-up (core `SystemState::admits`), answered by `register/begin` before a
171
+ * passkey is made and by `register/finish` before its challenge is spent.
172
+ * `reason` says why, so a page can say "invite only" or "this invite has
173
+ * expired" instead of the node's sentence:
174
+ *
175
+ * - `invite-only`: the cluster takes new accounts with an invite only.
176
+ * - `closed`: only a cluster sign-up invite (the operator's or the owner's) admits.
177
+ * - `unknown-invite`: the invite is not one the cluster knows (mistyped, revoked,
178
+ * or used up: a spent invite is gone).
179
+ * - `expired-invite`: past its expiry, or no use left.
180
+ * - `org-gone`: the organization the invite was for was deleted.
181
+ */
182
+ export class SignUpRefused extends CalimeroError {
183
+ constructor(message, details = {}) {
184
+ super(403, 'SIGN_UP_REFUSED', message, details);
185
+ this.name = 'SignUpRefused';
186
+ this.reason = signUpRefusal(message);
187
+ }
188
+ }
189
+ function signUpRefusal(message) {
190
+ if (/invite only/.test(message))
191
+ return 'invite-only';
192
+ if (/pre-authorized|sign-up invite/.test(message))
193
+ return 'closed';
194
+ if (/unknown invite/.test(message))
195
+ return 'unknown-invite';
196
+ if (/invite has expired/.test(message))
197
+ return 'expired-invite';
198
+ if (/organization is gone/.test(message))
199
+ return 'org-gone';
200
+ return 'other';
201
+ }
168
202
  /** `429 QUOTA_EXCEEDED`: the caller holds as many of something (origins, blobs, ...) as it may. */
169
203
  export class QuotaExceeded extends CalimeroError {
170
204
  constructor(message, details = {}) {
@@ -265,6 +299,8 @@ export function errorFrom(status, body, retryAfterHeader) {
265
299
  return new OriginTaken(message, details);
266
300
  case '429 QUOTA_EXCEEDED':
267
301
  return new QuotaExceeded(message, details);
302
+ case '403 SIGN_UP_REFUSED':
303
+ return new SignUpRefused(message, details);
268
304
  case '412 CONFIRM_REQUIRED':
269
305
  return new ConfirmRequired(message, details);
270
306
  case '413 ARGS_TOO_LARGE':
@@ -1,9 +1,9 @@
1
1
  export { CalimeroClient, deployerKey, frontendManifest, pageDeployment } from './client.js';
2
2
  export { DEFAULT_DIRECTORY, DirectoryError } from './directory.js';
3
3
  export type { DirectoryFailure } from './directory.js';
4
- export { AppError, ArgsTooLarge, BadOrigin, CalimeroError, ConfirmCancelled, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, NotFound, OriginNotRegistered, OriginTaken, QuotaExceeded, ReleaseDeadlineError, TrapError, UnavailableError, WrongNode, errorFrom, } from './errors.js';
5
- export type { Committed } from './errors.js';
6
- export type { AppInfo, AppXcalls, BlobContent, BlobInfo, DeadLetter, Deployer, DeployerGrant, DeployersInfo, DeploymentInfo, DeploymentOffer, DeploymentOrgs, FrontendManifest, MeInfo, PackageOrigin, PackageOriginAdded, PackageOriginRemoved, PackageOrigins, SignInOptions, PublicDeployment, CallResult, CalimeroClientOptions, CalimeroConnectOptions, CloudEvent, CalimeroSession, PackageInfo, PackageInstalled, CloudRetryOptions, OrgInfo, OrgUpgradeTarget, PresenceEntry, UpgradeRun, ViewResult, } from './client.js';
4
+ export { AppError, ArgsTooLarge, BadOrigin, CalimeroError, ConfirmCancelled, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, NotFound, OriginNotRegistered, OriginTaken, QuotaExceeded, ReleaseDeadlineError, SignUpRefused, TrapError, UnavailableError, WrongNode, errorFrom, } from './errors.js';
5
+ export type { Committed, SignUpRefusal } from './errors.js';
6
+ export type { AppInfo, AppXcalls, BlobContent, BlobInfo, DeadLetter, Deployer, DeployerGrant, DeployersInfo, DeploymentInfo, DeploymentOffer, DeploymentOrgs, FrontendManifest, MeInfo, PackageOrigin, PackageOriginAdded, PackageOriginRemoved, PackageOrigins, SignInOptions, SignUpOptions, SignUpPolicy, PublicDeployment, CallResult, CalimeroClientOptions, CalimeroConnectOptions, CloudEvent, CalimeroSession, PackageInfo, PackageInstalled, CloudRetryOptions, OrgInfo, OrgUpgradeTarget, PresenceEntry, UpgradeRun, ViewResult, } from './client.js';
7
7
  export { claimedRelease, fetchAttestedKey, freshCollateral, MOCK_QUOTE_HEADER } from './attestation.js';
8
8
  export type { AttestationDoc, CloudPolicy, CloudReleasePolicy } from './attestation.js';
9
9
  export { browserPasskey, b64url, fromB64url } from './passkey.js';
@@ -1,6 +1,6 @@
1
1
  export { CalimeroClient, deployerKey, frontendManifest, pageDeployment } from './client.js';
2
2
  export { DEFAULT_DIRECTORY, DirectoryError } from './directory.js';
3
- export { AppError, ArgsTooLarge, BadOrigin, CalimeroError, ConfirmCancelled, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, NotFound, OriginNotRegistered, OriginTaken, QuotaExceeded, ReleaseDeadlineError, TrapError, UnavailableError, WrongNode, errorFrom, } from './errors.js';
3
+ export { AppError, ArgsTooLarge, BadOrigin, CalimeroError, ConfirmCancelled, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, NotFound, OriginNotRegistered, OriginTaken, QuotaExceeded, ReleaseDeadlineError, SignUpRefused, TrapError, UnavailableError, WrongNode, errorFrom, } from './errors.js';
4
4
  export { claimedRelease, fetchAttestedKey, freshCollateral, MOCK_QUOTE_HEADER } from './attestation.js';
5
5
  export { browserPasskey, b64url, fromB64url } from './passkey.js';
6
6
  export { MAX_REPORT_PAGE, RELEASE_VERIFIER, compareVersions, confirmationCode, consentReturn, pageQuery, pendingApprovalsFrom, publisherBindingBytes, publisherBindingMessage, releaseConsent, releaseNotesUrl, stalledBy, upgradeConsent, verifyReleaseUrl, withdrawConsent, } from './approvals.js';
@@ -1,9 +1,9 @@
1
- function R(r){return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}function ye(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 Ur="Noise_NK_25519_AESGCM_SHA256",Le=32,Tr=16,kr=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Fe=class r{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(Ur),t=new Uint8Array(32);return t.set(e),new r(t)}async mixHash(e){this.h=await Sr(y(this.h,e))}async mixKey(e){let[t,n]=await At(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:wt(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:wt(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),t}split(){return At(this.ck,new Uint8Array)}};async function bt(r,e,t){let n=await Fe.initialize();await n.mixHash(e),await n.mixHash(r);let i=await j(t);return await n.mixHash(i.publicKey),await n.mixKey(await ee(i.privateKey,r)),{message1:y(i.publicKey,await n.encryptAndHash(new Uint8Array)),async finish(o){if(o.length<Le+Tr)throw new Error("Noise: message 2 is too short");let a=o.slice(0,Le);return await n.mixHash(a),await n.mixKey(await ee(i.privateKey,a)),{payload:await n.decryptAndHash(o.slice(Le)),split:await n.split()}}}}async function j(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(kr,r),{name:"X25519"},!0,["deriveBits"]),t=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Cr(t.x)}}async function ee(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 wt(r){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(r),!1),e}async function Sr(r){return new Uint8Array(await crypto.subtle.digest("SHA-256",r))}async function He(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 At(r,e){let t=await He(r,e),n=await He(t,new Uint8Array([1])),i=await He(t,y(n,new Uint8Array([2])));return[n,i]}function Cr(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 xt="/sealed/v2/handshake",Ut="/sealed/v2",re="application/vnd.calimero.sealed",Ge=2,vr=new TextEncoder().encode("calimero/sealed-http/v2"),te=16,Ir=1+te+8,Or=0,Dr=1,Nr=2,Mr=1+64*1024+16,_r=1024,$r=6e4,Br="calimero.tee-attest.transport-key.v1",Kr=[101,204,205,304],Tt=new TextEncoder,ne=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 je(r,e){let t=await crypto.subtle.digest("SHA-256",y(Tt.encode(Br),r,e));return new Uint8Array(t)}function Qe(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 Rt(i,n,await Et(o))}catch(g){if(!(g instanceof ne)||!s)throw g;return o=Promise.resolve().then(s),Rt(i,n,await Et(o))}},d=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,H)=>b.push([H,P]));let N={method:h.method,path:f.pathname.slice(t.length)+f.search,headers:b},E=new Uint8Array(await h.arrayBuffer()),U=p?.signal??(g instanceof Request?g.signal:void 0),M=async P=>{let{requestId:H,header:W,envelope:fe}=await Lr(P,N,E),F=await i(`${n}${Ut}`,{method:"POST",headers:{"content-type":re},body:fe,signal:U});if(F.headers.get("content-type")!==re)throw await St(F);return Fr(F,P.responseKey,W,H)},[$e,Be]=await d();try{return await M($e)}catch(P){if(!(P instanceof S)||P.code!=="unknown_session")throw P;return M(await u(Be))}}}async function Et(r){let e=await r;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function Rt(r,e,t){try{return await Pt(r,e,t)}catch(n){if(!(n instanceof S)||n.code!=="busy")throw n;return await new Promise(i=>setTimeout(i,n.retryAfterMs??1e3)),Pt(r,e,t)}}async function Pt(r,e,t){let n=await bt(t,vr),i=await r(`${e}${xt}`,{method:"POST",headers:{"content-type":re},body:y(new Uint8Array([Ge]),t,n.message1)});if(i.headers.get("content-type")!==re)throw await St(i);let s=await jr(i,_r);return Vr(n,s)}async function Vr(r,e){if(e[0]!==Ge)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!==te+4)throw new Error("The handshake reply is malformed");let s=n.slice(0,te),o=new DataView(n.buffer,n.byteOffset).getUint32(te,!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-$r,header(d){let u=new Uint8Array(Ir);return u[0]=Ge,u.set(s,1),new DataView(u.buffer).setBigUint64(1+te,BigInt(d),!1),u}}}async function Lr(r,e,t){let n=r.nextRequestId;r.nextRequestId+=1;let i=r.header(n),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:kt(n,0),additionalData:i},r.requestKey,Hr(e,t));return{requestId:n,header:i,envelope:y(i,new Uint8Array(s))}}function kt(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 Hr(r,e){let t=Tt.encode(JSON.stringify(r)),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t.length,!1),y(n,t,e)}async function Fr(r,e,t,n){if(!r.body)throw new Error("The sealed response has no body");let i=Gr(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:kt(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!==Or)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(Kr.includes(c.status))return await i.cancel(),new Response(null,{status:c.status,headers:c.headers});let d=new ReadableStream({async pull(u){try{let g=await o();g?g.kind===Dr?u.enqueue(g.data):g.kind===Nr?(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(d,{status:c.status,headers:c.headers})}function Gr(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>Mr)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 jr(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 St(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 ne;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 Ct=[{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"]}],vt=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var Qr="1.2.840.10045.2.1",qr={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},Jr={"P-256":32,"P-384":48},zr={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function It(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=It(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=It(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 he(r){return r.bytes.slice(r.offset,r.end)}function Q(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 Yr(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,d,u]=i.slice(2).map(Number);return Date.UTC(s,o-1,a,c,d,u)}function qe(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,d,u,g,p,...h]=s.slice(o);m(a,2,"The serial number");let f=Q(A(m(t,48,"The signature algorithm"))[0]);if(Q(A(m(c,48,"The signature algorithm"))[0])!==f)throw new Error("it names two different signature algorithms");let N=zr[f];if(!N)throw new Error(`it is signed with ${f}, not ECDSA with SHA-256 or SHA-384`);let[E,U]=A(m(u,48,"The validity")).map(Yr);if(U===void 0)throw new Error("its validity is incomplete");let[M,$e]=A(m(p,48,"The public key"));m($e,3,"The public key");let[Be,P]=A(m(M,48,"The key algorithm"));if(Q(Be)!==Qr)throw new Error("its key is not an elliptic-curve key");let H=qr[Q(P)];if(!H)throw new Error("its key is on a curve other than P-256 or P-384");let W=new Map,fe=h.find(Ke=>Ke.tag===163);if(fe){let[Ke]=A(fe);for(let xr of A(m(Ke,48,"The extensions"))){let G=A(m(xr,48,"An extension"));if(G.length===3)m(G[1],1,"An extension's critical flag");else if(G.length!==2)throw new Error("it has a malformed extension");let Ve=Q(G[0]);if(W.has(Ve))throw new Error(`it has extension ${Ve} twice`);W.set(Ve,C(m(G[G.length-1],4,"An extension value")))}}let F=C(m(n,3,"The signature"));if(F[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:r,tbs:he(e),signatureHash:N,signature:F.slice(1),issuer:he(m(d,48,"The issuer")),subject:he(m(g,48,"The subject")),notBefore:E,notAfter:U,spki:he(p),curve:H,extensions:W}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function Ot(r){return A(m(q(r),48,"The list")).map(Q)}function Zr(r,e){let t=Jr[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=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 me(r,e,t,n,i){let s;try{s=Zr(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 x(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 Je(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 x(t[0][1],e)}var Xr="2.5.29.17",Wr="2.5.29.37",en="1.3.6.1.5.5.7.3.3",tn="1.3.6.1.4.1.57264.1.8",rn="1.3.6.1.4.1.57264.1.1",nn=134,sn=12,on=48,an=new TextEncoder,J=r=>new TextDecoder().decode(r);async function we(r,e,t,n){let{base64Signature:i,cert:s,rekorBundle:o}=un(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=x(i,"The bundle signature"),d=Je(J(x(s,"The bundle certificate")),"The bundle certificate"),u=qe(d),g=vt.find(U=>U.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=an.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await me(x(g.publicKey,"The Rekor key"),"P-256","SHA-256",x(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(!Mt(f,g.validFor))throw new Error(`Rekor log ${g.baseUrl} was not in use at ${ie(f)}, when the entry says it was logged`);let b=gn(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(!ze(x(b.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let E=Je(J(x(b.publicKey,"The logged certificate")),"The logged certificate");if(!ze(E,d))throw new Error("The bundle's certificate is not the one Rekor logged");if(u.curve!=="P-256"||!await me(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 cn(u,f),dn(u,t),{integratedTime:a.integratedTime}}async function cn(r,e){if(!Nt(r,e))throw new Error(`The signing certificate was valid ${ie(r.notBefore)} to ${ie(r.notAfter)}, not at ${ie(e)} when Rekor logged it`);let t=[];for(let n of Ct){let i=n.certChain.map(o=>qe(x(o,"A Fulcio certificate")));if(!await Dt(r,i[0]))continue;let s=await ln(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 ${ie(e)}: ${t.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function ln(r,e,t){if(!Mt(t,e))return"the trust root says it was not issuing certificates then";for(let[n,i]of r.entries()){if(!Nt(i,t))return`its certificate ${n} was not valid then`;let s=r[n+1]??i;if(!await Dt(i,s))return`its certificate ${n} is not signed by the next`}}async function Dt(r,e){return ze(r.issuer,e.subject)?me(e.spki,e.curve,r.signatureHash,r.signature,r.tbs):!1}function dn(r,e){let t=r.extensions.get(Xr);if(!t)throw new Error("The signing certificate names no identity");let n=A(m(q(t),on,"The subject alternative name")),i=n.filter(d=>d.tag===nn).map(d=>J(C(d)));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(tn),o=r.extensions.get(rn),a=s?J(C(m(q(s),sn,"The OIDC issuer"))):o?J(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(Wr);if(!c||!Ot(c).includes(en))throw new Error("The signing certificate is not for code signing")}function un(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 gn(r){let e;try{e=JSON.parse(J(x(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 Nt(r,e){return r.notBefore<=e&&e<=r.notAfter}function Mt(r,e){return Date.parse(e.start)<=r&&(e.end===void 0||r<=Date.parse(e.end))}function ie(r){return new Date(r).toISOString()}function ze(r,e){return r.length===e.length&&r.every((t,n)=>t===e[n])}var pn=/^[0-9a-f]{96}$/,fn=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function $(r){let e=z(r.allowedMrtd??[],"allowedMrtd"),t=(r.allowedMeasurements??[]).map((a,c)=>{let d=`allowedMeasurements[${c}]`;return fn.map(u=>z([a?.[u]??""],`${d}.${u}`)[0]).join()}),n=[z(r.allowedRtmr0??[],"allowedRtmr0"),z(r.allowedRtmr1??[],"allowedRtmr1"),z(r.allowedRtmr2??[],"allowedRtmr2"),z(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:d,collateral:u})=>{let g=hn(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=yn(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,U)=>{let M=n[U];if(M.length>0&&!M.includes(R(E)))throw new Error(`RTMR${U} ${R(E)} is not one this verifier trusts`)}),R(f.reportData)!==`${c}${d}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function z(r,e){return r.map(t=>{let n=t.trim().toLowerCase();if(!pn.test(n))throw new Error(`${e} holds ${JSON.stringify(t)}, which is not a 48-byte hex measurement`);return n})}function yn(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 hn(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 mn=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],_="locked-read-only";function Ye(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 d=(c.allowed_tcb_statuses??["uptodate"]).map(u=>wn(u,a));return n=n===void 0?d:n.filter(u=>d.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 wn(r,e){let t=mn.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 Ze=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"}),An=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],Ae="https://cloud.calimero.network",Xe=`${Ae}/api/tee/pcs`;async function $t(r,e,t={}){let n=typeof r=="string"?new TextEncoder().encode(r):r;await we(n,e,{identity:t.identity??Ze.identity,issuer:t.issuer??Ze.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=>An.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 We(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 Bt="https://github.com/calimero-network/mero-tee/releases/download";async function et(r,e={}){let t=`mero-tee-v${v(r,"version")}`,n=`${(e.base??Bt).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 tt(r,e){return`${r.replace(/\/+$/,"")}/api/tee/node-releases/${v(e,"version")}`}async function be(r){let e=v(r.minReleaseVersion,"minReleaseVersion"),t=v(r.release?.version,"The release version"),n=await $t(r.release.publishedMrtds,r.release.bundle,{expectedVersion:t,identity:r.identity,issuer:r.issuer});if(se(t,e)<0)throw new Error(`Release ${t} is older than the minimum trusted, ${e}`);return Ye([n],{profile:r.profile,allowDebugProfile:r.allowDebugProfile})}function bn(r){return v(r.minReleaseVersion,"minReleaseVersion"),Object.assign(async t=>{let n=await be({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 se(r,e){let[t,n]=_t(r),[i,s]=_t(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[d,u]=[o[c],a[c]];if(d===void 0||u===void 0)return d===void 0?-1:1;let[g,p]=[/^\d+$/.test(d),/^\d+$/.test(u)],h=g&&p?Math.sign(Number(d)-Number(u)):g!==p?g?-1:1:d<u?-1:d>u?1:0;if(h!==0)return h}return 0}function _t(r){let e=Kt.exec(r);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var Lt="MOCK_TDX_QUOTE_V1";function En(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 rt(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 Vt;async function nt(r){Vt??(Vt=import("@phala/dcap-qvl"));let e=await Vt,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 Ht(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(se(i,t)<0)throw new Error(`mero-tee release ${i} is older than the minimum ${t}`);return i}async function Rn(r,e,t){let n=e.releaseSource;return typeof n=="function"?n(r):n==="github"?et(r,{fetch:t}):We(tt(n??Ae,r),{fetch:t})}function Pn(r){let e=r.collateralSource??Xe;return e==="intel"?async t=>(await nt("getCollateralFromPcs"))(t):async t=>(await nt("getCollateral"))(e,t)}function Ft(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 xn(r,e,t,n){let i=Ht(r,t.minReleaseVersion),s=await be({release:await Rn(i,t,n),profile:t.profile??_,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer}),o=Ft(t.fetchCollateral??Pn(t),t);return $({dcapVerify:t.dcapVerify??await nt("verify"),fetchCollateral:o,now:t.now,...s})(e)}async function it(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=ye(o.transportKey,"transportKey",32),c=e.appHash?ye(e.appHash,"appHash",32):new Uint8Array(32),d=await je(c,a),u=En(o.quote),g=new TextEncoder().encode(Lt);if(rt(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(!rt(f.slice(0,32),ye(n,"nonce",32))||!rt(f.slice(32),d))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(d)},h;if(e.verifyQuote)h=await e.verifyQuote(p);else if(e.release)h=await xn(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 st="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 Un(r,e){return`${r.replace(/\/+$/,"")}/${encodeURIComponent(e)}`}async function ot(r,e,t){let n;try{n=await t(Un(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=Tn(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,d=typeof c=="number"&&Number.isFinite(c)&&c>=1?c:60;return{nodes:o,refreshAfterSeconds:d}}function Tn(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 at(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[...Gt(n,t),...Gt(i,t)]}function Gt(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"}},Y=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"}},Ee=class extends w{constructor(e,t={}){super(404,"NOT_FOUND",e,t),this.name="NotFound"}},Z=class extends w{constructor(e,t={}){super(412,"CONFIRM_REQUIRED",e,t),this.name="ConfirmRequired"}},oe=class extends Error{constructor(t){super("the passkey confirmation was cancelled");this.cause=t;this.name="ConfirmCancelled"}},Re=class extends w{constructor(e,t={}){super(413,"ARGS_TOO_LARGE",e,t),this.name="ArgsTooLarge"}},Pe=class extends w{constructor(e,t={}){super(409,"IDEMPOTENCY_MISMATCH",e,t),this.name="IdempotencyMismatch"}},xe=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"}},K=class extends w{constructor(e,t={}){let n=typeof t.origin=="string"?t.origin:"",i=typeof t.package=="string"?t.package:"",s=n?`this site (${n})`:"this site";super(403,"ORIGIN_NOT_REGISTERED",`${s} is not registered for ${i||"any package"}${e?` (${e})`:""}`,t),this.name="OriginNotRegistered",this.origin=n,this.package=i,this.nodeMessage=e}},Te=class extends w{constructor(e,t,n={}){super(400,e,t,n),this.name="BadOrigin"}},ke=class extends w{constructor(e,t={}){super(409,"ORIGIN_TAKEN",e,t),this.name="OriginTaken"}},Se=class extends w{constructor(e,t={}){super(429,"QUOTA_EXCEEDED",e,t),this.name="QuotaExceeded"}},Ce=class extends w{constructor(e,t={}){super(422,"APP_ERROR",e,t),this.name="AppError";let{appCode:n,fields:i}=kn(t);this.appCode=n,this.fields=i}},ve=class extends w{constructor(e,t={}){super(422,"TRAP",e,t),this.name="TrapError",this.kind=typeof t.kind=="string"?t.kind:""}},V=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 Ie(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function kn(r){let e=typeof r.code=="string"?r:Ie(r.error);return{appCode:typeof e.code=="string"?e.code:"",fields:{...Ie(e.fields)}}}function Sn(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 Oe(r,e,t){let n=Ie(e),i=typeof n.error=="string"?n.error:"ERROR",s=typeof n.message=="string"?n.message:"",o=Ie(n.details);if(r===503)return new V(i,s,o,Sn(o,t));switch(`${r} ${i}`){case"401 UNAUTHENTICATED":return new Y(s,o);case"421 WRONG_NODE":return new B(s,o);case"404 NOT_FOUND":return new Ee(s,o);case"409 IDEMPOTENCY_MISMATCH":return new Pe(s,o);case"409 RELEASE_DEADLINE":return new xe(s,o);case"409 CONSENT_STALE":return new Ue(s,o);case"403 ORIGIN_NOT_REGISTERED":return new K(s,o);case"400 BAD_ORIGIN":case"400 BAD_RP_ID":return new Te(i,s,o);case"409 ORIGIN_TAKEN":return new ke(s,o);case"429 QUOTA_EXCEEDED":return new Se(s,o);case"412 CONFIRM_REQUIRED":return new Z(s,o);case"413 ARGS_TOO_LARGE":return new Re(s,o);case"422 APP_ERROR":return new Ce(s,o);case"422 TRAP":return new ve(s,o);default:return new w(r,i,s,o)}}function k(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 ae=r=>r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);function jt(r){let e=new Error(r);return e.name="NotAllowedError",e}function Cn(){return{async create(r){let e=r,t=await navigator.credentials.create({publicKey:{challenge:ae(I(e.challenge)),rp:e.rp,user:{...e.user,id:ae(I(e.user.id))},pubKeyCredParams:e.pubKeyCredParams,excludeCredentials:(e.excludeCredentials??[]).map(i=>({type:i.type,id:ae(I(i.id))})),authenticatorSelection:e.authenticatorSelection,attestation:"none",timeout:e.timeout}});if(!t)throw jt("passkey creation was cancelled");let n=t.response;return{attestationObject:k(new Uint8Array(n.attestationObject)),clientDataJson:k(new Uint8Array(n.clientDataJSON))}},async get(r,e,t){let n=await navigator.credentials.get({publicKey:{challenge:ae(r),rpId:e,userVerification:"preferred",allowCredentials:(t??[]).map(s=>({type:"public-key",id:ae(I(s))}))}});if(!n)throw jt("passkey sign-in was cancelled");let i=n.response;return{credentialId:k(new Uint8Array(n.rawId)),authenticatorData:k(new Uint8Array(i.authenticatorData)),clientDataJson:k(new Uint8Array(i.clientDataJSON)),signature:k(new Uint8Array(i.signature))}}}}var ct=100;function le(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>ct)throw new RangeError(`limit is 1 to ${ct}`);e.set("limit",String(r.limit))}let t=e.toString();return t?`?${t}`:""}function ce(r,e){try{return se(r,e)}catch{return r<e?-1:r>e?1:0}}function Qt(r,e,t=Date.now()/1e3){if(r===null||r.length===0)return null;let n=r.reduce((s,o)=>ce(s,o)>=0?s:o),i=null;for(let s of e)s.afterSecs<=t&&ce(n,s.version)<0&&(i===null||ce(s.version,i.version)>0)&&(i=s);return i}function qt(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 ye(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 Tr="Noise_NK_25519_AESGCM_SHA256",Fe=32,kr=16,Sr=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Ge=class r{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(Tr),t=new Uint8Array(32);return t.set(e),new r(t)}async mixHash(e){this.h=await vr(y(this.h,e))}async mixKey(e){let[t,n]=await bt(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:At(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:At(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),t}split(){return bt(this.ck,new Uint8Array)}};async function Et(r,e,t){let n=await Ge.initialize();await n.mixHash(e),await n.mixHash(r);let i=await j(t);return await n.mixHash(i.publicKey),await n.mixKey(await ee(i.privateKey,r)),{message1:y(i.publicKey,await n.encryptAndHash(new Uint8Array)),async finish(o){if(o.length<Fe+kr)throw new Error("Noise: message 2 is too short");let a=o.slice(0,Fe);return await n.mixHash(a),await n.mixKey(await ee(i.privateKey,a)),{payload:await n.decryptAndHash(o.slice(Fe)),split:await n.split()}}}}async function j(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(Sr,r),{name:"X25519"},!0,["deriveBits"]),t=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Cr(t.x)}}async function ee(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 At(r){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(r),!1),e}async function vr(r){return new Uint8Array(await crypto.subtle.digest("SHA-256",r))}async function He(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 bt(r,e){let t=await He(r,e),n=await He(t,new Uint8Array([1])),i=await He(t,y(n,new Uint8Array([2])));return[n,i]}function Cr(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 Ut="/sealed/v2/handshake",Tt="/sealed/v2",re="application/vnd.calimero.sealed",je=2,Ir=new TextEncoder().encode("calimero/sealed-http/v2"),te=16,Or=1+te+8,Dr=0,Nr=1,Mr=2,_r=1+64*1024+16,$r=1024,Br=6e4,Kr="calimero.tee-attest.transport-key.v1",Vr=[101,204,205,304],kt=new TextEncoder,ne=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 qe(r,e){let t=await crypto.subtle.digest("SHA-256",y(kt.encode(Kr),r,e));return new Uint8Array(t)}function Qe(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 Rt(o))}catch(g){if(!(g instanceof ne)||!s)throw g;return o=Promise.resolve().then(s),Pt(i,n,await Rt(o))}},d=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,F)=>b.push([F,P]));let N={method:h.method,path:f.pathname.slice(t.length)+f.search,headers:b},E=new Uint8Array(await h.arrayBuffer()),U=p?.signal??(g instanceof Request?g.signal:void 0),M=async P=>{let{requestId:F,header:W,envelope:fe}=await Fr(P,N,E),H=await i(`${n}${Tt}`,{method:"POST",headers:{"content-type":re},body:fe,signal:U});if(H.headers.get("content-type")!==re)throw await vt(H);return Gr(H,P.responseKey,W,F)},[Be,Ke]=await d();try{return await M(Be)}catch(P){if(!(P instanceof S)||P.code!=="unknown_session")throw P;return M(await u(Ke))}}}async function Rt(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 xt(r,e,t)}catch(n){if(!(n instanceof S)||n.code!=="busy")throw n;return await new Promise(i=>setTimeout(i,n.retryAfterMs??1e3)),xt(r,e,t)}}async function xt(r,e,t){let n=await Et(t,Ir),i=await r(`${e}${Ut}`,{method:"POST",headers:{"content-type":re},body:y(new Uint8Array([je]),t,n.message1)});if(i.headers.get("content-type")!==re)throw await vt(i);let s=await qr(i,$r);return Lr(n,s)}async function Lr(r,e){if(e[0]!==je)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!==te+4)throw new Error("The handshake reply is malformed");let s=n.slice(0,te),o=new DataView(n.buffer,n.byteOffset).getUint32(te,!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-Br,header(d){let u=new Uint8Array(Or);return u[0]=je,u.set(s,1),new DataView(u.buffer).setBigUint64(1+te,BigInt(d),!1),u}}}async function Fr(r,e,t){let n=r.nextRequestId;r.nextRequestId+=1;let i=r.header(n),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:St(n,0),additionalData:i},r.requestKey,Hr(e,t));return{requestId:n,header:i,envelope:y(i,new Uint8Array(s))}}function St(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 Hr(r,e){let t=kt.encode(JSON.stringify(r)),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t.length,!1),y(n,t,e)}async function Gr(r,e,t,n){if(!r.body)throw new Error("The sealed response has no body");let i=jr(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:St(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!==Dr)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 d=new ReadableStream({async pull(u){try{let g=await o();g?g.kind===Nr?u.enqueue(g.data):g.kind===Mr?(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(d,{status:c.status,headers:c.headers})}function jr(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>_r)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 qr(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 vt(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 ne;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 Ct=[{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"]}],It=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var Qr="1.2.840.10045.2.1",Jr={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},zr={"P-256":32,"P-384":48},Yr={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function Ot(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=Ot(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=Ot(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 he(r){return r.bytes.slice(r.offset,r.end)}function q(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 Zr(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,d,u]=i.slice(2).map(Number);return Date.UTC(s,o-1,a,c,d,u)}function Je(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,d,u,g,p,...h]=s.slice(o);m(a,2,"The serial number");let f=q(A(m(t,48,"The signature algorithm"))[0]);if(q(A(m(c,48,"The signature algorithm"))[0])!==f)throw new Error("it names two different signature algorithms");let N=Yr[f];if(!N)throw new Error(`it is signed with ${f}, not ECDSA with SHA-256 or SHA-384`);let[E,U]=A(m(u,48,"The validity")).map(Zr);if(U===void 0)throw new Error("its validity is incomplete");let[M,Be]=A(m(p,48,"The public key"));m(Be,3,"The public key");let[Ke,P]=A(m(M,48,"The key algorithm"));if(q(Ke)!==Qr)throw new Error("its key is not an elliptic-curve key");let F=Jr[q(P)];if(!F)throw new Error("its key is on a curve other than P-256 or P-384");let W=new Map,fe=h.find(Ve=>Ve.tag===163);if(fe){let[Ve]=A(fe);for(let Ur of A(m(Ve,48,"The extensions"))){let G=A(m(Ur,48,"An extension"));if(G.length===3)m(G[1],1,"An extension's critical flag");else if(G.length!==2)throw new Error("it has a malformed extension");let Le=q(G[0]);if(W.has(Le))throw new Error(`it has extension ${Le} twice`);W.set(Le,v(m(G[G.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:he(e),signatureHash:N,signature:H.slice(1),issuer:he(m(d,48,"The issuer")),subject:he(m(g,48,"The subject")),notBefore:E,notAfter:U,spki:he(p),curve:F,extensions:W}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function Dt(r){return A(m(Q(r),48,"The list")).map(q)}function Xr(r,e){let t=zr[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 me(r,e,t,n,i){let s;try{s=Xr(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 x(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 ze(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 x(t[0][1],e)}var Wr="2.5.29.17",en="2.5.29.37",tn="1.3.6.1.5.5.7.3.3",rn="1.3.6.1.4.1.57264.1.8",nn="1.3.6.1.4.1.57264.1.1",sn=134,on=12,an=48,cn=new TextEncoder,J=r=>new TextDecoder().decode(r);async function we(r,e,t,n){let{base64Signature:i,cert:s,rekorBundle:o}=gn(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=x(i,"The bundle signature"),d=ze(J(x(s,"The bundle certificate")),"The bundle certificate"),u=Je(d),g=It.find(U=>U.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=cn.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await me(x(g.publicKey,"The Rekor key"),"P-256","SHA-256",x(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(!_t(f,g.validFor))throw new Error(`Rekor log ${g.baseUrl} was not in use at ${ie(f)}, when the entry says it was logged`);let b=pn(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(!Ye(x(b.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let E=ze(J(x(b.publicKey,"The logged certificate")),"The logged certificate");if(!Ye(E,d))throw new Error("The bundle's certificate is not the one Rekor logged");if(u.curve!=="P-256"||!await me(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 ln(u,f),un(u,t),{integratedTime:a.integratedTime}}async function ln(r,e){if(!Mt(r,e))throw new Error(`The signing certificate was valid ${ie(r.notBefore)} to ${ie(r.notAfter)}, not at ${ie(e)} when Rekor logged it`);let t=[];for(let n of Ct){let i=n.certChain.map(o=>Je(x(o,"A Fulcio certificate")));if(!await Nt(r,i[0]))continue;let s=await dn(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 ${ie(e)}: ${t.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function dn(r,e,t){if(!_t(t,e))return"the trust root says it was not issuing certificates then";for(let[n,i]of r.entries()){if(!Mt(i,t))return`its certificate ${n} was not valid then`;let s=r[n+1]??i;if(!await Nt(i,s))return`its certificate ${n} is not signed by the next`}}async function Nt(r,e){return Ye(r.issuer,e.subject)?me(e.spki,e.curve,r.signatureHash,r.signature,r.tbs):!1}function un(r,e){let t=r.extensions.get(Wr);if(!t)throw new Error("The signing certificate names no identity");let n=A(m(Q(t),an,"The subject alternative name")),i=n.filter(d=>d.tag===sn).map(d=>J(v(d)));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(rn),o=r.extensions.get(nn),a=s?J(v(m(Q(s),on,"The OIDC issuer"))):o?J(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(en);if(!c||!Dt(c).includes(tn))throw new Error("The signing certificate is not for code signing")}function gn(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 pn(r){let e;try{e=JSON.parse(J(x(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 Mt(r,e){return r.notBefore<=e&&e<=r.notAfter}function _t(r,e){return Date.parse(e.start)<=r&&(e.end===void 0||r<=Date.parse(e.end))}function ie(r){return new Date(r).toISOString()}function Ye(r,e){return r.length===e.length&&r.every((t,n)=>t===e[n])}var fn=/^[0-9a-f]{96}$/,yn=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function $(r){let e=z(r.allowedMrtd??[],"allowedMrtd"),t=(r.allowedMeasurements??[]).map((a,c)=>{let d=`allowedMeasurements[${c}]`;return yn.map(u=>z([a?.[u]??""],`${d}.${u}`)[0]).join()}),n=[z(r.allowedRtmr0??[],"allowedRtmr0"),z(r.allowedRtmr1??[],"allowedRtmr1"),z(r.allowedRtmr2??[],"allowedRtmr2"),z(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:d,collateral:u})=>{let g=mn(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=hn(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,U)=>{let M=n[U];if(M.length>0&&!M.includes(R(E)))throw new Error(`RTMR${U} ${R(E)} is not one this verifier trusts`)}),R(f.reportData)!==`${c}${d}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function z(r,e){return r.map(t=>{let n=t.trim().toLowerCase();if(!fn.test(n))throw new Error(`${e} holds ${JSON.stringify(t)}, which is not a 48-byte hex measurement`);return n})}function hn(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 mn(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 wn=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],_="locked-read-only";function Ze(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 d=(c.allowed_tcb_statuses??["uptodate"]).map(u=>An(u,a));return n=n===void 0?d:n.filter(u=>d.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 An(r,e){let t=wn.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 Xe=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"}),bn=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],Ae="https://cloud.calimero.network",We=`${Ae}/api/tee/pcs`;async function Bt(r,e,t={}){let n=typeof r=="string"?new TextEncoder().encode(r):r;await we(n,e,{identity:t.identity??Xe.identity,issuer:t.issuer??Xe.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=>bn.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 et(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 Kt="https://github.com/calimero-network/mero-tee/releases/download";async function tt(r,e={}){let t=`mero-tee-v${C(r,"version")}`,n=`${(e.base??Kt).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 rt(r,e){return`${r.replace(/\/+$/,"")}/api/tee/node-releases/${C(e,"version")}`}async function be(r){let e=C(r.minReleaseVersion,"minReleaseVersion"),t=C(r.release?.version,"The release version"),n=await Bt(r.release.publishedMrtds,r.release.bundle,{expectedVersion:t,identity:r.identity,issuer:r.issuer});if(se(t,e)<0)throw new Error(`Release ${t} is older than the minimum trusted, ${e}`);return Ze([n],{profile:r.profile,allowDebugProfile:r.allowDebugProfile})}function En(r){return C(r.minReleaseVersion,"minReleaseVersion"),Object.assign(async t=>{let n=await be({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 Vt=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function C(r,e){let t=typeof r=="string"?Vt.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 se(r,e){let[t,n]=$t(r),[i,s]=$t(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[d,u]=[o[c],a[c]];if(d===void 0||u===void 0)return d===void 0?-1:1;let[g,p]=[/^\d+$/.test(d),/^\d+$/.test(u)],h=g&&p?Math.sign(Number(d)-Number(u)):g!==p?g?-1:1:d<u?-1:d>u?1:0;if(h!==0)return h}return 0}function $t(r){let e=Vt.exec(r);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var Ft="MOCK_TDX_QUOTE_V1";function Rn(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 nt(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 Lt;async function it(r){Lt??(Lt=import("@phala/dcap-qvl"));let e=await Lt,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 Ht(r,e){let t=C(e,"minReleaseVersion"),n=String(r.release?.version??"").trim().replace(/^mero-tee-v/,"").replace(/^v/,""),i=C(n,"The release the node names");if(se(i,t)<0)throw new Error(`mero-tee release ${i} is older than the minimum ${t}`);return i}async function Pn(r,e,t){let n=e.releaseSource;return typeof n=="function"?n(r):n==="github"?tt(r,{fetch:t}):et(rt(n??Ae,r),{fetch:t})}function xn(r){let e=r.collateralSource??We;return e==="intel"?async t=>(await it("getCollateralFromPcs"))(t):async t=>(await it("getCollateral"))(e,t)}function Gt(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 Un(r,e,t,n){let i=Ht(r,t.minReleaseVersion),s=await be({release:await Pn(i,t,n),profile:t.profile??_,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer}),o=Gt(t.fetchCollateral??xn(t),t);return $({dcapVerify:t.dcapVerify??await it("verify"),fetchCollateral:o,now:t.now,...s})(e)}async function st(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=ye(o.transportKey,"transportKey",32),c=e.appHash?ye(e.appHash,"appHash",32):new Uint8Array(32),d=await qe(c,a),u=Rn(o.quote),g=new TextEncoder().encode(Ft);if(nt(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(!nt(f.slice(0,32),ye(n,"nonce",32))||!nt(f.slice(32),d))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(d)},h;if(e.verifyQuote)h=await e.verifyQuote(p);else if(e.release)h=await Un(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 ot="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 Tn(r,e){return`${r.replace(/\/+$/,"")}/${encodeURIComponent(e)}`}async function at(r,e,t){let n;try{n=await t(Tn(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=kn(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,d=typeof c=="number"&&Number.isFinite(c)&&c>=1?c:60;return{nodes:o,refreshAfterSeconds:d}}function kn(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 ct(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[...jt(n,t),...jt(i,t)]}function jt(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"}},Y=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"}},Ee=class extends w{constructor(e,t={}){super(404,"NOT_FOUND",e,t),this.name="NotFound"}},Z=class extends w{constructor(e,t={}){super(412,"CONFIRM_REQUIRED",e,t),this.name="ConfirmRequired"}},oe=class extends Error{constructor(t){super("the passkey confirmation was cancelled");this.cause=t;this.name="ConfirmCancelled"}},Re=class extends w{constructor(e,t={}){super(413,"ARGS_TOO_LARGE",e,t),this.name="ArgsTooLarge"}},Pe=class extends w{constructor(e,t={}){super(409,"IDEMPOTENCY_MISMATCH",e,t),this.name="IdempotencyMismatch"}},xe=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"}},K=class extends w{constructor(e,t={}){let n=typeof t.origin=="string"?t.origin:"",i=typeof t.package=="string"?t.package:"",s=n?`this site (${n})`:"this site";super(403,"ORIGIN_NOT_REGISTERED",`${s} is not registered for ${i||"any package"}${e?` (${e})`:""}`,t),this.name="OriginNotRegistered",this.origin=n,this.package=i,this.nodeMessage=e}},Te=class extends w{constructor(e,t,n={}){super(400,e,t,n),this.name="BadOrigin"}},ke=class extends w{constructor(e,t={}){super(409,"ORIGIN_TAKEN",e,t),this.name="OriginTaken"}},Se=class extends w{constructor(e,t={}){super(403,"SIGN_UP_REFUSED",e,t),this.name="SignUpRefused",this.reason=Sn(e)}};function Sn(r){return/invite only/.test(r)?"invite-only":/pre-authorized|sign-up invite/.test(r)?"closed":/unknown invite/.test(r)?"unknown-invite":/invite has expired/.test(r)?"expired-invite":/organization is gone/.test(r)?"org-gone":"other"}var ve=class extends w{constructor(e,t={}){super(429,"QUOTA_EXCEEDED",e,t),this.name="QuotaExceeded"}},Ce=class extends w{constructor(e,t={}){super(422,"APP_ERROR",e,t),this.name="AppError";let{appCode:n,fields:i}=vn(t);this.appCode=n,this.fields=i}},Ie=class extends w{constructor(e,t={}){super(422,"TRAP",e,t),this.name="TrapError",this.kind=typeof t.kind=="string"?t.kind:""}},V=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 Oe(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function vn(r){let e=typeof r.code=="string"?r:Oe(r.error);return{appCode:typeof e.code=="string"?e.code:"",fields:{...Oe(e.fields)}}}function Cn(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 De(r,e,t){let n=Oe(e),i=typeof n.error=="string"?n.error:"ERROR",s=typeof n.message=="string"?n.message:"",o=Oe(n.details);if(r===503)return new V(i,s,o,Cn(o,t));switch(`${r} ${i}`){case"401 UNAUTHENTICATED":return new Y(s,o);case"421 WRONG_NODE":return new B(s,o);case"404 NOT_FOUND":return new Ee(s,o);case"409 IDEMPOTENCY_MISMATCH":return new Pe(s,o);case"409 RELEASE_DEADLINE":return new xe(s,o);case"409 CONSENT_STALE":return new Ue(s,o);case"403 ORIGIN_NOT_REGISTERED":return new K(s,o);case"400 BAD_ORIGIN":case"400 BAD_RP_ID":return new Te(i,s,o);case"409 ORIGIN_TAKEN":return new ke(s,o);case"429 QUOTA_EXCEEDED":return new ve(s,o);case"403 SIGN_UP_REFUSED":return new Se(s,o);case"412 CONFIRM_REQUIRED":return new Z(s,o);case"413 ARGS_TOO_LARGE":return new Re(s,o);case"422 APP_ERROR":return new Ce(s,o);case"422 TRAP":return new Ie(s,o);default:return new w(r,i,s,o)}}function k(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 ae=r=>r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);function qt(r){let e=new Error(r);return e.name="NotAllowedError",e}function In(){return{async create(r){let e=r,t=await navigator.credentials.create({publicKey:{challenge:ae(I(e.challenge)),rp:e.rp,user:{...e.user,id:ae(I(e.user.id))},pubKeyCredParams:e.pubKeyCredParams,excludeCredentials:(e.excludeCredentials??[]).map(i=>({type:i.type,id:ae(I(i.id))})),authenticatorSelection:e.authenticatorSelection,attestation:"none",timeout:e.timeout}});if(!t)throw qt("passkey creation was cancelled");let n=t.response;return{attestationObject:k(new Uint8Array(n.attestationObject)),clientDataJson:k(new Uint8Array(n.clientDataJSON))}},async get(r,e,t){let n=await navigator.credentials.get({publicKey:{challenge:ae(r),rpId:e,userVerification:"preferred",allowCredentials:(t??[]).map(s=>({type:"public-key",id:ae(I(s))}))}});if(!n)throw qt("passkey sign-in was cancelled");let i=n.response;return{credentialId:k(new Uint8Array(n.rawId)),authenticatorData:k(new Uint8Array(i.authenticatorData)),clientDataJson:k(new Uint8Array(i.clientDataJSON)),signature:k(new Uint8Array(i.signature))}}}}var lt=100;function le(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>lt)throw new RangeError(`limit is 1 to ${lt}`);e.set("limit",String(r.limit))}let t=e.toString();return t?`?${t}`:""}function ce(r,e){try{return se(r,e)}catch{return r<e?-1:r>e?1:0}}function Qt(r,e,t=Date.now()/1e3){if(r===null||r.length===0)return null;let n=r.reduce((s,o)=>ce(s,o)>=0?s:o),i=null;for(let s of e)s.afterSecs<=t&&ce(n,s.version)<0&&(i===null||ce(s.version,i.version)>0)&&(i=s);return i}function Jt(r,e,t,n){return`calimero-publisher-binding/v1
2
2
  ${r}
3
3
  ${e}
4
4
  ${t}
5
- ${n}`}function vn(r,e,t,n){return new TextEncoder().encode(qt(r,e,t,n))}var In="0123456789ABCDEFGHJKMNPQRSTVWXYZ";async function lt(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+=In[t>>>27-5*i&31];return n}function On(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 Jt="https://mero-tee.vercel.app";function zt(r){return`https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(r)}`}function Yt(r){return`${Jt}/mero-tee?release_tag=${encodeURIComponent(`mero-tee-v${r}`)}`}function dt(r,e,t=Date.now()/1e3){let n=c=>e.deadlines.find(d=>d.version===c)??null,i=r.governance.releases==="owner",s=r.governance.appUpgrades==="owner",o=r.clusterReleases.filter(c=>!c.approved).sort((c,d)=>ce(d.release,c.release)).map(c=>({version:c.release,nodes:c.nodes,actionable:i,releaseNotesUrl:zt(c.release),verifyUrl:Yt(c.release),deadline:n(c.release)})),a=[];for(let c of r.apps){let d=c.availableVersions??[];c.package===null||d.length===0||a.push({app:c.app,name:c.name??null,package:c.package.package,from:c.package.version,to:d[d.length-1],available:d,actionable:s})}return{scope:r.scope,governance:r.governance,approvedReleases:r.approvedReleases,releases:o,upgrades:a,stalledBy:Qt(r.approvedReleases,e.deadlines,t),actionable:o.some(c=>c.actionable)||a.some(c=>c.actionable)}}function Zt(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 Dn(r,e,t){return Zt(r,e,t,{withdraw:!0})}function Nn(r,e,t){return{kind:"upgrade",subject:{app:r,toVersion:e},returnTo:t}}function tr(r){return"account"in r?`account:${r.account}`:`org:${r.org}`}async function Mn(r,e=fetch){let t=r??globalThis.location?.origin;if(!t)throw new Error("no page origin to read the frontend manifest from; pass `origin`");let n=await e(new URL("/.well-known/calimero.json",t).toString());if(!n.ok)throw await ut(n);let i=await n.json();return{...i,deployments:i.deployments??[]}}function _n(r){let e=r??globalThis.location?.href;if(!e)return null;try{return new URL(e).searchParams.get("deployment")||null}catch{return null}}function l(r){return encodeURIComponent(r)}function $n(r){return r instanceof S&&r.status===413?Oe(413,{error:"TOO_LARGE",message:r.message.replace(/^Sealed request refused: /,"")}):r}async function ut(r){let e=await r.text().catch(()=>""),t={};try{t=e?JSON.parse(e):{}}catch{t={message:e}}return Oe(r.status,t,r.headers.get("retry-after"))}async function*Bn(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 On(r,e,t,n){return new TextEncoder().encode(Jt(r,e,t,n))}var Dn="0123456789ABCDEFGHJKMNPQRSTVWXYZ";async function dt(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+=Dn[t>>>27-5*i&31];return n}function Nn(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 zt="https://mero-tee.vercel.app";function Yt(r){return`https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(r)}`}function Zt(r){return`${zt}/mero-tee?release_tag=${encodeURIComponent(`mero-tee-v${r}`)}`}function ut(r,e,t=Date.now()/1e3){let n=c=>e.deadlines.find(d=>d.version===c)??null,i=r.governance.releases==="owner",s=r.governance.appUpgrades==="owner",o=r.clusterReleases.filter(c=>!c.approved).sort((c,d)=>ce(d.release,c.release)).map(c=>({version:c.release,nodes:c.nodes,actionable:i,releaseNotesUrl:Yt(c.release),verifyUrl:Zt(c.release),deadline:n(c.release)})),a=[];for(let c of r.apps){let d=c.availableVersions??[];c.package===null||d.length===0||a.push({app:c.app,name:c.name??null,package:c.package.package,from:c.package.version,to:d[d.length-1],available:d,actionable:s})}return{scope:r.scope,governance:r.governance,approvedReleases:r.approvedReleases,releases:o,upgrades:a,stalledBy:Qt(r.approvedReleases,e.deadlines,t),actionable:o.some(c=>c.actionable)||a.some(c=>c.actionable)}}function Xt(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 Mn(r,e,t){return Xt(r,e,t,{withdraw:!0})}function _n(r,e,t){return{kind:"upgrade",subject:{app:r,toVersion:e},returnTo:t}}function rr(r){return"account"in r?`account:${r.account}`:`org:${r.org}`}async function $n(r,e=fetch){let t=r??globalThis.location?.origin;if(!t)throw new Error("no page origin to read the frontend manifest from; pass `origin`");let n=await e(new URL("/.well-known/calimero.json",t).toString());if(!n.ok)throw await gt(n);let i=await n.json();return{...i,deployments:i.deployments??[]}}function Bn(r){let e=r??globalThis.location?.href;if(!e)return null;try{return new URL(e).searchParams.get("deployment")||null}catch{return null}}function l(r){return encodeURIComponent(r)}function Kn(r){return r instanceof S&&r.status===413?De(413,{error:"TOO_LARGE",message:r.message.replace(/^Sealed request refused: /,"")}):r}async function gt(r){let e=await r.text().catch(()=>""),t={};try{t=e?JSON.parse(e):{}}catch{t={message:e}}return De(r.status,t,r.headers.get("retry-after"))}async function*Vn(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
7
  `))>=0;){let a=n.slice(0,o);n=n.slice(o+2);let c="",d="",u="";for(let p of a.split(`
8
- `))p.startsWith("id:")?c=p.slice(3).trim():p.startsWith("event:")?d=p.slice(6).trim():p.startsWith("data:")&&(u+=p.slice(5).trim());if(!d&&!u)continue;let g=u;try{g=JSON.parse(u)}catch{}yield{id:c,kind:d,data:g}}}}function Xt(r){return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}function Wt(){return`node:c-${k(crypto.getRandomValues(new Uint8Array(16)))}`}var Kn={retries:6,baseDelayMs:200,maxDelayMs:2e3};function Vn(r,e){return Math.min(e.baseDelayMs*2**r,e.maxDelayMs)}function er(r){return r==="auth/refresh"||r.startsWith("auth/passkey/")}var gt=class r{constructor(e){this.at=0;this.channels=new Map;this.networkFailures=new WeakSet;this.packageOrigins={list:async e=>{let{origins:t}=await this.get(`package-origins/${l(e)}`);return t??[]},add:(e,t,n,i={})=>this.confirmed("POST",`package-origins/${l(e)}`,i.rpId===void 0?{origin:t}:{origin:t,rpId:i.rpId},n),remove:(e,t,n)=>this.confirmed("DELETE",`package-origins/${l(e)}`,{origin:t},n)};let t=s=>s.replace(/\/+$/,"");this.nodeUrls=[...new Set([e.baseUrl,...e.nodes??[]].map(t))],this.policy=e.policy,this.retry={...Kn,...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??st,n=e.random??Math.random,i=e.fetch??((d,u)=>fetch(d,u)),s=await ot(t,e.cluster,i),[o,...a]=at(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=Qe({baseUrl:e,transportPublicKey:()=>it(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=ot(e.directory,e.cluster,this.raw).then(t=>{let n=this.nodeUrl,i=at(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 d=this.nodeUrl;try{return await this.channel(d)(`${d}/${t}`,{method:e,headers:a,body:c,signal:o})}catch(u){throw $n(u)}}async send(e,t,n,i,s,o){let a=!1,c=!1;for(;;){let[d,u]=[this.auth,this.nodeUrl],g=await this.request(e,t,n,i,s,o);if(g.ok)return g;let p=await ut(g);if(p instanceof B&&!c){if(c=!0,this.moveOn(u)&&!er(t))continue}else if(p instanceof Y&&!a&&this.mayRefresh(d,t)){a=!0,await this.renew(d);continue}throw p}}mayRefresh(e,t){return e!==void 0&&this.current!==void 0&&!er(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 d=0;;d++){c=this.nodeUrl,o.add(c);try{return await this.json(e,t,n)}catch(g){if(g instanceof V)a=g;else if(g instanceof TypeError&&this.networkFailures.has(g))a=new V("NETWORK",`the node could not be reached: ${g.message}`,{},void 0,g);else throw g}if(d>=s)break;let u=Vn(d,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,n={}){let i=this.pageOrigin(n),s=await this.begin("auth/passkey/register/begin",i===void 0?{name:t}:{name:t,origin:i},i),o=await e.create(s.options),a=await this.postConfirmed("auth/passkey/register/finish",{challengeId:s.challengeId,registration:o},e);return this.useSession(a),a}async signIn(e,t={}){let n=this.pageOrigin(t),i=await this.begin("auth/passkey/login/begin",n===void 0?void 0:{origin:n},n),s=i.options.rpId??i.options.rp?.id??"",o=await e.get(I(i.options.challenge),s),a=await this.post("auth/passkey/login/finish",{challengeId:i.challengeId,assertion:o});return this.useSession(a),a}pageOrigin(e){if(e.origin!==void 0)return e.origin??void 0;let t=globalThis.location?.origin;return!t||t==="null"||new Set(this.nodeUrls.map(i=>{try{return new URL(i).origin}catch{return i}})).has(t)?void 0:t}async begin(e,t,n){try{return await this.post(e,t)}catch(i){throw i instanceof K&&!i.origin&&n!==void 0?new K(i.nodeMessage,{...i.details,origin:n}):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/${l(e)}`,t)}async labelPasskey(e,t){await this.post(`auth/passkeys/${l(e)}`,{label:t})}usage(){return this.get("auth/usage")}async attestation(){let e=Xt(crypto.getRandomValues(new Uint8Array(32))),t=await this.raw(`${this.nodeUrl}/attestation?nonce=${e}`);if(!t.ok)throw await ut(t);return await t.json()}async listApiKeys(){let{keys:e}=await this.get("auth/apikeys");return e}async revokeApiKey(e,t){await this.deleteConfirmed(`auth/apikeys/${l(e)}`,t)}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,n={}){let i=(typeof n=="string"?n:n.contentType)??"application/octet-stream";return this.json("POST",`apps/${l(e)}/blobs`,void 0,t,i)}async downloadBlob(e,t){return(await this.blobContent(e,t)).data}async downloadBlobGranted(e,t,n){return(await this.blobContent(e,t,{grant:n})).data}async blobContent(e,t,n={}){let i=n.grant===void 0?"":`?grant=${encodeURIComponent(n.grant)}`,s=await this.send("GET",`apps/${l(e)}/blobs/${l(t)}${i}`);return{data:new Uint8Array(await s.arrayBuffer()),contentType:s.headers.get("content-type")??"application/octet-stream"}}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})}appXcalls(e){return this.get(`apps/${l(e)}/xcalls`)}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 Z)||!i)throw o;let a=o.details,c;try{c=await i.get(I(a.challenge),a.rpId,a.allowCredentials)}catch(d){let u=d?.name;throw u==="NotAllowedError"||u==="AbortError"?new oe(d):d}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??Wt();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??Wt();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/${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*Bn(n.body)}async publishPresence(e,t,n){await this.post(`apps/${l(e)}/presence`,{seq:t,state:n===null?null:Xt(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}${le(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 dt(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 lt(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${le(e)}`)}opsOrgs(e={}){return this.get(`ops/orgs${le(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,i){await this.postConfirmed(`orgs/${l(e)}/members`,{account:t,role:n},i)}removeMember(e,t,n){return this.deleteConfirmed(`orgs/${l(e)}/members/${l(t)}`,n)}async setCapabilities(e,t,n,i={}){await this.postConfirmed(`orgs/${l(e)}/capabilities`,{capabilities:t,...i},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,s={}){await this.postConfirmed(`orgs/${l(e)}/teams/${l(t)}/members`,{account:n,...s},i)}async removeTeamMember(e,t,n,i){await this.deleteConfirmed(`orgs/${l(e)}/teams/${l(t)}/members/${l(n)}`,i)}async invite(e,t,n,i=[],s={}){let{token:o}=await this.postConfirmed(`orgs/${l(e)}/invites`,{role:t,teams:i,...s},n);return o}redeemInvite(e){return this.post(`invites/${l(e)}/redeem`)}grantDeployer(e,t,n={}){let i=n.until instanceof Date?n.until.toISOString():n.until;return this.postConfirmed("deployers",{deployer:e,...i===void 0?{}:{until:i}},t)}deployers(){return this.get("deployers")}async revokeDeployer(e,t){let n=typeof e=="string"?e:tr(e);await this.deleteConfirmed(`deployers/${l(n)}`,t)}async createDeployment(e,t,n){let{id:i}=await this.postConfirmed("deployments",{name:e,owner:t},n);return i}async deployments(){let{deployments:e}=await this.get("deployments");return e}deployment(e){return this.get(`deployments/${l(e)}`)}async deleteDeployment(e,t){await this.deleteConfirmed(`deployments/${l(e)}`,t)}offerApp(e,t,n){return this.postConfirmed(`deployments/${l(e)}/apps`,{...t},n)}async withdrawApp(e,t,n){await this.deleteConfirmed(`deployments/${l(e)}/apps/${l(t)}`,n)}deploymentOrgs(e){return this.get(`deployments/${l(e)}/orgs`)}};var pt={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},Ln=pt.JOIN_OPEN_TEAMS;function Hn(...r){return r.reduce((e,t)=>e|pt[t],0)}function De(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]=De(r[i]^r[e],16),r[n]=r[n]+r[i]>>>0,r[t]=De(r[t]^r[n],12),r[e]=r[e]+r[t]>>>0,r[i]=De(r[i]^r[e],8),r[n]=r[n]+r[i]>>>0,r[t]=De(r[t]^r[n],7)}function rr(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0}function sr(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]=rr(r,o*4);n[12]=e>>>0;for(let o=0;o<3;o+=1)n[13+o]=rr(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 Fn(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=sr(r,o,t),c=Math.min(s+64,n.length);for(let d=s;d<c;d+=1)i[d]=n[d]^a[d-s]}return i}function ft(r){let e=0n;for(let t=r.length-1;t>=0;t-=1)e=e<<8n|BigInt(r[t]);return e}var Gn=(1n<<130n)-5n;function jn(r,e){let t=ft(r.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,n=ft(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)),d=ft(c)+(1n<<BigInt(8*c.length));i=(i+d)*t%Gn}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 nr(r){return new Uint8Array((16-r%16)%16)}function ir(r){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(r),!0),e}function Qn(r,e){let t=[r,nr(r.length),e,nr(e.length),ir(r.length),ir(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 qn(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 or(r,e,t,n=new Uint8Array(0)){qn(r,e);let i=sr(r,0,e).subarray(0,32),s=Fn(r,1,e,t),o=jn(i,Qn(n,s)),a=new Uint8Array(s.length+16);return a.set(s),a.set(o,s.length),a}var cr=32,Jn=1,zn=3,Yn=2,Zn=32,Xn=32,Wn=12,X=r=>new TextEncoder().encode(r),ue=r=>new Uint8Array([r>>8&255,r&255]),ar=y(X("KEM"),ue(cr)),de=y(X("HPKE"),ue(cr),ue(Jn),ue(zn));async function lr(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 ei(r,e,t){let n=new Uint8Array(t),i=new Uint8Array(0);for(let s=1,o=0;o<t;s+=1)i=await lr(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 Ne(r,e,t,n){return lr(e,y(X("HPKE-v1"),r,X(t),n))}function yt(r,e,t,n,i){return ei(e,y(ue(i),X("HPKE-v1"),r,X(t),n),i)}async function ti(r,e){let t=await Ne(ar,new Uint8Array(0),"eae_prk",r);return yt(ar,t,"shared_secret",e,Zn)}async function ri(r,e){let t=new Uint8Array(0),n=await Ne(de,t,"psk_id_hash",t),i=await Ne(de,t,"info_hash",e),s=y(new Uint8Array([Yn]),n,i),o=await Ne(de,r,"secret",t);return{key:await yt(de,o,"key",s,Xn),nonce:await yt(de,o,"base_nonce",s,Wn)}}async function dr(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 j(s),a=await j(e),c=y(await ee(o.privateKey,r),await ee(a.privateKey,r)),d=await ti(c,y(o.publicKey,r,a.publicKey)),{key:u,nonce:g}=await ri(d,t);return{enc:o.publicKey,ciphertext:or(u,g,n,i)}}var pr="mero-agent-gate/attest/v3",fr="mero-agent-gate/provision/v2",ni=/^[a-z0-9][a-z0-9-]{0,62}$/,ii=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,ur=64,gr=64*1024,D=class extends Error{constructor(t,n,i){super(t);this.status=n;this.code=i;this.name="AgentGateError"}};function yr(r){if(!ni.test(r))throw new Error(`Agent id ${JSON.stringify(r)} must match [a-z0-9][a-z0-9-]{0,62}`)}function ge(r){return new TextEncoder().encode(r)}function hr(r){let e=ge(r);return y(new Uint8Array([e.length]),e)}function L(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}function Me(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 mr(r,e,t,n){let i=new Uint8Array(32),s=y(ge(pr),r,hr(e),t??i,n??i);return new Uint8Array(await crypto.subtle.digest("SHA-256",s))}function wr(r,e){return y(ge(fr),r,hr(e))}async function si(){let r=crypto.getRandomValues(new Uint8Array(32));return{secret:r,publicKey:await _e(r)}}async function _e(r){if(r.length!==32)throw new Error("An owner key is 32 bytes");return L((await j(r)).publicKey)}function Ar(r,e){return`${r.replace(/\/+$/,"")}${e}`}async function br(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 ht(r){let e=r.agentId??"";e&&yr(e);let t=crypto.getRandomValues(new Uint8Array(32)),n=await br(r.fetch??fetch,Ar(r.gateUrl,"/attest"),{nonceB64:L(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=Me(n.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),s=n.signingPublicKeyB64?Me(n.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,o=n.ownerPublicKeyB64?Me(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 mr(i,e,s,o);return await r.verifier({quoteB64:n.quoteB64,nonce:R(t),reportDataSuffix:R(a)}),{agentId:e,provisioningPublicKey:L(i),...s?{signingPublicKey:L(s)}:{},...o?{ownerPublicKey:L(o)}:{}}}async function Er(r,e){let t=await _e(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 oi(r){let e=Object.keys(r);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>ur)throw new Error(`At most ${ur} secrets at once`);for(let t of e){if(!ii.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(ge(r[t]).length>gr)throw new Error(`Secret ${t} is over ${gr} bytes`)}}async function Rr(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 Er(n,i),a=Me(n.provisioningPublicKey,"provisioningPublicKey",32),c=await dr(a,i,wr(a,n.agentId),ge(JSON.stringify(s)));return br(r,Ar(e,t),{agentId:n.agentId,provisioningPublicKeyB64:n.provisioningPublicKey,senderPublicKeyB64:o,encappedKeyB64:L(c.enc),ciphertextB64:L(c.ciphertext)})}async function ai(r){oi(r.secrets);let e=r.fetch??fetch,t=await Rr(e,r.gateUrl,"/provision",r.agent,r.ownerSecret,{secrets:r.secrets}),n=await ht({gateUrl:r.gateUrl,agentId:r.agent.agentId,verifier:r.verifier,fetch:e}),i=await _e(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 ci(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 Rr(e,r.gateUrl,"/release",r.agent,r.ownerSecret,{release:!0}),(await ht({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 mt=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),li=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function di(r,e,t={}){let n=typeof r=="string"?new TextEncoder().encode(r):r;await we(n,e,{identity:t.identity??mt.identity,issuer:t.issuer??mt.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 Pr(i),i}function Pr(r){for(let e of li)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 ui=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function gi(r){let e=ui.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 pe=r=>r.trim().replace(/^0x/i,"");function pi(r,e){return Pr(r),$({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:r.allowed_tcb_statuses.map(gi),allowedMrtd:r.allowed_mrtd.map(pe),allowedRtmr0:r.allowed_rtmr0.map(pe),allowedRtmr1:r.allowed_rtmr1.map(pe),allowedRtmr2:r.allowed_rtmr2.map(pe),allowedRtmr3:r.allowed_rtmr3.map(pe)})}export{pr as AGENT_ATTEST_DOMAIN,fr as AGENT_PROVISION_INFO_DOMAIN,D as AgentGateError,Ce as AppError,Re as ArgsTooLarge,Te as BadOrigin,gt as CalimeroClient,w as CalimeroError,oe as ConfirmCancelled,Z as ConfirmRequired,Ue as ConsentStale,Xe as DEFAULT_COLLATERAL_MIRROR,st as DEFAULT_DIRECTORY,Ln as DEFAULT_ORG_CAPABILITIES,Ae as DEFAULT_RELEASE_MIRROR,T as DirectoryError,Bt as GITHUB_RELEASES,xt as HANDSHAKE_PATH,Pe as IdempotencyMismatch,mt as KMS_RELEASE_SIGNER,Y as LoginRequired,ct as MAX_REPORT_PAGE,Lt as MOCK_QUOTE_HEADER,Ze as NODE_RELEASE_SIGNER,Ee as NotFound,pt as ORG_CAPABILITIES,K as OriginNotRegistered,ke as OriginTaken,_ as PRODUCTION_PROFILE,Se as QuotaExceeded,Jt as RELEASE_VERIFIER,xe as ReleaseDeadlineError,re as SEALED_CONTENT_TYPE,Ut as SEALED_PATH,S as SealedTransportError,ne as StaleTransportKeyError,ve as TrapError,V as UnavailableError,B as WrongNode,mr as agentKeyBinding,pi as agentQuoteVerifier,ht as attestAgent,k as b64url,Cn as browserPasskey,Er as checkOwner,Ht as claimedRelease,tt as cloudNodeReleaseUrl,ce as compareVersions,lt as confirmationCode,On as consentReturn,$ as createQuoteVerifier,Qe as createSealedFetch,bn as createSignedReleaseVerifier,tr as deployerKey,Oe as errorFrom,it as fetchAttestedKey,et as fetchGithubNodeRelease,We as fetchNodeRelease,Ft as freshCollateral,I as fromB64url,Mn as frontendManifest,si as generateOwnerKey,Hn as orgCapabilities,_e as ownerPublicKey,_n as pageDeployment,le as pageQuery,dt as pendingApprovalsFrom,ai as provisionAgent,wr as provisionInfo,vn as publisherBindingBytes,qt as publisherBindingMessage,ci as releaseAgent,Zt as releaseConsent,zt as releaseNotesUrl,Qt as stalledBy,je as transportKeyBinding,be as trustSignedRelease,Ye as trustedMeasurementsFromReleases,Nn as upgradeConsent,yr as validateAgentId,Yt as verifyReleaseUrl,di as verifySignedAgentPolicy,$t as verifySignedNodeRelease,Dn as withdrawConsent};
8
+ `))p.startsWith("id:")?c=p.slice(3).trim():p.startsWith("event:")?d=p.slice(6).trim():p.startsWith("data:")&&(u+=p.slice(5).trim());if(!d&&!u)continue;let g=u;try{g=JSON.parse(u)}catch{}yield{id:c,kind:d,data:g}}}}function Wt(r){return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}function er(){return`node:c-${k(crypto.getRandomValues(new Uint8Array(16)))}`}var Ln={retries:6,baseDelayMs:200,maxDelayMs:2e3};function Fn(r,e){return Math.min(e.baseDelayMs*2**r,e.maxDelayMs)}function tr(r){return r==="auth/refresh"||r.startsWith("auth/passkey/")}var pt=class r{constructor(e){this.at=0;this.channels=new Map;this.networkFailures=new WeakSet;this.packageOrigins={list:async e=>{let{origins:t}=await this.get(`package-origins/${l(e)}`);return t??[]},add:(e,t,n,i={})=>this.confirmed("POST",`package-origins/${l(e)}`,i.rpId===void 0?{origin:t}:{origin:t,rpId:i.rpId},n),remove:(e,t,n)=>this.confirmed("DELETE",`package-origins/${l(e)}`,{origin:t},n)};let t=s=>s.replace(/\/+$/,"");this.nodeUrls=[...new Set([e.baseUrl,...e.nodes??[]].map(t))],this.policy=e.policy,this.retry={...Ln,...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??ot,n=e.random??Math.random,i=e.fetch??((d,u)=>fetch(d,u)),s=await at(t,e.cluster,i),[o,...a]=ct(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=Qe({baseUrl:e,transportPublicKey:()=>st(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=at(e.directory,e.cluster,this.raw).then(t=>{let n=this.nodeUrl,i=ct(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 d=this.nodeUrl;try{return await this.channel(d)(`${d}/${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[d,u]=[this.auth,this.nodeUrl],g=await this.request(e,t,n,i,s,o);if(g.ok)return g;let p=await gt(g);if(p instanceof B&&!c){if(c=!0,this.moveOn(u)&&!tr(t))continue}else if(p instanceof Y&&!a&&this.mayRefresh(d,t)){a=!0,await this.renew(d);continue}throw p}}mayRefresh(e,t){return e!==void 0&&this.current!==void 0&&!tr(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 d=0;;d++){c=this.nodeUrl,o.add(c);try{return await this.json(e,t,n)}catch(g){if(g instanceof V)a=g;else if(g instanceof TypeError&&this.networkFailures.has(g))a=new V("NETWORK",`the node could not be reached: ${g.message}`,{},void 0,g);else throw g}if(d>=s)break;let u=Fn(d,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,n={}){let i=this.pageOrigin(n),s=n.invite?{invite:n.invite}:{},o=await this.begin("auth/passkey/register/begin",i===void 0?{name:t,...s}:{name:t,origin:i,...s},i),a=await e.create(o.options),c=await this.postConfirmed("auth/passkey/register/finish",{challengeId:o.challengeId,registration:a,...s},e);return this.useSession(c),c}signUpPolicy(){return this.get("sign-up")}async signIn(e,t={}){let n=this.pageOrigin(t),i=await this.begin("auth/passkey/login/begin",n===void 0?void 0:{origin:n},n),s=i.options.rpId??i.options.rp?.id??"",o=await e.get(I(i.options.challenge),s),a=await this.post("auth/passkey/login/finish",{challengeId:i.challengeId,assertion:o});return this.useSession(a),a}pageOrigin(e){if(e.origin!==void 0)return e.origin??void 0;let t=globalThis.location?.origin;return!t||t==="null"||new Set(this.nodeUrls.map(i=>{try{return new URL(i).origin}catch{return i}})).has(t)?void 0:t}async begin(e,t,n){try{return await this.post(e,t)}catch(i){throw i instanceof K&&!i.origin&&n!==void 0?new K(i.nodeMessage,{...i.details,origin:n}):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/${l(e)}`,t)}async labelPasskey(e,t){await this.post(`auth/passkeys/${l(e)}`,{label:t})}usage(){return this.get("auth/usage")}async attestation(){let e=Wt(crypto.getRandomValues(new Uint8Array(32))),t=await this.raw(`${this.nodeUrl}/attestation?nonce=${e}`);if(!t.ok)throw await gt(t);return await t.json()}async listApiKeys(){let{keys:e}=await this.get("auth/apikeys");return e}async revokeApiKey(e,t){await this.deleteConfirmed(`auth/apikeys/${l(e)}`,t)}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,n={}){let i=(typeof n=="string"?n:n.contentType)??"application/octet-stream";return this.json("POST",`apps/${l(e)}/blobs`,void 0,t,i)}async downloadBlob(e,t){return(await this.blobContent(e,t)).data}async downloadBlobGranted(e,t,n){return(await this.blobContent(e,t,{grant:n})).data}async blobContent(e,t,n={}){let i=n.grant===void 0?"":`?grant=${encodeURIComponent(n.grant)}`,s=await this.send("GET",`apps/${l(e)}/blobs/${l(t)}${i}`);return{data:new Uint8Array(await s.arrayBuffer()),contentType:s.headers.get("content-type")??"application/octet-stream"}}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})}appXcalls(e){return this.get(`apps/${l(e)}/xcalls`)}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 Z)||!i)throw o;let a=o.details,c;try{c=await i.get(I(a.challenge),a.rpId,a.allowCredentials)}catch(d){let u=d?.name;throw u==="NotAllowedError"||u==="AbortError"?new oe(d):d}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??er();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??er();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/${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*Vn(n.body)}async publishPresence(e,t,n){await this.post(`apps/${l(e)}/presence`,{seq:t,state:n===null?null:Wt(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}${le(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 ut(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 dt(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${le(e)}`)}opsOrgs(e={}){return this.get(`ops/orgs${le(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,i){await this.postConfirmed(`orgs/${l(e)}/members`,{account:t,role:n},i)}removeMember(e,t,n){return this.deleteConfirmed(`orgs/${l(e)}/members/${l(t)}`,n)}async setCapabilities(e,t,n,i={}){await this.postConfirmed(`orgs/${l(e)}/capabilities`,{capabilities:t,...i},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,s={}){await this.postConfirmed(`orgs/${l(e)}/teams/${l(t)}/members`,{account:n,...s},i)}async removeTeamMember(e,t,n,i){await this.deleteConfirmed(`orgs/${l(e)}/teams/${l(t)}/members/${l(n)}`,i)}async invite(e,t,n,i=[],s={}){let{token:o}=await this.postConfirmed(`orgs/${l(e)}/invites`,{role:t,teams:i,...s},n);return o}redeemInvite(e){return this.post(`invites/${l(e)}/redeem`)}grantDeployer(e,t,n={}){let i=n.until instanceof Date?n.until.toISOString():n.until;return this.postConfirmed("deployers",{deployer:e,...i===void 0?{}:{until:i}},t)}deployers(){return this.get("deployers")}async revokeDeployer(e,t){let n=typeof e=="string"?e:rr(e);await this.deleteConfirmed(`deployers/${l(n)}`,t)}async createDeployment(e,t,n){let{id:i}=await this.postConfirmed("deployments",{name:e,owner:t},n);return i}async deployments(){let{deployments:e}=await this.get("deployments");return e}deployment(e){return this.get(`deployments/${l(e)}`)}async deleteDeployment(e,t){await this.deleteConfirmed(`deployments/${l(e)}`,t)}offerApp(e,t,n){return this.postConfirmed(`deployments/${l(e)}/apps`,{...t},n)}async withdrawApp(e,t,n){await this.deleteConfirmed(`deployments/${l(e)}/apps/${l(t)}`,n)}deploymentOrgs(e){return this.get(`deployments/${l(e)}/orgs`)}};var ft={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},Hn=ft.JOIN_OPEN_TEAMS;function Gn(...r){return r.reduce((e,t)=>e|ft[t],0)}function Ne(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]=Ne(r[i]^r[e],16),r[n]=r[n]+r[i]>>>0,r[t]=Ne(r[t]^r[n],12),r[e]=r[e]+r[t]>>>0,r[i]=Ne(r[i]^r[e],8),r[n]=r[n]+r[i]>>>0,r[t]=Ne(r[t]^r[n],7)}function nr(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0}function or(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]=nr(r,o*4);n[12]=e>>>0;for(let o=0;o<3;o+=1)n[13+o]=nr(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 jn(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=or(r,o,t),c=Math.min(s+64,n.length);for(let d=s;d<c;d+=1)i[d]=n[d]^a[d-s]}return i}function yt(r){let e=0n;for(let t=r.length-1;t>=0;t-=1)e=e<<8n|BigInt(r[t]);return e}var qn=(1n<<130n)-5n;function Qn(r,e){let t=yt(r.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,n=yt(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)),d=yt(c)+(1n<<BigInt(8*c.length));i=(i+d)*t%qn}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 ir(r){return new Uint8Array((16-r%16)%16)}function sr(r){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(r),!0),e}function Jn(r,e){let t=[r,ir(r.length),e,ir(e.length),sr(r.length),sr(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 zn(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 ar(r,e,t,n=new Uint8Array(0)){zn(r,e);let i=or(r,0,e).subarray(0,32),s=jn(r,1,e,t),o=Qn(i,Jn(n,s)),a=new Uint8Array(s.length+16);return a.set(s),a.set(o,s.length),a}var lr=32,Yn=1,Zn=3,Xn=2,Wn=32,ei=32,ti=12,X=r=>new TextEncoder().encode(r),ue=r=>new Uint8Array([r>>8&255,r&255]),cr=y(X("KEM"),ue(lr)),de=y(X("HPKE"),ue(lr),ue(Yn),ue(Zn));async function dr(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 ri(r,e,t){let n=new Uint8Array(t),i=new Uint8Array(0);for(let s=1,o=0;o<t;s+=1)i=await dr(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 Me(r,e,t,n){return dr(e,y(X("HPKE-v1"),r,X(t),n))}function ht(r,e,t,n,i){return ri(e,y(ue(i),X("HPKE-v1"),r,X(t),n),i)}async function ni(r,e){let t=await Me(cr,new Uint8Array(0),"eae_prk",r);return ht(cr,t,"shared_secret",e,Wn)}async function ii(r,e){let t=new Uint8Array(0),n=await Me(de,t,"psk_id_hash",t),i=await Me(de,t,"info_hash",e),s=y(new Uint8Array([Xn]),n,i),o=await Me(de,r,"secret",t);return{key:await ht(de,o,"key",s,ei),nonce:await ht(de,o,"base_nonce",s,ti)}}async function ur(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 j(s),a=await j(e),c=y(await ee(o.privateKey,r),await ee(a.privateKey,r)),d=await ni(c,y(o.publicKey,r,a.publicKey)),{key:u,nonce:g}=await ii(d,t);return{enc:o.publicKey,ciphertext:ar(u,g,n,i)}}var fr="mero-agent-gate/attest/v3",yr="mero-agent-gate/provision/v2",si=/^[a-z0-9][a-z0-9-]{0,62}$/,oi=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,gr=64,pr=64*1024,D=class extends Error{constructor(t,n,i){super(t);this.status=n;this.code=i;this.name="AgentGateError"}};function hr(r){if(!si.test(r))throw new Error(`Agent id ${JSON.stringify(r)} must match [a-z0-9][a-z0-9-]{0,62}`)}function ge(r){return new TextEncoder().encode(r)}function mr(r){let e=ge(r);return y(new Uint8Array([e.length]),e)}function L(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}function _e(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 wr(r,e,t,n){let i=new Uint8Array(32),s=y(ge(fr),r,mr(e),t??i,n??i);return new Uint8Array(await crypto.subtle.digest("SHA-256",s))}function Ar(r,e){return y(ge(yr),r,mr(e))}async function ai(){let r=crypto.getRandomValues(new Uint8Array(32));return{secret:r,publicKey:await $e(r)}}async function $e(r){if(r.length!==32)throw new Error("An owner key is 32 bytes");return L((await j(r)).publicKey)}function br(r,e){return`${r.replace(/\/+$/,"")}${e}`}async function Er(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 mt(r){let e=r.agentId??"";e&&hr(e);let t=crypto.getRandomValues(new Uint8Array(32)),n=await Er(r.fetch??fetch,br(r.gateUrl,"/attest"),{nonceB64:L(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=_e(n.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),s=n.signingPublicKeyB64?_e(n.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,o=n.ownerPublicKeyB64?_e(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 wr(i,e,s,o);return await r.verifier({quoteB64:n.quoteB64,nonce:R(t),reportDataSuffix:R(a)}),{agentId:e,provisioningPublicKey:L(i),...s?{signingPublicKey:L(s)}:{},...o?{ownerPublicKey:L(o)}:{}}}async function Rr(r,e){let t=await $e(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 ci(r){let e=Object.keys(r);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>gr)throw new Error(`At most ${gr} secrets at once`);for(let t of e){if(!oi.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(ge(r[t]).length>pr)throw new Error(`Secret ${t} is over ${pr} bytes`)}}async function Pr(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 Rr(n,i),a=_e(n.provisioningPublicKey,"provisioningPublicKey",32),c=await ur(a,i,Ar(a,n.agentId),ge(JSON.stringify(s)));return Er(r,br(e,t),{agentId:n.agentId,provisioningPublicKeyB64:n.provisioningPublicKey,senderPublicKeyB64:o,encappedKeyB64:L(c.enc),ciphertextB64:L(c.ciphertext)})}async function li(r){ci(r.secrets);let e=r.fetch??fetch,t=await Pr(e,r.gateUrl,"/provision",r.agent,r.ownerSecret,{secrets:r.secrets}),n=await mt({gateUrl:r.gateUrl,agentId:r.agent.agentId,verifier:r.verifier,fetch:e}),i=await $e(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 di(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 Pr(e,r.gateUrl,"/release",r.agent,r.ownerSecret,{release:!0}),(await mt({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 wt=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),ui=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function gi(r,e,t={}){let n=typeof r=="string"?new TextEncoder().encode(r):r;await we(n,e,{identity:t.identity??wt.identity,issuer:t.issuer??wt.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 xr(i),i}function xr(r){for(let e of ui)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 pi=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function fi(r){let e=pi.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 pe=r=>r.trim().replace(/^0x/i,"");function yi(r,e){return xr(r),$({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:r.allowed_tcb_statuses.map(fi),allowedMrtd:r.allowed_mrtd.map(pe),allowedRtmr0:r.allowed_rtmr0.map(pe),allowedRtmr1:r.allowed_rtmr1.map(pe),allowedRtmr2:r.allowed_rtmr2.map(pe),allowedRtmr3:r.allowed_rtmr3.map(pe)})}export{fr as AGENT_ATTEST_DOMAIN,yr as AGENT_PROVISION_INFO_DOMAIN,D as AgentGateError,Ce as AppError,Re as ArgsTooLarge,Te as BadOrigin,pt as CalimeroClient,w as CalimeroError,oe as ConfirmCancelled,Z as ConfirmRequired,Ue as ConsentStale,We as DEFAULT_COLLATERAL_MIRROR,ot as DEFAULT_DIRECTORY,Hn as DEFAULT_ORG_CAPABILITIES,Ae as DEFAULT_RELEASE_MIRROR,T as DirectoryError,Kt as GITHUB_RELEASES,Ut as HANDSHAKE_PATH,Pe as IdempotencyMismatch,wt as KMS_RELEASE_SIGNER,Y as LoginRequired,lt as MAX_REPORT_PAGE,Ft as MOCK_QUOTE_HEADER,Xe as NODE_RELEASE_SIGNER,Ee as NotFound,ft as ORG_CAPABILITIES,K as OriginNotRegistered,ke as OriginTaken,_ as PRODUCTION_PROFILE,ve as QuotaExceeded,zt as RELEASE_VERIFIER,xe as ReleaseDeadlineError,re as SEALED_CONTENT_TYPE,Tt as SEALED_PATH,S as SealedTransportError,Se as SignUpRefused,ne as StaleTransportKeyError,Ie as TrapError,V as UnavailableError,B as WrongNode,wr as agentKeyBinding,yi as agentQuoteVerifier,mt as attestAgent,k as b64url,In as browserPasskey,Rr as checkOwner,Ht as claimedRelease,rt as cloudNodeReleaseUrl,ce as compareVersions,dt as confirmationCode,Nn as consentReturn,$ as createQuoteVerifier,Qe as createSealedFetch,En as createSignedReleaseVerifier,rr as deployerKey,De as errorFrom,st as fetchAttestedKey,tt as fetchGithubNodeRelease,et as fetchNodeRelease,Gt as freshCollateral,I as fromB64url,$n as frontendManifest,ai as generateOwnerKey,Gn as orgCapabilities,$e as ownerPublicKey,Bn as pageDeployment,le as pageQuery,ut as pendingApprovalsFrom,li as provisionAgent,Ar as provisionInfo,On as publisherBindingBytes,Jt as publisherBindingMessage,di as releaseAgent,Xt as releaseConsent,Yt as releaseNotesUrl,Qt as stalledBy,qe as transportKeyBinding,be as trustSignedRelease,Ze as trustedMeasurementsFromReleases,_n as upgradeConsent,hr as validateAgentId,Zt as verifyReleaseUrl,gi as verifySignedAgentPolicy,Bt as verifySignedNodeRelease,Mn as withdrawConsent};
9
9
  //# sourceMappingURL=index.browser.mjs.map