@calimero-network/mero-react 9.2.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, compareSemver, AuthRevokedError, HTTPError, classifyError } 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,6 +44,680 @@ var ConnectionType = /* @__PURE__ */ ((ConnectionType2) => {
44
44
  ConnectionType2["Custom"] = "custom";
45
45
  return ConnectionType2;
46
46
  })(ConnectionType || {});
47
+ var KEY = "calimero.delegated.connection";
48
+ var CREDENTIAL_KEY = "calimero.delegated.credential";
49
+ function readDelegatedSession() {
50
+ if (typeof sessionStorage === "undefined") return null;
51
+ try {
52
+ const raw = sessionStorage.getItem(KEY);
53
+ return raw ? JSON.parse(raw) : null;
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+ function saveDelegatedSession(s) {
59
+ try {
60
+ sessionStorage.setItem(KEY, JSON.stringify(s));
61
+ } catch {
62
+ }
63
+ }
64
+ function clearDelegatedSession() {
65
+ try {
66
+ sessionStorage.removeItem(KEY);
67
+ } catch {
68
+ }
69
+ }
70
+ function readDelegatedCredential() {
71
+ const session = readDelegatedSession();
72
+ if (session) {
73
+ const { account, credential, deviceSecret } = session;
74
+ return { account, credential, deviceSecret };
75
+ }
76
+ if (typeof sessionStorage === "undefined") return null;
77
+ try {
78
+ const raw = sessionStorage.getItem(CREDENTIAL_KEY);
79
+ if (!raw) return null;
80
+ const parsed = JSON.parse(raw);
81
+ if (!parsed.account || !parsed.credential || !parsed.deviceSecret) return null;
82
+ return parsed;
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+ function saveDelegatedCredential(c) {
88
+ try {
89
+ sessionStorage.setItem(CREDENTIAL_KEY, JSON.stringify(c));
90
+ } catch {
91
+ }
92
+ }
93
+ function clearDelegatedCredential() {
94
+ try {
95
+ sessionStorage.removeItem(CREDENTIAL_KEY);
96
+ } catch {
97
+ }
98
+ }
99
+ function persistedNonces(relayUrl) {
100
+ const key = nonceKey(relayUrl);
101
+ return {
102
+ next: async () => {
103
+ let n = 0n;
104
+ try {
105
+ n = readNonceFloor(relayUrl);
106
+ } catch {
107
+ n = 0n;
108
+ }
109
+ try {
110
+ localStorage.setItem(key, String(n + 1n));
111
+ } catch {
112
+ }
113
+ return n;
114
+ }
115
+ };
116
+ }
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) {
134
+ try {
135
+ if (readNonceFloor(relayUrl) <= nonce) localStorage.setItem(nonceKey(relayUrl), String(nonce + 1n));
136
+ } catch {
137
+ }
138
+ }
139
+ var RELAY_NODE_KEY_PREFIX = "calimero.delegated.relay-node-key.";
140
+ function relayOrigin(relayUrl) {
141
+ return relayUrl.replace(/\/+$/, "");
142
+ }
143
+ function pinRelayNodeKey(relayUrl, nodeKey) {
144
+ localStorage.setItem(RELAY_NODE_KEY_PREFIX + relayOrigin(relayUrl), nodeKey.trim().toLowerCase());
145
+ }
146
+ function readPinnedRelayNodeKey(relayUrl) {
147
+ try {
148
+ const v = localStorage.getItem(RELAY_NODE_KEY_PREFIX + relayOrigin(relayUrl));
149
+ return v && /^[0-9a-f]{64}$/.test(v) ? v : null;
150
+ } catch {
151
+ return null;
152
+ }
153
+ }
154
+ function isLoopback(relayUrl) {
155
+ try {
156
+ const { hostname } = new URL(relayUrl);
157
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
158
+ } catch {
159
+ return false;
160
+ }
161
+ }
162
+ var TRUSTED_RELAY_PROFILE = "locked-read-only";
163
+ var MIN_RELAY_RELEASE = "2.3.99";
164
+ var loadedDcap;
165
+ function relayQuoteVerifier(relayUrl) {
166
+ const verify = async (attestation) => {
167
+ loadedDcap ?? (loadedDcap = import('@phala/dcap-qvl').then(
168
+ ({ verify: dcapVerify }) => dcapVerify,
169
+ (error) => {
170
+ loadedDcap = void 0;
171
+ throw error;
172
+ }
173
+ ));
174
+ return createSignedReleaseVerifier({
175
+ dcapVerify: await loadedDcap,
176
+ release: async () => fetchNodeRelease(cloudNodeReleaseUrl(DEFAULT_RELEASE_MIRROR, await fetchNodeReleaseVersion(relayUrl))),
177
+ profile: TRUSTED_RELAY_PROFILE,
178
+ minReleaseVersion: MIN_RELAY_RELEASE
179
+ })(attestation);
180
+ };
181
+ return Object.assign(verify, { includeCollateral: true });
182
+ }
183
+ async function resolveRelayNodeKey(relayUrl) {
184
+ const pinned = readPinnedRelayNodeKey(relayUrl);
185
+ if (pinned) return pinned;
186
+ try {
187
+ const local = isLoopback(relayUrl);
188
+ const { nodeKey } = await attestRelayNodeKey({
189
+ relayUrl,
190
+ allowMock: local,
191
+ ...local ? {} : { verify: relayQuoteVerifier(relayUrl) }
192
+ });
193
+ pinRelayNodeKey(relayUrl, nodeKey);
194
+ return nodeKey;
195
+ } catch (e) {
196
+ console.warn("[mero-react] could not learn the relay node key from its attestation", e);
197
+ return null;
198
+ }
199
+ }
200
+ function jwtExpiryMs(token) {
201
+ try {
202
+ const payload = JSON.parse(atob(token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")));
203
+ return typeof payload.exp === "number" ? payload.exp * 1e3 : null;
204
+ } catch {
205
+ return null;
206
+ }
207
+ }
208
+ function relaySession(s, nodeKey) {
209
+ let token = null;
210
+ let inflight = null;
211
+ return async () => {
212
+ const exp = token ? jwtExpiryMs(token) : null;
213
+ if (token && (exp === null || exp - Date.now() > 3e4)) return token;
214
+ if (!inflight) {
215
+ inflight = login({
216
+ nodeUrl: s.relayUrl,
217
+ node: nodeKey,
218
+ deviceSecret: s.deviceSecret,
219
+ accountProof: s.credential,
220
+ audience: defaultAudience()
221
+ }).then((minted) => {
222
+ token = minted.accessToken;
223
+ return token;
224
+ }).catch((e) => {
225
+ console.warn("[mero-react] relay login failed", e);
226
+ token = null;
227
+ return void 0;
228
+ }).finally(() => {
229
+ inflight = null;
230
+ });
231
+ }
232
+ return inflight;
233
+ };
234
+ }
235
+ function buildDelegatedClient(s, _contextId) {
236
+ if (!s.relayUrl) return null;
237
+ const nodeKey = readPinnedRelayNodeKey(s.relayUrl);
238
+ return createMeroClient({
239
+ transport: "relay",
240
+ relay: {
241
+ relayUrl: s.relayUrl,
242
+ authorAccount: s.account,
243
+ authorProof: s.credential,
244
+ deviceSecret: s.deviceSecret,
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)
248
+ },
249
+ // The certificate authenticates the requests too, not just the writes.
250
+ //
251
+ // This is the whole of what reads and events need: the device key signs each
252
+ // request, and the node verifies it against the account's certificate with no
253
+ // store read and no prior relationship. Measured against a node built from
254
+ // core `aecba573b`: `listNamespaces` and `getContexts` answer `200` and are
255
+ // caller-scoped, `/sse` answers `200`, and a real write arrives on the stream
256
+ // as a `StateMutation` frame.
257
+ //
258
+ // What this replaces is a session minted by `login()` plus the relay node's
259
+ // signing key learned out of band — two inputs, one of which the cloud does
260
+ // not publish, for an answer the certificate already gives.
261
+ proof: { credential: s.credential, deviceSecret: s.deviceSecret },
262
+ // A session, when this relay's node key is pinned. A hosted relay's
263
+ // forward-auth accepts a Bearer token and not the proof above, so without
264
+ // one every admin read there is a 401. Given a session the client uses it
265
+ // for every admin call; a relay with no pinned key keeps the proof path.
266
+ session: nodeKey ? relaySession({ ...s, relayUrl: s.relayUrl }, nodeKey) : void 0,
267
+ // Events too. `/sse` on a relay sits behind the same forward-auth, so the
268
+ // proof above gets a 401 there; with the node key the client observes
269
+ // through its own device-certificate login instead.
270
+ observe: nodeKey ? { nodeKey } : void 0
271
+ });
272
+ }
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
+ }
47
721
 
48
722
  // src/auth/node-trust.ts
49
723
  function sameOrigin(a, b) {
@@ -317,6 +991,7 @@ function MeroProvider({
317
991
  packageName,
318
992
  packageVersion,
319
993
  registryUrl,
994
+ cloudBaseUrl,
320
995
  timeoutMs = 3e4,
321
996
  allowedNodeUrls,
322
997
  tokenStore: tokenStoreProp
@@ -326,6 +1001,9 @@ function MeroProvider({
326
1001
  [tokenStoreProp]
327
1002
  );
328
1003
  const [mero, setMero] = useState(null);
1004
+ const [delegated, setDelegated] = useState(
1005
+ () => readDelegatedSession()
1006
+ );
329
1007
  const [isAuthenticated, setIsAuthenticated] = useState(false);
330
1008
  const [isOnline, setIsOnline] = useState(true);
331
1009
  const [isLoading, setIsLoading] = useState(true);
@@ -394,6 +1072,12 @@ function MeroProvider({
394
1072
  },
395
1073
  [mode, packageName, packageVersion, registryUrl]
396
1074
  );
1075
+ const connectWithAccount = useCallback((session) => {
1076
+ saveDelegatedSession(session);
1077
+ const { account, credential, deviceSecret } = session;
1078
+ saveDelegatedCredential({ account, credential, deviceSecret });
1079
+ setDelegated(session);
1080
+ }, []);
397
1081
  const logout = useCallback(() => {
398
1082
  if (meroRef.current) {
399
1083
  meroRef.current.clearToken();
@@ -401,6 +1085,9 @@ function MeroProvider({
401
1085
  }
402
1086
  tokenStore.clear();
403
1087
  clearAllStorage();
1088
+ clearDelegatedSession();
1089
+ clearDelegatedCredential();
1090
+ setDelegated(null);
404
1091
  setMero(null);
405
1092
  setIsAuthenticated(false);
406
1093
  setNodeUrlState(null);
@@ -410,6 +1097,44 @@ function MeroProvider({
410
1097
  meroRef.current = null;
411
1098
  }, [tokenStore]);
412
1099
  useEffect(() => {
1100
+ if (!delegated) return;
1101
+ const relayUrl = (contextId ? relayForContext(delegated.account, contextId) : null) ?? delegated.relayUrl;
1102
+ const routed = { ...delegated, relayUrl };
1103
+ const client2 = buildDelegatedClient(routed);
1104
+ const awaitingKey = Boolean(client2 && relayUrl && !readPinnedRelayNodeKey(relayUrl));
1105
+ if (!awaitingKey) setMero(client2);
1106
+ setIsAuthenticated(true);
1107
+ setIsOnline(true);
1108
+ setNodeUrlState(relayUrl);
1109
+ setIsLoading(awaitingKey);
1110
+ let active = true;
1111
+ (async () => {
1112
+ if (!client2 || !relayUrl) return;
1113
+ if (awaitingKey) {
1114
+ const nodeKey = await resolveRelayNodeKey(relayUrl);
1115
+ if (!active) return;
1116
+ setMero(nodeKey ? buildDelegatedClient(routed) ?? client2 : client2);
1117
+ setIsLoading(false);
1118
+ if (!nodeKey) return;
1119
+ }
1120
+ try {
1121
+ const contexts = await listDelegatedContexts(delegated);
1122
+ const apps = [
1123
+ ...new Set((contexts ?? []).map((c) => c.applicationId).filter(Boolean))
1124
+ ];
1125
+ if (!active) return;
1126
+ if (apps.length === 1) {
1127
+ setApplicationIdState(apps[0]);
1128
+ }
1129
+ } catch {
1130
+ }
1131
+ })();
1132
+ return () => {
1133
+ active = false;
1134
+ };
1135
+ }, [delegated, contextId]);
1136
+ useEffect(() => {
1137
+ if (delegated) return;
413
1138
  let active = true;
414
1139
  const init = async () => {
415
1140
  const callback = callbackRef.current;
@@ -487,7 +1212,7 @@ function MeroProvider({
487
1212
  return () => {
488
1213
  active = false;
489
1214
  };
490
- }, [createMeroInstance, checkAuth, allowedNodeUrls, tokenStore]);
1215
+ }, [createMeroInstance, checkAuth, allowedNodeUrls, tokenStore, delegated]);
491
1216
  useEffect(() => {
492
1217
  if (!isAuthenticated || !meroRef.current) return;
493
1218
  let active = true;
@@ -498,6 +1223,7 @@ function MeroProvider({
498
1223
  const onError = (err) => {
499
1224
  if (!active) return;
500
1225
  setIsOnline(false);
1226
+ if (delegated) return;
501
1227
  if (err instanceof AuthRevokedError) {
502
1228
  logout();
503
1229
  return;
@@ -541,7 +1267,17 @@ function MeroProvider({
541
1267
  sse.off("connect", onConnect);
542
1268
  sse.off("error", onError);
543
1269
  };
544
- }, [isAuthenticated, mero, checkAuth, logout]);
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]);
545
1281
  const contextValue = useMemo(
546
1282
  () => ({
547
1283
  mero,
@@ -552,10 +1288,16 @@ function MeroProvider({
552
1288
  contextId,
553
1289
  contextIdentity,
554
1290
  connectToNode,
1291
+ connectWithAccount,
1292
+ isDelegated: delegated !== null,
1293
+ admin,
1294
+ can: delegated !== null ? { createNamespace: Boolean(packageName), createContext: true, invite: true, upgrade: false } : { createNamespace: true, createContext: true, invite: true, upgrade: true },
1295
+ app: { packageName, packageVersion, registryUrl },
1296
+ cloudBaseUrl,
555
1297
  logout,
556
1298
  isLoading
557
1299
  }),
558
- [mero, isAuthenticated, isOnline, nodeUrl, applicationId, contextId, contextIdentity, connectToNode, logout, isLoading]
1300
+ [mero, admin, isAuthenticated, isOnline, nodeUrl, applicationId, contextId, contextIdentity, connectToNode, connectWithAccount, delegated, logout, isLoading, packageName, packageVersion, registryUrl, cloudBaseUrl]
559
1301
  );
560
1302
  return /* @__PURE__ */ jsx(MeroContext.Provider, { value: contextValue, children });
561
1303
  }
@@ -1287,6 +2029,315 @@ function ConnectButton({
1287
2029
  }
1288
2030
  );
1289
2031
  }
2032
+ var DEVICE_KEY = "calimero.device";
2033
+ var STATE_KEY = "calimero.enrol.state";
2034
+ var HOSTED_WALLET = "https://wallet.cloud.calimero.network/account-enroll";
2035
+ var hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
2036
+ function chooseRelay(relays) {
2037
+ const reachable = relays.filter(
2038
+ (r) => typeof r.relayUrl === "string" && r.relayUrl.length > 0
2039
+ );
2040
+ const fresh = reachable.find((r) => r.fresh);
2041
+ if (fresh) return { relayUrl: fresh.relayUrl, note: null };
2042
+ if (reachable.length > 0) {
2043
+ return {
2044
+ relayUrl: reachable[0].relayUrl,
2045
+ note: "Connected through a relay whose last heartbeat has lapsed \u2014 it may not answer. It was the only one with an address."
2046
+ };
2047
+ }
2048
+ if (relays.length > 0) {
2049
+ return {
2050
+ relayUrl: null,
2051
+ note: `Signed in. Your account has ${relays.length} relay${relays.length === 1 ? "" : "s"} assigned, but the cloud knows no address for any of them yet, so there is nowhere to write through for the moment. Reads and writes resume as soon as one reports in.`
2052
+ };
2053
+ }
2054
+ return {
2055
+ relayUrl: null,
2056
+ note: "Signed in, with nowhere to write yet: a new account is a member of nothing, so no node serves it. Redeeming an invitation admits this account to a namespace and gives it a relay \u2014 that is the normal first step, not an error."
2057
+ };
2058
+ }
2059
+ async function deviceKeys() {
2060
+ const had = localStorage.getItem(DEVICE_KEY);
2061
+ if (had) {
2062
+ const parsed = JSON.parse(had);
2063
+ if (parsed.kemSk && parsed.signSk && parsed.signPk && parsed.kemPk) {
2064
+ return parsed;
2065
+ }
2066
+ localStorage.removeItem(DEVICE_KEY);
2067
+ }
2068
+ const sign = await crypto.subtle.generateKey({ name: "Ed25519" }, true, [
2069
+ "sign",
2070
+ "verify"
2071
+ ]);
2072
+ let agree;
2073
+ try {
2074
+ agree = await crypto.subtle.generateKey({ name: "X25519" }, true, [
2075
+ "deriveBits"
2076
+ ]);
2077
+ } catch {
2078
+ throw new Error(
2079
+ "this browser cannot generate an X25519 key, so it cannot receive wrapped scope keys. Chrome 133+ and Safari 17+ support it; enrolling without one would certify a delivery key nothing holds the secret for."
2080
+ );
2081
+ }
2082
+ const keys = {
2083
+ signPk: hex(await crypto.subtle.exportKey("raw", sign.publicKey)),
2084
+ signSk: hex((await crypto.subtle.exportKey("pkcs8", sign.privateKey)).slice(16)),
2085
+ kemPk: hex(await crypto.subtle.exportKey("raw", agree.publicKey)),
2086
+ kemSk: hex((await crypto.subtle.exportKey("pkcs8", agree.privateKey)).slice(16))
2087
+ };
2088
+ localStorage.setItem(DEVICE_KEY, JSON.stringify(keys));
2089
+ return keys;
2090
+ }
2091
+ function ConnectButtonAccount({
2092
+ className,
2093
+ style,
2094
+ theme,
2095
+ defaults = {}
2096
+ }) {
2097
+ const { isAuthenticated, isOnline, nodeUrl, isDelegated, connectToNode, connectWithAccount, logout, cloudBaseUrl } = useMero();
2098
+ const [isDropdownOpen, setIsDropdownOpen] = useState(false);
2099
+ const [isNodeModalOpen, setIsNodeModalOpen] = useState(false);
2100
+ const [isAccountOpen, setIsAccountOpen] = useState(false);
2101
+ const [note, setNote] = useState(null);
2102
+ const dropdownRef = useRef(null);
2103
+ const walletUrl = defaults.walletUrl ?? HOSTED_WALLET;
2104
+ const resolvedTheme = useMemo(() => theme ? resolveMeroTheme(theme) : null, [theme]);
2105
+ const themeVars = useMemo(
2106
+ () => resolvedTheme ? themeToCssVars(resolvedTheme) : void 0,
2107
+ [resolvedTheme]
2108
+ );
2109
+ useEffect(() => {
2110
+ const onOutside = (e) => {
2111
+ if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
2112
+ setIsDropdownOpen(false);
2113
+ }
2114
+ };
2115
+ document.addEventListener("mousedown", onOutside);
2116
+ return () => document.removeEventListener("mousedown", onOutside);
2117
+ }, []);
2118
+ const callbackRef = useRef(void 0);
2119
+ const callbackErrorRef = useRef(null);
2120
+ if (callbackRef.current === void 0 && typeof window !== "undefined") {
2121
+ try {
2122
+ callbackRef.current = readEnrolmentCallback();
2123
+ } catch (e) {
2124
+ callbackRef.current = null;
2125
+ callbackErrorRef.current = e instanceof Error ? e.message : String(e);
2126
+ }
2127
+ }
2128
+ const completingRef = useRef(false);
2129
+ useEffect(() => {
2130
+ if (callbackErrorRef.current) {
2131
+ setNote(callbackErrorRef.current);
2132
+ callbackErrorRef.current = null;
2133
+ return;
2134
+ }
2135
+ const back = callbackRef.current;
2136
+ if (!back || completingRef.current) return;
2137
+ completingRef.current = true;
2138
+ let cancelled = false;
2139
+ (async () => {
2140
+ try {
2141
+ const keys = await deviceKeys();
2142
+ const sent = (() => {
2143
+ try {
2144
+ return sessionStorage.getItem(STATE_KEY);
2145
+ } catch {
2146
+ return null;
2147
+ }
2148
+ })();
2149
+ try {
2150
+ sessionStorage.removeItem(STATE_KEY);
2151
+ } catch {
2152
+ }
2153
+ if (!sent) {
2154
+ setNote(
2155
+ 'This enrolment could not be verified as one this tab started, so it was not accepted. Start again from "Enrol with your account".'
2156
+ );
2157
+ return;
2158
+ }
2159
+ const enrolled = await completeDeviceEnrolment({
2160
+ ...back,
2161
+ devicePublicKey: keys.signPk,
2162
+ kemPublicKey: keys.kemPk,
2163
+ expectState: sent
2164
+ });
2165
+ saveDelegatedCredential({
2166
+ account: enrolled.account,
2167
+ credential: enrolled.credential,
2168
+ deviceSecret: keys.signSk
2169
+ });
2170
+ const cloud = new CloudClient({
2171
+ cloudBaseUrl,
2172
+ routingCredential: {
2173
+ credential: enrolled.credential,
2174
+ deviceSecret: keys.signSk
2175
+ }
2176
+ });
2177
+ const chosen = chooseRelay(await cloud.getAccountRelays(enrolled.account));
2178
+ if (chosen.note) setNote(chosen.note);
2179
+ connectWithAccount({
2180
+ relayUrl: chosen.relayUrl,
2181
+ account: enrolled.account,
2182
+ credential: enrolled.credential,
2183
+ deviceSecret: keys.signSk
2184
+ });
2185
+ } catch (e) {
2186
+ if (!cancelled) setNote(e instanceof Error ? e.message : String(e));
2187
+ }
2188
+ })();
2189
+ return () => {
2190
+ cancelled = true;
2191
+ };
2192
+ }, [connectWithAccount, cloudBaseUrl]);
2193
+ const goToWallet = useCallback(async () => {
2194
+ const keys = await deviceKeys();
2195
+ const state = hex(crypto.getRandomValues(new Uint8Array(16)));
2196
+ try {
2197
+ sessionStorage.setItem(STATE_KEY, state);
2198
+ } catch {
2199
+ }
2200
+ window.location.assign(
2201
+ deviceEnrolmentUrl({
2202
+ walletUrl,
2203
+ devicePublicKey: keys.signPk,
2204
+ kemPublicKey: keys.kemPk,
2205
+ returnTo: window.location.origin + window.location.pathname,
2206
+ state
2207
+ })
2208
+ );
2209
+ }, [walletUrl]);
2210
+ if (isAuthenticated && !isOnline) {
2211
+ return /* @__PURE__ */ jsx("div", { className: "mero-connect-container", style: { ...themeVars, display: "inline-block" }, children: /* @__PURE__ */ jsxs(
2212
+ "button",
2213
+ {
2214
+ className: ["mero-connect-button", "mero-reconnecting", className].filter(Boolean).join(" "),
2215
+ style,
2216
+ disabled: true,
2217
+ "aria-label": "Reconnecting...",
2218
+ children: [
2219
+ /* @__PURE__ */ jsx(CalimeroLogo, { size: 18, className: "mero-logo" }),
2220
+ "Reconnecting..."
2221
+ ]
2222
+ }
2223
+ ) });
2224
+ }
2225
+ if (isAuthenticated) {
2226
+ return /* @__PURE__ */ jsxs(
2227
+ "div",
2228
+ {
2229
+ ref: dropdownRef,
2230
+ className: "mero-connect-container",
2231
+ style: { ...themeVars, position: "relative", display: "inline-block" },
2232
+ children: [
2233
+ /* @__PURE__ */ jsxs(
2234
+ "button",
2235
+ {
2236
+ className: ["mero-connect-button", "mero-connected", className].filter(Boolean).join(" "),
2237
+ style,
2238
+ onClick: () => setIsDropdownOpen((p) => !p),
2239
+ "aria-label": "Connected",
2240
+ children: [
2241
+ /* @__PURE__ */ jsx(CalimeroLogo, { size: 18, className: "mero-logo" }),
2242
+ isDelegated ? "Connected (account)" : "Connected"
2243
+ ]
2244
+ }
2245
+ ),
2246
+ isDropdownOpen && /* @__PURE__ */ jsxs("div", { className: "mero-dropdown", children: [
2247
+ /* @__PURE__ */ jsx("div", { className: "mero-dropdown-info", title: nodeUrl || "", children: nodeUrl ?? (isDelegated ? "no relay yet" : null) }),
2248
+ !isDelegated && nodeUrl && /* @__PURE__ */ jsx(
2249
+ "a",
2250
+ {
2251
+ href: new URL("admin-dashboard/", nodeUrl).toString(),
2252
+ target: "_blank",
2253
+ rel: "noopener noreferrer",
2254
+ className: "mero-dropdown-item",
2255
+ children: "Dashboard"
2256
+ }
2257
+ ),
2258
+ /* @__PURE__ */ jsx(
2259
+ "button",
2260
+ {
2261
+ className: "mero-dropdown-item",
2262
+ onClick: () => {
2263
+ setIsDropdownOpen(false);
2264
+ logout();
2265
+ },
2266
+ children: "Log out"
2267
+ }
2268
+ )
2269
+ ] })
2270
+ ]
2271
+ }
2272
+ );
2273
+ }
2274
+ return /* @__PURE__ */ jsxs("div", { className: "mero-connect-container", style: { ...themeVars, display: "inline-block" }, children: [
2275
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: 8, flexWrap: "wrap" }, children: [
2276
+ /* @__PURE__ */ jsxs(
2277
+ "button",
2278
+ {
2279
+ className: ["mero-connect-button", className].filter(Boolean).join(" "),
2280
+ style,
2281
+ onClick: () => setIsNodeModalOpen(true),
2282
+ children: [
2283
+ /* @__PURE__ */ jsx(CalimeroLogo, { size: 18, className: "mero-logo" }),
2284
+ "I run a node"
2285
+ ]
2286
+ }
2287
+ ),
2288
+ /* @__PURE__ */ jsx(
2289
+ "button",
2290
+ {
2291
+ className: ["mero-connect-button", className].filter(Boolean).join(" "),
2292
+ style,
2293
+ onClick: () => setIsAccountOpen((p) => !p),
2294
+ children: "I have an account"
2295
+ }
2296
+ )
2297
+ ] }),
2298
+ isAccountOpen && /* @__PURE__ */ jsxs(
2299
+ "div",
2300
+ {
2301
+ style: {
2302
+ marginTop: 12,
2303
+ padding: 14,
2304
+ border: "1px solid rgba(127,127,127,.35)",
2305
+ borderRadius: 8,
2306
+ display: "grid",
2307
+ gap: 8,
2308
+ maxWidth: 520,
2309
+ textAlign: "left",
2310
+ font: "13px system-ui, sans-serif"
2311
+ },
2312
+ children: [
2313
+ /* @__PURE__ */ jsx("button", { className: "mero-connect-button", onClick: goToWallet, children: "Enrol with your account" }),
2314
+ /* @__PURE__ */ jsx("p", { style: { margin: 0, opacity: 0.75 }, children: "You will approve a device key on the wallet's own page, then come back here. The relay never sees your account root \u2014 only the certificate it signed." }),
2315
+ /* @__PURE__ */ jsx("p", { style: { margin: 0, opacity: 0.75 }, children: "That one certificate is all of it: finding the relay that serves your account, writing through it, reading your own contexts and namespaces, and live events. Nothing to paste in." }),
2316
+ defaults.walletUrl && /* Shown only when an app overrode it, so a local rig can see at a
2317
+ glance that it is not enrolling against the hosted wallet. */
2318
+ /* @__PURE__ */ jsxs("p", { style: { margin: 0, opacity: 0.6 }, children: [
2319
+ "Enrolling at ",
2320
+ /* @__PURE__ */ jsx("code", { children: walletUrl }),
2321
+ ", not the hosted wallet."
2322
+ ] })
2323
+ ]
2324
+ }
2325
+ ),
2326
+ note && /* @__PURE__ */ jsx("p", { style: { font: "13px system-ui, sans-serif", color: "#b3261e" }, children: note }),
2327
+ /* @__PURE__ */ jsx(
2328
+ LoginModal,
2329
+ {
2330
+ isOpen: isNodeModalOpen,
2331
+ onConnect: (url) => {
2332
+ setIsNodeModalOpen(false);
2333
+ connectToNode(url);
2334
+ },
2335
+ onClose: () => setIsNodeModalOpen(false),
2336
+ theme: resolvedTheme ?? theme
2337
+ }
2338
+ )
2339
+ ] });
2340
+ }
1290
2341
 
1291
2342
  // src/utils/base58.ts
1292
2343
  var ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
@@ -1308,8 +2359,6 @@ function base58ToHex(input) {
1308
2359
  for (let k = 0; k < input.length && input[k] === "1"; k++) bytes.push(0);
1309
2360
  return bytes.reverse().map((b) => b.toString(16).padStart(2, "0")).join("");
1310
2361
  }
1311
-
1312
- // src/hooks/index.ts
1313
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.";
1314
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.";
1315
2364
  var REPLAY_RECONCILE_MS = 50;
@@ -1605,7 +2654,7 @@ function extractAliasContextId(value) {
1605
2654
  return null;
1606
2655
  }
1607
2656
  function useExecute(contextId, executorId) {
1608
- const { mero } = useMero();
2657
+ const { mero, isDelegated } = useMero();
1609
2658
  const [loading, setLoading] = useState(false);
1610
2659
  const [error, setError] = useState(null);
1611
2660
  const mountedRef = useRef(true);
@@ -1618,7 +2667,13 @@ function useExecute(contextId, executorId) {
1618
2667
  const execute = useCallback(
1619
2668
  async (method, params) => {
1620
2669
  if (!mero || !contextId || !executorId) {
1621
- if (mountedRef.current) setError(new Error("Not connected"));
2670
+ if (mountedRef.current) {
2671
+ setError(
2672
+ new Error(
2673
+ !mero && isDelegated ? "No relay for this account yet, so there is nowhere to send this write. Redeeming an invitation admits the account to a namespace and gives it a relay; reads and events resume with it." : "Not connected"
2674
+ )
2675
+ );
2676
+ }
1622
2677
  return null;
1623
2678
  }
1624
2679
  if (mountedRef.current) {
@@ -1641,7 +2696,7 @@ function useExecute(contextId, executorId) {
1641
2696
  if (mountedRef.current) setLoading(false);
1642
2697
  }
1643
2698
  },
1644
- [mero, contextId, executorId]
2699
+ [mero, contextId, executorId, isDelegated]
1645
2700
  );
1646
2701
  return { execute, loading, error };
1647
2702
  }
@@ -1669,14 +2724,22 @@ function useSubscription(input, callback) {
1669
2724
  }, [mero, contextIdsKey, groupIdsKey]);
1670
2725
  }
1671
2726
  function useContexts(applicationId) {
1672
- const { mero } = useMero();
2727
+ const { mero, isDelegated } = useMero();
1673
2728
  const { data, loading, error, refetch } = useAsyncResource(
1674
2729
  mero ? async () => {
2730
+ if (isDelegated) {
2731
+ const session = readDelegatedSession();
2732
+ const listed = session ? await listDelegatedContexts(session) : [];
2733
+ const own = listed.filter(
2734
+ (c) => !applicationId || c.applicationId === applicationId
2735
+ );
2736
+ return mapApplicationContexts(own);
2737
+ }
1675
2738
  const response = applicationId ? await mero.admin.getContextsForApplication(applicationId) : await mero.admin.getContexts();
1676
2739
  return mapApplicationContexts(response.contexts ?? []);
1677
2740
  } : null,
1678
2741
  [],
1679
- [mero, applicationId]
2742
+ [mero, applicationId, isDelegated]
1680
2743
  );
1681
2744
  return { contexts: data, loading, error, refetch };
1682
2745
  }
@@ -1908,17 +2971,58 @@ function useContextDiscovery(options) {
1908
2971
  return { context, loading, error, discover, reset };
1909
2972
  }
1910
2973
  function useCreateContext() {
1911
- const { mero } = useMero();
2974
+ const { mero, isDelegated } = useMero();
1912
2975
  const { loading, error, run } = useAsyncMutation();
1913
2976
  const createContext2 = useCallback(
1914
2977
  async (request) => {
2978
+ if (isDelegated) {
2979
+ const session = readDelegatedSession();
2980
+ if (!session || !request.groupId) return null;
2981
+ return run(
2982
+ () => createDelegatedContext(session, {
2983
+ namespaceId: request.groupId,
2984
+ applicationId: request.applicationId,
2985
+ initializationParams: request.initializationParams
2986
+ })
2987
+ );
2988
+ }
1915
2989
  if (!mero) return null;
1916
2990
  return run(() => mero.admin.createContext(request));
1917
2991
  },
1918
- [mero, run]
2992
+ [mero, run, isDelegated]
1919
2993
  );
1920
2994
  return { createContext: createContext2, loading, error };
1921
2995
  }
2996
+ function useCreatePrivateContext() {
2997
+ const { mero, isDelegated } = useMero();
2998
+ const { loading, error, run } = useAsyncMutation();
2999
+ const createPrivateContext = useCallback(
3000
+ async (request) => {
3001
+ if (isDelegated) {
3002
+ const session = readDelegatedSession();
3003
+ if (!session) return null;
3004
+ return run(() => createDelegatedPrivateContext(session, request));
3005
+ }
3006
+ if (!mero) return null;
3007
+ return run(async () => {
3008
+ const { groupId } = await mero.admin.createGroupInNamespace(request.namespaceId, {
3009
+ visibility: "restricted"
3010
+ });
3011
+ await mero.admin.addGroupMembers(groupId, {
3012
+ members: request.members.map((identity) => ({ identity, role: "Member" }))
3013
+ });
3014
+ const { contextId } = await mero.admin.createContext({
3015
+ applicationId: request.applicationId,
3016
+ groupId,
3017
+ initializationParams: request.initializationParams
3018
+ });
3019
+ return { contextId };
3020
+ });
3021
+ },
3022
+ [mero, run, isDelegated]
3023
+ );
3024
+ return { createPrivateContext, loading, error };
3025
+ }
1922
3026
  function useDeleteContext() {
1923
3027
  const { mero } = useMero();
1924
3028
  const { loading, error, run } = useAsyncMutation();
@@ -1944,14 +3048,23 @@ function useJoinContext(options = {}) {
1944
3048
  return { joinContext, loading, error, failure };
1945
3049
  }
1946
3050
  function useJoinSubgroupInheritance() {
1947
- const { mero } = useMero();
3051
+ const { mero, isDelegated } = useMero();
1948
3052
  const { loading, error, run } = useAsyncMutation();
1949
3053
  const joinSubgroupInheritance = useCallback(
1950
3054
  async (groupId) => {
3055
+ if (isDelegated) {
3056
+ const session = readDelegatedSession();
3057
+ if (!session) return null;
3058
+ return run(async () => {
3059
+ await governRoot(session, groupId, memberJoinedOpenOp({ member: session.account, groupId, credential: session.credential }));
3060
+ const { publicKey } = await signerFromSecret(session.deviceSecret);
3061
+ return { groupId, memberPublicKey: publicKey, wasInherited: false };
3062
+ });
3063
+ }
1951
3064
  if (!mero) return null;
1952
3065
  return run(() => mero.admin.joinSubgroupInheritance(groupId));
1953
3066
  },
1954
- [mero, run]
3067
+ [mero, run, isDelegated]
1955
3068
  );
1956
3069
  return { joinSubgroupInheritance, loading, error };
1957
3070
  }
@@ -1974,14 +3087,19 @@ function useGroupInfo(groupId) {
1974
3087
  return { groupInfo: data, loading, error, refetch };
1975
3088
  }
1976
3089
  function useDeleteGroup() {
1977
- const { mero } = useMero();
3090
+ const { mero, isDelegated } = useMero();
1978
3091
  const { loading, error, run } = useAsyncMutation();
1979
3092
  const deleteGroup = useCallback(
1980
3093
  async (groupId) => {
3094
+ if (isDelegated) {
3095
+ const session = readDelegatedSession();
3096
+ if (!session) return null;
3097
+ return run(() => governRoot(session, groupId, groupDeletedOp(groupId)));
3098
+ }
1981
3099
  if (!mero) return null;
1982
3100
  return run(() => mero.admin.deleteGroup(groupId));
1983
3101
  },
1984
- [mero, run]
3102
+ [mero, run, isDelegated]
1985
3103
  );
1986
3104
  return { deleteGroup, loading, error };
1987
3105
  }
@@ -1998,26 +3116,42 @@ function useSyncGroup() {
1998
3116
  return { syncGroup, loading, error };
1999
3117
  }
2000
3118
  function useAddGroupMembers() {
2001
- const { mero } = useMero();
3119
+ const { mero, isDelegated } = useMero();
2002
3120
  const { loading, error, run } = useAsyncMutation();
2003
3121
  const addGroupMembers = useCallback(
2004
3122
  async (groupId, request) => {
3123
+ if (isDelegated) {
3124
+ const session = readDelegatedSession();
3125
+ if (!session) return null;
3126
+ return run(async () => {
3127
+ for (const m of request.members) {
3128
+ await governGroup(session, groupId, memberAddedOp(m.identity, m.role));
3129
+ }
3130
+ });
3131
+ }
2005
3132
  if (!mero) return null;
2006
3133
  return run(() => mero.admin.addGroupMembers(groupId, request));
2007
3134
  },
2008
- [mero, run]
3135
+ [mero, run, isDelegated]
2009
3136
  );
2010
3137
  return { addGroupMembers, loading, error };
2011
3138
  }
2012
3139
  function useRemoveGroupMembers() {
2013
- const { mero } = useMero();
3140
+ const { mero, isDelegated } = useMero();
2014
3141
  const { loading, error, run } = useAsyncMutation();
2015
3142
  const removeGroupMembers = useCallback(
2016
3143
  async (groupId, request) => {
3144
+ if (isDelegated) {
3145
+ const session = readDelegatedSession();
3146
+ if (!session) return null;
3147
+ return run(async () => {
3148
+ for (const member of request.members) await governGroup(session, groupId, memberRemovedOp(member));
3149
+ });
3150
+ }
2017
3151
  if (!mero) return null;
2018
3152
  return run(() => mero.admin.removeGroupMembers(groupId, request));
2019
3153
  },
2020
- [mero, run]
3154
+ [mero, run, isDelegated]
2021
3155
  );
2022
3156
  return { removeGroupMembers, loading, error };
2023
3157
  }
@@ -2058,23 +3192,43 @@ function useNamespaceIdentity(namespaceId) {
2058
3192
  return { identity: data, loading, error, refetch };
2059
3193
  }
2060
3194
  function useNamespacesForApplication(applicationId) {
2061
- const { mero } = useMero();
3195
+ const { mero, isDelegated } = useMero();
2062
3196
  const { data, loading, error, refetch } = useAsyncResource(
2063
- mero && applicationId ? () => mero.admin.listNamespacesForApplication(applicationId) : null,
3197
+ mero && applicationId ? isDelegated ? async () => {
3198
+ const session = readDelegatedSession();
3199
+ const listed = session ? await listDelegatedNamespaces(session) : [];
3200
+ return listed.filter((ns) => ns.targetApplicationId === applicationId);
3201
+ } : () => mero.admin.listNamespacesForApplication(applicationId) : null,
2064
3202
  [],
2065
- [mero, applicationId]
3203
+ [mero, applicationId, isDelegated]
2066
3204
  );
2067
3205
  return { namespaces: data, loading, error, refetch };
2068
3206
  }
3207
+ var DEFAULT_REGISTRY_URL = "https://apps.calimero.network";
2069
3208
  function useCreateNamespace() {
2070
- const { mero } = useMero();
3209
+ const { mero, isDelegated, app } = useMero();
2071
3210
  const { loading, error, run } = useAsyncMutation();
2072
3211
  const createNamespace = useCallback(
2073
3212
  async (request) => {
3213
+ if (isDelegated) {
3214
+ const session = readDelegatedSession();
3215
+ if (!session) return null;
3216
+ const pkg = app.packageName;
3217
+ return run(async () => {
3218
+ if (!pkg) {
3219
+ throw new Error("this app names no registry package, so a founded namespace could not be given its application");
3220
+ }
3221
+ const version = app.packageVersion ?? await latestPublishedVersion(app.registryUrl ?? DEFAULT_REGISTRY_URL, pkg);
3222
+ return foundDelegatedNamespace(session, {
3223
+ defaultCapabilities: 231,
3224
+ application: { applicationId: request.applicationId, package: pkg, version }
3225
+ });
3226
+ });
3227
+ }
2074
3228
  if (!mero) return null;
2075
3229
  return run(() => mero.admin.createNamespace(request));
2076
3230
  },
2077
- [mero, run]
3231
+ [mero, run, isDelegated, app]
2078
3232
  );
2079
3233
  return { createNamespace, loading, error };
2080
3234
  }
@@ -2139,14 +3293,32 @@ function useRedeemInvitation() {
2139
3293
  return { redeem, outcome, loading };
2140
3294
  }
2141
3295
  function useCreateGroupInNamespace() {
2142
- const { mero } = useMero();
3296
+ const { mero, isDelegated } = useMero();
2143
3297
  const { loading, error, run } = useAsyncMutation();
2144
3298
  const createGroupInNamespace = useCallback(
2145
3299
  async (namespaceId, request) => {
3300
+ if (isDelegated) {
3301
+ const session = readDelegatedSession();
3302
+ if (!session) return null;
3303
+ return run(async () => {
3304
+ const { groupId } = await governRoot(
3305
+ session,
3306
+ namespaceId,
3307
+ // The id is derived from a fresh salt (core#4244); a node refuses any other.
3308
+ (await subgroupCreation({
3309
+ parentId: namespaceId,
3310
+ restricted: request?.visibility !== "open",
3311
+ admin: session.account
3312
+ })).op
3313
+ );
3314
+ rememberGroupNamespace(session.account, groupId, namespaceId);
3315
+ return { groupId };
3316
+ });
3317
+ }
2146
3318
  if (!mero) return null;
2147
3319
  return run(() => mero.admin.createGroupInNamespace(namespaceId, request));
2148
3320
  },
2149
- [mero, run]
3321
+ [mero, run, isDelegated]
2150
3322
  );
2151
3323
  return { createGroupInNamespace, loading, error };
2152
3324
  }
@@ -2160,38 +3332,55 @@ function useNamespaceGroups(namespaceId) {
2160
3332
  return { groups: data, loading, error, refetch };
2161
3333
  }
2162
3334
  function useUpdateMemberRole() {
2163
- const { mero } = useMero();
3335
+ const { mero, isDelegated } = useMero();
2164
3336
  const { loading, error, run } = useAsyncMutation();
2165
3337
  const updateMemberRole = useCallback(
2166
3338
  async (groupId, identity, request) => {
3339
+ if (isDelegated) {
3340
+ const session = readDelegatedSession();
3341
+ if (!session) return null;
3342
+ return run(() => governGroup(session, groupId, memberRoleSetOp(identity, request.role)));
3343
+ }
2167
3344
  if (!mero) return null;
2168
3345
  return run(() => mero.admin.updateMemberRole(groupId, identity, request));
2169
3346
  },
2170
- [mero, run]
3347
+ [mero, run, isDelegated]
2171
3348
  );
2172
3349
  return { updateMemberRole, loading, error };
2173
3350
  }
2174
3351
  function useSetDefaultCapabilities() {
2175
- const { mero } = useMero();
3352
+ const { mero, isDelegated } = useMero();
2176
3353
  const { loading, error, run } = useAsyncMutation();
2177
3354
  const setDefaultCapabilities = useCallback(
2178
3355
  async (groupId, request) => {
3356
+ if (isDelegated) {
3357
+ const session = readDelegatedSession();
3358
+ if (!session) return null;
3359
+ return run(() => governGroup(session, groupId, defaultCapabilitiesSetOp(request.defaultCapabilities)));
3360
+ }
2179
3361
  if (!mero) return null;
2180
3362
  return run(() => mero.admin.setDefaultCapabilities(groupId, request));
2181
3363
  },
2182
- [mero, run]
3364
+ [mero, run, isDelegated]
2183
3365
  );
2184
3366
  return { setDefaultCapabilities, loading, error };
2185
3367
  }
2186
3368
  function useSetSubgroupVisibility() {
2187
- const { mero } = useMero();
3369
+ const { mero, isDelegated } = useMero();
2188
3370
  const { loading, error, run } = useAsyncMutation();
2189
3371
  const setSubgroupVisibility = useCallback(
2190
3372
  async (groupId, request) => {
3373
+ if (isDelegated) {
3374
+ const session = readDelegatedSession();
3375
+ if (!session) return null;
3376
+ return run(
3377
+ () => governGroup(session, groupId, subgroupVisibilitySetOp(request.subgroupVisibility === "open" ? "open" : "restricted"))
3378
+ );
3379
+ }
2191
3380
  if (!mero) return null;
2192
3381
  return run(() => mero.admin.setSubgroupVisibility(groupId, request));
2193
3382
  },
2194
- [mero, run]
3383
+ [mero, run, isDelegated]
2195
3384
  );
2196
3385
  return { setSubgroupVisibility, loading, error };
2197
3386
  }
@@ -2226,38 +3415,53 @@ function useSetTeeAdmissionPolicy() {
2226
3415
  return { setTeeAdmissionPolicy, loading, error };
2227
3416
  }
2228
3417
  function useSetGroupMetadata() {
2229
- const { mero } = useMero();
3418
+ const { mero, isDelegated } = useMero();
2230
3419
  const { loading, error, run } = useAsyncMutation();
2231
3420
  const setGroupMetadata = useCallback(
2232
3421
  async (groupId, request) => {
3422
+ if (isDelegated) {
3423
+ const session = readDelegatedSession();
3424
+ if (!session) return null;
3425
+ return run(() => governGroup(session, groupId, groupMetadataSetOp(request)));
3426
+ }
2233
3427
  if (!mero) return null;
2234
3428
  return run(() => mero.admin.setGroupMetadata(groupId, request));
2235
3429
  },
2236
- [mero, run]
3430
+ [mero, run, isDelegated]
2237
3431
  );
2238
3432
  return { setGroupMetadata, loading, error };
2239
3433
  }
2240
3434
  function useSetMemberMetadata() {
2241
- const { mero } = useMero();
3435
+ const { mero, isDelegated } = useMero();
2242
3436
  const { loading, error, run } = useAsyncMutation();
2243
3437
  const setMemberMetadata = useCallback(
2244
3438
  async (groupId, identity, request) => {
3439
+ if (isDelegated) {
3440
+ const session = readDelegatedSession();
3441
+ if (!session) return null;
3442
+ return run(() => governGroup(session, groupId, memberMetadataSetOp(identity, request)));
3443
+ }
2245
3444
  if (!mero) return null;
2246
3445
  return run(() => mero.admin.setMemberMetadata(groupId, identity, request));
2247
3446
  },
2248
- [mero, run]
3447
+ [mero, run, isDelegated]
2249
3448
  );
2250
3449
  return { setMemberMetadata, loading, error };
2251
3450
  }
2252
3451
  function useSetContextMetadata() {
2253
- const { mero } = useMero();
3452
+ const { mero, isDelegated } = useMero();
2254
3453
  const { loading, error, run } = useAsyncMutation();
2255
3454
  const setContextMetadata = useCallback(
2256
3455
  async (groupId, contextId, request) => {
3456
+ if (isDelegated) {
3457
+ const session = readDelegatedSession();
3458
+ if (!session) return null;
3459
+ return run(() => governGroup(session, groupId, contextMetadataSetOp(contextId, request)));
3460
+ }
2257
3461
  if (!mero) return null;
2258
3462
  return run(() => mero.admin.setContextMetadata(groupId, contextId, request));
2259
3463
  },
2260
- [mero, run]
3464
+ [mero, run, isDelegated]
2261
3465
  );
2262
3466
  return { setContextMetadata, loading, error };
2263
3467
  }
@@ -2416,14 +3620,22 @@ function useRetryGroupUpgrade() {
2416
3620
  return { retryGroupUpgrade, loading, error };
2417
3621
  }
2418
3622
  function useReparentGroup() {
2419
- const { mero } = useMero();
3623
+ const { mero, isDelegated } = useMero();
2420
3624
  const { loading, error, run } = useAsyncMutation();
2421
3625
  const reparentGroup = useCallback(
2422
3626
  async (childGroupId, request) => {
3627
+ if (isDelegated) {
3628
+ const session = readDelegatedSession();
3629
+ if (!session) return null;
3630
+ return run(async () => {
3631
+ await governRoot(session, childGroupId, groupReparentedOp(childGroupId, request.newParentId));
3632
+ return { reparented: true };
3633
+ });
3634
+ }
2423
3635
  if (!mero) return null;
2424
3636
  return run(() => mero.admin.reparentGroup(childGroupId, request));
2425
3637
  },
2426
- [mero, run]
3638
+ [mero, run, isDelegated]
2427
3639
  );
2428
3640
  return { reparentGroup, loading, error };
2429
3641
  }
@@ -2437,14 +3649,19 @@ function useSubgroups(groupId) {
2437
3649
  return { subgroups: data, loading, error, refetch };
2438
3650
  }
2439
3651
  function useDetachContextFromGroup() {
2440
- const { mero } = useMero();
3652
+ const { mero, isDelegated } = useMero();
2441
3653
  const { loading, error, run } = useAsyncMutation();
2442
3654
  const detachContextFromGroup = useCallback(
2443
3655
  async (groupId, contextId) => {
3656
+ if (isDelegated) {
3657
+ const session = readDelegatedSession();
3658
+ if (!session) return null;
3659
+ return run(() => governGroup(session, groupId, contextDetachedOp(contextId)));
3660
+ }
2444
3661
  if (!mero) return null;
2445
3662
  return run(() => mero.admin.detachContextFromGroup(groupId, contextId));
2446
3663
  },
2447
- [mero, run]
3664
+ [mero, run, isDelegated]
2448
3665
  );
2449
3666
  return { detachContextFromGroup, loading, error };
2450
3667
  }
@@ -2956,7 +4173,365 @@ function MigrationAdminPanel({ namespaceId, pollIntervalMs, className }) {
2956
4173
  ] })
2957
4174
  ] });
2958
4175
  }
4176
+ function normaliseAccount(account) {
4177
+ if (!account) return null;
4178
+ const trimmed = account.trim().toLowerCase();
4179
+ const bare = trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
4180
+ return bare.length > 0 ? bare : null;
4181
+ }
4182
+ function isInvited(node, invited) {
4183
+ if (invited.size === 0) return true;
4184
+ const account = normaliseAccount(node.account);
4185
+ return account !== null && invited.has(account);
4186
+ }
4187
+ async function resolveRelayFromInvitation(input) {
4188
+ const cloud = input.cloud ?? new CloudClient({
4189
+ cloudBaseUrl: input.cloudBaseUrl,
4190
+ routingCredential: { credential: input.credential, deviceSecret: input.deviceSecret }
4191
+ });
4192
+ let nodes;
4193
+ let servable;
4194
+ try {
4195
+ const routing = await cloud.getNamespaceRouting(input.namespaceId);
4196
+ nodes = routing.nodes;
4197
+ servable = routing.servable;
4198
+ } catch (e) {
4199
+ return {
4200
+ ok: false,
4201
+ step: "admitters-lookup",
4202
+ reason: `The cloud could not be asked which nodes serve namespace ${input.namespaceId}: ${e instanceof Error ? e.message : String(e)}. Nothing is known about the invitation yet \u2014 this is the lookup failing, not the invitation.`
4203
+ };
4204
+ }
4205
+ if (nodes.length === 0) {
4206
+ return {
4207
+ ok: false,
4208
+ step: "no-nodes",
4209
+ reason: "The cloud lists no nodes serving this namespace, so there is no hosted node to be admitted through. The namespace has no fleet assignment \u2014 whoever invited you is running their own node, and admission has to go through a node the cloud routes to."
4210
+ };
4211
+ }
4212
+ const invited = new Set(
4213
+ (input.admitters ?? []).map(normaliseAccount).filter((a) => a !== null)
4214
+ );
4215
+ const named = nodes.filter((n) => isInvited(n, invited));
4216
+ if (named.length === 0) {
4217
+ return {
4218
+ ok: false,
4219
+ step: "not-invited",
4220
+ reason: `${nodes.length} node${nodes.length === 1 ? "" : "s"} serve this namespace, but your invitation names none of them. The signed admitter list is a snapshot from when the invitation was minted, so a node assigned since is healthy and will still refuse the claim. Ask for a fresh invitation.`
4221
+ };
4222
+ }
4223
+ const usable = named.filter((n) => n.canAdmit);
4224
+ const candidates = usable.length > 0 ? usable : named;
4225
+ const advisory = usable.length === 0 || !servable;
4226
+ const addressable = candidates.filter(
4227
+ (n) => typeof n.relayUrl === "string" && n.relayUrl.length > 0
4228
+ );
4229
+ if (addressable.length === 0) {
4230
+ return {
4231
+ ok: false,
4232
+ step: "no-relay-url",
4233
+ reason: "A node your invitation names can admit you, but the cloud knows no address for it yet, so there would be nothing to connect through afterwards. Try again shortly."
4234
+ };
4235
+ }
4236
+ const chosen = addressable.find((n) => n.canExecute) ?? addressable.find((n) => n.fresh) ?? addressable[0];
4237
+ return {
4238
+ ok: true,
4239
+ relayUrl: chosen.relayUrl,
4240
+ // The cloud's ready-made URL when it gave one, so the path is never rebuilt
4241
+ // from a guess; the fallback is the documented route on the same origin.
4242
+ admitUrl: chosen.admitUrl ?? `${chosen.relayUrl.replace(/\/+$/, "")}/admin-api/namespaces/${input.namespaceId}/admit`,
4243
+ admitterAccount: chosen.account,
4244
+ peerId: chosen.peerId,
4245
+ writable: chosen.canExecute,
4246
+ // Stale when the node's own heartbeat lapsed OR when the cloud's summary
4247
+ // disagrees with trying it at all. Both mean the same thing to a caller:
4248
+ // this was attempted on advisory data, so if the admit fails that is why.
4249
+ stale: !chosen.fresh || advisory
4250
+ };
4251
+ }
4252
+ function explainAdmitFailure(status, body) {
4253
+ const detail = body ? `: ${body}` : "";
4254
+ switch (status) {
4255
+ case 400:
4256
+ return `The node refused the join as malformed (400)${detail}. The signature covers the invitation exactly as sent, so an edited or re-serialised invitation fails here \u2014 as does a namespace id that is not the invitation's own group.`;
4257
+ case 403:
4258
+ return `The node refused to carry this join (403)${detail}. Either it is not in the invitation's signed admitters list \u2014 being live and listed by the cloud is not the same thing \u2014 or the invitation itself was rejected as expired or not the inviter\u2019s to issue.`;
4259
+ case 409:
4260
+ return `That node holds no device of its own, so it cannot endorse anyone (409)${detail}. Another admitter from the same invitation would work.`;
4261
+ default:
4262
+ return `The join was not published (HTTP ${status})${detail}.`;
4263
+ }
4264
+ }
4265
+ function joinNonce(account) {
4266
+ const source = createLocalStorageNonceSource(`calimero.delegated.joinnonce.${account}`);
4267
+ return () => source.next();
4268
+ }
4269
+ function origin(url) {
4270
+ return url.replace(/\/+$/, "");
4271
+ }
4272
+ async function joinWithNode(input) {
4273
+ const { account, credential, deviceSecret } = input.credential;
4274
+ let signedOp;
4275
+ try {
4276
+ signedOp = await signMemberJoinOp({
4277
+ namespaceId: input.namespaceId,
4278
+ member: account,
4279
+ invitation: input.invitation,
4280
+ credential,
4281
+ deviceSecret,
4282
+ nonce: await (input.deps?.nonce ?? joinNonce(account))()
4283
+ });
4284
+ } catch (e) {
4285
+ return {
4286
+ ok: false,
4287
+ step: "sign",
4288
+ reason: `The join op could not be signed, so nothing was sent: ${e instanceof Error ? e.message : String(e)}`
4289
+ };
4290
+ }
4291
+ const body = { invitation: input.invitation, signedOp };
4292
+ const url = input.admitUrl ?? `${origin(input.nodeUrl)}/admin-api/namespaces/${input.namespaceId}/admit`;
4293
+ const doFetch = input.deps?.fetch ?? fetch;
4294
+ let response;
4295
+ try {
4296
+ response = await doFetch(url, {
4297
+ method: "POST",
4298
+ // No Authorization header and no request proof, deliberately: the route is
4299
+ // unauthenticated because the joiner's signature is the authorization.
4300
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
4301
+ body: JSON.stringify(body)
4302
+ });
4303
+ } catch (e) {
4304
+ return {
4305
+ ok: false,
4306
+ step: "admit",
4307
+ reason: `The admitter at ${input.nodeUrl} could not be reached: ${e instanceof Error ? e.message : String(e)}. The invitation is untouched \u2014 this is the node being unreachable, not a refusal.`
4308
+ };
4309
+ }
4310
+ const text = await response.text();
4311
+ if (!response.ok) {
4312
+ return {
4313
+ ok: false,
4314
+ step: "admit",
4315
+ status: response.status,
4316
+ reason: explainAdmitFailure(response.status, text)
4317
+ };
4318
+ }
4319
+ let published = false;
4320
+ try {
4321
+ const parsed = text ? JSON.parse(text) : {};
4322
+ published = parsed.data?.published === true;
4323
+ } catch {
4324
+ published = false;
4325
+ }
4326
+ return {
4327
+ ok: true,
4328
+ published,
4329
+ session: { relayUrl: origin(input.nodeUrl), account, credential, deviceSecret }
4330
+ };
4331
+ }
4332
+
4333
+ // src/delegated/bootstrap-from-invitation.ts
4334
+ async function bootstrapFromInvitation(input) {
4335
+ const resolve = input.deps?.resolve ?? resolveRelayFromInvitation;
4336
+ const join = input.deps?.join ?? joinWithNode;
4337
+ let relay = null;
4338
+ let nodeUrl = input.nodeUrl;
4339
+ let admitUrl;
4340
+ if (!nodeUrl) {
4341
+ const resolved = await resolve({
4342
+ namespaceId: input.namespaceId,
4343
+ // The signed list, read off the invitation itself rather than passed
4344
+ // separately: two sources for one fact is how an intersection ends up
4345
+ // being performed against the wrong list.
4346
+ admitters: input.invitation.invitation.admitters,
4347
+ credential: input.credential.credential,
4348
+ deviceSecret: input.credential.deviceSecret,
4349
+ cloudBaseUrl: input.cloudBaseUrl
4350
+ });
4351
+ if (!resolved.ok) return resolved;
4352
+ relay = resolved;
4353
+ nodeUrl = resolved.relayUrl;
4354
+ admitUrl = resolved.admitUrl;
4355
+ }
4356
+ const joined = await join({
4357
+ nodeUrl,
4358
+ admitUrl,
4359
+ namespaceId: input.namespaceId,
4360
+ invitation: input.invitation,
4361
+ credential: input.credential,
4362
+ deps: { fetch: input.deps?.fetch, nonce: input.deps?.nonce }
4363
+ });
4364
+ if (!joined.ok) return joined;
4365
+ return { ok: true, published: joined.published, relay, session: joined.session };
4366
+ }
4367
+ function useDelegatedBootstrap(options = {}) {
4368
+ const { connectWithAccount, cloudBaseUrl: providerCloud } = useMero();
4369
+ const [running, setRunning] = useState(false);
4370
+ const [result, setResult] = useState(null);
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
+ );
4377
+ const relayUrl = readDelegatedSession()?.relayUrl ?? null;
4378
+ const cloudBaseUrl = options.cloudBaseUrl ?? providerCloud;
4379
+ const bootstrap = useCallback(
4380
+ async (input) => {
4381
+ const held = readDelegatedCredential();
4382
+ if (!held) {
4383
+ const failure = {
4384
+ ok: false,
4385
+ step: "no-credential",
4386
+ reason: "This tab holds no enrolled account, so there is no identity to admit. Enrol with your account first \u2014 the invitation is then what gives it its first membership."
4387
+ };
4388
+ setResult(failure);
4389
+ return failure;
4390
+ }
4391
+ setRunning(true);
4392
+ try {
4393
+ const outcome = await bootstrapFromInvitation({
4394
+ namespaceId: input.namespaceId,
4395
+ invitation: input.invitation,
4396
+ credential: held,
4397
+ nodeUrl: input.nodeUrl,
4398
+ cloudBaseUrl
4399
+ });
4400
+ setResult(outcome);
4401
+ if (outcome.ok) {
4402
+ if (outcome.session.relayUrl) {
4403
+ rememberRelay(held.account, outcome.session.relayUrl, {
4404
+ namespaceId: input.namespaceId,
4405
+ contextId: input.contextId
4406
+ });
4407
+ }
4408
+ connectWithAccount(outcome.session);
4409
+ }
4410
+ return outcome;
4411
+ } finally {
4412
+ setRunning(false);
4413
+ }
4414
+ },
4415
+ [cloudBaseUrl, connectWithAccount]
4416
+ );
4417
+ return {
4418
+ credential,
4419
+ needsBootstrap: credential !== null && relayUrl === null,
4420
+ running,
4421
+ result,
4422
+ bootstrap
4423
+ };
4424
+ }
4425
+ function statusOf(err) {
4426
+ if (!err || typeof err !== "object") return void 0;
4427
+ const e = err;
4428
+ for (const c of [e.status, e.response?.status, e.statusCode]) {
4429
+ if (typeof c === "number" && Number.isFinite(c)) return c;
4430
+ }
4431
+ return void 0;
4432
+ }
4433
+ var STEP_LABEL = {
4434
+ "no-credential": "No enrolled account",
4435
+ "admitters-lookup": "Admitters lookup failed",
4436
+ "no-nodes": "No hosted node serves this namespace",
4437
+ "not-invited": "This invitation names none of the serving nodes",
4438
+ "invited-unreachable": "The invited admitter cannot take a join right now",
4439
+ "no-relay-url": "The invited admitter has no address yet",
4440
+ sign: "The join could not be signed",
4441
+ admit: "The admitter refused the join"
4442
+ };
4443
+ function accountJoinIsFinal(failure) {
4444
+ if (failure.step === "admit") return failure.status === 400 || failure.status === 403;
4445
+ return failure.step === "not-invited" || failure.step === "sign";
4446
+ }
4447
+ function isFinalInvitationError(message) {
4448
+ if (!message) return false;
4449
+ const m = message.toLowerCase();
4450
+ return [
4451
+ "invitation expired",
4452
+ "expired invitation",
4453
+ "invalid invitation",
4454
+ "invitation is invalid",
4455
+ "malformed invitation",
4456
+ "malformed payload",
4457
+ "invalid signature",
4458
+ "signature verification failed",
4459
+ "not admin",
4460
+ "revoked",
4461
+ "already a member"
4462
+ ].some((t) => m.includes(t));
4463
+ }
4464
+ function useJoinInvitation() {
4465
+ const { mero, isDelegated } = useMero();
4466
+ const { credential, bootstrap } = useDelegatedBootstrap();
4467
+ const [joining, setJoining] = useState(false);
4468
+ const joinInvitation = useCallback(
4469
+ async (input) => {
4470
+ setJoining(true);
4471
+ try {
4472
+ const asAccount = isDelegated || credential !== null && mero === null;
4473
+ if (asAccount) {
4474
+ const outcome = await bootstrap({
4475
+ namespaceId: input.namespaceId,
4476
+ invitation: input.invitation,
4477
+ contextId: input.contextId
4478
+ });
4479
+ if (outcome.ok) return { ok: true };
4480
+ return {
4481
+ ok: false,
4482
+ step: outcome.step,
4483
+ reason: `${STEP_LABEL[outcome.step]}. ${outcome.reason}`,
4484
+ final: accountJoinIsFinal(outcome),
4485
+ ...outcome.status !== void 0 ? { status: outcome.status } : {}
4486
+ };
4487
+ }
4488
+ if (!mero) {
4489
+ return { ok: false, step: "node-join", reason: "Not connected to a node.", final: false };
4490
+ }
4491
+ await mero.admin.joinNamespace(input.namespaceId, { invitation: input.invitation });
4492
+ if (input.contextId) await mero.admin.joinContext(input.contextId);
4493
+ return { ok: true };
4494
+ } catch (e) {
4495
+ const reason = e instanceof Error ? e.message : String(e);
4496
+ const status = statusOf(e);
4497
+ return {
4498
+ ok: false,
4499
+ step: "node-join",
4500
+ reason,
4501
+ final: isFinalInvitationError(reason),
4502
+ ...status !== void 0 ? { status } : {}
4503
+ };
4504
+ } finally {
4505
+ setJoining(false);
4506
+ }
4507
+ },
4508
+ [mero, isDelegated, credential, bootstrap]
4509
+ );
4510
+ const memberships = useCallback(async () => {
4511
+ const asAccount = isDelegated || credential !== null && mero === null;
4512
+ const ids = (list) => list.map((n) => n.namespaceId ?? n.groupId ?? n.id ?? "").filter(Boolean);
4513
+ if (asAccount) {
4514
+ const session = readDelegatedSession();
4515
+ return session ? ids(await listDelegatedNamespaces(session)) : [];
4516
+ }
4517
+ if (!mero) return [];
4518
+ return ids(await mero.admin.listNamespaces());
4519
+ }, [mero, isDelegated, credential]);
4520
+ const invitationRedeemer = useCallback(
4521
+ (input) => ({
4522
+ join: async () => {
4523
+ const outcome = await joinInvitation(input);
4524
+ if (!outcome.ok) {
4525
+ throw Object.assign(new Error(outcome.reason), outcome.status !== void 0 ? { status: outcome.status } : {});
4526
+ }
4527
+ },
4528
+ memberships
4529
+ }),
4530
+ [joinInvitation, memberships]
4531
+ );
4532
+ return { joinInvitation, joining, memberships, invitationRedeemer };
4533
+ }
2959
4534
 
2960
- export { AppMode, CalimeroLogo, ConnectButton, ConnectionType, DEFAULT_MIGRATION_POLL_INTERVAL_MS, LoginModal, MERO_CSS_VARS, MeroContext, MeroProvider, MigrationAdminPanel, MigrationPendingBanner, clearAllStorage, clearApplicationId, clearContextId, clearContextIdentity, clearNodeUrl, clearTokenNodeUrl, cssVar, defaultMeroTheme, getApplicationId, getContextId, getContextIdentity, getNodeUrl, getTokenNodeUrl, localStorageTokenStorage, resolveMeroTheme, setApplicationId, setContextId, setContextIdentity, setNodeUrl, setTokenNodeUrl, themeToCssVars, useAddGroupMembers, useAppVersion, useApplicationContexts, useBlobInfo, useBlobUrl, useContextDiscovery, useContextGroup, useContexts, useCreateContext, useCreateGroupInNamespace, useCreateNamespace, useCreateNamespaceInvitation, useDefaultCapabilities, useDeleteContext, useDeleteGroup, useDeleteNamespace, useDetachContextFromGroup, useEphemeral, useExecute, useGroupAppVersion, useGroupCapabilities, useGroupContexts, useGroupInfo, useGroupInvitations, useGroupMembers, useGroupMetadata, useGroupUpgradeStatus, useInstallFromRegistry, useJoinContext, useJoinGroup, 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 };
2961
4536
  //# sourceMappingURL=index.js.map
2962
4537
  //# sourceMappingURL=index.js.map