@calimero-network/mero-js 27.5.0 → 28.1.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.
@@ -16,6 +16,44 @@ import { CalimeroError, ConfirmCancelled, ConfirmRequired, LoginRequired, Unavai
16
16
  import { b64url, fromB64url } from './passkey.js';
17
17
  import { confirmationCode, pageQuery, pendingApprovalsFrom, } from './approvals.js';
18
18
  export { AppError, ArgsTooLarge, CalimeroError, ConfirmCancelled, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, NotFound, ReleaseDeadlineError, TrapError, UnavailableError, WrongNode, errorFrom, } from './errors.js';
19
+ /** A deployer's key, as `GET /deployers` lists it and `DELETE /deployers/{key}` takes it. */
20
+ export function deployerKey(deployer) {
21
+ return 'account' in deployer ? `account:${deployer.account}` : `org:${deployer.org}`;
22
+ }
23
+ /**
24
+ * Read the `/.well-known/calimero.json` of the frontend at `origin` (by
25
+ * default the page's own). Served in the clear by the frontend host, like the
26
+ * page itself: for choosing a deployment and the API URL to connect to, never
27
+ * for trust (the client attests the node it then talks to).
28
+ */
29
+ export async function frontendManifest(origin, fetcher = fetch) {
30
+ const base = origin ?? globalThis.location?.origin;
31
+ if (!base)
32
+ throw new Error('no page origin to read the frontend manifest from; pass `origin`');
33
+ const response = await fetcher(new URL('/.well-known/calimero.json', base).toString());
34
+ if (!response.ok)
35
+ throw await refusal(response);
36
+ const manifest = (await response.json());
37
+ return { ...manifest, deployments: manifest.deployments ?? [] };
38
+ }
39
+ /**
40
+ * The deployment a frontend page was opened for: the node serves
41
+ * `/d/{deployment}/` by redirecting to `/{version}/…?deployment={id}`, so the
42
+ * page creates its instances from that deployment
43
+ * (`createApp(name, { deployment, package })`). `null` when the page was
44
+ * not opened through a deployment. `href` defaults to `window.location.href`.
45
+ */
46
+ export function pageDeployment(href) {
47
+ const at = href ?? globalThis.location?.href;
48
+ if (!at)
49
+ return null;
50
+ try {
51
+ return new URL(at).searchParams.get('deployment') || null;
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ }
19
57
  /** One URL path segment, so an id cannot reach another route. */
20
58
  function seg(value) {
21
59
  return encodeURIComponent(value);
@@ -478,19 +516,21 @@ export class CalimeroClient {
478
516
  me() {
479
517
  return this.get('auth/me');
480
518
  }
481
- /** Add another passkey (another device) to the signed-in account; answers its credential id. */
482
- async addPasskey(passkey) {
519
+ /**
520
+ * Add another passkey (another device, `passkey`) to the signed-in account;
521
+ * answers its credential id. The node asks for the approval of a passkey
522
+ * the account already has (`412 CONFIRM_REQUIRED`, never the new one),
523
+ * which `approver` gives.
524
+ */
525
+ async addPasskey(passkey, approver) {
483
526
  const begin = await this.post('auth/passkeys/add/begin');
484
527
  const registration = await passkey.create(begin.options);
485
- const { credentialId } = await this.post('auth/passkeys/add/finish', {
486
- challengeId: begin.challengeId,
487
- registration,
488
- });
528
+ const { credentialId } = await this.postConfirmed('auth/passkeys/add/finish', { challengeId: begin.challengeId, registration }, approver);
489
529
  return credentialId;
490
530
  }
491
- /** Remove one of the account's passkeys (not the last). */
492
- async removePasskey(credentialId) {
493
- await this.delete(`auth/passkeys/${seg(credentialId)}`);
531
+ /** Remove one of the account's passkeys (not the last), approved with `passkey` (one it has). */
532
+ async removePasskey(credentialId, passkey) {
533
+ await this.deleteConfirmed(`auth/passkeys/${seg(credentialId)}`, passkey);
494
534
  }
495
535
  /** Name one of the account's passkeys (a device label); `''` clears the name. */
496
536
  async labelPasskey(credentialId, label) {
@@ -519,9 +559,13 @@ export class CalimeroClient {
519
559
  async revokeApiKey(keyId) {
520
560
  await this.delete(`auth/apikeys/${seg(keyId)}`);
521
561
  }
522
- /** Create an API key for an agent or server. The key is returned once. */
523
- createApiKey(options) {
524
- return this.post('auth/apikeys', options);
562
+ /**
563
+ * Create an API key for an agent or server, approved with the account's
564
+ * `passkey` (`412 CONFIRM_REQUIRED`); needs a passkey session (an API key
565
+ * is refused `403`). The key is returned once.
566
+ */
567
+ createApiKey(options, passkey) {
568
+ return this.postConfirmed('auth/apikeys', { ...options }, passkey);
525
569
  }
526
570
  // ---------------------------------------------------------------- apps
527
571
  /** Upload a raw WASM bundle (development clusters only); answers its hash. */
@@ -529,14 +573,41 @@ export class CalimeroClient {
529
573
  const { hash } = await this.json('POST', 'bundles', undefined, wasm);
530
574
  return hash;
531
575
  }
532
- /** Upload a blob for `app`: `blobId` is base58 (what apps print), `id` hex. */
533
- uploadBlob(app, data) {
534
- return this.json('POST', `apps/${seg(app)}/blobs`, undefined, data);
576
+ /**
577
+ * Upload a blob for `app`: `blobId` is base58 (what apps print), `id` hex.
578
+ * `contentType` (default `application/octet-stream`; printable ASCII, the
579
+ * node refuses another with `400`) is sent as the upload's `Content-Type`:
580
+ * a component app records it and serves downloads with it. A component
581
+ * app holding as many blobs as it may answers `429 QUOTA_EXCEEDED`.
582
+ */
583
+ uploadBlob(app, data, contentType = {}) {
584
+ const mime = (typeof contentType === 'string' ? contentType : contentType.contentType) ?? 'application/octet-stream';
585
+ return this.json('POST', `apps/${seg(app)}/blobs`, undefined, data, mime);
535
586
  }
536
587
  /** One of `app`'s blobs, by id (base58 or hex). */
537
588
  async downloadBlob(app, id) {
538
- const response = await this.send('GET', `apps/${seg(app)}/blobs/${seg(id)}`);
539
- return new Uint8Array(await response.arrayBuffer());
589
+ return (await this.blobContent(app, id)).data;
590
+ }
591
+ /**
592
+ * Download a component app's blob with a grant one of its runs handed out
593
+ * (`BlobRef::grant`, up to 24 h). No session needed: the grant is the
594
+ * permission. A bad or expired grant answers `NotFound`, as a missing blob.
595
+ */
596
+ async downloadBlobGranted(app, id, grant) {
597
+ return (await this.blobContent(app, id, { grant })).data;
598
+ }
599
+ /**
600
+ * {@link downloadBlob} (or, with `grant`, {@link downloadBlobGranted}) with
601
+ * the content type the node serves it as: the uploader's, for a component
602
+ * app; `application/octet-stream` otherwise.
603
+ */
604
+ async blobContent(app, id, options = {}) {
605
+ const query = options.grant === undefined ? '' : `?grant=${encodeURIComponent(options.grant)}`;
606
+ const response = await this.send('GET', `apps/${seg(app)}/blobs/${seg(id)}${query}`);
607
+ return {
608
+ data: new Uint8Array(await response.arrayBuffer()),
609
+ contentType: response.headers.get('content-type') ?? 'application/octet-stream',
610
+ };
540
611
  }
541
612
  /** `app`'s blobs. */
542
613
  async listBlobs(app) {
@@ -600,6 +671,15 @@ export class CalimeroClient {
600
671
  async setAppMetadata(app, metadata) {
601
672
  await this.post(`apps/${seg(app)}/metadata`, { metadata });
602
673
  }
674
+ /**
675
+ * A component app's xcalls: how many messages wait in its outbox, and the
676
+ * dead letters (never delivered), newest last. Its owner's or an org
677
+ * admin's (`403` to anyone else); `409 NOT_SUPPORTED` for an app on the
678
+ * wasmer runtime, whose xcalls are follow-ups.
679
+ */
680
+ appXcalls(app) {
681
+ return this.get(`apps/${seg(app)}/xcalls`);
682
+ }
603
683
  /** What the app's storage holds: `{ keys, bytes, blobs, blobBytes }`. */
604
684
  appStorage(app) {
605
685
  return this.get(`apps/${seg(app)}/storage`);
@@ -631,12 +711,19 @@ export class CalimeroClient {
631
711
  }
632
712
  /**
633
713
  * POST `body` to `path`, answering a `412 CONFIRM_REQUIRED` with `passkey`'s
634
- * assertion over the node's challenge (deleting an org, approving a release, ...).
714
+ * assertion over the node's challenge (deleting an org, approving a release,
715
+ * adding a member, ...): the same body again, with `confirm`. Without a
716
+ * passkey (a caller in plain JavaScript passing none) the `412` reaches the
717
+ * caller as {@link ConfirmRequired}, carrying the challenge.
635
718
  */
636
719
  postConfirmed(path, body, passkey) {
637
720
  return this.confirmed('POST', path, body, passkey);
638
721
  }
639
- /** {@link postConfirmed} for a DELETE (deleting an organization). */
722
+ /**
723
+ * {@link postConfirmed} for a DELETE (deleting an organization, removing a
724
+ * member or a passkey): `body` (`{}` by default) goes as JSON, and the
725
+ * confirmed retry carries `confirm` beside it.
726
+ */
640
727
  deleteConfirmed(path, passkey, body = {}) {
641
728
  return this.confirmed('DELETE', path, body, passkey);
642
729
  }
@@ -645,7 +732,7 @@ export class CalimeroClient {
645
732
  return await send(body);
646
733
  }
647
734
  catch (error) {
648
- if (!(error instanceof ConfirmRequired))
735
+ if (!(error instanceof ConfirmRequired) || !passkey)
649
736
  throw error;
650
737
  const d = error.details;
651
738
  let assertion;
@@ -666,7 +753,13 @@ export class CalimeroClient {
666
753
  /**
667
754
  * Create an app instance from a bundle hash, or from a package release
668
755
  * (`{ package, version?, service? }`, installed from the registry first if
669
- * the cluster lacks it).
756
+ * the cluster lacks it). With `deployment`, the instance runs the release
757
+ * that deployment offers for `package` (`version`, if given, must be it)
758
+ * and records the deployment; no install, no deployer grant. A package or
759
+ * version it does not offer answers `400 NOT_OFFERED`, several offered
760
+ * releases with no `version` `400 VERSION_REQUIRED`, and an unknown
761
+ * `service` `400 NO_SUCH_SERVICE`. A page opened through `/d/{deployment}/`
762
+ * finds its deployment with {@link pageDeployment}.
670
763
  */
671
764
  async createApp(name, bundle, options = {}) {
672
765
  const target = typeof bundle === 'string' ? { bundle } : bundle;
@@ -973,20 +1066,24 @@ export class CalimeroClient {
973
1066
  async liftReleaseDeadline(version) {
974
1067
  await this.delete(`ops/releases/${seg(version)}/deadline`);
975
1068
  }
976
- /** Add a member, or change their role. */
977
- async setMember(org, account, role) {
978
- await this.post(`orgs/${seg(org)}/members`, { account, role });
1069
+ /** Add a member, or change their role, approved with the caller's `passkey`. */
1070
+ async setMember(org, account, role, passkey) {
1071
+ await this.postConfirmed(`orgs/${seg(org)}/members`, { account, role }, passkey);
979
1072
  }
980
- removeMember(org, account) {
981
- return this.delete(`orgs/${seg(org)}/members/${seg(account)}`);
1073
+ /**
1074
+ * Remove a member, or leave (`account` the caller's own), approved with the
1075
+ * caller's `passkey`.
1076
+ */
1077
+ removeMember(org, account, passkey) {
1078
+ return this.deleteConfirmed(`orgs/${seg(org)}/members/${seg(account)}`, passkey);
982
1079
  }
983
1080
  /**
984
1081
  * Set capability bits ({@link ORG_CAPABILITIES}): for a member (`account`),
985
1082
  * for a member of one team (`account` and `team`), or the organization's
986
- * default (neither).
1083
+ * default (neither). Approved with the caller's `passkey`.
987
1084
  */
988
- async setCapabilities(org, capabilities, at = {}) {
989
- await this.post(`orgs/${seg(org)}/capabilities`, { capabilities, ...at });
1085
+ async setCapabilities(org, capabilities, passkey, at = {}) {
1086
+ await this.postConfirmed(`orgs/${seg(org)}/capabilities`, { capabilities, ...at }, passkey);
990
1087
  }
991
1088
  async createTeam(org, name, join, parent) {
992
1089
  const { teamId } = await this.post(`orgs/${seg(org)}/teams`, { name, join, parent });
@@ -1006,18 +1103,104 @@ export class CalimeroClient {
1006
1103
  async deleteTeam(org, team) {
1007
1104
  await this.delete(`orgs/${seg(org)}/teams/${seg(team)}`);
1008
1105
  }
1009
- /** Add a member to a team, or change their row: role, lead, capability bits. */
1010
- async setTeamMember(org, team, account, row = {}) {
1011
- await this.post(`orgs/${seg(org)}/teams/${seg(team)}/members`, { account, ...row });
1106
+ /**
1107
+ * Add a member to a team, or change their row: role, lead, capability bits.
1108
+ * Approved with the caller's `passkey`.
1109
+ */
1110
+ async setTeamMember(org, team, account, passkey, row = {}) {
1111
+ await this.postConfirmed(`orgs/${seg(org)}/teams/${seg(team)}/members`, { account, ...row }, passkey);
1012
1112
  }
1013
- async removeTeamMember(org, team, account) {
1014
- await this.delete(`orgs/${seg(org)}/teams/${seg(team)}/members/${seg(account)}`);
1113
+ /** Remove a member from a team, approved with the caller's `passkey`. */
1114
+ async removeTeamMember(org, team, account, passkey) {
1115
+ await this.deleteConfirmed(`orgs/${seg(org)}/teams/${seg(team)}/members/${seg(account)}`, passkey);
1015
1116
  }
1016
- async invite(org, role, teams = [], options = {}) {
1017
- const { token } = await this.post(`orgs/${seg(org)}/invites`, { role, teams, ...options });
1117
+ /**
1118
+ * Make an invite into `org` (and `teams`), approved with the caller's
1119
+ * `passkey`; answers its token, which {@link redeemInvite} takes (no
1120
+ * approval there).
1121
+ */
1122
+ async invite(org, role, passkey, teams = [], options = {}) {
1123
+ const { token } = await this.postConfirmed(`orgs/${seg(org)}/invites`, { role, teams, ...options }, passkey);
1018
1124
  return token;
1019
1125
  }
1020
1126
  redeemInvite(token) {
1021
1127
  return this.post(`invites/${seg(token)}/redeem`);
1022
1128
  }
1129
+ // ---------------------------------------------------------------- deployers
1130
+ /**
1131
+ * Let an account or organization install apps where the cluster's
1132
+ * deployments are `granted`, until `until` (RFC 3339 or a `Date`; absent,
1133
+ * the grant does not end). The cluster's owner grants it, approved with
1134
+ * `passkey`, where governance says `deployers: owner`; elsewhere the
1135
+ * operator grants with its key, and this is refused `403`.
1136
+ */
1137
+ grantDeployer(deployer, passkey, options = {}) {
1138
+ const until = options.until instanceof Date ? options.until.toISOString() : options.until;
1139
+ return this.postConfirmed('deployers', { deployer, ...(until === undefined ? {} : { until }) }, passkey);
1140
+ }
1141
+ /**
1142
+ * Who may install apps on the cluster: its deployments rule, who grants
1143
+ * deployers, its owner and every grant. For the cluster's owner, or the
1144
+ * operator (its token, `useApiKey`).
1145
+ */
1146
+ deployers() {
1147
+ return this.get('deployers');
1148
+ }
1149
+ /**
1150
+ * End a deployer's grant (`deployer`, or its key `account:{id}` /
1151
+ * `org:{id}`), as the cluster's owner, approved with `passkey`. Apps it
1152
+ * installed, and the apps running them, stay.
1153
+ */
1154
+ async revokeDeployer(deployer, passkey) {
1155
+ const key = typeof deployer === 'string' ? deployer : deployerKey(deployer);
1156
+ await this.deleteConfirmed(`deployers/${seg(key)}`, passkey);
1157
+ }
1158
+ // ---------------------------------------------------------------- deployments
1159
+ /**
1160
+ * Create a deployment: `owner`'s (the caller's own account, or an
1161
+ * organization where it holds `MANAGE_APPLICATION` org-wide) list of the
1162
+ * apps it offers, named `name` (1 to 64 characters, one line) for
1163
+ * customers. Approved with `passkey`; where deployments are `granted` the
1164
+ * caller needs a deployer grant. Answers the deployment's id.
1165
+ */
1166
+ async createDeployment(name, owner, passkey) {
1167
+ const { id } = await this.postConfirmed('deployments', { name, owner }, passkey);
1168
+ return id;
1169
+ }
1170
+ /** The deployments the caller manages: its account's, and its organizations' where it holds `MANAGE_APPLICATION`. */
1171
+ async deployments() {
1172
+ const { deployments } = await this.get('deployments');
1173
+ return deployments;
1174
+ }
1175
+ /** A deployment as anyone may read it: its name, its owner's kind and name, and the apps it offers. Public. */
1176
+ deployment(id) {
1177
+ return this.get(`deployments/${seg(id)}`);
1178
+ }
1179
+ /** Delete a deployment that offers nothing and has no instances, approved with `passkey`. */
1180
+ async deleteDeployment(id, passkey) {
1181
+ await this.deleteConfirmed(`deployments/${seg(id)}`, passkey);
1182
+ }
1183
+ /**
1184
+ * Offer `package@version` (installed, and seen by the caller) as `app`
1185
+ * (1 to 64 letters, digits, `.`, `_`, `-`) in deployment `id`, or move an
1186
+ * offered app to another release of its package. Approved with `passkey`.
1187
+ */
1188
+ offerApp(id, offer, passkey) {
1189
+ return this.postConfirmed(`deployments/${seg(id)}/apps`, { ...offer }, passkey);
1190
+ }
1191
+ /**
1192
+ * Withdraw `app` from deployment `id`, approved with `passkey`; refused
1193
+ * while an instance created from the deployment still runs it.
1194
+ */
1195
+ async withdrawApp(id, app, passkey) {
1196
+ await this.deleteConfirmed(`deployments/${seg(id)}/apps/${seg(app)}`, passkey);
1197
+ }
1198
+ /**
1199
+ * The organizations with instances created from deployment `id`, for its
1200
+ * managers: each one's id, name, instance count, apps and releases, and
1201
+ * first instance. Never members, teams or app data.
1202
+ */
1203
+ deploymentOrgs(id) {
1204
+ return this.get(`deployments/${seg(id)}/orgs`);
1205
+ }
1023
1206
  }
@@ -1,9 +1,9 @@
1
- export { CalimeroClient } from './client.js';
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
4
  export { AppError, ArgsTooLarge, CalimeroError, ConfirmCancelled, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, NotFound, ReleaseDeadlineError, TrapError, UnavailableError, WrongNode, errorFrom, } from './errors.js';
5
5
  export type { Committed } from './errors.js';
6
- export type { AppInfo, BlobInfo, CallResult, CalimeroClientOptions, CalimeroConnectOptions, CloudEvent, CalimeroSession, PackageInfo, PackageInstalled, CloudRetryOptions, OrgInfo, OrgUpgradeTarget, PresenceEntry, UpgradeRun, ViewResult, } from './client.js';
6
+ export type { AppInfo, AppXcalls, BlobContent, BlobInfo, DeadLetter, Deployer, DeployerGrant, DeployersInfo, DeploymentInfo, DeploymentOffer, DeploymentOrgs, FrontendManifest, 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,4 +1,4 @@
1
- export { CalimeroClient } from './client.js';
1
+ export { CalimeroClient, deployerKey, frontendManifest, pageDeployment } from './client.js';
2
2
  export { DEFAULT_DIRECTORY, DirectoryError } from './directory.js';
3
3
  export { AppError, ArgsTooLarge, CalimeroError, ConfirmCancelled, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, NotFound, ReleaseDeadlineError, TrapError, UnavailableError, WrongNode, errorFrom, } from './errors.js';
4
4
  export { claimedRelease, fetchAttestedKey, freshCollateral, MOCK_QUOTE_HEADER } from './attestation.js';