@calimero-network/mero-react 9.3.0 → 9.4.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/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createContext, useMemo, useState, useRef, useCallback, useEffect, useContext } from 'react';
2
- import { LocalStorageTokenStore, parseAuthCallback, MeroJs, buildAuthLoginUrl, DEFAULT_LOCAL_NODE_PORTS, discoverLocalNodes, nodeEndpoint, readEnrolmentCallback, completeDeviceEnrolment, CloudClient, deviceEnrolmentUrl, memberJoinedOpenOp, signerFromSecret, groupDeletedOp, memberAddedOp, memberRemovedOp, subgroupCreation, memberRoleSetOp, defaultCapabilitiesSetOp, subgroupVisibilitySetOp, groupMetadataSetOp, memberMetadataSetOp, contextMetadataSetOp, groupReparentedOp, contextDetachedOp, compareSemver, signMemberJoinOp, AuthRevokedError, HTTPError, attestRelayNodeKey, createMeroClient, RelayClient, classifyError, createLocalStorageNonceSource, login, defaultAudience, createSignedReleaseVerifier, fetchNodeRelease, cloudNodeReleaseUrl, DEFAULT_RELEASE_MIRROR, fetchNodeReleaseVersion } from '@calimero-network/mero-js';
2
+ import { signGroupInvitation, LocalStorageTokenStore, parseAuthCallback, MeroJs, buildAuthLoginUrl, DEFAULT_LOCAL_NODE_PORTS, discoverLocalNodes, nodeEndpoint, readEnrolmentCallback, completeDeviceEnrolment, CloudClient, deviceEnrolmentUrl, memberJoinedOpenOp, signerFromSecret, groupDeletedOp, memberAddedOp, memberRemovedOp, subgroupCreation, memberRoleSetOp, defaultCapabilitiesSetOp, subgroupVisibilitySetOp, groupMetadataSetOp, memberMetadataSetOp, contextMetadataSetOp, groupReparentedOp, contextDetachedOp, compareSemver, signMemberJoinOp, AuthRevokedError, HTTPError, memberLeftOp, memberCapabilitySetOp, attestRelayNodeKey, createMeroClient, RelayClient, classifyError, createLocalStorageNonceSource, login, defaultAudience, createSignedReleaseVerifier, fetchNodeRelease, cloudNodeReleaseUrl, DEFAULT_RELEASE_MIRROR, fetchNodeReleaseVersion } from '@calimero-network/mero-js';
3
3
  export * from '@calimero-network/mero-js';
4
4
  export { CAPABILITIES, DEFAULT_LOCAL_NODE_PORTS, discoverLocalNodes, hasCap, localNodeUrl, nodeEndpoint, probeNodeHealth, withCap, withoutCap } from '@calimero-network/mero-js';
5
5
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
@@ -44,242 +44,6 @@ var ConnectionType = /* @__PURE__ */ ((ConnectionType2) => {
44
44
  ConnectionType2["Custom"] = "custom";
45
45
  return ConnectionType2;
46
46
  })(ConnectionType || {});
47
-
48
- // src/auth/node-trust.ts
49
- function sameOrigin(a, b) {
50
- try {
51
- return new URL(a).origin === new URL(b).origin;
52
- } catch {
53
- return false;
54
- }
55
- }
56
- function resolveTrustedNodeUrl(params) {
57
- const { candidate, initiated, allowedNodeUrls } = params;
58
- if (!candidate) {
59
- return { url: initiated ?? null, rejected: false };
60
- }
61
- if (initiated) {
62
- return sameOrigin(candidate, initiated) ? { url: candidate, rejected: false } : { url: null, rejected: true };
63
- }
64
- if (allowedNodeUrls && allowedNodeUrls.length > 0) {
65
- return allowedNodeUrls.some((u) => sameOrigin(candidate, u)) ? { url: candidate, rejected: false } : { url: null, rejected: true };
66
- }
67
- return { url: null, rejected: true };
68
- }
69
-
70
- // src/auth/token-adoption.ts
71
- var HOUR_MS = 36e5;
72
- function decodeJwtClaims(token) {
73
- try {
74
- const parts = token.split(".");
75
- if (parts.length !== 3) return null;
76
- let b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
77
- while (b64.length % 4) b64 += "=";
78
- const payload = JSON.parse(atob(b64));
79
- if (!payload || typeof payload !== "object") return null;
80
- const { iat, exp } = payload;
81
- return {
82
- iat: typeof iat === "number" && iat > 0 ? iat : void 0,
83
- exp: typeof exp === "number" && exp > 0 ? exp : void 0
84
- };
85
- } catch {
86
- return null;
87
- }
88
- }
89
- function expiresAtFromJwt(token, fallbackMs = Date.now() + HOUR_MS) {
90
- const exp = decodeJwtClaims(token)?.exp;
91
- return exp ? exp * 1e3 : fallbackMs;
92
- }
93
- function isCallbackNewer(callbackAccessToken, stored) {
94
- const incoming = decodeJwtClaims(callbackAccessToken);
95
- if (!incoming) return false;
96
- const current = decodeJwtClaims(stored.access_token);
97
- if (current) {
98
- if (incoming.iat !== void 0 && current.iat !== void 0 && incoming.iat !== current.iat) {
99
- return incoming.iat > current.iat;
100
- }
101
- if (incoming.exp !== void 0 && current.exp !== void 0 && incoming.exp !== current.exp) {
102
- return incoming.exp > current.exp;
103
- }
104
- return false;
105
- }
106
- return incoming.exp !== void 0 && incoming.exp * 1e3 > stored.expires_at;
107
- }
108
- function resolveTokenAdoption(params) {
109
- const { callbackAccessToken, callbackRefreshToken, callbackNodeUrl, stored, storedNodeUrl } = params;
110
- const bundle = (refreshToken2) => ({
111
- access_token: callbackAccessToken,
112
- refresh_token: refreshToken2,
113
- expires_at: expiresAtFromJwt(callbackAccessToken)
114
- });
115
- if (!stored?.access_token) {
116
- return { adopt: true, tokens: bundle(callbackRefreshToken), reason: "fresh-login" };
117
- }
118
- const sameNode = !!storedNodeUrl && sameOrigin(callbackNodeUrl, storedNodeUrl);
119
- if (!sameNode) {
120
- return { adopt: true, tokens: bundle(callbackRefreshToken), reason: "node-changed" };
121
- }
122
- const refreshToken = callbackRefreshToken || stored.refresh_token;
123
- if (isCallbackNewer(callbackAccessToken, stored)) {
124
- return { adopt: true, tokens: bundle(refreshToken), reason: "newer" };
125
- }
126
- if (!stored.refresh_token && callbackRefreshToken) {
127
- return {
128
- adopt: true,
129
- tokens: { ...stored, refresh_token: callbackRefreshToken },
130
- reason: "fill-refresh"
131
- };
132
- }
133
- return { adopt: false, reason: "stale" };
134
- }
135
-
136
- // src/storage/index.ts
137
- var STORAGE_KEYS = {
138
- ACCESS_TOKEN: "mero:access_token",
139
- REFRESH_TOKEN: "mero:refresh_token",
140
- EXPIRES_AT: "mero:expires_at",
141
- NODE_URL: "mero:node_url",
142
- // The node the token bundle currently in the TokenStore was issued by. Distinct
143
- // from NODE_URL, which `connectToNode` overwrites with the *target* node before
144
- // redirecting to login — so at callback time NODE_URL names where we are going,
145
- // not who minted the tokens we still hold. Telling those apart is what lets the
146
- // SSO callback re-seed on a node change without mistaking a different node's
147
- // bundle for a rotated one (see auth/token-adoption.ts).
148
- TOKEN_NODE_URL: "mero:token_node_url",
149
- APPLICATION_ID: "mero:application_id",
150
- CONTEXT_ID: "mero:context_id",
151
- CONTEXT_IDENTITY: "mero:context_identity"
152
- };
153
- var _storageAvailable = null;
154
- function isLocalStorageAvailable() {
155
- if (_storageAvailable !== null) return _storageAvailable;
156
- try {
157
- if (typeof window === "undefined" || !window.localStorage) {
158
- _storageAvailable = false;
159
- return false;
160
- }
161
- const testKey = "__mero_test__";
162
- localStorage.setItem(testKey, "test");
163
- localStorage.removeItem(testKey);
164
- _storageAvailable = true;
165
- } catch {
166
- _storageAvailable = false;
167
- }
168
- return _storageAvailable;
169
- }
170
- var localStorageTokenStorage = {
171
- async get() {
172
- if (!isLocalStorageAvailable()) {
173
- return null;
174
- }
175
- try {
176
- const accessToken = localStorage.getItem(STORAGE_KEYS.ACCESS_TOKEN);
177
- const refreshToken = localStorage.getItem(STORAGE_KEYS.REFRESH_TOKEN);
178
- const expiresAt = localStorage.getItem(STORAGE_KEYS.EXPIRES_AT);
179
- if (!accessToken || !refreshToken) {
180
- return null;
181
- }
182
- return {
183
- access_token: accessToken,
184
- refresh_token: refreshToken,
185
- expires_at: expiresAt ? parseInt(expiresAt, 10) : Date.now() + 36e5
186
- };
187
- } catch (e) {
188
- console.error("[mero-react] Failed to get token from storage:", e);
189
- return null;
190
- }
191
- },
192
- async set(token) {
193
- if (!isLocalStorageAvailable()) {
194
- return;
195
- }
196
- try {
197
- localStorage.setItem(STORAGE_KEYS.ACCESS_TOKEN, token.access_token);
198
- localStorage.setItem(STORAGE_KEYS.REFRESH_TOKEN, token.refresh_token);
199
- localStorage.setItem(STORAGE_KEYS.EXPIRES_AT, token.expires_at.toString());
200
- } catch (e) {
201
- console.error("[mero-react] Failed to save token to storage:", e);
202
- }
203
- },
204
- async clear() {
205
- if (!isLocalStorageAvailable()) {
206
- return;
207
- }
208
- try {
209
- localStorage.removeItem(STORAGE_KEYS.ACCESS_TOKEN);
210
- localStorage.removeItem(STORAGE_KEYS.REFRESH_TOKEN);
211
- localStorage.removeItem(STORAGE_KEYS.EXPIRES_AT);
212
- } catch (e) {
213
- console.error("[mero-react] Failed to clear token from storage:", e);
214
- }
215
- }
216
- };
217
- function getNodeUrl() {
218
- if (!isLocalStorageAvailable()) return null;
219
- return localStorage.getItem(STORAGE_KEYS.NODE_URL);
220
- }
221
- function setNodeUrl(url) {
222
- if (!isLocalStorageAvailable()) return;
223
- localStorage.setItem(STORAGE_KEYS.NODE_URL, url);
224
- }
225
- function clearNodeUrl() {
226
- if (!isLocalStorageAvailable()) return;
227
- localStorage.removeItem(STORAGE_KEYS.NODE_URL);
228
- }
229
- function getTokenNodeUrl() {
230
- if (!isLocalStorageAvailable()) return null;
231
- return localStorage.getItem(STORAGE_KEYS.TOKEN_NODE_URL);
232
- }
233
- function setTokenNodeUrl(url) {
234
- if (!isLocalStorageAvailable()) return;
235
- localStorage.setItem(STORAGE_KEYS.TOKEN_NODE_URL, url);
236
- }
237
- function clearTokenNodeUrl() {
238
- if (!isLocalStorageAvailable()) return;
239
- localStorage.removeItem(STORAGE_KEYS.TOKEN_NODE_URL);
240
- }
241
- function getApplicationId() {
242
- if (!isLocalStorageAvailable()) return null;
243
- return localStorage.getItem(STORAGE_KEYS.APPLICATION_ID);
244
- }
245
- function setApplicationId(id) {
246
- if (!isLocalStorageAvailable()) return;
247
- localStorage.setItem(STORAGE_KEYS.APPLICATION_ID, id);
248
- }
249
- function clearApplicationId() {
250
- if (!isLocalStorageAvailable()) return;
251
- localStorage.removeItem(STORAGE_KEYS.APPLICATION_ID);
252
- }
253
- function getContextId() {
254
- if (!isLocalStorageAvailable()) return null;
255
- return localStorage.getItem(STORAGE_KEYS.CONTEXT_ID);
256
- }
257
- function setContextId(id) {
258
- if (!isLocalStorageAvailable()) return;
259
- localStorage.setItem(STORAGE_KEYS.CONTEXT_ID, id);
260
- }
261
- function clearContextId() {
262
- if (!isLocalStorageAvailable()) return;
263
- localStorage.removeItem(STORAGE_KEYS.CONTEXT_ID);
264
- }
265
- function getContextIdentity() {
266
- if (!isLocalStorageAvailable()) return null;
267
- return localStorage.getItem(STORAGE_KEYS.CONTEXT_IDENTITY);
268
- }
269
- function setContextIdentity(id) {
270
- if (!isLocalStorageAvailable()) return;
271
- localStorage.setItem(STORAGE_KEYS.CONTEXT_IDENTITY, id);
272
- }
273
- function clearContextIdentity() {
274
- if (!isLocalStorageAvailable()) return;
275
- localStorage.removeItem(STORAGE_KEYS.CONTEXT_IDENTITY);
276
- }
277
- function clearAllStorage() {
278
- if (!isLocalStorageAvailable()) return;
279
- Object.values(STORAGE_KEYS).forEach((key) => {
280
- localStorage.removeItem(key);
281
- });
282
- }
283
47
  var KEY = "calimero.delegated.connection";
