@calimero-network/mero-js 29.7.7 → 29.8.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 +1 -1
- package/dist/cloud-v2/client.d.ts +160 -3
- package/dist/cloud-v2/client.js +65 -2
- package/dist/cloud-v2/index.d.ts +1 -1
- package/dist/index.browser.mjs +1 -1
- package/dist/index.browser.mjs.map +3 -3
- package/dist/index.cjs +61 -2
- package/dist/index.cjs.map +2 -2
- package/dist/index.mjs +61 -2
- package/dist/index.mjs.map +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -104,7 +104,7 @@ Pinned measurements go through `policy.verifyQuote` (`createQuoteVerifier`).
|
|
|
104
104
|
- **Apps**: `createApp`, `listApps`, `getApp`, `deleteApp`, `setAccess`, `setAppMetadata`, `appStorage`, `appAbi`, `upgradeApp`, `transferApp`.
|
|
105
105
|
- **Calls**: `call`, `callConfirmed`, `view`, `events`. A call always carries an idempotency key, and is sent again with it while the node answers `503`, then to the next node.
|
|
106
106
|
- **Blobs and presence**: `uploadBlob`, `downloadBlob`, `listBlobs`, `blobInfo`, `deleteBlob`; `publishPresence`, `presence`, `presenceStream`.
|
|
107
|
-
- **Organizations**: `createOrg`, `getOrg`, `deleteOrg`, `setOrgMetadata`, `setMember`, `removeMember`, `setMemberMetadata`, `setCapabilities` (`ORG_CAPABILITIES`), teams, `invite`, `redeemInvite`, recovery (`setRecoveryKey`, `startRecovery`, `cancelRecovery`, `finishRecovery`; `newRecoverySeed`, `recoveryPublicKey`). Setting or removing a member or team member, capabilities and
|
|
107
|
+
- **Organizations**: `createOrg`, `getOrg`, `deleteOrg`, `setOrgMetadata`, `setMember`, `removeMember`, `setMemberMetadata`, `setCapabilities` (`ORG_CAPABILITIES`), `setTeamDefaultCapabilities`, teams, app teams (`listAppTeams`, `scopeApps`), `invite`, `redeemInvite`, `listInvites`, `revokeInvite`, recovery (`setRecoveryKey`, `startRecovery`, `cancelRecovery`, `finishRecovery`; `newRecoverySeed`, `recoveryPublicKey`). Setting or removing a member or team member, capabilities, invites (minting and revoking) and scoping apps are approved with the caller's passkey; redeeming an invite is not.
|
|
108
108
|
- **Owner decisions** (passkey approval, never from an app's frontend): `upgradeOrg`, `upgradeRun`, `retryUpgradeRun`, `approveRelease`, `approveOutbound`, `bindPublisher`, `upgradePublished`.
|
|
109
109
|
- **Approvals from an app**: `appsReport`, `releaseRules`, `pendingApprovals`, then `requestConsent` / `openConsentPage` to send the user to the node's consent page, and `consentResult`. Show the answer's `code` to the user before sending them to `url` (`openConsentPage`'s `confirm` hook); they should see the same code on the page (`confirmationCode(requestId)` checks it). See [Ask your users to approve node images and app upgrades](https://calimero-network.github.io/mero-js/guides/user-approvals/).
|
|
110
110
|
- **Operator** (ops token): `opsApps`, `opsOrgs`, `opsServedOrigins` (every custom domain the log holds, by package label), `setReleaseDeadline`, `liftReleaseDeadline`.
|
|
@@ -133,6 +133,119 @@ export interface OrgInfo extends Record<string, unknown> {
|
|
|
133
133
|
} | null;
|
|
134
134
|
/** The recovery key and any recovery under way; absent while the organization has none. */
|
|
135
135
|
recovery?: OrgRecovery;
|
|
136
|
+
/** How it holds its apps ({@link OrgMode}); absent from nodes before app teams. */
|
|
137
|
+
mode?: OrgMode;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* How an organization holds its apps, derived from its app teams (core
|
|
141
|
+
* `OrgMode`): `legacy` has none (its apps use organization access),
|
|
142
|
+
* `standalone` has only open ones (everyone has every app), `shared` has a
|
|
143
|
+
* closed one (each app lists who is in it).
|
|
144
|
+
*/
|
|
145
|
+
export type OrgMode = 'legacy' | 'standalone' | 'shared';
|
|
146
|
+
/** One app team, as `GET /orgs/{org}/app-teams` lists it ({@link CalimeroClient.listAppTeams}). */
|
|
147
|
+
export interface AppTeam {
|
|
148
|
+
/** The package this team is the app team of (one per package per organization). */
|
|
149
|
+
package: string;
|
|
150
|
+
teamId: string;
|
|
151
|
+
name: string;
|
|
152
|
+
/** `everyone` (open) or `invite` (closed). */
|
|
153
|
+
join: 'everyone' | 'invite';
|
|
154
|
+
/** How many of the organization's people are in the team. */
|
|
155
|
+
memberCount: number;
|
|
156
|
+
/** Capability bits everyone in the team holds there ({@link ORG_CAPABILITIES}); `null` when unset. */
|
|
157
|
+
defaultCapabilities: number | null;
|
|
158
|
+
/** Whether the caller is in the team. */
|
|
159
|
+
member: boolean;
|
|
160
|
+
/** Whether the caller manages it (its lead, an ancestor's lead, or an admin). */
|
|
161
|
+
manages: boolean;
|
|
162
|
+
}
|
|
163
|
+
/** `GET /orgs/{org}/app-teams`: the organization's mode and its app teams. A guest sees only the app teams they are in. */
|
|
164
|
+
export interface AppTeams {
|
|
165
|
+
mode: OrgMode;
|
|
166
|
+
appTeams: AppTeam[];
|
|
167
|
+
}
|
|
168
|
+
/** One package to give an app team ({@link CalimeroClient.scopeApps}, core `ScopeApp`). */
|
|
169
|
+
export interface ScopeApp {
|
|
170
|
+
package: string;
|
|
171
|
+
/** The team's name when one is made, 1..64 characters (absent: the package's display name, else the package id). */
|
|
172
|
+
name?: string;
|
|
173
|
+
/**
|
|
174
|
+
* The instances to move onto the team (absent: every organization-access
|
|
175
|
+
* instance of the package here; `[]`: none, for a fresh install).
|
|
176
|
+
*/
|
|
177
|
+
instances?: string[];
|
|
178
|
+
}
|
|
179
|
+
/** What {@link CalimeroClient.scopeApps} asks for; every field absent takes the node's default. */
|
|
180
|
+
export interface ScopeAppsOptions {
|
|
181
|
+
/** At most 64 packages (absent: every package with an organization-access instance here). */
|
|
182
|
+
apps?: ScopeApp[];
|
|
183
|
+
/** Close every app team (absent: when the organization then holds two or more). */
|
|
184
|
+
shared?: boolean;
|
|
185
|
+
}
|
|
186
|
+
/** One package's app team after {@link CalimeroClient.scopeApps}. */
|
|
187
|
+
export interface ScopedAppTeam {
|
|
188
|
+
package: string;
|
|
189
|
+
teamId: string;
|
|
190
|
+
/** Whether the team was made now (`false`: it existed already). */
|
|
191
|
+
created: boolean;
|
|
192
|
+
/** The instances moved onto it. */
|
|
193
|
+
apps: string[];
|
|
194
|
+
/** How many rows were added for people who reached those instances. */
|
|
195
|
+
added: number;
|
|
196
|
+
}
|
|
197
|
+
/** `POST /orgs/{org}/app-teams`: the organization's mode after, and each package's team. */
|
|
198
|
+
export interface ScopeAppsResult {
|
|
199
|
+
mode: OrgMode;
|
|
200
|
+
teams: ScopedAppTeam[];
|
|
201
|
+
}
|
|
202
|
+
/** A pending organization invite, as `GET /orgs/{org}/invites` lists it (never its token). */
|
|
203
|
+
export interface OrgInvite {
|
|
204
|
+
/** The invite's key, which {@link CalimeroClient.revokeInvite} takes. */
|
|
205
|
+
inviteKey: string;
|
|
206
|
+
role: 'guest' | 'member' | 'admin';
|
|
207
|
+
/** The teams it adds its holder to. */
|
|
208
|
+
teams: string[];
|
|
209
|
+
usesLeft: number;
|
|
210
|
+
/** Unix seconds. */
|
|
211
|
+
expiresAt: number;
|
|
212
|
+
/** Listed until revoked, even past `expiresAt`. */
|
|
213
|
+
expired: boolean;
|
|
214
|
+
/** The account that made it; `null` for invites made before core recorded it. */
|
|
215
|
+
createdBy: string | null;
|
|
216
|
+
/** Unix seconds; `null` for invites made before core recorded it. */
|
|
217
|
+
createdAt: number | null;
|
|
218
|
+
}
|
|
219
|
+
/** One direct row of a team ({@link TeamInfo}). */
|
|
220
|
+
export interface TeamMemberInfo {
|
|
221
|
+
account: string;
|
|
222
|
+
role: 'lead' | 'member' | 'readOnly';
|
|
223
|
+
/** Their effective bits there: their row's own, else the organization's with the team's default on top. */
|
|
224
|
+
capabilities: number;
|
|
225
|
+
}
|
|
226
|
+
/** `GET /orgs/{org}/teams/{team}` ({@link CalimeroClient.getTeam}). */
|
|
227
|
+
export interface TeamInfo extends Record<string, unknown> {
|
|
228
|
+
teamId: string;
|
|
229
|
+
name: string;
|
|
230
|
+
parent: string | null;
|
|
231
|
+
join: 'everyone' | 'invite';
|
|
232
|
+
metadata: unknown;
|
|
233
|
+
/** The package it is the app team of (`metadata.app.package` on a top-level team), else `null`. */
|
|
234
|
+
package?: string | null;
|
|
235
|
+
/** Capability bits everyone in the team holds there on top of their own; `null` when unset. */
|
|
236
|
+
defaultCapabilities?: number | null;
|
|
237
|
+
members: TeamMemberInfo[];
|
|
238
|
+
/** The child teams the caller sees. */
|
|
239
|
+
children: string[];
|
|
240
|
+
apps: Array<{
|
|
241
|
+
appId: string;
|
|
242
|
+
name: string;
|
|
243
|
+
contextId: string;
|
|
244
|
+
}>;
|
|
245
|
+
/** The caller's direct row's role, if any. */
|
|
246
|
+
myRole: 'lead' | 'member' | 'readOnly' | null;
|
|
247
|
+
/** Whether the caller is in the team. */
|
|
248
|
+
member: boolean;
|
|
136
249
|
}
|
|
137
250
|
/** An organization's recovery key (core `Org::recovery`). */
|
|
138
251
|
export interface OrgRecovery {
|
|
@@ -1112,15 +1225,30 @@ export declare class CalimeroClient {
|
|
|
1112
1225
|
removeMember(org: string, account: string, passkey: PasskeyProvider): Promise<Record<string, unknown>>;
|
|
1113
1226
|
/**
|
|
1114
1227
|
* Set capability bits ({@link ORG_CAPABILITIES}): for a member (`account`),
|
|
1115
|
-
* for a member of one team (`account` and `team`),
|
|
1116
|
-
*
|
|
1228
|
+
* for a member of one team (`account` and `team`), a team's default
|
|
1229
|
+
* (`team` alone, {@link setTeamDefaultCapabilities}), or the
|
|
1230
|
+
* organization's default (neither). Approved with the caller's `passkey`.
|
|
1117
1231
|
*/
|
|
1118
1232
|
setCapabilities(org: string, capabilities: number, passkey: PasskeyProvider, at?: {
|
|
1119
1233
|
account?: string;
|
|
1120
1234
|
team?: string;
|
|
1121
1235
|
}): Promise<void>;
|
|
1236
|
+
/**
|
|
1237
|
+
* Set the capability bits everyone in `team` holds there on top of their
|
|
1238
|
+
* own, unless their row sets its own (`POST /orgs/{org}/capabilities` with
|
|
1239
|
+
* `team` and no `account`): `ORG_CAPABILITIES.INVITE_MEMBERS` is "members
|
|
1240
|
+
* may invite others to this app". The team's managers, or whoever holds
|
|
1241
|
+
* `MANAGE_MEMBERS` on it; approved with the caller's `passkey`
|
|
1242
|
+
* (`__set_default_capabilities { team, capabilities }`).
|
|
1243
|
+
*/
|
|
1244
|
+
setTeamDefaultCapabilities(org: string, team: string, capabilities: number, passkey: PasskeyProvider): Promise<void>;
|
|
1122
1245
|
createTeam(org: string, name: string, join: 'everyone' | 'invite', parent?: string): Promise<string>;
|
|
1123
|
-
|
|
1246
|
+
/**
|
|
1247
|
+
* A team the caller sees: its rows (each with its effective capabilities),
|
|
1248
|
+
* children, apps, the package it is the app team of and its default
|
|
1249
|
+
* capabilities.
|
|
1250
|
+
*/
|
|
1251
|
+
getTeam(org: string, team: string): Promise<TeamInfo>;
|
|
1124
1252
|
/**
|
|
1125
1253
|
* Rename, change who may join, set the app's metadata, or move the team:
|
|
1126
1254
|
* `parent: null` moves it to the top, an absent `parent` leaves it.
|
|
@@ -1154,6 +1282,35 @@ export declare class CalimeroClient {
|
|
|
1154
1282
|
uses?: number;
|
|
1155
1283
|
}): Promise<string>;
|
|
1156
1284
|
redeemInvite(token: string): Promise<Record<string, unknown>>;
|
|
1285
|
+
/**
|
|
1286
|
+
* The organization's pending invites the caller may see (never a token):
|
|
1287
|
+
* every one for an owner or admin, their own, and those naming only teams
|
|
1288
|
+
* they manage. Expired ones are listed (`expired: true`) until revoked. A
|
|
1289
|
+
* caller outside the organization: {@link NotFound}.
|
|
1290
|
+
*/
|
|
1291
|
+
listInvites(org: string): Promise<OrgInvite[]>;
|
|
1292
|
+
/**
|
|
1293
|
+
* Withdraw an invite by its key ({@link listInvites}), approved with the
|
|
1294
|
+
* caller's `passkey` (`__revoke_invite { inviteKey }`). One the caller may
|
|
1295
|
+
* not see: {@link NotFound}.
|
|
1296
|
+
*/
|
|
1297
|
+
revokeInvite(org: string, inviteKey: string, passkey: PasskeyProvider): Promise<void>;
|
|
1298
|
+
/**
|
|
1299
|
+
* The organization's mode and its app teams (one per package), for any
|
|
1300
|
+
* member; a guest sees only those they are in. A caller outside the
|
|
1301
|
+
* organization: {@link NotFound}.
|
|
1302
|
+
*/
|
|
1303
|
+
listAppTeams(org: string): Promise<AppTeams>;
|
|
1304
|
+
/**
|
|
1305
|
+
* Give apps their own access lists in one step (owner or admin): find or
|
|
1306
|
+
* make each package's app team, add everyone who reaches its instances now,
|
|
1307
|
+
* and move those instances onto it; with `shared`, close every app team.
|
|
1308
|
+
* Idempotent per package. Approved with the caller's `passkey`
|
|
1309
|
+
* (`__scope_apps { apps, shared }`); a refusal is `400 REJECTED` with the
|
|
1310
|
+
* node's reason. For a fresh standalone install pass
|
|
1311
|
+
* `{ apps: [{ package, name, instances: [] }] }`.
|
|
1312
|
+
*/
|
|
1313
|
+
scopeApps(org: string, passkey: PasskeyProvider, options?: ScopeAppsOptions): Promise<ScopeAppsResult>;
|
|
1157
1314
|
/**
|
|
1158
1315
|
* The web origins `{package}`'s managers registered so a frontend they host
|
|
1159
1316
|
* themselves can sign users in with passkeys ({@link PackageOrigins}).
|
package/dist/cloud-v2/client.js
CHANGED
|
@@ -1339,16 +1339,33 @@ export class CalimeroClient {
|
|
|
1339
1339
|
}
|
|
1340
1340
|
/**
|
|
1341
1341
|
* Set capability bits ({@link ORG_CAPABILITIES}): for a member (`account`),
|
|
1342
|
-
* for a member of one team (`account` and `team`),
|
|
1343
|
-
*
|
|
1342
|
+
* for a member of one team (`account` and `team`), a team's default
|
|
1343
|
+
* (`team` alone, {@link setTeamDefaultCapabilities}), or the
|
|
1344
|
+
* organization's default (neither). Approved with the caller's `passkey`.
|
|
1344
1345
|
*/
|
|
1345
1346
|
async setCapabilities(org, capabilities, passkey, at = {}) {
|
|
1346
1347
|
await this.postConfirmed(`orgs/${seg(org)}/capabilities`, { capabilities, ...at }, passkey);
|
|
1347
1348
|
}
|
|
1349
|
+
/**
|
|
1350
|
+
* Set the capability bits everyone in `team` holds there on top of their
|
|
1351
|
+
* own, unless their row sets its own (`POST /orgs/{org}/capabilities` with
|
|
1352
|
+
* `team` and no `account`): `ORG_CAPABILITIES.INVITE_MEMBERS` is "members
|
|
1353
|
+
* may invite others to this app". The team's managers, or whoever holds
|
|
1354
|
+
* `MANAGE_MEMBERS` on it; approved with the caller's `passkey`
|
|
1355
|
+
* (`__set_default_capabilities { team, capabilities }`).
|
|
1356
|
+
*/
|
|
1357
|
+
async setTeamDefaultCapabilities(org, team, capabilities, passkey) {
|
|
1358
|
+
await this.postConfirmed(`orgs/${seg(org)}/capabilities`, { team, capabilities }, passkey);
|
|
1359
|
+
}
|
|
1348
1360
|
async createTeam(org, name, join, parent) {
|
|
1349
1361
|
const { teamId } = await this.post(`orgs/${seg(org)}/teams`, { name, join, parent });
|
|
1350
1362
|
return teamId;
|
|
1351
1363
|
}
|
|
1364
|
+
/**
|
|
1365
|
+
* A team the caller sees: its rows (each with its effective capabilities),
|
|
1366
|
+
* children, apps, the package it is the app team of and its default
|
|
1367
|
+
* capabilities.
|
|
1368
|
+
*/
|
|
1352
1369
|
getTeam(org, team) {
|
|
1353
1370
|
return this.get(`orgs/${seg(org)}/teams/${seg(team)}`);
|
|
1354
1371
|
}
|
|
@@ -1386,6 +1403,52 @@ export class CalimeroClient {
|
|
|
1386
1403
|
redeemInvite(token) {
|
|
1387
1404
|
return this.post(`invites/${seg(token)}/redeem`);
|
|
1388
1405
|
}
|
|
1406
|
+
/**
|
|
1407
|
+
* The organization's pending invites the caller may see (never a token):
|
|
1408
|
+
* every one for an owner or admin, their own, and those naming only teams
|
|
1409
|
+
* they manage. Expired ones are listed (`expired: true`) until revoked. A
|
|
1410
|
+
* caller outside the organization: {@link NotFound}.
|
|
1411
|
+
*/
|
|
1412
|
+
async listInvites(org) {
|
|
1413
|
+
const { invites } = await this.get(`orgs/${seg(org)}/invites`);
|
|
1414
|
+
return invites;
|
|
1415
|
+
}
|
|
1416
|
+
/**
|
|
1417
|
+
* Withdraw an invite by its key ({@link listInvites}), approved with the
|
|
1418
|
+
* caller's `passkey` (`__revoke_invite { inviteKey }`). One the caller may
|
|
1419
|
+
* not see: {@link NotFound}.
|
|
1420
|
+
*/
|
|
1421
|
+
async revokeInvite(org, inviteKey, passkey) {
|
|
1422
|
+
await this.deleteConfirmed(`orgs/${seg(org)}/invites/${seg(inviteKey)}`, passkey);
|
|
1423
|
+
}
|
|
1424
|
+
// ---------------------------------------------------------------- app teams
|
|
1425
|
+
/**
|
|
1426
|
+
* The organization's mode and its app teams (one per package), for any
|
|
1427
|
+
* member; a guest sees only those they are in. A caller outside the
|
|
1428
|
+
* organization: {@link NotFound}.
|
|
1429
|
+
*/
|
|
1430
|
+
listAppTeams(org) {
|
|
1431
|
+
return this.get(`orgs/${seg(org)}/app-teams`);
|
|
1432
|
+
}
|
|
1433
|
+
/**
|
|
1434
|
+
* Give apps their own access lists in one step (owner or admin): find or
|
|
1435
|
+
* make each package's app team, add everyone who reaches its instances now,
|
|
1436
|
+
* and move those instances onto it; with `shared`, close every app team.
|
|
1437
|
+
* Idempotent per package. Approved with the caller's `passkey`
|
|
1438
|
+
* (`__scope_apps { apps, shared }`); a refusal is `400 REJECTED` with the
|
|
1439
|
+
* node's reason. For a fresh standalone install pass
|
|
1440
|
+
* `{ apps: [{ package, name, instances: [] }] }`.
|
|
1441
|
+
*/
|
|
1442
|
+
scopeApps(org, passkey, options = {}) {
|
|
1443
|
+
// The node refuses unknown fields and reads an absent one as its default,
|
|
1444
|
+
// so only the fields given go.
|
|
1445
|
+
const body = {};
|
|
1446
|
+
if (options.apps !== undefined)
|
|
1447
|
+
body.apps = options.apps;
|
|
1448
|
+
if (options.shared !== undefined)
|
|
1449
|
+
body.shared = options.shared;
|
|
1450
|
+
return this.postConfirmed(`orgs/${seg(org)}/app-teams`, body, passkey);
|
|
1451
|
+
}
|
|
1389
1452
|
// ---------------------------------------------------------------- deployers
|
|
1390
1453
|
/**
|
|
1391
1454
|
* Let an account or organization install apps where the cluster's
|
package/dist/cloud-v2/index.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ export { DEFAULT_DIRECTORY, DirectoryError } from './directory.js';
|
|
|
3
3
|
export type { DirectoryFailure } from './directory.js';
|
|
4
4
|
export { AppError, ArgsTooLarge, BadOrigin, CalimeroError, ClusterNotUpgraded, ConfirmCancelled, ConfirmPromptBlocked, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, NotFound, NotServing, OriginNotRegistered, OriginTaken, PasskeyUnknownHere, QuotaExceeded, RecoveryNotReady, ReleaseDeadlineError, SignUpRefused, TrapError, UnavailableError, WrongNode, WrongRecoveryCode, errorFrom, } from './errors.js';
|
|
5
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, ServedOrigin, ServedOrigins, SignInOptions, AccountRecovery, SignUpOptions, SignUpPolicy, PublicDeployment, CallResult, CalimeroClientOptions, CalimeroConnectOptions, CloudEvent, CalimeroSession, PackageInfo, PackageInstalled, CloudRetryOptions, OrgInfo, OrgRecovery, RecoveryTimes, OrgUpgradeTarget, PresenceEntry, UpgradeRun, ViewResult, } from './client.js';
|
|
6
|
+
export type { AppInfo, AppTeam, AppTeams, AppXcalls, BlobContent, BlobInfo, DeadLetter, Deployer, DeployerGrant, DeployersInfo, DeploymentInfo, DeploymentOffer, DeploymentOrgs, FrontendManifest, MeInfo, PackageOrigin, PackageOriginAdded, PackageOriginRemoved, PackageOrigins, ServedOrigin, ServedOrigins, SignInOptions, AccountRecovery, SignUpOptions, SignUpPolicy, PublicDeployment, CallResult, CalimeroClientOptions, CalimeroConnectOptions, CloudEvent, CalimeroSession, PackageInfo, PackageInstalled, CloudRetryOptions, OrgInfo, OrgInvite, OrgMode, OrgRecovery, RecoveryTimes, OrgUpgradeTarget, PresenceEntry, ScopeApp, ScopeAppsOptions, ScopeAppsResult, ScopedAppTeam, TeamInfo, TeamMemberInfo, 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';
|
package/dist/index.browser.mjs
CHANGED
|
@@ -5,5 +5,5 @@ ${r}
|
|
|
5
5
|
${n}`}function Xn(t,e,r,n){return new TextEncoder().encode(lt(t,e,r,n))}var Wn="0123456789ABCDEFGHJKMNPQRSTVWXYZ";async function br(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t))),r=(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0,n="";for(let i=0;i<6;i++)i===3&&(n+="-"),n+=Wn[r>>>27-5*i&31];return n}function ei(t){let e=typeof t=="string"?new URL(t):t,r=e.searchParams.get("request_id"),n=e.searchParams.get("result");return!r||n!=="approved"&&n!=="declined"?null:{requestId:r,result:n}}var dt="https://mero-tee.vercel.app";function ut(t){return`https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(t)}`}function gt(t){return`${dt}/mero-tee?release_tag=${encodeURIComponent(`mero-tee-v${t}`)}`}function Er(t,e,r=Date.now()/1e3){let n=c=>e.deadlines.find(d=>d.version===c)??null,i=t.governance.releases==="owner",s=t.governance.appUpgrades==="owner",o=t.clusterReleases.filter(c=>!c.approved).sort((c,d)=>de(d.release,c.release)).map(c=>({version:c.release,nodes:c.nodes,actionable:i,releaseNotesUrl:ut(c.release),verifyUrl:gt(c.release),deadline:n(c.release)})),a=[];for(let c of t.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:t.scope,governance:t.governance,approvedReleases:t.approvedReleases,releases:o,upgrades:a,stalledBy:ct(t.approvedReleases,e.deadlines,r),actionable:o.some(c=>c.actionable)||a.some(c=>c.actionable)}}function pt(t,e,r,n={}){return{kind:"release",scope:t.kind==="org"?{org:t.org}:"account",subject:n.withdraw?{version:e,withdraw:!0}:{version:e},returnTo:r}}function ri(t,e,r){return pt(t,e,r,{withdraw:!0})}function ti(t,e,r){return{kind:"upgrade",subject:{app:t,toVersion:e},returnTo:r}}function mt(t){return"account"in t?`account:${t.account}`:`org:${t.org}`}async function ni(t,e=fetch){let r=t??globalThis.location?.origin;if(!r)throw new Error("no page origin to read the frontend manifest from; pass `origin`");let n=await e(new URL("/.well-known/calimero.json",r).toString());if(!n.ok)throw await Rr(n);let i=await n.json();return{...i,deployments:i.deployments??[]}}function ii(t){let e=t??globalThis.location?.href;if(!e)return null;try{return new URL(e).searchParams.get("deployment")||null}catch{return null}}function si(t,e){return t==="required"||t==="preferred"||t==="discouraged"?t:e}function oi(t){let e=t,r=e?.name,n=typeof e?.message=="string"?e.message:"";return r==="InvalidStateError"||/not focused|already pending/i.test(n)?new ae(t):r==="NotAllowedError"||r==="AbortError"?new oe(t):t}function l(t){return encodeURIComponent(t)}function ai(t){return t instanceof T&&t.status===413?Ke(413,{error:"TOO_LARGE",message:t.message.replace(/^Sealed request refused: /,"")}):t}async function Rr(t){let e=await t.text().catch(()=>""),r={};try{r=e?JSON.parse(e):{}}catch{r={message:e}}return Ke(t.status,r,t.headers.get("retry-after"))}async function*ci(t){let e=t.getReader(),r=new TextDecoder,n="";for(;;){let{value:i,done:s}=await e.read();if(s)return;n+=r.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 ft(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function yt(){return`node:c-${P(crypto.getRandomValues(new Uint8Array(16)))}`}var li={retries:6,baseDelayMs:200,maxDelayMs:2e3};function di(t,e){return Math.min(e.baseDelayMs*2**t,e.maxDelayMs)}function ht(t){return t==="auth/refresh"||t.startsWith("auth/passkey/")||ui.has(t)}var ui=new Set(["auth/recovery/begin","auth/recovery/start","auth/recovery/finish"]),Pr=class t{constructor(e){this.at=0;this.channels=new Map;this.networkFailures=new WeakSet;this.packageOrigins={list:async e=>{let{origins:r}=await this.get(`package-origins/${l(e)}`);return r??[]},add:(e,r,n,i={})=>this.confirmed("POST",`package-origins/${l(e)}`,{origin:r,...i.rpId===void 0?{}:{rpId:i.rpId},...i.served?{served:!0}:{}},n),remove:(e,r,n)=>this.confirmed("DELETE",`package-origins/${l(e)}`,{origin:r},n)};let r=s=>s.replace(/\/+$/,"");this.nodeUrls=[...new Set([e.baseUrl,...e.nodes??[]].map(r))],this.policy=e.policy,this.retry={...li,...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 r=e.directory??gr,n=e.random??Math.random,i=e.fetch??((d,u)=>fetch(d,u)),s=await pr(r,e.cluster,i),[o,...a]=fr(s.nodes,e.zone,n),c=new t({baseUrl:o,nodes:a,policy:e.policy,fetch:e.fetch,retry:e.retry});return c.source={directory:r,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 r=this.channels.get(e);return r||(r=We({baseUrl:e,transportPublicKey:()=>ur(e,this.policy,this.raw),fetch:this.raw}),this.channels.set(e,r)),r}moveOn(e){return this.nodeUrls.length<2?!1:(this.nodeUrl===e&&(this.at=(this.at+1)%this.nodeUrls.length),!0)}failOver(e,r){if(this.nodeUrl!==e&&!r.has(this.nodeUrl))return!0;let n=this.nodeUrls.length;for(let i=1;i<n;i++){let s=(this.at+i)%n;if(!r.has(this.nodeUrls[s]))return this.at=s,this.reread(),!0}return!1}reread(){let e=this.source;!e||e.reading||(e.reading=pr(e.directory,e.cluster,this.raw).then(r=>{let n=this.nodeUrl,i=fr(r.nodes,e.zone,e.random);this.nodeUrls=[n,...i.filter(s=>s!==n)],this.at=0,e.due=Date.now()+r.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,r,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}/${r}`,{method:e,headers:a,body:c,signal:o})}catch(u){throw ai(u)}}async send(e,r,n,i,s,o){let a=!1,c=!1;for(;;){let[d,u]=[this.auth,this.nodeUrl],g=await this.request(e,r,n,i,s,o);if(g.ok)return g;let p=await Rr(g);if(p instanceof K&&!c){if(c=!0,this.moveOn(u)&&!ht(r))continue}else if(p instanceof B&&!a&&this.mayRefresh(d,r)){a=!0,await this.renew(d);continue}throw p}}mayRefresh(e,r){return e!==void 0&&this.current!==void 0&&!ht(r)}async renew(e){this.auth===e&&await this.refresh()}async json(e,r,n,i,s){let a=await(await this.send(e,r,n,i,s)).text();return a?JSON.parse(a):{}}async retried(e,r,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,r,n)}catch(g){if(g instanceof L)a=g;else if(g instanceof TypeError&&this.networkFailures.has(g))a=new L("NETWORK",`the node could not be reached: ${g.message}`,{},void 0,g);else throw g}if(d>=s)break;let u=di(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,r={}){return this.json("POST",e,r)}get(e){return this.json("GET",e)}put(e,r={}){return this.json("PUT",e,r)}delete(e,r){return this.json("DELETE",e,r)}async signUp(e,r,n={}){let i=this.pageOrigin(n),s=n.invite?{invite:n.invite}:{},o=await this.begin("auth/passkey/register/begin",i===void 0?{name:r,...s}:{name:r,origin:i,...s},i),a=n.signal,c=await(a?e.create(o.options,{signal:a}):e.create(o.options)),d=await this.confirmed("POST","auth/passkey/register/finish",{challengeId:o.challengeId,registration:c,...s},e,void 0,"preferred",a);return this.useSession(d),d}signUpPolicy(){return this.get("sign-up")}async signIn(e,r={}){let n=this.pageOrigin(r),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=O(i.options.challenge),a=await(r.signal?e.get(o,s,void 0,{signal:r.signal}):e.get(o,s)),c=await this.post("auth/passkey/login/finish",{challengeId:i.challengeId,assertion:a});return this.useSession(c),c}pageOrigin(e){if(e.origin!==void 0)return e.origin??void 0;let r=globalThis.location?.origin;return!r||r==="null"||new Set(this.nodeUrls.map(i=>{try{return new URL(i).origin}catch{return i}})).has(r)?void 0:r}async begin(e,r,n){try{return await this.post(e,r)}catch(i){throw i instanceof V&&!i.origin&&n!==void 0?new V(i.nodeMessage,{...i.details,origin:n}):i}}refresh(){if(!this.refreshing){let e=this.exchangeRefresh();this.refreshing=e;let r=()=>{this.refreshing===e&&(this.refreshing=void 0)};e.then(r,r)}return this.refreshing}async exchangeRefresh(){let e=this.current;if(!e)throw new Error("no session to refresh");let r;for(let n=1;r===void 0;n++)try{r=await this.post("auth/refresh",{refreshToken:e.refreshToken})}catch(i){if(!(i instanceof K)||n>=this.nodeUrls.length)throw i}return this.current===e&&this.useSession(r),r}async signOut(){await this.signingOut("auth/logout")}async signOutEverywhere(){await this.signingOut("auth/logout-all")}async signingOut(e){try{await this.post(e)}finally{this.auth=void 0,this.current=void 0}}me(){return this.get("auth/me")}async addPasskey(e,r){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},r);return s}async removePasskey(e,r){await this.deleteConfirmed(`auth/passkeys/${l(e)}`,r)}async labelPasskey(e,r){await this.post(`auth/passkeys/${l(e)}`,{label:r})}async createRecoveryCode(e){let{code:r}=await this.postConfirmed("auth/recovery",{},e);return r}async removeRecoveryCode(e){await this.deleteConfirmed("auth/recovery",e)}async startAccountRecovery(e,r){try{let n=await this.post("auth/recovery/begin",{code:e}),i=await r.create(n.options);return await this.post("auth/recovery/start",{challengeId:n.challengeId,code:e,registration:i})}catch(n){throw n instanceof B?new ce(n.message.replace(/^401 UNAUTHENTICATED: /,""),n.details):n}}async cancelAccountRecovery(e){await this.postConfirmed("auth/recovery/cancel",{},e)}async finishAccountRecovery(e,r){let n=await this.postConfirmed("auth/recovery/finish",r?{accountId:r}:{},e);return this.useSession(n),n}usage(){return this.get("auth/usage")}async attestation(){let e=ft(crypto.getRandomValues(new Uint8Array(32))),r=await this.raw(`${this.nodeUrl}/attestation?nonce=${e}`);if(!r.ok)throw await Rr(r);return await r.json()}async listApiKeys(){let{keys:e}=await this.get("auth/apikeys");return e}async revokeApiKey(e,r){await this.deleteConfirmed(`auth/apikeys/${l(e)}`,r)}createApiKey(e,r){return this.postConfirmed("auth/apikeys",{...e},r)}async uploadBundle(e){let{hash:r}=await this.json("POST","bundles",void 0,e);return r}uploadBlob(e,r,n={}){let i=(typeof n=="string"?n:n.contentType)??"application/octet-stream";return this.json("POST",`apps/${l(e)}/blobs`,void 0,r,i)}async downloadBlob(e,r){return(await this.blobContent(e,r)).data}async downloadBlobGranted(e,r,n){return(await this.blobContent(e,r,{grant:n})).data}async blobContent(e,r,n={}){let i=n.grant===void 0?"":`?grant=${encodeURIComponent(n.grant)}`,s=await this.send("GET",`apps/${l(e)}/blobs/${l(r)}${i}`);return{data:new Uint8Array(await s.arrayBuffer()),contentType:s.headers.get("content-type")??"application/octet-stream"}}async listBlobs(e){let{blobs:r}=await this.get(`apps/${l(e)}/blobs`);return r}blobInfo(e,r){return this.get(`apps/${l(e)}/blobs/${l(r)}/info`)}async deleteBlob(e,r){await this.delete(`apps/${l(e)}/blobs/${l(r)}`)}uploadPackage(e){return this.json("POST","packages",void 0,e,"application/octet-stream")}installPackage(e,r){return this.post("packages/install",{package:e,version:r})}async packages(){let{packages:e}=await this.get("packages");return e}package(e){return this.get(`packages/${l(e)}`)}uninstallPackage(e,r){return this.delete(r===void 0?`packages/${l(e)}`:`packages/${l(e)}/${l(r)}`)}async listApps(e={}){let r=new URLSearchParams;e.package&&r.set("package",e.package),e.bundle&&r.set("bundle",e.bundle);let n=r.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,r){await this.post(`apps/${l(e)}/access`,{access:r})}async setAppMetadata(e,r){await this.post(`apps/${l(e)}/metadata`,{metadata:r})}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,r,n){await this.postConfirmed(`apps/${l(e)}/transfer`,{to:r},n)}upgradeApp(e,r,n){let i=`apps/${l(e)}/upgrade`;return n?this.postConfirmed(i,r,n):this.post(i,r)}postConfirmed(e,r,n){return this.confirmed("POST",e,r,n)}deleteConfirmed(e,r,n={}){return this.confirmed("DELETE",e,n,r)}async confirmed(e,r,n,i,s=c=>this.json(e,r,c),o="required",a){try{return await s(n)}catch(c){if(!(c instanceof Z)||!i)throw c;let d=c.details,u;try{u=await i.get(O(d.challenge),d.rpId,d.allowCredentials,{userVerification:si(d.userVerification,o),...a?{signal:a}:{}})}catch(g){throw oi(g)}return s({...n,confirm:{challengeId:d.challengeId,assertion:u}})}}async createApp(e,r,n={}){let i=typeof r=="string"?{bundle:r}:r,{appId:s}=await this.post("apps",{name:e,...i,...n});return s}call(e,r,n={},i){let s=i??yt();return this.retried("POST",`apps/${l(e)}/intents`,{method:r,args:n,idempotencyKey:s})}async callConfirmed(e,r,n,i,s){let o=`apps/${l(e)}/intents`,a=s??yt();return this.confirmed("POST",o,{method:r,args:n,idempotencyKey:a},i,c=>this.retried("POST",o,c,c.confirm!==void 0))}view(e,r,n={},i={}){return this.retried("POST",`apps/${l(e)}/views`,{method:r,args:n,consistency:i.stale?"stale":"strong",minIndex:i.minIndex??0})}events(e,r=0,n){return this.stream(`apps/${l(e)}/events?from=${r}`,n)}async*stream(e,r){let n=await this.send("GET",e,void 0,void 0,void 0,r);if(!n.body)throw new y(n.status,"EVENTS","the event stream has no body");yield*ci(n.body)}async publishPresence(e,r,n){await this.post(`apps/${l(e)}/presence`,{seq:r,state:n===null?null:ft(n)})}async presence(e){let{present:r}=await this.get(`apps/${l(e)}/presence`);return r}presenceStream(e,r){return this.stream(`apps/${l(e)}/presence/stream`,r)}async setAlias(e,r){await this.put(`auth/aliases/${l(e)}`,{app:r})}async aliases(){let{aliases:e}=await this.get("auth/aliases");return e}async alias(e){let{appId:r}=await this.get(`auth/aliases/${l(e)}`);return r}async deleteAlias(e){await this.delete(`auth/aliases/${l(e)}`)}async createOrg(e,r={}){let n={name:e};r.recoveryKey!==void 0&&(n.recoveryKey=r.recoveryKey);let{orgId:i}=await this.post("orgs",n);return i}async setRecoveryKey(e,r,n){await this.postConfirmed(`orgs/${l(e)}/recovery`,{publicKey:r},n)}async startRecovery(e,r){let n=(await this.me()).accountId,i=P(crypto.getRandomValues(new Uint8Array(16))),s=await wr(r,e,n,i);return this.post(`orgs/${l(e)}/recovery/start`,{nonce:i,signature:s})}async cancelRecovery(e,r){await this.postConfirmed(`orgs/${l(e)}/recovery/cancel`,{},r)}finishRecovery(e,r){return this.postConfirmed(`orgs/${l(e)}/recovery/finish`,{},r)}getOrg(e){return this.get(`orgs/${l(e)}`)}async deleteOrg(e,r){await this.deleteConfirmed(`orgs/${l(e)}`,r)}async setOrgMetadata(e,r){await this.post(`orgs/${l(e)}/metadata`,{metadata:r})}async setMemberMetadata(e,r,n){await this.post(`orgs/${l(e)}/members/${l(r)}/metadata`,{metadata:n})}upgradeOrg(e,r,n){return this.postConfirmed(`orgs/${l(e)}/upgrade`,{...r},n)}upgradeRun(e,r){return this.get(`orgs/${l(e)}/upgrades/${l(r)}`)}retryUpgradeRun(e,r,n){return this.postConfirmed(`orgs/${l(e)}/upgrades/${l(r)}/retry`,{},n)}async approveRelease(e,r,n,i=!0){let s=e===null?"auth/releases":`orgs/${l(e)}/releases`;return this.postConfirmed(s,{version:r,approved:i},n)}async approveOutbound(e,r,n,i={}){let s=e===null?"auth/outbound":`orgs/${l(e)}/outbound`;return this.postConfirmed(s,{package:r,prefixes:i.prefixes??"manifest",replace:i.replace??!1},n)}appsReport(e,r={}){let n=e===null?"auth/apps":`orgs/${l(e)}/apps`;return this.get(`${n}${ue(r)}`)}async appsReportAll(e){let r=await this.appsReport(e),n=[...r.apps],i=r.next;for(;i!==null;){let s=await this.appsReport(e,{after:i});n.push(...s.apps),i=s.next}return{...r,apps:n,next:null}}releaseRules(){return this.get("releases")}async pendingApprovals(e=null){let[r,n]=await Promise.all([this.appsReportAll(e),this.releaseRules()]);return Er(r,n)}requestConsent(e){return this.post("consent/requests",e)}async openConsentPage(e,r={}){let n=typeof r=="function"?{navigate:r}:r,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 br(s.requestId);if(s.code!==o)throw new y(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,r={}){let n=r.intervalMs??2e3;for(;;){let i=await this.consentResult(e);if(i.status!=="pending"||r.signal?.aborted||r.expiresAt!==void 0&&Date.now()/1e3>=r.expiresAt)return i;await new Promise(s=>setTimeout(s,n))}}publisherBinding(e){return this.get(`publishers/${l(e)}`)}bindPublisher(e,r,n){return this.postConfirmed(`orgs/${l(e)}/publishers`,{...r},n)}upgradePublished(e,r,n,i){return this.postConfirmed(`orgs/${l(e)}/packages/${l(r)}/upgrade`,{...n},i)}opsApps(e={}){return this.get(`ops/apps${ue(e)}`)}opsOrgs(e={}){return this.get(`ops/orgs${ue(e)}`)}opsServedOrigins(){return this.get("ops/served-origins")}async setReleaseDeadline(e,r){let n=typeof r=="string"?r:r.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,r,n,i){await this.postConfirmed(`orgs/${l(e)}/members`,{account:r,role:n},i)}removeMember(e,r,n){return this.deleteConfirmed(`orgs/${l(e)}/members/${l(r)}`,n)}async setCapabilities(e,r,n,i={}){await this.postConfirmed(`orgs/${l(e)}/capabilities`,{capabilities:r,...i},n)}async createTeam(e,r,n,i){let{teamId:s}=await this.post(`orgs/${l(e)}/teams`,{name:r,join:n,parent:i});return s}getTeam(e,r){return this.get(`orgs/${l(e)}/teams/${l(r)}`)}async updateTeam(e,r,n){await this.post(`orgs/${l(e)}/teams/${l(r)}`,n)}async deleteTeam(e,r){await this.delete(`orgs/${l(e)}/teams/${l(r)}`)}async setTeamMember(e,r,n,i,s={}){await this.postConfirmed(`orgs/${l(e)}/teams/${l(r)}/members`,{account:n,...s},i)}async removeTeamMember(e,r,n,i){await this.deleteConfirmed(`orgs/${l(e)}/teams/${l(r)}/members/${l(n)}`,i)}async invite(e,r,n,i=[],s={}){let{token:o}=await this.postConfirmed(`orgs/${l(e)}/invites`,{role:r,teams:i,...s},n);return o}redeemInvite(e){return this.post(`invites/${l(e)}/redeem`)}grantDeployer(e,r,n={}){let i=n.until instanceof Date?n.until.toISOString():n.until;return this.postConfirmed("deployers",{deployer:e,...i===void 0?{}:{until:i}},r)}deployers(){return this.get("deployers")}async revokeDeployer(e,r){let n=typeof e=="string"?e:mt(e);await this.deleteConfirmed(`deployers/${l(n)}`,r)}async createDeployment(e,r,n){let{id:i}=await this.postConfirmed("deployments",{name:e,owner:r},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,r){await this.deleteConfirmed(`deployments/${l(e)}`,r)}offerApp(e,r,n){return this.postConfirmed(`deployments/${l(e)}/apps`,{...r},n)}async withdrawApp(e,r,n){await this.deleteConfirmed(`deployments/${l(e)}/apps/${l(r)}`,n)}deploymentOrgs(e){return this.get(`deployments/${l(e)}/orgs`)}};var xr={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},gi=xr.JOIN_OPEN_TEAMS;function pi(...t){return t.reduce((e,r)=>e|xr[r],0)}function Ve(t,e){return(t<<e|t>>>32-e)>>>0}function I(t,e,r,n,i){t[e]=t[e]+t[r]>>>0,t[i]=Ve(t[i]^t[e],16),t[n]=t[n]+t[i]>>>0,t[r]=Ve(t[r]^t[n],12),t[e]=t[e]+t[r]>>>0,t[i]=Ve(t[i]^t[e],8),t[n]=t[n]+t[i]>>>0,t[r]=Ve(t[r]^t[n],7)}function wt(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function Et(t,e,r){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]=wt(t,o*4);n[12]=e>>>0;for(let o=0;o<3;o+=1)n[13+o]=wt(r,o*4);let i=n.slice();for(let o=0;o<10;o+=1)I(i,0,4,8,12),I(i,1,5,9,13),I(i,2,6,10,14),I(i,3,7,11,15),I(i,0,5,10,15),I(i,1,6,11,12),I(i,2,7,8,13),I(i,3,4,9,14);let s=new Uint8Array(64);for(let o=0;o<16;o+=1){let a=i[o]+n[o]>>>0;s[o*4]=a&255,s[o*4+1]=a>>>8&255,s[o*4+2]=a>>>16&255,s[o*4+3]=a>>>24&255}return s}function fi(t,e,r,n){let i=new Uint8Array(n.length);for(let s=0,o=e;s<n.length;s+=64,o+=1){let a=Et(t,o,r),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 vr(t){let e=0n;for(let r=t.length-1;r>=0;r-=1)e=e<<8n|BigInt(t[r]);return e}var yi=(1n<<130n)-5n;function hi(t,e){let r=vr(t.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,n=vr(t.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=vr(c)+(1n<<BigInt(8*c.length));i=(i+d)*r%yi}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 At(t){return new Uint8Array((16-t%16)%16)}function bt(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function mi(t,e){let r=[t,At(t.length),e,At(e.length),bt(t.length),bt(e.length)],n=new Uint8Array(r.reduce((s,o)=>s+o.length,0)),i=0;for(let s of r)n.set(s,i),i+=s.length;return n}function wi(t,e){if(t.length!==32)throw new Error("ChaCha20-Poly1305 needs a 32-byte key");if(e.length!==12)throw new Error("ChaCha20-Poly1305 needs a 12-byte nonce")}function Rt(t,e,r,n=new Uint8Array(0)){wi(t,e);let i=Et(t,0,e).subarray(0,32),s=fi(t,1,e,r),o=hi(i,mi(n,s)),a=new Uint8Array(s.length+16);return a.set(s),a.set(o,s.length),a}var xt=32,Ai=1,bi=3,Ei=2,Ri=32,Pi=32,xi=12,X=t=>new TextEncoder().encode(t),pe=t=>new Uint8Array([t>>8&255,t&255]),Pt=h(X("KEM"),pe(xt)),ge=h(X("HPKE"),pe(xt),pe(Ai),pe(bi));async function vt(t,e){let r=t.length===0?new Uint8Array(32):t,n=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",n,e))}async function vi(t,e,r){let n=new Uint8Array(r),i=new Uint8Array(0);for(let s=1,o=0;o<r;s+=1)i=await vt(t,h(i,e,new Uint8Array([s]))),n.set(i.subarray(0,Math.min(i.length,r-o)),o),o+=i.length;return n}function Le(t,e,r,n){return vt(e,h(X("HPKE-v1"),t,X(r),n))}function Ur(t,e,r,n,i){return vi(e,h(pe(i),X("HPKE-v1"),t,X(r),n),i)}async function Ui(t,e){let r=await Le(Pt,new Uint8Array(0),"eae_prk",t);return Ur(Pt,r,"shared_secret",e,Ri)}async function ki(t,e){let r=new Uint8Array(0),n=await Le(ge,r,"psk_id_hash",r),i=await Le(ge,r,"info_hash",e),s=h(new Uint8Array([Ei]),n,i),o=await Le(ge,t,"secret",r);return{key:await Ur(ge,o,"key",s,Pi),nonce:await Ur(ge,o,"base_nonce",s,xi)}}async function Ut(t,e,r,n,i=new Uint8Array(0),s){if(t.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let o=await q(s),a=await q(e),c=h(await ee(o.privateKey,t),await ee(a.privateKey,t)),d=await Ui(c,h(o.publicKey,t,a.publicKey)),{key:u,nonce:g}=await ki(d,r);return{enc:o.publicKey,ciphertext:Rt(u,g,n,i)}}var St="mero-agent-gate/attest/v3",Ct="mero-agent-gate/provision/v2",Ti=/^[a-z0-9][a-z0-9-]{0,62}$/,Si=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,kt=64,Tt=64*1024,D=class extends Error{constructor(r,n,i){super(r);this.status=n;this.code=i;this.name="AgentGateError"}};function Ot(t){if(!Ti.test(t))throw new Error(`Agent id ${JSON.stringify(t)} must match [a-z0-9][a-z0-9-]{0,62}`)}function fe(t){return new TextEncoder().encode(t)}function It(t){let e=fe(t);return h(new Uint8Array([e.length]),e)}function G(t){let e="";for(let r of t)e+=String.fromCharCode(r);return btoa(e)}function Ge(t,e,r){let n;try{n=Uint8Array.from(atob(t.trim()),i=>i.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(r!==void 0&&n.length!==r)throw new Error(`${e} is not ${r} bytes`);return n}async function Dt(t,e,r,n){let i=new Uint8Array(32),s=h(fe(St),t,It(e),r??i,n??i);return new Uint8Array(await crypto.subtle.digest("SHA-256",s))}function Nt(t,e){return h(fe(Ct),t,It(e))}async function Ci(){let t=crypto.getRandomValues(new Uint8Array(32));return{secret:t,publicKey:await He(t)}}async function He(t){if(t.length!==32)throw new Error("An owner key is 32 bytes");return G((await q(t)).publicKey)}function _t(t,e){return`${t.replace(/\/+$/,"")}${e}`}async function Mt(t,e,r){let n=await t(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)}),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 kr(t){let e=t.agentId??"";e&&Ot(e);let r=crypto.getRandomValues(new Uint8Array(32)),n=await Mt(t.fetch??fetch,_t(t.gateUrl,"/attest"),{nonceB64:G(r),...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=Ge(n.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),s=n.signingPublicKeyB64?Ge(n.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,o=n.ownerPublicKeyB64?Ge(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 Dt(i,e,s,o);return await t.verifier({quoteB64:n.quoteB64,nonce:R(r),reportDataSuffix:R(a)}),{agentId:e,provisioningPublicKey:G(i),...s?{signingPublicKey:G(s)}:{},...o?{ownerPublicKey:G(o)}:{}}}async function $t(t,e){let r=await He(e);if(t.ownerPublicKey&&t.ownerPublicKey!==r)throw new D(`This agent is claimed by another key (${t.ownerPublicKey}); it is not yours. Send it nothing and do not authorize its signing key`,void 0,"not_yours");return r}function Oi(t){let e=Object.keys(t);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>kt)throw new Error(`At most ${kt} secrets at once`);for(let r of e){if(!Si.test(r))throw new Error(`Secret name ${JSON.stringify(r)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);if(typeof t[r]!="string")throw new Error(`Secret ${r} is not a string`);if(fe(t[r]).length>Tt)throw new Error(`Secret ${r} is over ${Tt} bytes`)}}async function Bt(t,e,r,n,i,s){if(!n.agentId)throw new Error("This quote names no agent; attest with the agent id");let o=await $t(n,i),a=Ge(n.provisioningPublicKey,"provisioningPublicKey",32),c=await Ut(a,i,Nt(a,n.agentId),fe(JSON.stringify(s)));return Mt(t,_t(e,r),{agentId:n.agentId,provisioningPublicKeyB64:n.provisioningPublicKey,senderPublicKeyB64:o,encappedKeyB64:G(c.enc),ciphertextB64:G(c.ciphertext)})}async function Ii(t){Oi(t.secrets);let e=t.fetch??fetch,r=await Bt(e,t.gateUrl,"/provision",t.agent,t.ownerSecret,{secrets:t.secrets}),n=await kr({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e}),i=await He(t.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(t.agent.signingPublicKey&&t.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:r?.written??[],claimed:r?.claimed===!0}}async function Di(t){if(!t.agent.ownerPublicKey)throw new Error("This agent is not claimed; there is nothing to release");let e=t.fetch??fetch;if(await Bt(e,t.gateUrl,"/release",t.agent,t.ownerSecret,{release:!0}),(await kr({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e})).ownerPublicKey)throw new D("The gate says it released the agent, but its quote still names an owner")}var Tr=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),Ni=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function _i(t,e,r={}){let n=typeof t=="string"?new TextEncoder().encode(t):t;await be(n,e,{identity:r.identity??Tr.identity,issuer:r.issuer??Tr.issuer});let i;try{i=JSON.parse(new TextDecoder().decode(n))}catch{throw new Error("The signed agent policy is not JSON")}let s=r.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=r.profile??M;if(i.profile!==o)throw new Error(`The signed agent policy is for the ${JSON.stringify(i.profile)} profile, not ${o}`);if(r.expectedVersion!==void 0&&i.version!==r.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(i.version)}, not ${r.expectedVersion}`);return Kt(i),i}function Kt(t){for(let e of Ni)if(!Array.isArray(t?.[e])||t[e].length===0)throw new Error(`The agent policy's ${e} is empty, so no agent would be accepted`)}var Mi=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function $i(t){let e=Mi.find(r=>r.toLowerCase()===t.trim().toLowerCase());if(!e)throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(t)}`);return e}var ye=t=>t.trim().replace(/^0x/i,"");function Bi(t,e){return Kt(t),$({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:t.allowed_tcb_statuses.map($i),allowedMrtd:t.allowed_mrtd.map(ye),allowedRtmr0:t.allowed_rtmr0.map(ye),allowedRtmr1:t.allowed_rtmr1.map(ye),allowedRtmr2:t.allowed_rtmr2.map(ye),allowedRtmr3:t.allowed_rtmr3.map(ye)})}export{St as AGENT_ATTEST_DOMAIN,Ct as AGENT_PROVISION_INFO_DOMAIN,D as AgentGateError,Me as AppError,ve as ArgsTooLarge,Se as BadOrigin,Pr as CalimeroClient,y as CalimeroError,Ie as ClusterNotUpgraded,oe as ConfirmCancelled,ae as ConfirmPromptBlocked,Z as ConfirmRequired,Te as ConsentStale,sr as DEFAULT_COLLATERAL_MIRROR,gr as DEFAULT_DIRECTORY,gi as DEFAULT_ORG_CAPABILITIES,Ee as DEFAULT_RELEASE_MIRROR,k as DirectoryError,Jr as GITHUB_RELEASES,_r as HANDSHAKE_PATH,Ue as IdempotencyMismatch,Tr as KMS_RELEASE_SIGNER,B as LoginRequired,mr as MAX_RECOVERY_NONCE_BYTES,Ar as MAX_REPORT_PAGE,Xr as MOCK_QUOTE_HEADER,ir as NODE_RELEASE_SIGNER,xe as NotFound,Oe as NotServing,xr as ORG_CAPABILITIES,V as OriginNotRegistered,Ce as OriginTaken,M as PRODUCTION_PROFILE,Pe as PasskeyUnknownHere,_e as QuotaExceeded,nt as RECOVERY_DOMAIN,dt as RELEASE_VERIFIER,De as RecoveryNotReady,ke as ReleaseDeadlineError,te as SEALED_CONTENT_TYPE,Mr as SEALED_PATH,T as SealedTransportError,Ne as SignUpRefused,ne as StaleTransportKeyError,$e as TrapError,L as UnavailableError,K as WrongNode,ce as WrongRecoveryCode,Dt as agentKeyBinding,Bi as agentQuoteVerifier,kr as attestAgent,P as b64url,Qn as browserPasskey,$t as checkOwner,Wr as claimedRelease,cr as cloudNodeReleaseUrl,de as compareVersions,br as confirmationCode,ei as consentReturn,$ as createQuoteVerifier,We as createSealedFetch,Mn as createSignedReleaseVerifier,mt as deployerKey,Ke as errorFrom,ur as fetchAttestedKey,ar as fetchGithubNodeRelease,or as fetchNodeRelease,et as freshCollateral,O as fromB64url,ni as frontendManifest,Ci as generateOwnerKey,Yn as newRecoverySeed,pi as orgCapabilities,He as ownerPublicKey,ii as pageDeployment,ue as pageQuery,zn as parseRecoverySeed,Er as pendingApprovalsFrom,Ii as provisionAgent,Nt as provisionInfo,Xn as publisherBindingBytes,lt as publisherBindingMessage,it as recoveryMessage,Zn as recoveryPublicKey,Jn as recoverySeedText,Di as releaseAgent,pt as releaseConsent,ut as releaseNotesUrl,wr as signRecovery,ct as stalledBy,Xe as transportKeyBinding,Re as trustSignedRelease,nr as trustedMeasurementsFromReleases,ti as upgradeConsent,Ot as validateAgentId,gt as verifyReleaseUrl,_i as verifySignedAgentPolicy,Yr as verifySignedNodeRelease,ri 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 ft(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function yt(){return`node:c-${P(crypto.getRandomValues(new Uint8Array(16)))}`}var li={retries:6,baseDelayMs:200,maxDelayMs:2e3};function di(t,e){return Math.min(e.baseDelayMs*2**t,e.maxDelayMs)}function ht(t){return t==="auth/refresh"||t.startsWith("auth/passkey/")||ui.has(t)}var ui=new Set(["auth/recovery/begin","auth/recovery/start","auth/recovery/finish"]),Pr=class t{constructor(e){this.at=0;this.channels=new Map;this.networkFailures=new WeakSet;this.packageOrigins={list:async e=>{let{origins:r}=await this.get(`package-origins/${l(e)}`);return r??[]},add:(e,r,n,i={})=>this.confirmed("POST",`package-origins/${l(e)}`,{origin:r,...i.rpId===void 0?{}:{rpId:i.rpId},...i.served?{served:!0}:{}},n),remove:(e,r,n)=>this.confirmed("DELETE",`package-origins/${l(e)}`,{origin:r},n)};let r=s=>s.replace(/\/+$/,"");this.nodeUrls=[...new Set([e.baseUrl,...e.nodes??[]].map(r))],this.policy=e.policy,this.retry={...li,...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 r=e.directory??gr,n=e.random??Math.random,i=e.fetch??((d,u)=>fetch(d,u)),s=await pr(r,e.cluster,i),[o,...a]=fr(s.nodes,e.zone,n),c=new t({baseUrl:o,nodes:a,policy:e.policy,fetch:e.fetch,retry:e.retry});return c.source={directory:r,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 r=this.channels.get(e);return r||(r=We({baseUrl:e,transportPublicKey:()=>ur(e,this.policy,this.raw),fetch:this.raw}),this.channels.set(e,r)),r}moveOn(e){return this.nodeUrls.length<2?!1:(this.nodeUrl===e&&(this.at=(this.at+1)%this.nodeUrls.length),!0)}failOver(e,r){if(this.nodeUrl!==e&&!r.has(this.nodeUrl))return!0;let n=this.nodeUrls.length;for(let i=1;i<n;i++){let s=(this.at+i)%n;if(!r.has(this.nodeUrls[s]))return this.at=s,this.reread(),!0}return!1}reread(){let e=this.source;!e||e.reading||(e.reading=pr(e.directory,e.cluster,this.raw).then(r=>{let n=this.nodeUrl,i=fr(r.nodes,e.zone,e.random);this.nodeUrls=[n,...i.filter(s=>s!==n)],this.at=0,e.due=Date.now()+r.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,r,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}/${r}`,{method:e,headers:a,body:c,signal:o})}catch(u){throw ai(u)}}async send(e,r,n,i,s,o){let a=!1,c=!1;for(;;){let[d,u]=[this.auth,this.nodeUrl],g=await this.request(e,r,n,i,s,o);if(g.ok)return g;let p=await Rr(g);if(p instanceof K&&!c){if(c=!0,this.moveOn(u)&&!ht(r))continue}else if(p instanceof B&&!a&&this.mayRefresh(d,r)){a=!0,await this.renew(d);continue}throw p}}mayRefresh(e,r){return e!==void 0&&this.current!==void 0&&!ht(r)}async renew(e){this.auth===e&&await this.refresh()}async json(e,r,n,i,s){let a=await(await this.send(e,r,n,i,s)).text();return a?JSON.parse(a):{}}async retried(e,r,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,r,n)}catch(g){if(g instanceof L)a=g;else if(g instanceof TypeError&&this.networkFailures.has(g))a=new L("NETWORK",`the node could not be reached: ${g.message}`,{},void 0,g);else throw g}if(d>=s)break;let u=di(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,r={}){return this.json("POST",e,r)}get(e){return this.json("GET",e)}put(e,r={}){return this.json("PUT",e,r)}delete(e,r){return this.json("DELETE",e,r)}async signUp(e,r,n={}){let i=this.pageOrigin(n),s=n.invite?{invite:n.invite}:{},o=await this.begin("auth/passkey/register/begin",i===void 0?{name:r,...s}:{name:r,origin:i,...s},i),a=n.signal,c=await(a?e.create(o.options,{signal:a}):e.create(o.options)),d=await this.confirmed("POST","auth/passkey/register/finish",{challengeId:o.challengeId,registration:c,...s},e,void 0,"preferred",a);return this.useSession(d),d}signUpPolicy(){return this.get("sign-up")}async signIn(e,r={}){let n=this.pageOrigin(r),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=O(i.options.challenge),a=await(r.signal?e.get(o,s,void 0,{signal:r.signal}):e.get(o,s)),c=await this.post("auth/passkey/login/finish",{challengeId:i.challengeId,assertion:a});return this.useSession(c),c}pageOrigin(e){if(e.origin!==void 0)return e.origin??void 0;let r=globalThis.location?.origin;return!r||r==="null"||new Set(this.nodeUrls.map(i=>{try{return new URL(i).origin}catch{return i}})).has(r)?void 0:r}async begin(e,r,n){try{return await this.post(e,r)}catch(i){throw i instanceof V&&!i.origin&&n!==void 0?new V(i.nodeMessage,{...i.details,origin:n}):i}}refresh(){if(!this.refreshing){let e=this.exchangeRefresh();this.refreshing=e;let r=()=>{this.refreshing===e&&(this.refreshing=void 0)};e.then(r,r)}return this.refreshing}async exchangeRefresh(){let e=this.current;if(!e)throw new Error("no session to refresh");let r;for(let n=1;r===void 0;n++)try{r=await this.post("auth/refresh",{refreshToken:e.refreshToken})}catch(i){if(!(i instanceof K)||n>=this.nodeUrls.length)throw i}return this.current===e&&this.useSession(r),r}async signOut(){await this.signingOut("auth/logout")}async signOutEverywhere(){await this.signingOut("auth/logout-all")}async signingOut(e){try{await this.post(e)}finally{this.auth=void 0,this.current=void 0}}me(){return this.get("auth/me")}async addPasskey(e,r){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},r);return s}async removePasskey(e,r){await this.deleteConfirmed(`auth/passkeys/${l(e)}`,r)}async labelPasskey(e,r){await this.post(`auth/passkeys/${l(e)}`,{label:r})}async createRecoveryCode(e){let{code:r}=await this.postConfirmed("auth/recovery",{},e);return r}async removeRecoveryCode(e){await this.deleteConfirmed("auth/recovery",e)}async startAccountRecovery(e,r){try{let n=await this.post("auth/recovery/begin",{code:e}),i=await r.create(n.options);return await this.post("auth/recovery/start",{challengeId:n.challengeId,code:e,registration:i})}catch(n){throw n instanceof B?new ce(n.message.replace(/^401 UNAUTHENTICATED: /,""),n.details):n}}async cancelAccountRecovery(e){await this.postConfirmed("auth/recovery/cancel",{},e)}async finishAccountRecovery(e,r){let n=await this.postConfirmed("auth/recovery/finish",r?{accountId:r}:{},e);return this.useSession(n),n}usage(){return this.get("auth/usage")}async attestation(){let e=ft(crypto.getRandomValues(new Uint8Array(32))),r=await this.raw(`${this.nodeUrl}/attestation?nonce=${e}`);if(!r.ok)throw await Rr(r);return await r.json()}async listApiKeys(){let{keys:e}=await this.get("auth/apikeys");return e}async revokeApiKey(e,r){await this.deleteConfirmed(`auth/apikeys/${l(e)}`,r)}createApiKey(e,r){return this.postConfirmed("auth/apikeys",{...e},r)}async uploadBundle(e){let{hash:r}=await this.json("POST","bundles",void 0,e);return r}uploadBlob(e,r,n={}){let i=(typeof n=="string"?n:n.contentType)??"application/octet-stream";return this.json("POST",`apps/${l(e)}/blobs`,void 0,r,i)}async downloadBlob(e,r){return(await this.blobContent(e,r)).data}async downloadBlobGranted(e,r,n){return(await this.blobContent(e,r,{grant:n})).data}async blobContent(e,r,n={}){let i=n.grant===void 0?"":`?grant=${encodeURIComponent(n.grant)}`,s=await this.send("GET",`apps/${l(e)}/blobs/${l(r)}${i}`);return{data:new Uint8Array(await s.arrayBuffer()),contentType:s.headers.get("content-type")??"application/octet-stream"}}async listBlobs(e){let{blobs:r}=await this.get(`apps/${l(e)}/blobs`);return r}blobInfo(e,r){return this.get(`apps/${l(e)}/blobs/${l(r)}/info`)}async deleteBlob(e,r){await this.delete(`apps/${l(e)}/blobs/${l(r)}`)}uploadPackage(e){return this.json("POST","packages",void 0,e,"application/octet-stream")}installPackage(e,r){return this.post("packages/install",{package:e,version:r})}async packages(){let{packages:e}=await this.get("packages");return e}package(e){return this.get(`packages/${l(e)}`)}uninstallPackage(e,r){return this.delete(r===void 0?`packages/${l(e)}`:`packages/${l(e)}/${l(r)}`)}async listApps(e={}){let r=new URLSearchParams;e.package&&r.set("package",e.package),e.bundle&&r.set("bundle",e.bundle);let n=r.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,r){await this.post(`apps/${l(e)}/access`,{access:r})}async setAppMetadata(e,r){await this.post(`apps/${l(e)}/metadata`,{metadata:r})}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,r,n){await this.postConfirmed(`apps/${l(e)}/transfer`,{to:r},n)}upgradeApp(e,r,n){let i=`apps/${l(e)}/upgrade`;return n?this.postConfirmed(i,r,n):this.post(i,r)}postConfirmed(e,r,n){return this.confirmed("POST",e,r,n)}deleteConfirmed(e,r,n={}){return this.confirmed("DELETE",e,n,r)}async confirmed(e,r,n,i,s=c=>this.json(e,r,c),o="required",a){try{return await s(n)}catch(c){if(!(c instanceof Z)||!i)throw c;let d=c.details,u;try{u=await i.get(O(d.challenge),d.rpId,d.allowCredentials,{userVerification:si(d.userVerification,o),...a?{signal:a}:{}})}catch(g){throw oi(g)}return s({...n,confirm:{challengeId:d.challengeId,assertion:u}})}}async createApp(e,r,n={}){let i=typeof r=="string"?{bundle:r}:r,{appId:s}=await this.post("apps",{name:e,...i,...n});return s}call(e,r,n={},i){let s=i??yt();return this.retried("POST",`apps/${l(e)}/intents`,{method:r,args:n,idempotencyKey:s})}async callConfirmed(e,r,n,i,s){let o=`apps/${l(e)}/intents`,a=s??yt();return this.confirmed("POST",o,{method:r,args:n,idempotencyKey:a},i,c=>this.retried("POST",o,c,c.confirm!==void 0))}view(e,r,n={},i={}){return this.retried("POST",`apps/${l(e)}/views`,{method:r,args:n,consistency:i.stale?"stale":"strong",minIndex:i.minIndex??0})}events(e,r=0,n){return this.stream(`apps/${l(e)}/events?from=${r}`,n)}async*stream(e,r){let n=await this.send("GET",e,void 0,void 0,void 0,r);if(!n.body)throw new y(n.status,"EVENTS","the event stream has no body");yield*ci(n.body)}async publishPresence(e,r,n){await this.post(`apps/${l(e)}/presence`,{seq:r,state:n===null?null:ft(n)})}async presence(e){let{present:r}=await this.get(`apps/${l(e)}/presence`);return r}presenceStream(e,r){return this.stream(`apps/${l(e)}/presence/stream`,r)}async setAlias(e,r){await this.put(`auth/aliases/${l(e)}`,{app:r})}async aliases(){let{aliases:e}=await this.get("auth/aliases");return e}async alias(e){let{appId:r}=await this.get(`auth/aliases/${l(e)}`);return r}async deleteAlias(e){await this.delete(`auth/aliases/${l(e)}`)}async createOrg(e,r={}){let n={name:e};r.recoveryKey!==void 0&&(n.recoveryKey=r.recoveryKey);let{orgId:i}=await this.post("orgs",n);return i}async setRecoveryKey(e,r,n){await this.postConfirmed(`orgs/${l(e)}/recovery`,{publicKey:r},n)}async startRecovery(e,r){let n=(await this.me()).accountId,i=P(crypto.getRandomValues(new Uint8Array(16))),s=await wr(r,e,n,i);return this.post(`orgs/${l(e)}/recovery/start`,{nonce:i,signature:s})}async cancelRecovery(e,r){await this.postConfirmed(`orgs/${l(e)}/recovery/cancel`,{},r)}finishRecovery(e,r){return this.postConfirmed(`orgs/${l(e)}/recovery/finish`,{},r)}getOrg(e){return this.get(`orgs/${l(e)}`)}async deleteOrg(e,r){await this.deleteConfirmed(`orgs/${l(e)}`,r)}async setOrgMetadata(e,r){await this.post(`orgs/${l(e)}/metadata`,{metadata:r})}async setMemberMetadata(e,r,n){await this.post(`orgs/${l(e)}/members/${l(r)}/metadata`,{metadata:n})}upgradeOrg(e,r,n){return this.postConfirmed(`orgs/${l(e)}/upgrade`,{...r},n)}upgradeRun(e,r){return this.get(`orgs/${l(e)}/upgrades/${l(r)}`)}retryUpgradeRun(e,r,n){return this.postConfirmed(`orgs/${l(e)}/upgrades/${l(r)}/retry`,{},n)}async approveRelease(e,r,n,i=!0){let s=e===null?"auth/releases":`orgs/${l(e)}/releases`;return this.postConfirmed(s,{version:r,approved:i},n)}async approveOutbound(e,r,n,i={}){let s=e===null?"auth/outbound":`orgs/${l(e)}/outbound`;return this.postConfirmed(s,{package:r,prefixes:i.prefixes??"manifest",replace:i.replace??!1},n)}appsReport(e,r={}){let n=e===null?"auth/apps":`orgs/${l(e)}/apps`;return this.get(`${n}${ue(r)}`)}async appsReportAll(e){let r=await this.appsReport(e),n=[...r.apps],i=r.next;for(;i!==null;){let s=await this.appsReport(e,{after:i});n.push(...s.apps),i=s.next}return{...r,apps:n,next:null}}releaseRules(){return this.get("releases")}async pendingApprovals(e=null){let[r,n]=await Promise.all([this.appsReportAll(e),this.releaseRules()]);return Er(r,n)}requestConsent(e){return this.post("consent/requests",e)}async openConsentPage(e,r={}){let n=typeof r=="function"?{navigate:r}:r,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 br(s.requestId);if(s.code!==o)throw new y(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,r={}){let n=r.intervalMs??2e3;for(;;){let i=await this.consentResult(e);if(i.status!=="pending"||r.signal?.aborted||r.expiresAt!==void 0&&Date.now()/1e3>=r.expiresAt)return i;await new Promise(s=>setTimeout(s,n))}}publisherBinding(e){return this.get(`publishers/${l(e)}`)}bindPublisher(e,r,n){return this.postConfirmed(`orgs/${l(e)}/publishers`,{...r},n)}upgradePublished(e,r,n,i){return this.postConfirmed(`orgs/${l(e)}/packages/${l(r)}/upgrade`,{...n},i)}opsApps(e={}){return this.get(`ops/apps${ue(e)}`)}opsOrgs(e={}){return this.get(`ops/orgs${ue(e)}`)}opsServedOrigins(){return this.get("ops/served-origins")}async setReleaseDeadline(e,r){let n=typeof r=="string"?r:r.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,r,n,i){await this.postConfirmed(`orgs/${l(e)}/members`,{account:r,role:n},i)}removeMember(e,r,n){return this.deleteConfirmed(`orgs/${l(e)}/members/${l(r)}`,n)}async setCapabilities(e,r,n,i={}){await this.postConfirmed(`orgs/${l(e)}/capabilities`,{capabilities:r,...i},n)}async setTeamDefaultCapabilities(e,r,n,i){await this.postConfirmed(`orgs/${l(e)}/capabilities`,{team:r,capabilities:n},i)}async createTeam(e,r,n,i){let{teamId:s}=await this.post(`orgs/${l(e)}/teams`,{name:r,join:n,parent:i});return s}getTeam(e,r){return this.get(`orgs/${l(e)}/teams/${l(r)}`)}async updateTeam(e,r,n){await this.post(`orgs/${l(e)}/teams/${l(r)}`,n)}async deleteTeam(e,r){await this.delete(`orgs/${l(e)}/teams/${l(r)}`)}async setTeamMember(e,r,n,i,s={}){await this.postConfirmed(`orgs/${l(e)}/teams/${l(r)}/members`,{account:n,...s},i)}async removeTeamMember(e,r,n,i){await this.deleteConfirmed(`orgs/${l(e)}/teams/${l(r)}/members/${l(n)}`,i)}async invite(e,r,n,i=[],s={}){let{token:o}=await this.postConfirmed(`orgs/${l(e)}/invites`,{role:r,teams:i,...s},n);return o}redeemInvite(e){return this.post(`invites/${l(e)}/redeem`)}async listInvites(e){let{invites:r}=await this.get(`orgs/${l(e)}/invites`);return r}async revokeInvite(e,r,n){await this.deleteConfirmed(`orgs/${l(e)}/invites/${l(r)}`,n)}listAppTeams(e){return this.get(`orgs/${l(e)}/app-teams`)}scopeApps(e,r,n={}){let i={};return n.apps!==void 0&&(i.apps=n.apps),n.shared!==void 0&&(i.shared=n.shared),this.postConfirmed(`orgs/${l(e)}/app-teams`,i,r)}grantDeployer(e,r,n={}){let i=n.until instanceof Date?n.until.toISOString():n.until;return this.postConfirmed("deployers",{deployer:e,...i===void 0?{}:{until:i}},r)}deployers(){return this.get("deployers")}async revokeDeployer(e,r){let n=typeof e=="string"?e:mt(e);await this.deleteConfirmed(`deployers/${l(n)}`,r)}async createDeployment(e,r,n){let{id:i}=await this.postConfirmed("deployments",{name:e,owner:r},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,r){await this.deleteConfirmed(`deployments/${l(e)}`,r)}offerApp(e,r,n){return this.postConfirmed(`deployments/${l(e)}/apps`,{...r},n)}async withdrawApp(e,r,n){await this.deleteConfirmed(`deployments/${l(e)}/apps/${l(r)}`,n)}deploymentOrgs(e){return this.get(`deployments/${l(e)}/orgs`)}};var xr={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},gi=xr.JOIN_OPEN_TEAMS;function pi(...t){return t.reduce((e,r)=>e|xr[r],0)}function Ve(t,e){return(t<<e|t>>>32-e)>>>0}function I(t,e,r,n,i){t[e]=t[e]+t[r]>>>0,t[i]=Ve(t[i]^t[e],16),t[n]=t[n]+t[i]>>>0,t[r]=Ve(t[r]^t[n],12),t[e]=t[e]+t[r]>>>0,t[i]=Ve(t[i]^t[e],8),t[n]=t[n]+t[i]>>>0,t[r]=Ve(t[r]^t[n],7)}function wt(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function Et(t,e,r){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]=wt(t,o*4);n[12]=e>>>0;for(let o=0;o<3;o+=1)n[13+o]=wt(r,o*4);let i=n.slice();for(let o=0;o<10;o+=1)I(i,0,4,8,12),I(i,1,5,9,13),I(i,2,6,10,14),I(i,3,7,11,15),I(i,0,5,10,15),I(i,1,6,11,12),I(i,2,7,8,13),I(i,3,4,9,14);let s=new Uint8Array(64);for(let o=0;o<16;o+=1){let a=i[o]+n[o]>>>0;s[o*4]=a&255,s[o*4+1]=a>>>8&255,s[o*4+2]=a>>>16&255,s[o*4+3]=a>>>24&255}return s}function fi(t,e,r,n){let i=new Uint8Array(n.length);for(let s=0,o=e;s<n.length;s+=64,o+=1){let a=Et(t,o,r),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 vr(t){let e=0n;for(let r=t.length-1;r>=0;r-=1)e=e<<8n|BigInt(t[r]);return e}var yi=(1n<<130n)-5n;function hi(t,e){let r=vr(t.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,n=vr(t.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=vr(c)+(1n<<BigInt(8*c.length));i=(i+d)*r%yi}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 At(t){return new Uint8Array((16-t%16)%16)}function bt(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function mi(t,e){let r=[t,At(t.length),e,At(e.length),bt(t.length),bt(e.length)],n=new Uint8Array(r.reduce((s,o)=>s+o.length,0)),i=0;for(let s of r)n.set(s,i),i+=s.length;return n}function wi(t,e){if(t.length!==32)throw new Error("ChaCha20-Poly1305 needs a 32-byte key");if(e.length!==12)throw new Error("ChaCha20-Poly1305 needs a 12-byte nonce")}function Rt(t,e,r,n=new Uint8Array(0)){wi(t,e);let i=Et(t,0,e).subarray(0,32),s=fi(t,1,e,r),o=hi(i,mi(n,s)),a=new Uint8Array(s.length+16);return a.set(s),a.set(o,s.length),a}var xt=32,Ai=1,bi=3,Ei=2,Ri=32,Pi=32,xi=12,X=t=>new TextEncoder().encode(t),pe=t=>new Uint8Array([t>>8&255,t&255]),Pt=h(X("KEM"),pe(xt)),ge=h(X("HPKE"),pe(xt),pe(Ai),pe(bi));async function vt(t,e){let r=t.length===0?new Uint8Array(32):t,n=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",n,e))}async function vi(t,e,r){let n=new Uint8Array(r),i=new Uint8Array(0);for(let s=1,o=0;o<r;s+=1)i=await vt(t,h(i,e,new Uint8Array([s]))),n.set(i.subarray(0,Math.min(i.length,r-o)),o),o+=i.length;return n}function Le(t,e,r,n){return vt(e,h(X("HPKE-v1"),t,X(r),n))}function Ur(t,e,r,n,i){return vi(e,h(pe(i),X("HPKE-v1"),t,X(r),n),i)}async function Ui(t,e){let r=await Le(Pt,new Uint8Array(0),"eae_prk",t);return Ur(Pt,r,"shared_secret",e,Ri)}async function ki(t,e){let r=new Uint8Array(0),n=await Le(ge,r,"psk_id_hash",r),i=await Le(ge,r,"info_hash",e),s=h(new Uint8Array([Ei]),n,i),o=await Le(ge,t,"secret",r);return{key:await Ur(ge,o,"key",s,Pi),nonce:await Ur(ge,o,"base_nonce",s,xi)}}async function Ut(t,e,r,n,i=new Uint8Array(0),s){if(t.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let o=await q(s),a=await q(e),c=h(await ee(o.privateKey,t),await ee(a.privateKey,t)),d=await Ui(c,h(o.publicKey,t,a.publicKey)),{key:u,nonce:g}=await ki(d,r);return{enc:o.publicKey,ciphertext:Rt(u,g,n,i)}}var St="mero-agent-gate/attest/v3",Ct="mero-agent-gate/provision/v2",Ti=/^[a-z0-9][a-z0-9-]{0,62}$/,Si=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,kt=64,Tt=64*1024,D=class extends Error{constructor(r,n,i){super(r);this.status=n;this.code=i;this.name="AgentGateError"}};function Ot(t){if(!Ti.test(t))throw new Error(`Agent id ${JSON.stringify(t)} must match [a-z0-9][a-z0-9-]{0,62}`)}function fe(t){return new TextEncoder().encode(t)}function It(t){let e=fe(t);return h(new Uint8Array([e.length]),e)}function G(t){let e="";for(let r of t)e+=String.fromCharCode(r);return btoa(e)}function Ge(t,e,r){let n;try{n=Uint8Array.from(atob(t.trim()),i=>i.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(r!==void 0&&n.length!==r)throw new Error(`${e} is not ${r} bytes`);return n}async function Dt(t,e,r,n){let i=new Uint8Array(32),s=h(fe(St),t,It(e),r??i,n??i);return new Uint8Array(await crypto.subtle.digest("SHA-256",s))}function Nt(t,e){return h(fe(Ct),t,It(e))}async function Ci(){let t=crypto.getRandomValues(new Uint8Array(32));return{secret:t,publicKey:await He(t)}}async function He(t){if(t.length!==32)throw new Error("An owner key is 32 bytes");return G((await q(t)).publicKey)}function _t(t,e){return`${t.replace(/\/+$/,"")}${e}`}async function Mt(t,e,r){let n=await t(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)}),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 kr(t){let e=t.agentId??"";e&&Ot(e);let r=crypto.getRandomValues(new Uint8Array(32)),n=await Mt(t.fetch??fetch,_t(t.gateUrl,"/attest"),{nonceB64:G(r),...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=Ge(n.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),s=n.signingPublicKeyB64?Ge(n.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,o=n.ownerPublicKeyB64?Ge(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 Dt(i,e,s,o);return await t.verifier({quoteB64:n.quoteB64,nonce:R(r),reportDataSuffix:R(a)}),{agentId:e,provisioningPublicKey:G(i),...s?{signingPublicKey:G(s)}:{},...o?{ownerPublicKey:G(o)}:{}}}async function $t(t,e){let r=await He(e);if(t.ownerPublicKey&&t.ownerPublicKey!==r)throw new D(`This agent is claimed by another key (${t.ownerPublicKey}); it is not yours. Send it nothing and do not authorize its signing key`,void 0,"not_yours");return r}function Oi(t){let e=Object.keys(t);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>kt)throw new Error(`At most ${kt} secrets at once`);for(let r of e){if(!Si.test(r))throw new Error(`Secret name ${JSON.stringify(r)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);if(typeof t[r]!="string")throw new Error(`Secret ${r} is not a string`);if(fe(t[r]).length>Tt)throw new Error(`Secret ${r} is over ${Tt} bytes`)}}async function Bt(t,e,r,n,i,s){if(!n.agentId)throw new Error("This quote names no agent; attest with the agent id");let o=await $t(n,i),a=Ge(n.provisioningPublicKey,"provisioningPublicKey",32),c=await Ut(a,i,Nt(a,n.agentId),fe(JSON.stringify(s)));return Mt(t,_t(e,r),{agentId:n.agentId,provisioningPublicKeyB64:n.provisioningPublicKey,senderPublicKeyB64:o,encappedKeyB64:G(c.enc),ciphertextB64:G(c.ciphertext)})}async function Ii(t){Oi(t.secrets);let e=t.fetch??fetch,r=await Bt(e,t.gateUrl,"/provision",t.agent,t.ownerSecret,{secrets:t.secrets}),n=await kr({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e}),i=await He(t.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(t.agent.signingPublicKey&&t.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:r?.written??[],claimed:r?.claimed===!0}}async function Di(t){if(!t.agent.ownerPublicKey)throw new Error("This agent is not claimed; there is nothing to release");let e=t.fetch??fetch;if(await Bt(e,t.gateUrl,"/release",t.agent,t.ownerSecret,{release:!0}),(await kr({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e})).ownerPublicKey)throw new D("The gate says it released the agent, but its quote still names an owner")}var Tr=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),Ni=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function _i(t,e,r={}){let n=typeof t=="string"?new TextEncoder().encode(t):t;await be(n,e,{identity:r.identity??Tr.identity,issuer:r.issuer??Tr.issuer});let i;try{i=JSON.parse(new TextDecoder().decode(n))}catch{throw new Error("The signed agent policy is not JSON")}let s=r.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=r.profile??M;if(i.profile!==o)throw new Error(`The signed agent policy is for the ${JSON.stringify(i.profile)} profile, not ${o}`);if(r.expectedVersion!==void 0&&i.version!==r.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(i.version)}, not ${r.expectedVersion}`);return Kt(i),i}function Kt(t){for(let e of Ni)if(!Array.isArray(t?.[e])||t[e].length===0)throw new Error(`The agent policy's ${e} is empty, so no agent would be accepted`)}var Mi=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function $i(t){let e=Mi.find(r=>r.toLowerCase()===t.trim().toLowerCase());if(!e)throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(t)}`);return e}var ye=t=>t.trim().replace(/^0x/i,"");function Bi(t,e){return Kt(t),$({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:t.allowed_tcb_statuses.map($i),allowedMrtd:t.allowed_mrtd.map(ye),allowedRtmr0:t.allowed_rtmr0.map(ye),allowedRtmr1:t.allowed_rtmr1.map(ye),allowedRtmr2:t.allowed_rtmr2.map(ye),allowedRtmr3:t.allowed_rtmr3.map(ye)})}export{St as AGENT_ATTEST_DOMAIN,Ct as AGENT_PROVISION_INFO_DOMAIN,D as AgentGateError,Me as AppError,ve as ArgsTooLarge,Se as BadOrigin,Pr as CalimeroClient,y as CalimeroError,Ie as ClusterNotUpgraded,oe as ConfirmCancelled,ae as ConfirmPromptBlocked,Z as ConfirmRequired,Te as ConsentStale,sr as DEFAULT_COLLATERAL_MIRROR,gr as DEFAULT_DIRECTORY,gi as DEFAULT_ORG_CAPABILITIES,Ee as DEFAULT_RELEASE_MIRROR,k as DirectoryError,Jr as GITHUB_RELEASES,_r as HANDSHAKE_PATH,Ue as IdempotencyMismatch,Tr as KMS_RELEASE_SIGNER,B as LoginRequired,mr as MAX_RECOVERY_NONCE_BYTES,Ar as MAX_REPORT_PAGE,Xr as MOCK_QUOTE_HEADER,ir as NODE_RELEASE_SIGNER,xe as NotFound,Oe as NotServing,xr as ORG_CAPABILITIES,V as OriginNotRegistered,Ce as OriginTaken,M as PRODUCTION_PROFILE,Pe as PasskeyUnknownHere,_e as QuotaExceeded,nt as RECOVERY_DOMAIN,dt as RELEASE_VERIFIER,De as RecoveryNotReady,ke as ReleaseDeadlineError,te as SEALED_CONTENT_TYPE,Mr as SEALED_PATH,T as SealedTransportError,Ne as SignUpRefused,ne as StaleTransportKeyError,$e as TrapError,L as UnavailableError,K as WrongNode,ce as WrongRecoveryCode,Dt as agentKeyBinding,Bi as agentQuoteVerifier,kr as attestAgent,P as b64url,Qn as browserPasskey,$t as checkOwner,Wr as claimedRelease,cr as cloudNodeReleaseUrl,de as compareVersions,br as confirmationCode,ei as consentReturn,$ as createQuoteVerifier,We as createSealedFetch,Mn as createSignedReleaseVerifier,mt as deployerKey,Ke as errorFrom,ur as fetchAttestedKey,ar as fetchGithubNodeRelease,or as fetchNodeRelease,et as freshCollateral,O as fromB64url,ni as frontendManifest,Ci as generateOwnerKey,Yn as newRecoverySeed,pi as orgCapabilities,He as ownerPublicKey,ii as pageDeployment,ue as pageQuery,zn as parseRecoverySeed,Er as pendingApprovalsFrom,Ii as provisionAgent,Nt as provisionInfo,Xn as publisherBindingBytes,lt as publisherBindingMessage,it as recoveryMessage,Zn as recoveryPublicKey,Jn as recoverySeedText,Di as releaseAgent,pt as releaseConsent,ut as releaseNotesUrl,wr as signRecovery,ct as stalledBy,Xe as transportKeyBinding,Re as trustSignedRelease,nr as trustedMeasurementsFromReleases,ti as upgradeConsent,Ot as validateAgentId,gt as verifyReleaseUrl,_i as verifySignedAgentPolicy,Yr as verifySignedNodeRelease,ri as withdrawConsent};
|
|
9
9
|
//# sourceMappingURL=index.browser.mjs.map
|