@calimero-network/mero-react 9.11.2 → 9.11.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -130,6 +130,8 @@ Every hook in this package goes through that `admin`, never the raw `mero.admin`
130
130
 
131
131
  How an account (delegated session) learns its `applicationId`: `packageName` decides. When the app passes one, the id is derived from the registry: `sha256(borsh((package, signerId)))` of the newest non-yanked bundle, exactly as merod computes it at install, so a brand-new account can found its first namespace (`admin.createNamespace({ applicationId })`) and an account already used in other apps is never handed one of THEIR ids. The account's own contexts on the relay are consulted only when the app passes no `packageName` (or the registry did not answer, after one `console.warn`): one distinct application across them is the answer; several leaves it `null` on purpose (nothing says which the tab is for). When the registry lists the package under more than one publisher, it stays `null`. `applicationIdForBundle` and `resolveApplicationIdFromRegistry` are exported for apps that need the same derivation.
132
132
 
133
+ On an account, `admin.createContext(request)` (and `useCreateContext`) signs a creation warrant the relay acts on: `applicationId`, `groupId`, `serviceName` (which service of a multi-service bundle, e.g. mero-docs' `registry`), `name`, `contextSeed` and `initializationParams` are all carried into it; `identitySecret` is not, since the account itself is the new context's member identity.
134
+
133
135
  Through `mero` you access the full MeroJs API:
134
136
 
135
137
  ```tsx
package/dist/index.cjs CHANGED
@@ -319,10 +319,79 @@ function relaySession(s, nodeKey) {
319
319
  return inflight;
320
320
  };
321
321
  }
322
+ var methodKinds = /* @__PURE__ */ new Map();
323
+ function isNotAView(e) {
324
+ return typeof e === "object" && e !== null && e.status === 409;
325
+ }
326
+ function readsThroughQuery(client2, relayUrl) {
327
+ const inner = client2.rpc;
328
+ const origin2 = relayOrigin(relayUrl);
329
+ const run = async (params) => {
330
+ const key = `${origin2}|${params.contextId}|${params.method}`;
331
+ if (methodKinds.get(key) !== "write") {
332
+ try {
333
+ const { returns } = await client2.admin.queryContext(params.contextId, {
334
+ method: params.method,
335
+ // The node defaults a warrant's missing `argsJson` to `{}`; the same here.
336
+ argsJson: params.argsJson ?? {}
337
+ });
338
+ methodKinds.set(key, "read");
339
+ return { returns, transport: "relay" };
340
+ } catch (e) {
341
+ if (isNotAView(e)) methodKinds.set(key, "write");
342
+ }
343
+ }
344
+ return inner.executeWithMetadata(params);
345
+ };
346
+ return {
347
+ get kind() {
348
+ return inner.kind;
349
+ },
350
+ get canSubscribe() {
351
+ return inner.canSubscribe;
352
+ },
353
+ execute: async (params) => (await run(params)).returns,
354
+ executeWithMetadata: run,
355
+ migrateMyEntries: (contextId) => inner.migrateMyEntries(contextId),
356
+ countMyPending: (contextId) => inner.countMyPending(contextId)
357
+ };
358
+ }
359
+ function dormantEvents(relayUrl) {
360
+ return new meroJs.SseClient({
361
+ baseUrl: relayUrl,
362
+ authorize: async () => ({}),
363
+ fetch: (_url, init) => new Promise((_, reject) => {
364
+ const abort = () => reject(Object.assign(new Error("the stream was closed before the relay was attested"), { name: "AbortError" }));
365
+ if (init?.signal?.aborted) return abort();
366
+ init?.signal?.addEventListener("abort", abort, { once: true });
367
+ })
368
+ });
369
+ }
370
+ function delegatedClient(client2, opts) {
371
+ const rpc = opts.session ? readsThroughQuery(client2, opts.relayUrl) : null;
372
+ let dormant = null;
373
+ return new Proxy(client2, {
374
+ get(target, prop) {
375
+ if (prop === "rpc" && rpc) return rpc;
376
+ if (!opts.attested) {
377
+ if (prop === "canSubscribe") return false;
378
+ if (prop === "events") return dormant ?? (dormant = dormantEvents(opts.relayUrl));
379
+ if (prop === "close") {
380
+ return () => {
381
+ dormant?.close();
382
+ target.close();
383
+ };
384
+ }
385
+ }
386
+ const value = Reflect.get(target, prop, target);
387
+ return typeof value === "function" ? value.bind(target) : value;
388
+ }
389
+ });
390
+ }
322
391
  function buildDelegatedClient(s, _contextId) {
323
392
  if (!s.relayUrl) return null;
324
393
  const nodeKey = readPinnedRelayNodeKey(s.relayUrl);
325
- return meroJs.createMeroClient({
394
+ const client2 = meroJs.createMeroClient({
326
395
  transport: "relay",
327
396
  relay: {
328
397
  relayUrl: s.relayUrl,
@@ -356,6 +425,11 @@ function buildDelegatedClient(s, _contextId) {
356
425
  // through its own device-certificate login instead.
357
426
  observe: nodeKey ? { nodeKey } : void 0
358
427
  });
428
+ return delegatedClient(client2, {
429
+ relayUrl: s.relayUrl,
430
+ session: nodeKey !== null,
431
+ attested: nodeKey !== null || isLoopback(s.relayUrl)
432
+ });
359
433
  }
360
434
  var RELAY_MAP_PREFIX = "calimero.delegated.relays.";
361
435
  function readRelayMap(account) {
@@ -530,6 +604,8 @@ async function createDelegatedContext(s, req, deps = {}) {
530
604
  const created = await client(s, relay, { next: async () => creationNonce }, deps.fetch).createContext({
531
605
  groupId: req.groupId ?? req.namespaceId,
532
606
  applicationId: req.applicationId,
607
+ serviceName: req.serviceName,
608
+ seed: req.contextSeed,
533
609
  initArgs: initArgsOf(req.initializationParams),
534
610
  name: req.name
535
611
  });
@@ -729,7 +805,7 @@ var NoRelayError = class extends Error {
729
805
  var InvitationNotClaimableError = class extends Error {
730
806
  constructor(namespaceId, reason) {
731
807
  super(
732
- reason === "not-hosted" ? `nobody could claim an invitation to ${namespaceId} yet: the namespace is not hosted in the cloud, so an invitee with no node has no relay to be admitted through. Link this account to your cloud user in the wallet and enable HA for the namespace, then invite.` : `nobody could claim an invitation to ${namespaceId}: the cloud routes to none of the relays or admins it would name as admitters`
808
+ reason === "not-hosted" ? `nobody could claim an invitation to ${namespaceId} yet: the namespace is not hosted in the cloud and has no relay in it, so an invitee with no node has no relay to be admitted through. Link this account to your cloud user in the wallet and enable HA for the namespace, then invite.` : `nobody could claim an invitation to ${namespaceId}: the cloud routes to none of the relays or admins it would name as admitters`
733
809
  );
734
810
  this.namespaceId = namespaceId;
735
811
  this.reason = reason;
@@ -907,14 +983,17 @@ function createAccountAdmin(input, deps = {}) {
907
983
  namespaceId,
908
984
  groupId: req.groupId,
909
985
  applicationId: req.applicationId,
986
+ serviceName: req.serviceName,
987
+ contextSeed: req.contextSeed,
910
988
  name: req.name,
911
989
  initializationParams: req.initializationParams
912
990
  });
913
- return { contextId, memberPublicKey: "", groupId: req.groupId };
991
+ return { contextId, memberPublicKey: s.account, groupId: req.groupId };
914
992
  },
915
993
  async createNamespaceInvitation(namespaceId) {
916
994
  const [{ members }, info] = await Promise.all([relay().listGroupMembers(namespaceId), relay().getGroupInfo(namespaceId)]);
917
995
  const relays = members.filter((m) => m.role === "RelayTee").map((m) => m.identity.toLowerCase());
996
+ let admitterAddrs;
918
997
  if (routing) {
919
998
  const named = new Set(
920
999
  relays.length > 0 ? relays : members.filter((m) => m.role === "Admin").map((m) => m.identity.toLowerCase())
@@ -925,8 +1004,10 @@ function createAccountAdmin(input, deps = {}) {
925
1004
  } catch {
926
1005
  }
927
1006
  if (nodes !== null) {
928
- if (nodes.length === 0) throw new InvitationNotClaimableError(namespaceId, "not-hosted");
929
- if (!nodes.some((n) => n.account !== null && named.has(n.account.toLowerCase()))) {
1007
+ if (nodes.length === 0) {
1008
+ if (relays.length === 0 || !s.relayUrl) throw new InvitationNotClaimableError(namespaceId, "not-hosted");
1009
+ admitterAddrs = [s.relayUrl];
1010
+ } else if (!nodes.some((n) => n.account !== null && named.has(n.account.toLowerCase()))) {
930
1011
  throw new InvitationNotClaimableError(namespaceId, "no-named-node");
931
1012
  }
932
1013
  }
@@ -936,6 +1017,7 @@ function createAccountAdmin(input, deps = {}) {
936
1017
  inviterAccount: s.account,
937
1018
  deviceSecret: s.deviceSecret,
938
1019
  ...relays.length > 0 ? { admitters: relays } : {},
1020
+ ...admitterAddrs ? { admitterAddrs } : {},
939
1021
  members,
940
1022
  applicationId: info.targetApplicationId,
941
1023
  appKey: info.appKey
@@ -1072,6 +1154,17 @@ function normaliseAccount(account) {
1072
1154
  const bare = trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
1073
1155
  return bare.length > 0 ? bare : null;
1074
1156
  }
1157
+ function httpAdmitterOrigins(addrs) {
1158
+ const out = [];
1159
+ for (const addr of addrs ?? []) {
1160
+ try {
1161
+ const url = new URL(addr);
1162
+ if (url.protocol === "http:" || url.protocol === "https:") out.push(addr.replace(/\/+$/, ""));
1163
+ } catch {
1164
+ }
1165
+ }
1166
+ return out;
1167
+ }
1075
1168
  function isInvited(node, invited) {
1076
1169
  if (invited.size === 0) return true;
1077
1170
  const account = normaliseAccount(node.account);
@@ -1096,6 +1189,23 @@ async function resolveRelayFromInvitation(input) {
1096
1189
  };
1097
1190
  }
1098
1191
  if (nodes.length === 0) {
1192
+ const [relayUrl] = httpAdmitterOrigins(input.admitterAddrs);
1193
+ if (relayUrl) {
1194
+ const admitters = (input.admitters ?? []).map(normaliseAccount).filter((a) => a !== null);
1195
+ return {
1196
+ ok: true,
1197
+ relayUrl,
1198
+ admitUrl: `${relayUrl}/admin-api/namespaces/${input.namespaceId}/admit`,
1199
+ admitterAccount: admitters.length === 1 ? admitters[0] : null,
1200
+ peerId: null,
1201
+ // The relay a founder's session runs through executes that founder's
1202
+ // warrants, so it authors on behalf; the node's answer to the first
1203
+ // write is the authoritative one, as for a cloud-routed node.
1204
+ writable: true,
1205
+ stale: false,
1206
+ via: "invitation"
1207
+ };
1208
+ }
1099
1209
  return {
1100
1210
  ok: false,
1101
1211
  step: "no-nodes",
@@ -1139,7 +1249,8 @@ async function resolveRelayFromInvitation(input) {
1139
1249
  // Stale when the node's own heartbeat lapsed OR when the cloud's summary
1140
1250
  // disagrees with trying it at all. Both mean the same thing to a caller:
1141
1251
  // this was attempted on advisory data, so if the admit fails that is why.
1142
- stale: !chosen.fresh || advisory
1252
+ stale: !chosen.fresh || advisory,
1253
+ via: "cloud"
1143
1254
  };
1144
1255
  }
1145
1256
 
@@ -1157,6 +1268,7 @@ async function bootstrapFromInvitation(input) {
1157
1268
  // separately: two sources for one fact is how an intersection ends up
1158
1269
  // being performed against the wrong list.
1159
1270
  admitters: input.invitation.invitation.admitters,
1271
+ admitterAddrs: input.invitation.admitter_addrs,
1160
1272
  credential: input.credential.credential,
1161
1273
  deviceSecret: input.credential.deviceSecret,
1162
1274
  cloudBaseUrl: input.cloudBaseUrl
@@ -3758,6 +3870,9 @@ function useCreateContext() {
3758
3870
  () => createDelegatedContext(session, {
3759
3871
  namespaceId: request.groupId,
3760
3872
  applicationId: request.applicationId,
3873
+ serviceName: request.serviceName,
3874
+ contextSeed: request.contextSeed,
3875
+ name: request.name,
3761
3876
  initializationParams: request.initializationParams
3762
3877
  })
3763
3878
  );