284
48
  var CREDENTIAL_KEY = "calimero.delegated.credential";
285
49
  function readDelegatedSession() {
@@ -332,13 +96,13 @@ function clearDelegatedCredential() {
332
96
  } catch {
333
97
  }
334
98
  }
335
- function persistedNonces(relayUrl, contextId) {
336
- const key = `calimero.nonce.${relayUrl}.${contextId ?? "no-context"}`;
99
+ function persistedNonces(relayUrl) {
100
+ const key = nonceKey(relayUrl);
337
101
  return {
338
102
  next: async () => {
339
103
  let n = 0n;
340
104
  try {
341
- n = BigInt(localStorage.getItem(key) ?? "0");
105
+ n = readNonceFloor(relayUrl);
342
106
  } catch {
343
107
  n = 0n;
344
108
  }
@@ -350,11 +114,25 @@ function persistedNonces(relayUrl, contextId) {
350
114
  }
351
115
  };
352
116
  }
353
- function markContextNonceSpent(relayUrl, contextId, nonce) {
354
- const key = `calimero.nonce.${relayUrl}.${contextId}`;
117
+ function nonceKey(relayUrl) {
118
+ return `calimero.nonce.${relayUrl}`;
119
+ }
120
+ function readNonceFloor(relayUrl) {
121
+ const own = localStorage.getItem(nonceKey(relayUrl));
122
+ if (own !== null) return BigInt(own);
123
+ const legacy = `${nonceKey(relayUrl)}.`;
124
+ let max = 0n;
125
+ for (let i = 0; i < localStorage.length; i++) {
126
+ const k = localStorage.key(i);
127
+ if (!k?.startsWith(legacy)) continue;
128
+ const v = BigInt(localStorage.getItem(k) ?? "0");
129
+ if (v > max) max = v;
130
+ }
131
+ return max;
132
+ }
133
+ function markContextNonceSpent(relayUrl, _contextId, nonce) {
355
134
  try {
356
- const current = BigInt(localStorage.getItem(key) ?? "0");
357
- if (current <= nonce) localStorage.setItem(key, String(nonce + 1n));
135
+ if (readNonceFloor(relayUrl) <= nonce) localStorage.setItem(nonceKey(relayUrl), String(nonce + 1n));
358
136
  } catch {
359
137
  }
360
138
  }
@@ -454,7 +232,7 @@ function relaySession(s, nodeKey) {
454
232
  return inflight;
455
233
  };
456
234
  }
457
- function buildDelegatedClient(s, contextId) {
235
+ function buildDelegatedClient(s, _contextId) {
458
236
  if (!s.relayUrl) return null;
459
237
  const nodeKey = readPinnedRelayNodeKey(s.relayUrl);
460
238
  return createMeroClient({
@@ -464,10 +242,9 @@ function buildDelegatedClient(s, contextId) {
464
242
  authorAccount: s.account,
465
243
  authorProof: s.credential,
466
244
  deviceSecret: s.deviceSecret,
467
- // The active context, passed in rather than stored on the record: the
468
- // relay client holds ONE nonce source while `execute` takes a context per
469
- // call, so the ledger has to be re-keyed when the chosen context changes.
470
- nonces: persistedNonces(s.relayUrl, contextId)
245
+ // One sequence per relay, whatever context is chosen: `execute` takes a
246
+ // context per call, so the nonce source must not depend on this one.
247
+ nonces: persistedNonces(s.relayUrl)
471
248
  },
472
249
  // The certificate authenticates the requests too, not just the writes.
473
250
  //
@@ -493,79 +270,689 @@ function buildDelegatedClient(s, contextId) {
493
270
  observe: nodeKey ? { nodeKey } : void 0
494
271
  });
495
272
  }
496
- var RELAY_MAP_PREFIX = "calimero.delegated.relays.";
497
- function readRelayMap(account) {
498
- try {
499
- const raw = localStorage.getItem(RELAY_MAP_PREFIX + account);
500
- const parsed = raw ? JSON.parse(raw) : {};
501
- return { namespaces: parsed.namespaces ?? {}, contexts: parsed.contexts ?? {} };
502
- } catch {
503
- return { namespaces: {}, contexts: {} };
504
- }
273
+ var RELAY_MAP_PREFIX = "calimero.delegated.relays.";
274
+ function readRelayMap(account) {
275
+ try {
276
+ const raw = localStorage.getItem(RELAY_MAP_PREFIX + account);
277
+ const parsed = raw ? JSON.parse(raw) : {};
278
+ return { namespaces: parsed.namespaces ?? {}, contexts: parsed.contexts ?? {} };
279
+ } catch {
280
+ return { namespaces: {}, contexts: {} };
281
+ }
282
+ }
283
+ function writeRelayMap(account, map) {
284
+ try {
285
+ localStorage.setItem(RELAY_MAP_PREFIX + account, JSON.stringify(map));
286
+ } catch {
287
+ }
288
+ }
289
+ function rememberRelay(account, relayUrl, at) {
290
+ const map = readRelayMap(account);
291
+ const url = relayOrigin(relayUrl);
292
+ if (at.namespaceId) map.namespaces[at.namespaceId] = url;
293
+ if (at.contextId) map.contexts[at.contextId] = url;
294
+ writeRelayMap(account, map);
295
+ }
296
+ function relayForContext(account, contextId) {
297
+ return readRelayMap(account).contexts[contextId] ?? null;
298
+ }
299
+ function knownRelays(s) {
300
+ const map = readRelayMap(s.account);
301
+ const all = [s.relayUrl, ...Object.values(map.namespaces), ...Object.values(map.contexts)].filter((u) => typeof u === "string" && u.length > 0).map(relayOrigin);
302
+ return [...new Set(all)];
303
+ }
304
+ async function listDelegatedContexts(s) {
305
+ const out = [];
306
+ const map = readRelayMap(s.account);
307
+ for (const relayUrl of knownRelays(s)) {
308
+ try {
309
+ if (!await resolveRelayNodeKey(relayUrl)) continue;
310
+ const client2 = buildDelegatedClient({ ...s, relayUrl }, null);
311
+ if (!client2) continue;
312
+ const { contexts } = await client2.admin.getContexts();
313
+ for (const c of contexts ?? []) {
314
+ out.push({ ...c, relayUrl });
315
+ map.contexts[c.id] = relayUrl;
316
+ }
317
+ } catch (e) {
318
+ console.warn(`[mero-react] could not list contexts on ${relayUrl}`, e);
319
+ }
320
+ }
321
+ writeRelayMap(s.account, map);
322
+ return out;
323
+ }
324
+ async function listDelegatedNamespaces(s) {
325
+ var _a, _b;
326
+ const out = [];
327
+ const seen = /* @__PURE__ */ new Set();
328
+ const map = readRelayMap(s.account);
329
+ for (const relayUrl of knownRelays(s)) {
330
+ try {
331
+ if (!await resolveRelayNodeKey(relayUrl)) continue;
332
+ const client2 = buildDelegatedClient({ ...s, relayUrl }, null);
333
+ if (!client2) continue;
334
+ for (const ns of await client2.admin.listNamespaces()) {
335
+ if (seen.has(ns.namespaceId)) continue;
336
+ seen.add(ns.namespaceId);
337
+ out.push({ ...ns, relayUrl });
338
+ (_a = map.namespaces)[_b = ns.namespaceId] ?? (_a[_b] = relayUrl);
339
+ }
340
+ } catch (e) {
341
+ console.warn(`[mero-react] could not list namespaces on ${relayUrl}`, e);
342
+ }
343
+ }
344
+ writeRelayMap(s.account, map);
345
+ return out;
346
+ }
347
+
348
+ // src/delegated/create-context.ts
349
+ function governanceNonce(relay, group) {
350
+ return { next: async () => nextGovernanceNonce(relay, group) };
351
+ }
352
+ function nextGovernanceNonce(relay, group) {
353
+ const key = `calimero.governance-nonce.${relay}.${group}`;
354
+ let last = 0n;
355
+ try {
356
+ last = BigInt(localStorage.getItem(key) ?? "0");
357
+ } catch {
358
+ }
359
+ const next = [last + 1n, BigInt(Date.now())].reduce((a, b) => a > b ? a : b);
360
+ try {
361
+ localStorage.setItem(key, String(next));
362
+ } catch {
363
+ }
364
+ return next;
365
+ }
366
+ function relayFor(s, namespaceId) {
367
+ const url = readRelayMap(s.account).namespaces[namespaceId] ?? s.relayUrl;
368
+ if (!url) throw new Error("no relay is known for this namespace, so there is nowhere to send this");
369
+ return url.replace(/\/+$/, "");
370
+ }
371
+ function initArgsOf(params) {
372
+ if (!params || params.length === 0) return {};
373
+ return JSON.parse(new TextDecoder().decode(Uint8Array.from(params)));
374
+ }
375
+ function client(s, relayUrl, nonces, fetch2) {
376
+ return new RelayClient({
377
+ relayUrl,
378
+ authorAccount: s.account,
379
+ authorProof: s.credential,
380
+ deviceSecret: s.deviceSecret,
381
+ nonces,
382
+ fetch: fetch2
383
+ });
384
+ }
385
+ async function createDelegatedContext(s, req, deps = {}) {
386
+ const relay = relayFor(s, req.namespaceId);
387
+ const creationNonce = 0n;
388
+ const created = await client(s, relay, { next: async () => creationNonce }, deps.fetch).createContext({
389
+ groupId: req.groupId ?? req.namespaceId,
390
+ applicationId: req.applicationId,
391
+ initArgs: initArgsOf(req.initializationParams),
392
+ name: req.name
393
+ });
394
+ markContextNonceSpent(relay, created.contextId, creationNonce);
395
+ rememberRelay(s.account, relay, { namespaceId: req.namespaceId, contextId: created.contextId });
396
+ return { contextId: created.contextId };
397
+ }
398
+ async function delegatedGovernance(s, req, deps = {}) {
399
+ const relay = relayFor(s, req.namespaceId);
400
+ return client(s, relay, governanceNonce(relay, req.group), deps.fetch).govern({ groupId: req.group, op: req.op });
401
+ }
402
+ async function createDelegatedPrivateContext(s, req, deps = {}) {
403
+ const { groupId } = await delegatedGovernance(
404
+ s,
405
+ {
406
+ namespaceId: req.namespaceId,
407
+ group: req.namespaceId,
408
+ // The id is derived from a fresh salt (core#4244); a node refuses any other.
409
+ op: (await subgroupCreation({ parentId: req.namespaceId, restricted: true, admin: s.account })).op
410
+ },
411
+ deps
412
+ );
413
+ for (const member of req.members) {
414
+ await delegatedGovernance(s, { namespaceId: req.namespaceId, group: groupId, op: memberAddedOp(member, "Member") }, deps);
415
+ }
416
+ const { contextId } = await createDelegatedContext(s, { ...req, groupId }, deps);
417
+ return { contextId, groupId };
418
+ }
419
+ async function foundDelegatedNamespace(s, req = {}, deps = {}) {
420
+ const relays = knownRelays(s).map((u) => u.replace(/\/+$/, ""));
421
+ const relay = relays[0];
422
+ if (!relay) throw new Error("no relay is known for this account, so there is nowhere to found a namespace");
423
+ const known = Object.entries(readRelayMap(s.account).namespaces).find(
424
+ ([, url]) => url.replace(/\/+$/, "") === relay
425
+ )?.[0];
426
+ if (!known) {
427
+ throw new Error("join a namespace on this relay first: its executor account is learned from one you are in");
428
+ }
429
+ const { executorAccount } = await client(s, relay, governanceNonce(relay, known), deps.fetch).describeGovernance(known);
430
+ let next = BigInt(Date.now());
431
+ const founded = await client(s, relay, { next: async () => next++ }, deps.fetch).foundNamespace({
432
+ executorAccount,
433
+ ...req.defaultCapabilities !== void 0 ? { defaultCapabilities: req.defaultCapabilities } : {},
434
+ ...req.application ? { application: req.application } : {}
435
+ });
436
+ try {
437
+ localStorage.setItem(`calimero.governance-nonce.${relay}.${founded.namespaceId}`, String(next));
438
+ } catch {
439
+ }
440
+ rememberRelay(s.account, relay, { namespaceId: founded.namespaceId });
441
+ if (req.application && founded.applicationSet !== true) {
442
+ throw new Error(
443
+ `founded ${founded.namespaceId} but could not give it its application: ${founded.applicationError ?? "unknown reason"}`
444
+ );
445
+ }
446
+ return { namespaceId: founded.namespaceId, teeEnabled: founded.teeEnabled };
447
+ }
448
+ async function latestPublishedVersion(registryUrl, pkg, fetchFn = globalThis.fetch) {
449
+ const url = `${registryUrl.replace(/\/+$/, "")}/api/v2/bundles?package=${encodeURIComponent(pkg)}`;
450
+ const response = await fetchFn(url, { headers: { Accept: "application/json" } });
451
+ if (!response.ok) throw new Error(`the registry has no ${pkg} (HTTP ${response.status})`);
452
+ const bundles = await response.json();
453
+ const newer = (a, b) => {
454
+ const [x, y] = [a, b].map((v) => v.split(/[.-]/).map((n) => Number.parseInt(n, 10) || 0));
455
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
456
+ if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0);
457
+ }
458
+ return false;
459
+ };
460
+ const latest = bundles.map((b) => b.appVersion).filter((v) => typeof v === "string" && v.length > 0).reduce((best, v) => !best || newer(v, best) ? v : best, void 0);
461
+ if (!latest) throw new Error(`the registry lists no version of ${pkg}`);
462
+ return latest;
463
+ }
464
+
465
+ // src/admin/node-admin.ts
466
+ function createNodeAdmin(input, deps = {}) {
467
+ const { admin, app } = input;
468
+ const latestVersion = deps.latestVersion ?? latestPublishedVersion;
469
+ async function ensureInstalled(applicationId) {
470
+ const { apps } = await admin.listApplications();
471
+ if (apps.some((a) => a.id === applicationId)) return;
472
+ if (!app.packageName) {
473
+ throw new Error(`application ${applicationId} is not installed on this node, and no packageName is set to install it`);
474
+ }
475
+ const version = app.packageVersion ?? await latestVersion(app.registryUrl ?? "https://apps.calimero.network", app.packageName);
476
+ const { applicationId: installed } = await admin.installApplication({ package: app.packageName, version });
477
+ if (installed !== applicationId) {
478
+ throw new Error(`installed ${app.packageName}@${version} as ${installed}, not ${applicationId}`);
479
+ }
480
+ }
481
+ const overrides = {
482
+ async createNamespace(req) {
483
+ await ensureInstalled(req.applicationId);
484
+ return admin.createNamespace(req);
485
+ }
486
+ };
487
+ return new Proxy(admin, {
488
+ get(target, prop, receiver) {
489
+ if (typeof prop === "string" && prop in overrides) return overrides[prop];
490
+ return Reflect.get(target, prop, receiver);
491
+ }
492
+ });
493
+ }
494
+
495
+ // src/delegated/govern.ts
496
+ var GROUP_NAMESPACE_PREFIX = "calimero.delegated.group-namespace.";
497
+ function readGroupNamespaces(account) {
498
+ try {
499
+ return JSON.parse(localStorage.getItem(GROUP_NAMESPACE_PREFIX + account) ?? "{}");
500
+ } catch {
501
+ return {};
502
+ }
503
+ }
504
+ function rememberGroupNamespace(account, groupId, namespaceId) {
505
+ try {
506
+ const all = readGroupNamespaces(account);
507
+ all[groupId] = namespaceId;
508
+ localStorage.setItem(GROUP_NAMESPACE_PREFIX + account, JSON.stringify(all));
509
+ } catch {
510
+ }
511
+ }
512
+ function namespaceOfGroup(s, groupId) {
513
+ if (readRelayMap(s.account).namespaces[groupId]) return groupId;
514
+ return readGroupNamespaces(s.account)[groupId];
515
+ }
516
+ function requireNamespace(s, groupId) {
517
+ const ns = namespaceOfGroup(s, groupId);
518
+ if (!ns) {
519
+ throw new Error(
520
+ `the namespace of group ${groupId} is not known to this account: it can manage only groups in namespaces it joined or subgroups it created`
521
+ );
522
+ }
523
+ return ns;
524
+ }
525
+ async function governGroup(s, groupId, op) {
526
+ return delegatedGovernance(s, { namespaceId: requireNamespace(s, groupId), group: groupId, op });
527
+ }
528
+ async function governRoot(s, groupId, op) {
529
+ const namespaceId = requireNamespace(s, groupId);
530
+ return delegatedGovernance(s, { namespaceId, group: namespaceId, op });
531
+ }
532
+
533
+ // src/delegated/account-admin.ts
534
+ var NotForAccountError = class extends Error {
535
+ constructor(method) {
536
+ super(`${method} is not available for an account: it needs a node`);
537
+ this.method = method;
538
+ this.name = "NotForAccountError";
539
+ }
540
+ };
541
+ var NoRelayError = class extends Error {
542
+ constructor(method) {
543
+ super(`${method} needs a relay, and this account has none yet: join from an invitation first`);
544
+ this.method = method;
545
+ this.name = "NoRelayError";
546
+ }
547
+ };
548
+ var EMPTY_READS = {
549
+ listNamespaces: async () => [],
550
+ listNamespacesForApplication: async () => [],
551
+ getContexts: async () => ({ contexts: [] })
552
+ };
553
+ var NODE_ONLY = /* @__PURE__ */ new Set([
554
+ "upgradeGroup",
555
+ "retryGroupUpgrade",
556
+ "abortMigration",
557
+ "installApplication",
558
+ "installDevApplication",
559
+ "uninstallApplication",
560
+ "generateContextIdentity",
561
+ "deleteContext",
562
+ "createAlias",
563
+ "deleteAlias"
564
+ ]);
565
+ function createAccountAdmin(input, deps = {}) {
566
+ const { session: s, read, app } = input;
567
+ const group = deps.govern?.group ?? governGroup;
568
+ const root = deps.govern?.root ?? governRoot;
569
+ const createContext2 = deps.createContext ?? createDelegatedContext;
570
+ const found = deps.found ?? foundDelegatedNamespace;
571
+ const latestVersion = deps.latestVersion ?? latestPublishedVersion;
572
+ const signInvitation = deps.signInvitation ?? signGroupInvitation;
573
+ const relay = () => {
574
+ if (read === null) throw new NoRelayError("this call");
575
+ return read;
576
+ };
577
+ async function isMemberOfContextGroup(contextId, knownGroupId) {
578
+ const groupId = knownGroupId ?? String(await relay().getContextGroup(contextId));
579
+ const { members } = await relay().listGroupMembers(groupId);
580
+ return members.some((m) => m.identity.toLowerCase() === s.account.toLowerCase());
581
+ }
582
+ const writes = {
583
+ // The node-wide `for-application` listing is not caller-scoped, so a relay
584
+ // refuses it to an account. Its own scoped list, filtered, is the answer.
585
+ async listNamespacesForApplication(applicationId) {
586
+ return (await relay().listNamespaces()).filter((ns) => ns.targetApplicationId === applicationId);
587
+ },
588
+ async getNodeIdentity() {
589
+ return { accountId: s.account, deviceId: null, publicKey: "", deviceCertified: true };
590
+ },
591
+ async createNamespace(req) {
592
+ if (!app.packageName) throw new NotForAccountError("createNamespace without a packageName");
593
+ const version = app.packageVersion ?? await latestVersion(app.registryUrl ?? "https://apps.calimero.network", app.packageName);
594
+ const { namespaceId } = await found(s, {
595
+ defaultCapabilities: 231,
596
+ application: { applicationId: req.applicationId, package: app.packageName, version }
597
+ });
598
+ if (req.name) await group(s, namespaceId, groupMetadataSetOp({ name: req.name }));
599
+ return { namespaceId };
600
+ },
601
+ async createGroupInNamespace(namespaceId, req = {}) {
602
+ const { op } = await subgroupCreation({ parentId: namespaceId, restricted: req.visibility !== "open", admin: s.account });
603
+ const { groupId } = await root(s, namespaceId, op);
604
+ rememberGroupNamespace(s.account, groupId, namespaceId);
605
+ if (req.groupName) await group(s, groupId, groupMetadataSetOp({ name: req.groupName }));
606
+ return { groupId };
607
+ },
608
+ async addGroupMembers(groupId, req) {
609
+ for (const m of req.members) await group(s, groupId, memberAddedOp(m.identity, m.role ?? "Member"));
610
+ },
611
+ async removeGroupMembers(groupId, req) {
612
+ for (const m of req.members) await group(s, groupId, memberRemovedOp(m));
613
+ },
614
+ async setGroupMetadata(groupId, req) {
615
+ await group(s, groupId, groupMetadataSetOp(req));
616
+ },
617
+ async setMemberMetadata(groupId, identity, req) {
618
+ await group(s, groupId, memberMetadataSetOp(identity, req));
619
+ },
620
+ async setContextMetadata(groupId, contextId, req) {
621
+ await group(s, groupId, contextMetadataSetOp(contextId, req));
622
+ },
623
+ async setDefaultCapabilities(groupId, req) {
624
+ await group(s, groupId, defaultCapabilitiesSetOp(req.defaultCapabilities));
625
+ },
626
+ async setSubgroupVisibility(groupId, req) {
627
+ await group(s, groupId, subgroupVisibilitySetOp(req.subgroupVisibility === "open" ? "open" : "restricted"));
628
+ },
629
+ async setMemberCapabilities(groupId, identity, req) {
630
+ await group(s, groupId, memberCapabilitySetOp(identity, req.capabilities));
631
+ },
632
+ async deleteGroup(groupId) {
633
+ await root(s, groupId, groupDeletedOp(groupId));
634
+ return { isDeleted: true };
635
+ },
636
+ async reparentGroup(childGroupId, req) {
637
+ await root(s, childGroupId, groupReparentedOp(childGroupId, req.newParentId));
638
+ return { reparented: true };
639
+ },
640
+ async leaveGroup(groupId) {
641
+ await group(s, groupId, memberLeftOp(s.account));
642
+ },
643
+ async leaveNamespace(namespaceId) {
644
+ await group(s, namespaceId, memberLeftOp(s.account));
645
+ },
646
+ // An account holds no context identity: leaving a context is leaving its group.
647
+ async leaveContext(contextId) {
648
+ const groupId = await relay().getContextGroup(contextId);
649
+ await group(s, String(groupId), memberLeftOp(s.account));
650
+ },
651
+ // An account runs as itself in every context it can reach (the relay
652
+ // executes as the account), so its identity there is the account. Owned
653
+ // when its account is a member of the context's group, as on a node a
654
+ // context identity is owned once the node has joined.
655
+ async getContextIdentitiesOwned(contextId) {
656
+ return { identities: await isMemberOfContextGroup(contextId) ? [s.account] : [] };
657
+ },
658
+ async joinContext(contextId) {
659
+ const groupId = String(await relay().getContextGroup(contextId));
660
+ if (await isMemberOfContextGroup(contextId, groupId)) {
661
+ return { contextId, memberPublicKey: s.account };
662
+ }
663
+ await root(s, groupId, memberJoinedOpenOp({ member: s.account, groupId, credential: s.credential }));
664
+ return { contextId, memberPublicKey: s.account };
665
+ },
666
+ async createContext(req) {
667
+ const info = await relay().getGroupInfo(req.groupId);
668
+ const namespaceId = info.namespaceId ?? req.groupId;
669
+ const { contextId } = await createContext2(s, {
670
+ namespaceId,
671
+ groupId: req.groupId,
672
+ applicationId: req.applicationId,
673
+ name: req.name,
674
+ initializationParams: req.initializationParams
675
+ });
676
+ return { contextId, memberPublicKey: "", groupId: req.groupId };
677
+ },
678
+ async createNamespaceInvitation(namespaceId) {
679
+ const [{ members }, info] = await Promise.all([relay().listGroupMembers(namespaceId), relay().getGroupInfo(namespaceId)]);
680
+ const relays = members.filter((m) => m.role === "RelayTee").map((m) => m.identity.toLowerCase());
681
+ const invitation = await signInvitation({
682
+ groupId: namespaceId,
683
+ inviterAccount: s.account,
684
+ deviceSecret: s.deviceSecret,
685
+ ...relays.length > 0 ? { admitters: relays } : {},
686
+ members,
687
+ applicationId: info.targetApplicationId,
688
+ appKey: info.appKey
689
+ });
690
+ return { invitation };
691
+ },
692
+ // The relay syncs its own view; an account has nothing to pull.
693
+ async syncGroup(groupId) {
694
+ return { groupId, synced: true };
695
+ }
696
+ };
697
+ if (read === null) {
698
+ return new Proxy({}, {
699
+ get(_target, prop) {
700
+ if (typeof prop !== "string") return void 0;
701
+ if (prop === "getNodeIdentity") return writes.getNodeIdentity;
702
+ if (prop in EMPTY_READS) return EMPTY_READS[prop];
703
+ return async () => {
704
+ throw new NoRelayError(prop);
705
+ };
706
+ }
707
+ });
708
+ }
709
+ return new Proxy(read, {
710
+ get(target, prop, receiver) {
711
+ if (typeof prop === "string" && prop in writes) return writes[prop];
712
+ if (typeof prop === "string" && NODE_ONLY.has(prop)) {
713
+ return async () => {
714
+ throw new NotForAccountError(prop);
715
+ };
716
+ }
717
+ return Reflect.get(target, prop, receiver);
718
+ }
719
+ });
720
+ }
721
+
722
+ // src/auth/node-trust.ts
723
+ function sameOrigin(a, b) {
724
+ try {
725
+ return new URL(a).origin === new URL(b).origin;
726
+ } catch {
727
+ return false;
728
+ }
729
+ }
730
+ function resolveTrustedNodeUrl(params) {
731
+ const { candidate, initiated, allowedNodeUrls } = params;
732
+ if (!candidate) {
733
+ return { url: initiated ?? null, rejected: false };
734
+ }
735
+ if (initiated) {
736
+ return sameOrigin(candidate, initiated) ? { url: candidate, rejected: false } : { url: null, rejected: true };
737
+ }
738
+ if (allowedNodeUrls && allowedNodeUrls.length > 0) {
739
+ return allowedNodeUrls.some((u) => sameOrigin(candidate, u)) ? { url: candidate, rejected: false } : { url: null, rejected: true };
740
+ }
741
+ return { url: null, rejected: true };
742
+ }
743
+
744
+ // src/auth/token-adoption.ts
745
+ var HOUR_MS = 36e5;
746
+ function decodeJwtClaims(token) {
747
+ try {
748
+ const parts = token.split(".");
749
+ if (parts.length !== 3) return null;
750
+ let b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
751
+ while (b64.length % 4) b64 += "=";
752
+ const payload = JSON.parse(atob(b64));
753
+ if (!payload || typeof payload !== "object") return null;
754
+ const { iat, exp } = payload;
755
+ return {
756
+ iat: typeof iat === "number" && iat > 0 ? iat : void 0,
757
+ exp: typeof exp === "number" && exp > 0 ? exp : void 0
758
+ };
759
+ } catch {
760
+ return null;
761
+ }
762
+ }
763
+ function expiresAtFromJwt(token, fallbackMs = Date.now() + HOUR_MS) {
764
+ const exp = decodeJwtClaims(token)?.exp;
765
+ return exp ? exp * 1e3 : fallbackMs;
766
+ }
767
+ function isCallbackNewer(callbackAccessToken, stored) {
768
+ const incoming = decodeJwtClaims(callbackAccessToken);
769
+ if (!incoming) return false;
770
+ const current = decodeJwtClaims(stored.access_token);
771
+ if (current) {
772
+ if (incoming.iat !== void 0 && current.iat !== void 0 && incoming.iat !== current.iat) {
773
+ return incoming.iat > current.iat;
774
+ }
775
+ if (incoming.exp !== void 0 && current.exp !== void 0 && incoming.exp !== current.exp) {
776
+ return incoming.exp > current.exp;
777
+ }
778
+ return false;
779
+ }
780
+ return incoming.exp !== void 0 && incoming.exp * 1e3 > stored.expires_at;
781
+ }
782
+ function resolveTokenAdoption(params) {
783
+ const { callbackAccessToken, callbackRefreshToken, callbackNodeUrl, stored, storedNodeUrl } = params;
784
+ const bundle = (refreshToken2) => ({
785
+ access_token: callbackAccessToken,
786
+ refresh_token: refreshToken2,
787
+ expires_at: expiresAtFromJwt(callbackAccessToken)
788
+ });
789
+ if (!stored?.access_token) {
790
+ return { adopt: true, tokens: bundle(callbackRefreshToken), reason: "fresh-login" };
791
+ }
792
+ const sameNode = !!storedNodeUrl && sameOrigin(callbackNodeUrl, storedNodeUrl);
793
+ if (!sameNode) {
794
+ return { adopt: true, tokens: bundle(callbackRefreshToken), reason: "node-changed" };
795
+ }
796
+ const refreshToken = callbackRefreshToken || stored.refresh_token;
797
+ if (isCallbackNewer(callbackAccessToken, stored)) {
798
+ return { adopt: true, tokens: bundle(refreshToken), reason: "newer" };
799
+ }
800
+ if (!stored.refresh_token && callbackRefreshToken) {
801
+ return {
802
+ adopt: true,
803
+ tokens: { ...stored, refresh_token: callbackRefreshToken },
804
+ reason: "fill-refresh"
805
+ };
806
+ }
807
+ return { adopt: false, reason: "stale" };
808
+ }
809
+
810
+ // src/storage/index.ts
811
+ var STORAGE_KEYS = {
812
+ ACCESS_TOKEN: "mero:access_token",
813
+ REFRESH_TOKEN: "mero:refresh_token",
814
+ EXPIRES_AT: "mero:expires_at",
815
+ NODE_URL: "mero:node_url",
816
+ // The node the token bundle currently in the TokenStore was issued by. Distinct
817
+ // from NODE_URL, which `connectToNode` overwrites with the *target* node before
818
+ // redirecting to login — so at callback time NODE_URL names where we are going,
819
+ // not who minted the tokens we still hold. Telling those apart is what lets the
820
+ // SSO callback re-seed on a node change without mistaking a different node's
821
+ // bundle for a rotated one (see auth/token-adoption.ts).
822
+ TOKEN_NODE_URL: "mero:token_node_url",
823
+ APPLICATION_ID: "mero:application_id",
824
+ CONTEXT_ID: "mero:context_id",
825
+ CONTEXT_IDENTITY: "mero:context_identity"
826
+ };
827
+ var _storageAvailable = null;
828
+ function isLocalStorageAvailable() {
829
+ if (_storageAvailable !== null) return _storageAvailable;
830
+ try {
831
+ if (typeof window === "undefined" || !window.localStorage) {
832
+ _storageAvailable = false;
833
+ return false;
834
+ }
835
+ const testKey = "__mero_test__";
836
+ localStorage.setItem(testKey, "test");
837
+ localStorage.removeItem(testKey);
838
+ _storageAvailable = true;
839
+ } catch {
840
+ _storageAvailable = false;
841
+ }
842
+ return _storageAvailable;
843
+ }
844
+ var localStorageTokenStorage = {
845
+ async get() {
846
+ if (!isLocalStorageAvailable()) {
847
+ return null;
848
+ }
849
+ try {
850
+ const accessToken = localStorage.getItem(STORAGE_KEYS.ACCESS_TOKEN);
851
+ const refreshToken = localStorage.getItem(STORAGE_KEYS.REFRESH_TOKEN);
852
+ const expiresAt = localStorage.getItem(STORAGE_KEYS.EXPIRES_AT);
853
+ if (!accessToken || !refreshToken) {
854
+ return null;
855
+ }
856
+ return {
857
+ access_token: accessToken,
858
+ refresh_token: refreshToken,
859
+ expires_at: expiresAt ? parseInt(expiresAt, 10) : Date.now() + 36e5
860
+ };
861
+ } catch (e) {
862
+ console.error("[mero-react] Failed to get token from storage:", e);
863
+ return null;
864
+ }
865
+ },
866
+ async set(token) {
867
+ if (!isLocalStorageAvailable()) {
868
+ return;
869
+ }
870
+ try {
871
+ localStorage.setItem(STORAGE_KEYS.ACCESS_TOKEN, token.access_token);
872
+ localStorage.setItem(STORAGE_KEYS.REFRESH_TOKEN, token.refresh_token);
873
+ localStorage.setItem(STORAGE_KEYS.EXPIRES_AT, token.expires_at.toString());
874
+ } catch (e) {
875
+ console.error("[mero-react] Failed to save token to storage:", e);
876
+ }
877
+ },
878
+ async clear() {
879
+ if (!isLocalStorageAvailable()) {
880
+ return;
881
+ }
882
+ try {
883
+ localStorage.removeItem(STORAGE_KEYS.ACCESS_TOKEN);
884
+ localStorage.removeItem(STORAGE_KEYS.REFRESH_TOKEN);
885
+ localStorage.removeItem(STORAGE_KEYS.EXPIRES_AT);
886
+ } catch (e) {
887
+ console.error("[mero-react] Failed to clear token from storage:", e);
888
+ }
889
+ }
890
+ };
891
+ function getNodeUrl() {
892
+ if (!isLocalStorageAvailable()) return null;
893
+ return localStorage.getItem(STORAGE_KEYS.NODE_URL);
894
+ }
895
+ function setNodeUrl(url) {
896
+ if (!isLocalStorageAvailable()) return;
897
+ localStorage.setItem(STORAGE_KEYS.NODE_URL, url);
898
+ }
899
+ function clearNodeUrl() {
900
+ if (!isLocalStorageAvailable()) return;
901
+ localStorage.removeItem(STORAGE_KEYS.NODE_URL);
902
+ }
903
+ function getTokenNodeUrl() {
904
+ if (!isLocalStorageAvailable()) return null;
905
+ return localStorage.getItem(STORAGE_KEYS.TOKEN_NODE_URL);
906
+ }
907
+ function setTokenNodeUrl(url) {
908
+ if (!isLocalStorageAvailable()) return;
909
+ localStorage.setItem(STORAGE_KEYS.TOKEN_NODE_URL, url);
910
+ }
911
+ function clearTokenNodeUrl() {
912
+ if (!isLocalStorageAvailable()) return;
913
+ localStorage.removeItem(STORAGE_KEYS.TOKEN_NODE_URL);
914
+ }
915
+ function getApplicationId() {
916
+ if (!isLocalStorageAvailable()) return null;
917
+ return localStorage.getItem(STORAGE_KEYS.APPLICATION_ID);
918
+ }
919
+ function setApplicationId(id) {
920
+ if (!isLocalStorageAvailable()) return;
921
+ localStorage.setItem(STORAGE_KEYS.APPLICATION_ID, id);
505
922
  }
506
- function writeRelayMap(account, map) {
507
- try {
508
- localStorage.setItem(RELAY_MAP_PREFIX + account, JSON.stringify(map));
509
- } catch {
510
- }
923
+ function clearApplicationId() {
924
+ if (!isLocalStorageAvailable()) return;
925
+ localStorage.removeItem(STORAGE_KEYS.APPLICATION_ID);
511
926
  }
512
- function rememberRelay(account, relayUrl, at) {
513
- const map = readRelayMap(account);
514
- const url = relayOrigin(relayUrl);
515
- if (at.namespaceId) map.namespaces[at.namespaceId] = url;
516
- if (at.contextId) map.contexts[at.contextId] = url;
517
- writeRelayMap(account, map);
927
+ function getContextId() {
928
+ if (!isLocalStorageAvailable()) return null;
929
+ return localStorage.getItem(STORAGE_KEYS.CONTEXT_ID);
518
930
  }
519
- function relayForContext(account, contextId) {
520
- return readRelayMap(account).contexts[contextId] ?? null;
931
+ function setContextId(id) {
932
+ if (!isLocalStorageAvailable()) return;
933
+ localStorage.setItem(STORAGE_KEYS.CONTEXT_ID, id);
521
934
  }
522
- function knownRelays(s) {
523
- const map = readRelayMap(s.account);
524
- const all = [s.relayUrl, ...Object.values(map.namespaces), ...Object.values(map.contexts)].filter((u) => typeof u === "string" && u.length > 0).map(relayOrigin);
525
- return [...new Set(all)];
935
+ function clearContextId() {
936
+ if (!isLocalStorageAvailable()) return;
937
+ localStorage.removeItem(STORAGE_KEYS.CONTEXT_ID);
526
938
  }
527
- async function listDelegatedContexts(s) {
528
- const out = [];
529
- const map = readRelayMap(s.account);
530
- for (const relayUrl of knownRelays(s)) {
531
- try {
532
- if (!await resolveRelayNodeKey(relayUrl)) continue;
533
- const client2 = buildDelegatedClient({ ...s, relayUrl }, null);
534
- if (!client2) continue;
535
- const { contexts } = await client2.admin.getContexts();
536
- for (const c of contexts ?? []) {
537
- out.push({ ...c, relayUrl });
538
- map.contexts[c.id] = relayUrl;
539
- }
540
- } catch (e) {
541
- console.warn(`[mero-react] could not list contexts on ${relayUrl}`, e);
542
- }
543
- }
544
- writeRelayMap(s.account, map);
545
- return out;
939
+ function getContextIdentity() {
940
+ if (!isLocalStorageAvailable()) return null;
941
+ return localStorage.getItem(STORAGE_KEYS.CONTEXT_IDENTITY);
546
942
  }
547
- async function listDelegatedNamespaces(s) {
548
- var _a, _b;
549
- const out = [];
550
- const seen = /* @__PURE__ */ new Set();
551
- const map = readRelayMap(s.account);
552
- for (const relayUrl of knownRelays(s)) {
553
- try {
554
- if (!await resolveRelayNodeKey(relayUrl)) continue;
555
- const client2 = buildDelegatedClient({ ...s, relayUrl }, null);
556
- if (!client2) continue;
557
- for (const ns of await client2.admin.listNamespaces()) {
558
- if (seen.has(ns.namespaceId)) continue;
559
- seen.add(ns.namespaceId);
560
- out.push({ ...ns, relayUrl });
561
- (_a = map.namespaces)[_b = ns.namespaceId] ?? (_a[_b] = relayUrl);
562
- }
563
- } catch (e) {
564
- console.warn(`[mero-react] could not list namespaces on ${relayUrl}`, e);
565
- }
566
- }
567
- writeRelayMap(s.account, map);
568
- return out;
943
+ function setContextIdentity(id) {
944
+ if (!isLocalStorageAvailable()) return;
945
+ localStorage.setItem(STORAGE_KEYS.CONTEXT_IDENTITY, id);
946
+ }
947
+ function clearContextIdentity() {
948
+ if (!isLocalStorageAvailable()) return;
949
+ localStorage.removeItem(STORAGE_KEYS.CONTEXT_IDENTITY);
950
+ }
951
+ function clearAllStorage() {
952
+ if (!isLocalStorageAvailable()) return;
953
+ Object.values(STORAGE_KEYS).forEach((key) => {
954
+ localStorage.removeItem(key);
955
+ });
569
956
  }
570
957
  var MeroContext = createContext(null);
571
958
  var isBrowser = typeof window !== "undefined";
@@ -604,6 +991,7 @@ function MeroProvider({
604
991
  packageName,
605
992
  packageVersion,
606
993
  registryUrl,
994
+ cloudBaseUrl,
607
995
  timeoutMs = 3e4,
608
996
  allowedNodeUrls,
609
997
  tokenStore: tokenStoreProp
@@ -712,7 +1100,7 @@ function MeroProvider({
712
1100
  if (!delegated) return;
713
1101
  const relayUrl = (contextId ? relayForContext(delegated.account, contextId) : null) ?? delegated.relayUrl;
714
1102
  const routed = { ...delegated, relayUrl };
715
- const client2 = buildDelegatedClient(routed, contextId);
1103
+ const client2 = buildDelegatedClient(routed);
716
1104
  const awaitingKey = Boolean(client2 && relayUrl && !readPinnedRelayNodeKey(relayUrl));
717
1105
  if (!awaitingKey) setMero(client2);
718
1106
  setIsAuthenticated(true);
@@ -725,7 +1113,7 @@ function MeroProvider({
725
1113
  if (awaitingKey) {
726
1114
  const nodeKey = await resolveRelayNodeKey(relayUrl);
727
1115
  if (!active) return;
728
- setMero(nodeKey ? buildDelegatedClient(routed, contextId) ?? client2 : client2);
1116
+ setMero(nodeKey ? buildDelegatedClient(routed) ?? client2 : client2);
729
1117
  setIsLoading(false);
730
1118
  if (!nodeKey) return;
731
1119
  }
@@ -880,6 +1268,16 @@ function MeroProvider({
880
1268
  sse.off("error", onError);
881
1269
  };
882
1270
  }, [isAuthenticated, mero, checkAuth, logout, delegated]);
1271
+ const admin = useMemo(() => {
1272
+ const app = { packageName, packageVersion, registryUrl };
1273
+ if (delegated !== null) {
1274
+ if (delegated.relayUrl === null) return createAccountAdmin({ session: delegated, read: null, app });
1275
+ if (!mero) return null;
1276
+ return createAccountAdmin({ session: delegated, read: mero.admin, app });
1277
+ }
1278
+ const nodeAdmin = mero?.admin;
1279
+ return nodeAdmin ? createNodeAdmin({ admin: nodeAdmin, app }) : null;
1280
+ }, [mero, delegated, packageName, packageVersion, registryUrl]);
883
1281
  const contextValue = useMemo(
884
1282
  () => ({
885
1283
  mero,
@@ -892,12 +1290,14 @@ function MeroProvider({
892
1290
  connectToNode,
893
1291
  connectWithAccount,
894
1292
  isDelegated: delegated !== null,
895
- can: delegated !== null ? { createNamespace: Boolean(packageName), createContext: true, invite: false } : { createNamespace: true, createContext: true, invite: true },
1293
+ admin,
1294
+ can: delegated !== null ? { createNamespace: Boolean(packageName), createContext: true, invite: true, upgrade: false } : { createNamespace: true, createContext: true, invite: true, upgrade: true },
896
1295
  app: { packageName, packageVersion, registryUrl },
1296
+ cloudBaseUrl,
897
1297
  logout,
898
1298
  isLoading
899
1299
  }),
900
- [mero, isAuthenticated, isOnline, nodeUrl, applicationId, contextId, contextIdentity, connectToNode, connectWithAccount, delegated, logout, isLoading, packageName, packageVersion, registryUrl]
1300
+ [mero, admin, isAuthenticated, isOnline, nodeUrl, applicationId, contextId, contextIdentity, connectToNode, connectWithAccount, delegated, logout, isLoading, packageName, packageVersion, registryUrl, cloudBaseUrl]
901
1301
  );
902
1302
  return /* @__PURE__ */ jsx(MeroContext.Provider, { value: contextValue, children });
903
1303
  }
@@ -1694,7 +2094,7 @@ function ConnectButtonAccount({
1694
2094
  theme,
1695
2095
  defaults = {}
1696
2096
  }) {
1697
- const { isAuthenticated, isOnline, nodeUrl, isDelegated, connectToNode, connectWithAccount, logout } = useMero();
2097
+ const { isAuthenticated, isOnline, nodeUrl, isDelegated, connectToNode, connectWithAccount, logout, cloudBaseUrl } = useMero();
1698
2098
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
1699
2099
  const [isNodeModalOpen, setIsNodeModalOpen] = useState(false);
1700
2100
  const [isAccountOpen, setIsAccountOpen] = useState(false);
@@ -1768,6 +2168,7 @@ function ConnectButtonAccount({
1768
2168
  deviceSecret: keys.signSk
1769
2169
  });
1770
2170
  const cloud = new CloudClient({
2171
+ cloudBaseUrl,
1771
2172
  routingCredential: {
1772
2173
  credential: enrolled.credential,
1773
2174
  deviceSecret: keys.signSk
@@ -1788,7 +2189,7 @@ function ConnectButtonAccount({
1788
2189
  return () => {
1789
2190
  cancelled = true;
1790
2191
  };
1791
- }, [connectWithAccount]);
2192
+ }, [connectWithAccount, cloudBaseUrl]);
1792
2193
  const goToWallet = useCallback(async () => {
1793
2194
  const keys = await deviceKeys();
1794
2195
  const state = hex(crypto.getRandomValues(new Uint8Array(16)));
@@ -1958,161 +2359,6 @@ function base58ToHex(input) {
1958
2359
  for (let k = 0; k < input.length && input[k] === "1"; k++) bytes.push(0);
1959
2360
  return bytes.reverse().map((b) => b.toString(16).padStart(2, "0")).join("");
1960
2361
  }
1961
- function governanceNonce(relay, group) {
1962
- return { next: async () => nextGovernanceNonce(relay, group) };
1963
- }
1964
- function nextGovernanceNonce(relay, group) {
1965
- const key = `calimero.governance-nonce.${relay}.${group}`;
1966
- let last = 0n;
1967
- try {
1968
- last = BigInt(localStorage.getItem(key) ?? "0");
1969
- } catch {
1970
- }
1971
- const next = [last + 1n, BigInt(Date.now())].reduce((a, b) => a > b ? a : b);
1972
- try {
1973
- localStorage.setItem(key, String(next));
1974
- } catch {
1975
- }
1976
- return next;
1977
- }
1978
- function relayFor(s, namespaceId) {
1979
- const url = readRelayMap(s.account).namespaces[namespaceId] ?? s.relayUrl;
1980
- if (!url) throw new Error("no relay is known for this namespace, so there is nowhere to send this");
1981
- return url.replace(/\/+$/, "");
1982
- }
1983
- function initArgsOf(params) {
1984
- if (!params || params.length === 0) return {};
1985
- return JSON.parse(new TextDecoder().decode(Uint8Array.from(params)));
1986
- }
1987
- function client(s, relayUrl, nonces, fetch2) {
1988
- return new RelayClient({
1989
- relayUrl,
1990
- authorAccount: s.account,
1991
- authorProof: s.credential,
1992
- deviceSecret: s.deviceSecret,
1993
- nonces,
1994
- fetch: fetch2
1995
- });
1996
- }
1997
- async function createDelegatedContext(s, req, deps = {}) {
1998
- const relay = relayFor(s, req.namespaceId);
1999
- const creationNonce = 0n;
2000
- const created = await client(s, relay, { next: async () => creationNonce }, deps.fetch).createContext({
2001
- groupId: req.groupId ?? req.namespaceId,
2002
- applicationId: req.applicationId,
2003
- initArgs: initArgsOf(req.initializationParams),
2004
- name: req.name
2005
- });
2006
- markContextNonceSpent(relay, created.contextId, creationNonce);
2007
- rememberRelay(s.account, relay, { namespaceId: req.namespaceId, contextId: created.contextId });
2008
- return { contextId: created.contextId };
2009
- }
2010
- async function delegatedGovernance(s, req, deps = {}) {
2011
- const relay = relayFor(s, req.namespaceId);
2012
- return client(s, relay, governanceNonce(relay, req.group), deps.fetch).govern({ groupId: req.group, op: req.op });
2013
- }
2014
- async function createDelegatedPrivateContext(s, req, deps = {}) {
2015
- const { groupId } = await delegatedGovernance(
2016
- s,
2017
- {
2018
- namespaceId: req.namespaceId,
2019
- group: req.namespaceId,
2020
- // The id is derived from a fresh salt (core#4244); a node refuses any other.
2021
- op: (await subgroupCreation({ parentId: req.namespaceId, restricted: true, admin: s.account })).op
2022
- },
2023
- deps
2024
- );
2025
- for (const member of req.members) {
2026
- await delegatedGovernance(s, { namespaceId: req.namespaceId, group: groupId, op: memberAddedOp(member, "Member") }, deps);
2027
- }
2028
- const { contextId } = await createDelegatedContext(s, { ...req, groupId }, deps);
2029
- return { contextId, groupId };
2030
- }
2031
- async function foundDelegatedNamespace(s, req = {}, deps = {}) {
2032
- const relays = knownRelays(s).map((u) => u.replace(/\/+$/, ""));
2033
- const relay = relays[0];
2034
- if (!relay) throw new Error("no relay is known for this account, so there is nowhere to found a namespace");
2035
- const known = Object.entries(readRelayMap(s.account).namespaces).find(
2036
- ([, url]) => url.replace(/\/+$/, "") === relay
2037
- )?.[0];
2038
- if (!known) {
2039
- throw new Error("join a namespace on this relay first: its executor account is learned from one you are in");
2040
- }
2041
- const { executorAccount } = await client(s, relay, governanceNonce(relay, known), deps.fetch).describeGovernance(known);
2042
- let next = BigInt(Date.now());
2043
- const founded = await client(s, relay, { next: async () => next++ }, deps.fetch).foundNamespace({
2044
- executorAccount,
2045
- ...req.defaultCapabilities !== void 0 ? { defaultCapabilities: req.defaultCapabilities } : {},
2046
- ...req.application ? { application: req.application } : {}
2047
- });
2048
- try {
2049
- localStorage.setItem(`calimero.governance-nonce.${relay}.${founded.namespaceId}`, String(next));
2050
- } catch {
2051
- }
2052
- rememberRelay(s.account, relay, { namespaceId: founded.namespaceId });
2053
- if (req.application && founded.applicationSet !== true) {
2054
- throw new Error(
2055
- `founded ${founded.namespaceId} but could not give it its application: ${founded.applicationError ?? "unknown reason"}`
2056
- );
2057
- }
2058
- return { namespaceId: founded.namespaceId, teeEnabled: founded.teeEnabled };
2059
- }
2060
- async function latestPublishedVersion(registryUrl, pkg, fetchFn = globalThis.fetch) {
2061
- const url = `${registryUrl.replace(/\/+$/, "")}/api/v2/bundles?package=${encodeURIComponent(pkg)}`;
2062
- const response = await fetchFn(url, { headers: { Accept: "application/json" } });
2063
- if (!response.ok) throw new Error(`the registry has no ${pkg} (HTTP ${response.status})`);
2064
- const bundles = await response.json();
2065
- const newer = (a, b) => {
2066
- const [x, y] = [a, b].map((v) => v.split(/[.-]/).map((n) => Number.parseInt(n, 10) || 0));
2067
- for (let i = 0; i < Math.max(x.length, y.length); i++) {
2068
- if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0);
2069
- }
2070
- return false;
2071
- };
2072
- const latest = bundles.map((b) => b.appVersion).filter((v) => typeof v === "string" && v.length > 0).reduce((best, v) => !best || newer(v, best) ? v : best, void 0);
2073
- if (!latest) throw new Error(`the registry lists no version of ${pkg}`);
2074
- return latest;
2075
- }
2076
-
2077
- // src/delegated/govern.ts
2078
- var GROUP_NAMESPACE_PREFIX = "calimero.delegated.group-namespace.";
2079
- function readGroupNamespaces(account) {
2080
- try {
2081
- return JSON.parse(localStorage.getItem(GROUP_NAMESPACE_PREFIX + account) ?? "{}");
2082
- } catch {
2083
- return {};
2084
- }
2085
- }
2086
- function rememberGroupNamespace(account, groupId, namespaceId) {
2087
- try {
2088
- const all = readGroupNamespaces(account);
2089
- all[groupId] = namespaceId;
2090
- localStorage.setItem(GROUP_NAMESPACE_PREFIX + account, JSON.stringify(all));
2091
- } catch {
2092
- }
2093
- }
2094
- function namespaceOfGroup(s, groupId) {
2095
- if (readRelayMap(s.account).namespaces[groupId]) return groupId;
2096
- return readGroupNamespaces(s.account)[groupId];
2097
- }
2098
- function requireNamespace(s, groupId) {
2099
- const ns = namespaceOfGroup(s, groupId);
2100
- if (!ns) {
2101
- throw new Error(
2102
- `the namespace of group ${groupId} is not known to this account: it can manage only groups in namespaces it joined or subgroups it created`
2103
- );
2104
- }
2105
- return ns;
2106
- }
2107
- async function governGroup(s, groupId, op) {
2108
- return delegatedGovernance(s, { namespaceId: requireNamespace(s, groupId), group: groupId, op });
2109
- }
2110
- async function governRoot(s, groupId, op) {
2111
- const namespaceId = requireNamespace(s, groupId);
2112
- return delegatedGovernance(s, { namespaceId, group: namespaceId, op });
2113
- }
2114
-
2115
- // src/hooks/index.ts
2116
2362
  var NO_EPHEMERAL_SURFACE_MESSAGE = "useEphemeral: this client has no `mero.ephemeral` surface. Ephemeral presence requires @calimero-network/mero-js >= 9.1.0; upgrade the installed @calimero-network/mero-js (and any lockfile pin) to use it.";
2117
2363
  var COULD_NOT_RESOLVE_IDENTITY_MESSAGE = "useEphemeral: could not resolve a local context identity, so your own presence cannot be filtered out. Pass includeSelf: true to accept this.";
2118
2364
  var REPLAY_RECONCILE_MS = 50;
@@ -4119,12 +4365,17 @@ async function bootstrapFromInvitation(input) {
4119
4365
  return { ok: true, published: joined.published, relay, session: joined.session };
4120
4366
  }
4121
4367
  function useDelegatedBootstrap(options = {}) {
4122
- const { connectWithAccount } = useMero();
4368
+ const { connectWithAccount, cloudBaseUrl: providerCloud } = useMero();
4123
4369
  const [running, setRunning] = useState(false);
4124
4370
  const [result, setResult] = useState(null);
4125
- const credential = readDelegatedCredential();
4371
+ const read = readDelegatedCredential();
4372
+ const credential = useMemo(
4373
+ () => read,
4374
+ // Keyed on the contents, not the parsed object.
4375
+ [read?.account, read?.credential, read?.deviceSecret]
4376
+ );
4126
4377
  const relayUrl = readDelegatedSession()?.relayUrl ?? null;
4127
- const { cloudBaseUrl } = options;
4378
+ const cloudBaseUrl = options.cloudBaseUrl ?? providerCloud;
4128
4379
  const bootstrap = useCallback(
4129
4380
  async (input) => {
4130
4381
  const held = readDelegatedCredential();
@@ -4238,7 +4489,7 @@ function useJoinInvitation() {
4238
4489
  return { ok: false, step: "node-join", reason: "Not connected to a node.", final: false };
4239
4490
  }
4240
4491
  await mero.admin.joinNamespace(input.namespaceId, { invitation: input.invitation });
4241
- await mero.admin.joinContext(input.contextId);
4492
+ if (input.contextId) await mero.admin.joinContext(input.contextId);
4242
4493
  return { ok: true };
4243
4494
  } catch (e) {
4244
4495
  const reason = e instanceof Error ? e.message : String(e);
@@ -4281,6 +4532,6 @@ function useJoinInvitation() {
4281
4532
  return { joinInvitation, joining, memberships, invitationRedeemer };
4282
4533
  }
4283
4534
 
4284
- export { AppMode, CalimeroLogo, ConnectButton, ConnectButtonAccount, ConnectionType, DEFAULT_MIGRATION_POLL_INTERVAL_MS, LoginModal, MERO_CSS_VARS, MeroContext, MeroProvider, MigrationAdminPanel, MigrationPendingBanner, bootstrapFromInvitation, clearAllStorage, clearApplicationId, clearContextId, clearContextIdentity, clearDelegatedCredential, clearNodeUrl, clearTokenNodeUrl, createDelegatedContext, cssVar, defaultMeroTheme, getApplicationId, getContextId, getContextIdentity, getNodeUrl, getTokenNodeUrl, isFinalInvitationError, joinWithNode, listDelegatedContexts, localStorageTokenStorage, normaliseAccount, pinRelayNodeKey, readDelegatedCredential, readPinnedRelayNodeKey, readRelayMap, relayForContext, rememberRelay, resolveMeroTheme, resolveRelayFromInvitation, saveDelegatedCredential, setApplicationId, setContextId, setContextIdentity, setNodeUrl, setTokenNodeUrl, themeToCssVars, useAddGroupMembers, useAppVersion, useApplicationContexts, useBlobInfo, useBlobUrl, useContextDiscovery, useContextGroup, useContexts, useCreateContext, useCreateGroupInNamespace, useCreateNamespace, useCreateNamespaceInvitation, useCreatePrivateContext, useDefaultCapabilities, useDelegatedBootstrap, useDeleteContext, useDeleteGroup, useDeleteNamespace, useDetachContextFromGroup, useEphemeral, useExecute, useGroupAppVersion, useGroupCapabilities, useGroupContexts, useGroupInfo, useGroupInvitations, useGroupMembers, useGroupMetadata, useGroupUpgradeStatus, useInstallFromRegistry, useJoinContext, useJoinGroup, useJoinInvitation, useJoinNamespace, useJoinSubgroupInheritance, useLatestVersion, useMemberMetadata, useMero, useMigrationEvents, useMigrationStatus, useMyAuthoredMigration, useNamespace, useNamespaceGroups, useNamespaceIdentity, useNamespaces, useNamespacesForApplication, useNodeIdentity, useRedeemInvitation, useRemoveGroupMembers, useReparentGroup, useResyncContext, useRetryGroupUpgrade, useSetContextMetadata, useSetDefaultCapabilities, useSetGroupMetadata, useSetMemberMetadata, useSetSubgroupVisibility, useSetTeeAdmissionPolicy, useSubgroupVisibility, useSubgroups, useSubscription, useSyncGroup, useUpdateMemberRole, useUpgradeGroup, useUploadBlob };
4535
+ export { AppMode, CalimeroLogo, ConnectButton, ConnectButtonAccount, ConnectionType, DEFAULT_MIGRATION_POLL_INTERVAL_MS, LoginModal, MERO_CSS_VARS, MeroContext, MeroProvider, MigrationAdminPanel, MigrationPendingBanner, NoRelayError, NotForAccountError, bootstrapFromInvitation, clearAllStorage, clearApplicationId, clearContextId, clearContextIdentity, clearDelegatedCredential, clearNodeUrl, clearTokenNodeUrl, createAccountAdmin, createDelegatedContext, createNodeAdmin, cssVar, defaultMeroTheme, getApplicationId, getContextId, getContextIdentity, getNodeUrl, getTokenNodeUrl, isFinalInvitationError, joinWithNode, listDelegatedContexts, localStorageTokenStorage, normaliseAccount, pinRelayNodeKey, readDelegatedCredential, readPinnedRelayNodeKey, readRelayMap, relayForContext, rememberRelay, resolveMeroTheme, resolveRelayFromInvitation, saveDelegatedCredential, setApplicationId, setContextId, setContextIdentity, setNodeUrl, setTokenNodeUrl, themeToCssVars, useAddGroupMembers, useAppVersion, useApplicationContexts, useBlobInfo, useBlobUrl, useContextDiscovery, useContextGroup, useContexts, useCreateContext, useCreateGroupInNamespace, useCreateNamespace, useCreateNamespaceInvitation, useCreatePrivateContext, useDefaultCapabilities, useDelegatedBootstrap, useDeleteContext, useDeleteGroup, useDeleteNamespace, useDetachContextFromGroup, useEphemeral, useExecute, useGroupAppVersion, useGroupCapabilities, useGroupContexts, useGroupInfo, useGroupInvitations, useGroupMembers, useGroupMetadata, useGroupUpgradeStatus, useInstallFromRegistry, useJoinContext, useJoinGroup, useJoinInvitation, useJoinNamespace, useJoinSubgroupInheritance, useLatestVersion, useMemberMetadata, useMero, useMigrationEvents, useMigrationStatus, useMyAuthoredMigration, useNamespace, useNamespaceGroups, useNamespaceIdentity, useNamespaces, useNamespacesForApplication, useNodeIdentity, useRedeemInvitation, useRemoveGroupMembers, useReparentGroup, useResyncContext, useRetryGroupUpgrade, useSetContextMetadata, useSetDefaultCapabilities, useSetGroupMetadata, useSetMemberMetadata, useSetSubgroupVisibility, useSetTeeAdmissionPolicy, useSubgroupVisibility, useSubgroups, useSubscription, useSyncGroup, useUpdateMemberRole, useUpgradeGroup, useUploadBlob };
4285
4536
  //# sourceMappingURL=index.js.map
4286
4537
  //# sourceMappingURL=index.js.map