@calimero-network/mero-react 9.11.3 → 9.11.5

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,7 +1,7 @@
1
1
  import { createContext, useMemo, useState, useRef, useCallback, useEffect, useContext } from 'react';
2
- import { signGroupInvitation, signMemberJoinOp, CloudClient, LocalStorageTokenStore, parseAuthCallback, MeroJs, buildAuthLoginUrl, readEnrolmentCallback, completeDeviceEnrolment, deviceEnrolmentUrl, DEFAULT_LOCAL_NODE_PORTS, discoverLocalNodes, nodeEndpoint, memberJoinedOpenOp, signerFromSecret, compareSemver, AuthRevokedError, HTTPError, contextDetachedOp, memberRoleSetOp, memberLeftOp, groupReparentedOp, groupDeletedOp, memberCapabilitySetOp, subgroupVisibilitySetOp, defaultCapabilitiesSetOp, contextMetadataSetOp, memberMetadataSetOp, groupMetadataSetOp, memberRemovedOp, memberAddedOp, subgroupCreation, createMeroClient, RelayClient, createLocalStorageNonceSource, classifyError, attestRelayNodeKey, login, defaultAudience, AccountNotLinkedError, AccountHaRefusedError, createSignedReleaseVerifier, fetchNodeRelease, cloudNodeReleaseUrl, DEFAULT_RELEASE_MIRROR, fetchNodeReleaseVersion } from '@calimero-network/mero-js';
2
+ import { LocalStorageTokenStore, readDelegatedSession, parseAuthCallback, MeroJs, buildAuthLoginUrl, saveDelegatedSession, saveDelegatedCredential, clearDelegatedSession, clearDelegatedCredential, relayForContext, buildDelegatedClient, readPinnedRelayNodeKey, learnRelayNodeKey, resolveApplicationIdFromRegistry, listDelegatedContexts, createAccountAdmin, createNodeAdmin, readEnrolmentCallback, completeDeviceEnrolment, CloudClient, deviceEnrolmentUrl, DEFAULT_LOCAL_NODE_PORTS, discoverLocalNodes, nodeEndpoint, createDelegatedContext, createDelegatedPrivateContext, governRoot, memberJoinedOpenOp, signerFromSecret, compareSemver, readDelegatedCredential, bootstrapFromInvitation, rememberRelay, carryExecutorAccount, listDelegatedNamespaces, AuthRevokedError, HTTPError, foundDelegatedNamespace, joinAsAccount, classifyError } from '@calimero-network/mero-js';
3
3
  export * from '@calimero-network/mero-js';
4
- export { CAPABILITIES, DEFAULT_LOCAL_NODE_PORTS, discoverLocalNodes, hasCap, localNodeUrl, nodeEndpoint, probeNodeHealth, withCap, withoutCap } from '@calimero-network/mero-js';
4
+ export { CAPABILITIES, DEFAULT_LOCAL_NODE_PORTS, HA_ACCOUNT_NOT_LINKED_MESSAGE, HA_REFUSAL_MESSAGES, InvitationNotClaimableError, NoRelayError, NotForAccountError, applicationIdForBundle, bootstrapFromInvitation, clearDelegatedCredential, createAccountAdmin, createDelegatedContext, createNodeAdmin, discoverLocalNodes, hasCap, joinWithNode, listDelegatedContexts, localNodeUrl, nodeEndpoint, normaliseAccount, pinRelayNodeKey, probeNodeHealth, readDelegatedCredential, readPinnedRelayNodeKey, readRelayMap, relayForContext, rememberRelay, resolveApplicationIdFromRegistry, resolveRelayFromInvitation, saveDelegatedCredential, selectLatestBundle, withCap, withoutCap } from '@calimero-network/mero-js';
5
5
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
6
6
  import { createPortal } from 'react-dom';
7
7
 
@@ -44,1163 +44,6 @@ 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 dcapVerifyFrom(mod) {
166
- const ns = mod;
167
- const verify = typeof ns.verify === "function" ? ns.verify : ns.default?.verify;
168
- if (typeof verify !== "function") {
169
- throw new TypeError("@phala/dcap-qvl loaded without a verify function");
170
- }
171
- return verify;
172
- }
173
- var RelayKeyTransportError = class extends Error {
174
- constructor(step, cause) {
175
- super(`${step}: ${cause instanceof Error ? cause.message : String(cause)}`);
176
- this.step = step;
177
- this.cause = cause;
178
- this.name = "RelayKeyTransportError";
179
- }
180
- };
181
- async function transport(step, run) {
182
- try {
183
- return await run();
184
- } catch (e) {
185
- throw e instanceof RelayKeyTransportError ? e : new RelayKeyTransportError(step, e);
186
- }
187
- }
188
- function relayFetch(marked) {
189
- return async (input, init) => {
190
- let response;
191
- try {
192
- response = await globalThis.fetch(input, init);
193
- } catch (e) {
194
- marked.failure = e;
195
- throw new RelayKeyTransportError(`reaching ${String(input)}`, e);
196
- }
197
- if (!response.ok) marked.failure ?? (marked.failure = new Error(`${String(input)} answered HTTP ${response.status}`));
198
- return response;
199
- };
200
- }
201
- function relayQuoteVerifier(relayUrl, fetchRelay) {
202
- const verify = async (attestation) => {
203
- const dcapVerify = await transport("loading the quote verifier", () => {
204
- loadedDcap ?? (loadedDcap = import('@phala/dcap-qvl').then(
205
- (mod) => dcapVerifyFrom(mod),
206
- (error) => {
207
- loadedDcap = void 0;
208
- throw error;
209
- }
210
- ));
211
- return loadedDcap;
212
- });
213
- return createSignedReleaseVerifier({
214
- dcapVerify,
215
- // Fetched only. Its signature, its version and the quote's registers are
216
- // all checked by the verifier after this returns, and none of that is a
217
- // transport question.
218
- release: () => transport(
219
- "fetching the release the relay runs",
220
- async () => fetchNodeRelease(
221
- cloudNodeReleaseUrl(DEFAULT_RELEASE_MIRROR, await fetchNodeReleaseVersion(relayUrl, { fetch: fetchRelay }))
222
- )
223
- ),
224
- profile: TRUSTED_RELAY_PROFILE,
225
- minReleaseVersion: MIN_RELAY_RELEASE
226
- })(attestation);
227
- };
228
- return Object.assign(verify, { includeCollateral: true });
229
- }
230
- async function attemptRelayNodeKey(relayUrl) {
231
- const pinned = readPinnedRelayNodeKey(relayUrl);
232
- if (pinned) return { kind: "learned", nodeKey: pinned };
233
- const marked = { failure: null };
234
- const fetchRelay = relayFetch(marked);
235
- try {
236
- const local = isLoopback(relayUrl);
237
- const { nodeKey } = await attestRelayNodeKey({
238
- relayUrl,
239
- allowMock: local,
240
- fetch: fetchRelay,
241
- ...local ? {} : { verify: relayQuoteVerifier(relayUrl, fetchRelay) }
242
- });
243
- pinRelayNodeKey(relayUrl, nodeKey);
244
- return { kind: "learned", nodeKey };
245
- } catch (e) {
246
- if (e instanceof RelayKeyTransportError || marked.failure) return { kind: "unavailable", error: e };
247
- return { kind: "refused", error: e };
248
- }
249
- }
250
- async function resolveRelayNodeKey(relayUrl) {
251
- const attempt = await attemptRelayNodeKey(relayUrl);
252
- if (attempt.kind === "learned") return attempt.nodeKey;
253
- console.warn("[mero-react] could not learn the relay node key from its attestation", attempt.error);
254
- return null;
255
- }
256
- var RELAY_NODE_KEY_RETRY_MS = [1e3, 2e3, 5e3, 1e4, 3e4];
257
- function pause(ms, signal) {
258
- return new Promise((resolve) => {
259
- if (signal?.aborted) return resolve();
260
- const timer = setTimeout(done, ms);
261
- function done() {
262
- clearTimeout(timer);
263
- signal?.removeEventListener("abort", done);
264
- resolve();
265
- }
266
- signal?.addEventListener("abort", done);
267
- });
268
- }
269
- async function learnRelayNodeKey(relayUrl, options = {}) {
270
- const { signal } = options;
271
- for (let failures = 0; !signal?.aborted; failures += 1) {
272
- const attempt = await attemptRelayNodeKey(relayUrl);
273
- if (attempt.kind === "learned") return attempt.nodeKey;
274
- if (attempt.kind === "refused") {
275
- console.warn("[mero-react] refusing the relay's attestation; its node key stays unknown", attempt.error);
276
- return null;
277
- }
278
- const wait = RELAY_NODE_KEY_RETRY_MS[Math.min(failures, RELAY_NODE_KEY_RETRY_MS.length - 1)];
279
- console.warn(
280
- `[mero-react] could not reach what proves the relay's node key; retrying in ${wait / 1e3} s`,
281
- attempt.error
282
- );
283
- await pause(wait, signal);
284
- }
285
- return null;
286
- }
287
- function jwtExpiryMs(token) {
288
- try {
289
- const payload = JSON.parse(atob(token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")));
290
- return typeof payload.exp === "number" ? payload.exp * 1e3 : null;
291
- } catch {
292
- return null;
293
- }
294
- }
295
- function relaySession(s, nodeKey) {
296
- let token = null;
297
- let inflight = null;
298
- return async () => {
299
- const exp = token ? jwtExpiryMs(token) : null;
300
- if (token && (exp === null || exp - Date.now() > 3e4)) return token;
301
- if (!inflight) {
302
- inflight = login({
303
- nodeUrl: s.relayUrl,
304
- node: nodeKey,
305
- deviceSecret: s.deviceSecret,
306
- accountProof: s.credential,
307
- audience: defaultAudience()
308
- }).then((minted) => {
309
- token = minted.accessToken;
310
- return token;
311
- }).catch((e) => {
312
- console.warn("[mero-react] relay login failed", e);
313
- token = null;
314
- return void 0;
315
- }).finally(() => {
316
- inflight = null;
317
- });
318
- }
319
- return inflight;
320
- };
321
- }
322
- function buildDelegatedClient(s, _contextId) {
323
- if (!s.relayUrl) return null;
324
- const nodeKey = readPinnedRelayNodeKey(s.relayUrl);
325
- return createMeroClient({
326
- transport: "relay",
327
- relay: {
328
- relayUrl: s.relayUrl,
329
- authorAccount: s.account,
330
- authorProof: s.credential,
331
- deviceSecret: s.deviceSecret,
332
- // One sequence per relay, whatever context is chosen: `execute` takes a
333
- // context per call, so the nonce source must not depend on this one.
334
- nonces: persistedNonces(s.relayUrl)
335
- },
336
- // The certificate authenticates the requests too, not just the writes.
337
- //
338
- // This is the whole of what reads and events need: the device key signs each
339
- // request, and the node verifies it against the account's certificate with no
340
- // store read and no prior relationship. Measured against a node built from
341
- // core `aecba573b`: `listNamespaces` and `getContexts` answer `200` and are
342
- // caller-scoped, `/sse` answers `200`, and a real write arrives on the stream
343
- // as a `StateMutation` frame.
344
- //
345
- // What this replaces is a session minted by `login()` plus the relay node's
346
- // signing key learned out of band — two inputs, one of which the cloud does
347
- // not publish, for an answer the certificate already gives.
348
- proof: { credential: s.credential, deviceSecret: s.deviceSecret },
349
- // A session, when this relay's node key is pinned. A hosted relay's
350
- // forward-auth accepts a Bearer token and not the proof above, so without
351
- // one every admin read there is a 401. Given a session the client uses it
352
- // for every admin call; a relay with no pinned key keeps the proof path.
353
- session: nodeKey ? relaySession({ ...s, relayUrl: s.relayUrl }, nodeKey) : void 0,
354
- // Events too. `/sse` on a relay sits behind the same forward-auth, so the
355
- // proof above gets a 401 there; with the node key the client observes
356
- // through its own device-certificate login instead.
357
- observe: nodeKey ? { nodeKey } : void 0
358
- });
359
- }
360
- var RELAY_MAP_PREFIX = "calimero.delegated.relays.";
361
- function readRelayMap(account) {
362
- try {
363
- const raw = localStorage.getItem(RELAY_MAP_PREFIX + account);
364
- const parsed = raw ? JSON.parse(raw) : {};
365
- return { namespaces: parsed.namespaces ?? {}, contexts: parsed.contexts ?? {} };
366
- } catch {
367
- return { namespaces: {}, contexts: {} };
368
- }
369
- }
370
- function writeRelayMap(account, map) {
371
- try {
372
- localStorage.setItem(RELAY_MAP_PREFIX + account, JSON.stringify(map));
373
- } catch {
374
- }
375
- }
376
- function rememberRelay(account, relayUrl, at) {
377
- const map = readRelayMap(account);
378
- const url = relayOrigin(relayUrl);
379
- if (at.namespaceId) map.namespaces[at.namespaceId] = url;
380
- if (at.contextId) map.contexts[at.contextId] = url;
381
- writeRelayMap(account, map);
382
- }
383
- function relayForContext(account, contextId) {
384
- return readRelayMap(account).contexts[contextId] ?? null;
385
- }
386
- function carryExecutorAccount(prev, next) {
387
- if (next.executorAccount || !prev?.executorAccount || !prev.relayUrl || !next.relayUrl) return next;
388
- if (relayOrigin(prev.relayUrl) !== relayOrigin(next.relayUrl)) return next;
389
- return { ...next, executorAccount: prev.executorAccount };
390
- }
391
- function knownRelays(s) {
392
- const map = readRelayMap(s.account);
393
- const all = [s.relayUrl, ...Object.values(map.namespaces), ...Object.values(map.contexts)].filter((u) => typeof u === "string" && u.length > 0).map(relayOrigin);
394
- return [...new Set(all)];
395
- }
396
- async function listDelegatedContexts(s) {
397
- const out = [];
398
- const map = readRelayMap(s.account);
399
- for (const relayUrl of knownRelays(s)) {
400
- try {
401
- if (!await resolveRelayNodeKey(relayUrl)) continue;
402
- const client2 = buildDelegatedClient({ ...s, relayUrl }, null);
403
- if (!client2) continue;
404
- const { contexts } = await client2.admin.getContexts();
405
- for (const c of contexts ?? []) {
406
- out.push({ ...c, relayUrl });
407
- map.contexts[c.id] = relayUrl;
408
- }
409
- } catch (e) {
410
- console.warn(`[mero-react] could not list contexts on ${relayUrl}`, e);
411
- }
412
- }
413
- writeRelayMap(s.account, map);
414
- return out;
415
- }
416
- async function listDelegatedNamespaces(s) {
417
- var _a, _b;
418
- const out = [];
419
- const seen = /* @__PURE__ */ new Set();
420
- const map = readRelayMap(s.account);
421
- for (const relayUrl of knownRelays(s)) {
422
- try {
423
- if (!await resolveRelayNodeKey(relayUrl)) continue;
424
- const client2 = buildDelegatedClient({ ...s, relayUrl }, null);
425
- if (!client2) continue;
426
- for (const ns of await client2.admin.listNamespaces()) {
427
- if (seen.has(ns.namespaceId)) continue;
428
- seen.add(ns.namespaceId);
429
- out.push({ ...ns, relayUrl });
430
- (_a = map.namespaces)[_b = ns.namespaceId] ?? (_a[_b] = relayUrl);
431
- }
432
- } catch (e) {
433
- console.warn(`[mero-react] could not list namespaces on ${relayUrl}`, e);
434
- }
435
- }
436
- writeRelayMap(s.account, map);
437
- return out;
438
- }
439
-
440
- // src/delegated/application-id.ts
441
- function borshString(s) {
442
- const bytes = new TextEncoder().encode(s);
443
- const out = new Uint8Array(4 + bytes.length);
444
- new DataView(out.buffer).setUint32(0, bytes.length, true);
445
- out.set(bytes, 4);
446
- return out;
447
- }
448
- async function applicationIdForBundle(pkg, signerId) {
449
- const a = borshString(pkg);
450
- const b = borshString(signerId);
451
- const tuple = new Uint8Array(a.length + b.length);
452
- tuple.set(a, 0);
453
- tuple.set(b, a.length);
454
- const digest = await crypto.subtle.digest("SHA-256", tuple);
455
- return Array.from(new Uint8Array(digest), (x) => x.toString(16).padStart(2, "0")).join("");
456
- }
457
- function newer(a, b) {
458
- const [x, y] = [a, b].map((v) => v.split(/[.-]/).map((n) => Number.parseInt(n, 10) || 0));
459
- for (let i = 0; i < Math.max(x.length, y.length); i++) {
460
- if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0);
461
- }
462
- return false;
463
- }
464
- function selectLatestBundle(bundles) {
465
- return bundles.filter((b) => !b.yanked && typeof b.appVersion === "string" && b.appVersion.length > 0).reduce((best, b) => !best || newer(b.appVersion, best.appVersion) ? b : best, void 0);
466
- }
467
- async function fetchRegistryBundles(registryUrl, pkg, fetchFn = globalThis.fetch) {
468
- const url = `${registryUrl.replace(/\/+$/, "")}/api/v2/bundles?package=${encodeURIComponent(pkg)}`;
469
- const response = await fetchFn(url, { headers: { Accept: "application/json" } });
470
- if (!response.ok) throw new Error(`the registry has no ${pkg} (HTTP ${response.status})`);
471
- const body = await response.json();
472
- return Array.isArray(body) ? body : [];
473
- }
474
- async function resolveApplicationIdFromRegistry(registryUrl, pkg, deps = {}) {
475
- const bundles = await fetchRegistryBundles(registryUrl, pkg, deps.fetch);
476
- const live = bundles.filter((b) => !b.yanked);
477
- const signers = [...new Set(live.map((b) => b.signerId).filter((s) => typeof s === "string" && s.length > 0))];
478
- if (signers.length > 1) {
479
- throw new Error(
480
- `the registry lists ${pkg} under more than one publisher (${signers.join(", ")}): refusing to guess which application it is`
481
- );
482
- }
483
- const latest = selectLatestBundle(live);
484
- if (!latest) throw new Error(`the registry lists no version of ${pkg}`);
485
- const signerId = latest.signerId;
486
- if (!signerId) throw new Error(`the registry names no publisher for ${pkg} ${latest.appVersion}`);
487
- return { applicationId: await applicationIdForBundle(pkg, signerId), signerId, version: latest.appVersion };
488
- }
489
-
490
- // src/delegated/create-context.ts
491
- function governanceNonce(relay, group) {
492
- return { next: async () => nextGovernanceNonce(relay, group) };
493
- }
494
- function nextGovernanceNonce(relay, group) {
495
- const key = `calimero.governance-nonce.${relay}.${group}`;
496
- let last = 0n;
497
- try {
498
- last = BigInt(localStorage.getItem(key) ?? "0");
499
- } catch {
500
- }
501
- const next = [last + 1n, BigInt(Date.now())].reduce((a, b) => a > b ? a : b);
502
- try {
503
- localStorage.setItem(key, String(next));
504
- } catch {
505
- }
506
- return next;
507
- }
508
- function relayFor(s, namespaceId) {
509
- const url = readRelayMap(s.account).namespaces[namespaceId] ?? s.relayUrl;
510
- if (!url) throw new Error("no relay is known for this namespace, so there is nowhere to send this");
511
- return url.replace(/\/+$/, "");
512
- }
513
- function initArgsOf(params) {
514
- if (!params || params.length === 0) return {};
515
- return JSON.parse(new TextDecoder().decode(Uint8Array.from(params)));
516
- }
517
- function client(s, relayUrl, nonces, fetch2) {
518
- return new RelayClient({
519
- relayUrl,
520
- authorAccount: s.account,
521
- authorProof: s.credential,
522
- deviceSecret: s.deviceSecret,
523
- nonces,
524
- fetch: fetch2
525
- });
526
- }
527
- async function createDelegatedContext(s, req, deps = {}) {
528
- const relay = relayFor(s, req.namespaceId);
529
- const creationNonce = 0n;
530
- const created = await client(s, relay, { next: async () => creationNonce }, deps.fetch).createContext({
531
- groupId: req.groupId ?? req.namespaceId,
532
- applicationId: req.applicationId,
533
- serviceName: req.serviceName,
534
- seed: req.contextSeed,
535
- initArgs: initArgsOf(req.initializationParams),
536
- name: req.name
537
- });
538
- markContextNonceSpent(relay, created.contextId, creationNonce);
539
- rememberRelay(s.account, relay, { namespaceId: req.namespaceId, contextId: created.contextId });
540
- return { contextId: created.contextId };
541
- }
542
- async function delegatedGovernance(s, req, deps = {}) {
543
- const relay = relayFor(s, req.namespaceId);
544
- return client(s, relay, governanceNonce(relay, req.group), deps.fetch).govern({ groupId: req.group, op: req.op });
545
- }
546
- async function createDelegatedPrivateContext(s, req, deps = {}) {
547
- const { groupId } = await delegatedGovernance(
548
- s,
549
- {
550
- namespaceId: req.namespaceId,
551
- group: req.namespaceId,
552
- // The id is derived from a fresh salt (core#4244); a node refuses any other.
553
- op: (await subgroupCreation({ parentId: req.namespaceId, restricted: true, admin: s.account })).op
554
- },
555
- deps
556
- );
557
- for (const member of req.members) {
558
- await delegatedGovernance(s, { namespaceId: req.namespaceId, group: groupId, op: memberAddedOp(member, "Member") }, deps);
559
- }
560
- const { contextId } = await createDelegatedContext(s, { ...req, groupId }, deps);
561
- return { contextId, groupId };
562
- }
563
- async function foundDelegatedNamespace(s, req = {}, deps = {}) {
564
- const relays = knownRelays(s).map((u) => u.replace(/\/+$/, ""));
565
- const relay = relays[0];
566
- if (!relay) throw new Error("no relay is known for this account, so there is nowhere to found a namespace");
567
- const known = Object.entries(readRelayMap(s.account).namespaces).find(
568
- ([, url]) => url.replace(/\/+$/, "") === relay
569
- )?.[0];
570
- const named = s.executorAccount && s.relayUrl && s.relayUrl.replace(/\/+$/, "") === relay ? s.executorAccount : null;
571
- if (!named && !known) {
572
- throw new Error(
573
- "the executor account of this relay is not known: join a namespace on it first, or connect with the relay's executor account (the cloud shows it beside the relay)"
574
- );
575
- }
576
- const executorAccount = named ?? (await client(s, relay, governanceNonce(relay, known), deps.fetch).describeGovernance(known)).executorAccount;
577
- let next = BigInt(Date.now());
578
- const founded = await client(s, relay, { next: async () => next++ }, deps.fetch).foundNamespace({
579
- executorAccount,
580
- ...req.defaultCapabilities !== void 0 ? { defaultCapabilities: req.defaultCapabilities } : {},
581
- ...req.application ? { application: req.application } : {}
582
- });
583
- try {
584
- localStorage.setItem(`calimero.governance-nonce.${relay}.${founded.namespaceId}`, String(next));
585
- } catch {
586
- }
587
- rememberRelay(s.account, relay, { namespaceId: founded.namespaceId });
588
- if (req.application && founded.applicationSet !== true) {
589
- throw new Error(
590
- `founded ${founded.namespaceId} but could not give it its application: ${founded.applicationError ?? "unknown reason"}`
591
- );
592
- }
593
- const ha = founded.teeEnabled ? await enableHaBestEffort(s, founded.namespaceId, founded.salt, relay, deps) : {
594
- haEnabled: false,
595
- haError: `the relay did not attest the founding, so no fleet node could be admitted for HA${founded.teeError ? `: ${founded.teeError}` : ""}`
596
- };
597
- return { namespaceId: founded.namespaceId, teeEnabled: founded.teeEnabled, ...ha };
598
- }
599
- var HA_ACCOUNT_NOT_LINKED_MESSAGE = "link this account to your cloud user in the wallet so invitees can find this namespace";
600
- var HA_REFUSAL_MESSAGES = {
601
- account_not_linked: HA_ACCOUNT_NOT_LINKED_MESSAGE,
602
- account_linked_to_several_users: "this account is linked to more than one cloud user, so the cloud cannot tell whose plan hosts the namespace: unlink it from all but one in the wallet",
603
- ha_request_pending: "another namespace of this account is still waiting to be hosted; the cloud hosts one new namespace at a time without a cloud sign-in. Sign in to the cloud and turn off hosting for the waiting namespace, or wait until it is hosted",
604
- unknown_relay: "the cloud does not run the relay this namespace was founded on, so it cannot host it",
605
- relay_not_dialable: "the relay this namespace was founded on has not reported its address to the cloud yet; try enabling hosting again shortly"
606
- };
607
- function blockingNamespace(e) {
608
- try {
609
- const body = JSON.parse(e.bodyText ?? "");
610
- const id = body?.detail?.namespace_id ?? body?.namespace_id;
611
- return typeof id === "string" && /^[0-9a-f]{64}$/i.test(id) ? id.toLowerCase() : null;
612
- } catch {
613
- return null;
614
- }
615
- }
616
- async function enableHaBestEffort(s, namespaceId, salt, relayUrl, deps) {
617
- try {
618
- await new CloudClient({ cloudBaseUrl: deps.cloudBaseUrl, fetch: deps.fetch }).enableHaAsAccount({
619
- namespaceId,
620
- salt,
621
- accountId: s.account,
622
- credential: s.credential,
623
- deviceSecret: s.deviceSecret,
624
- // The relay that founded it: the cloud hands it to the fleet node as its
625
- // admitter, so the node does not have to find it by discovery.
626
- relayUrl
627
- });
628
- return { haEnabled: true };
629
- } catch (e) {
630
- if (e instanceof AccountNotLinkedError) return { haEnabled: false, haError: HA_ACCOUNT_NOT_LINKED_MESSAGE };
631
- if (e instanceof AccountHaRefusedError && HA_REFUSAL_MESSAGES[e.code]) {
632
- const blocking = e.code === "ha_request_pending" ? blockingNamespace(e) : null;
633
- const message = HA_REFUSAL_MESSAGES[e.code];
634
- return { haEnabled: false, haError: blocking ? `${message} (waiting: ${blocking})` : message };
635
- }
636
- return { haEnabled: false, haError: e instanceof Error ? e.message : String(e) };
637
- }
638
- }
639
- async function latestPublishedVersion(registryUrl, pkg, fetchFn = globalThis.fetch) {
640
- const latest = selectLatestBundle(await fetchRegistryBundles(registryUrl, pkg, fetchFn));
641
- if (!latest) throw new Error(`the registry lists no version of ${pkg}`);
642
- return latest.appVersion;
643
- }
644
-
645
- // src/admin/node-admin.ts
646
- function createNodeAdmin(input, deps = {}) {
647
- const { admin, app } = input;
648
- const latestVersion = deps.latestVersion ?? latestPublishedVersion;
649
- async function ensureInstalled(applicationId) {
650
- const { apps } = await admin.listApplications();
651
- if (apps.some((a) => a.id === applicationId)) return;
652
- if (!app.packageName) {
653
- throw new Error(`application ${applicationId} is not installed on this node, and no packageName is set to install it`);
654
- }
655
- const version = app.packageVersion ?? await latestVersion(app.registryUrl ?? "https://apps.calimero.network", app.packageName);
656
- const { applicationId: installed } = await admin.installApplication({ package: app.packageName, version });
657
- if (installed !== applicationId) {
658
- throw new Error(`installed ${app.packageName}@${version} as ${installed}, not ${applicationId}`);
659
- }
660
- }
661
- const overrides = {
662
- async createNamespace(req) {
663
- await ensureInstalled(req.applicationId);
664
- return admin.createNamespace(req);
665
- }
666
- };
667
- return new Proxy(admin, {
668
- get(target, prop, receiver) {
669
- if (typeof prop === "string" && prop in overrides) return overrides[prop];
670
- return Reflect.get(target, prop, receiver);
671
- }
672
- });
673
- }
674
-
675
- // src/delegated/govern.ts
676
- var GROUP_NAMESPACE_PREFIX = "calimero.delegated.group-namespace.";
677
- var learned = /* @__PURE__ */ new Map();
678
- function readGroupNamespaces(account) {
679
- let stored = {};
680
- try {
681
- stored = JSON.parse(localStorage.getItem(GROUP_NAMESPACE_PREFIX + account) ?? "{}");
682
- } catch {
683
- }
684
- return { ...stored, ...learned.get(account) };
685
- }
686
- function rememberGroupNamespace(account, groupId, namespaceId) {
687
- learned.set(account, { ...learned.get(account), [groupId]: namespaceId });
688
- try {
689
- const all = readGroupNamespaces(account);
690
- all[groupId] = namespaceId;
691
- localStorage.setItem(GROUP_NAMESPACE_PREFIX + account, JSON.stringify(all));
692
- } catch {
693
- }
694
- }
695
- function namespaceOfGroup(s, groupId) {
696
- if (readRelayMap(s.account).namespaces[groupId]) return groupId;
697
- return readGroupNamespaces(s.account)[groupId];
698
- }
699
- function requireNamespace(s, groupId) {
700
- const ns = namespaceOfGroup(s, groupId);
701
- if (!ns) {
702
- throw new Error(
703
- `the namespace of group ${groupId} is not known to this account: it can manage only groups in namespaces it joined or subgroups it created`
704
- );
705
- }
706
- return ns;
707
- }
708
- async function governGroup(s, groupId, op) {
709
- return delegatedGovernance(s, { namespaceId: requireNamespace(s, groupId), group: groupId, op });
710
- }
711
- async function governRoot(s, groupId, op) {
712
- const namespaceId = requireNamespace(s, groupId);
713
- return delegatedGovernance(s, { namespaceId, group: namespaceId, op });
714
- }
715
-
716
- // src/delegated/account-admin.ts
717
- var NotForAccountError = class extends Error {
718
- constructor(method) {
719
- super(`${method} is not available for an account: it needs a node`);
720
- this.method = method;
721
- this.name = "NotForAccountError";
722
- }
723
- };
724
- var NoRelayError = class extends Error {
725
- constructor(method) {
726
- super(`${method} needs a relay, and this account has none yet: join from an invitation first`);
727
- this.method = method;
728
- this.name = "NoRelayError";
729
- }
730
- };
731
- var InvitationNotClaimableError = class extends Error {
732
- constructor(namespaceId, reason) {
733
- super(
734
- reason === "not-hosted" ? `nobody could claim an invitation to ${namespaceId} yet: the namespace is not hosted in the cloud, so an invitee with no node has no relay to be admitted through. Link this account to your cloud user in the wallet and enable HA for the namespace, then invite.` : `nobody could claim an invitation to ${namespaceId}: the cloud routes to none of the relays or admins it would name as admitters`
735
- );
736
- this.namespaceId = namespaceId;
737
- this.reason = reason;
738
- this.name = "InvitationNotClaimableError";
739
- }
740
- };
741
- var EMPTY_READS = {
742
- listNamespaces: async () => [],
743
- listNamespacesForApplication: async () => [],
744
- getContexts: async () => ({ contexts: [] })
745
- };
746
- var NODE_ONLY = /* @__PURE__ */ new Set([
747
- "upgradeGroup",
748
- "retryGroupUpgrade",
749
- "abortMigration",
750
- "installApplication",
751
- "installDevApplication",
752
- "uninstallApplication",
753
- "generateContextIdentity",
754
- "deleteContext",
755
- // A node's leaveContext is a local opt-out (a tombstone, its own identity rows)
756
- // and publishes nothing; an account has nothing local to opt out of, and
757
- // leaving the context's group instead is leaveGroup.
758
- "leaveContext",
759
- "createContextAlias",
760
- "createApplicationAlias",
761
- "createDeviceAlias",
762
- "deleteContextAlias",
763
- "deleteApplicationAlias",
764
- "deleteDeviceAlias",
765
- "lookupContextAlias",
766
- "lookupApplicationAlias",
767
- "lookupDeviceAlias",
768
- "listContextAliases",
769
- "listApplicationAliases",
770
- "listDeviceAliases",
771
- "deleteNamespace",
772
- "createGroupInvitation",
773
- "joinGroup",
774
- "setTeeAdmissionPolicy",
775
- "getTeeAdmissionPolicy",
776
- "deleteBlob",
777
- "listAccountDevices",
778
- "revokeAccountDevice"
779
- ]);
780
- function isAlreadyDirectMember(e) {
781
- if (!(e instanceof Error)) return false;
782
- const status = e.status;
783
- return (status === void 0 || status === 409) && /signer [0-9a-f]+ is a direct member/i.test(e.message);
784
- }
785
- function createAccountAdmin(input, deps = {}) {
786
- const { session: s, read, app } = input;
787
- const governGroupOp = deps.govern?.group ?? governGroup;
788
- const governRootOp = deps.govern?.root ?? governRoot;
789
- const createContext2 = deps.createContext ?? createDelegatedContext;
790
- const found = deps.found ?? foundDelegatedNamespace;
791
- const latestVersion = deps.latestVersion ?? latestPublishedVersion;
792
- const signInvitation = deps.signInvitation ?? signGroupInvitation;
793
- const join = deps.join;
794
- const routing = deps.routing;
795
- async function joinNamespace(namespaceId, req) {
796
- if (!join) throw new NotForAccountError("joinNamespace without a join handler");
797
- return join(namespaceId, req.invitation);
798
- }
799
- const relay = () => {
800
- if (read === null) throw new NoRelayError("this call");
801
- return read;
802
- };
803
- async function knowNamespaceOf(groupId) {
804
- if (namespaceOfGroup(s, groupId)) return;
805
- const info = await relay().getGroupInfo(groupId);
806
- rememberGroupNamespace(s.account, groupId, info.namespaceId ?? groupId);
807
- }
808
- const group = async (session, groupId, op) => {
809
- await knowNamespaceOf(groupId);
810
- return governGroupOp(session, groupId, op);
811
- };
812
- const root = async (session, groupId, op) => {
813
- await knowNamespaceOf(groupId);
814
- return governRootOp(session, groupId, op);
815
- };
816
- async function joinOpen(groupId) {
817
- try {
818
- await root(s, groupId, memberJoinedOpenOp({ member: s.account, groupId, credential: s.credential }));
819
- return true;
820
- } catch (e) {
821
- if (isAlreadyDirectMember(e)) return false;
822
- throw e;
823
- }
824
- }
825
- async function isMemberOfContextGroup(contextId, knownGroupId) {
826
- const groupId = String(await relay().getContextGroup(contextId));
827
- const { members } = await relay().listGroupMembers(groupId);
828
- return members.some((m) => m.identity.toLowerCase() === s.account.toLowerCase());
829
- }
830
- const writes = {
831
- // The node-wide `for-application` listing is not caller-scoped, so a relay
832
- // refuses it to an account. Its own scoped list, filtered, is the answer.
833
- async listNamespacesForApplication(applicationId) {
834
- return (await relay().listNamespaces()).filter((ns) => ns.targetApplicationId === applicationId);
835
- },
836
- async getNodeIdentity() {
837
- return { accountId: s.account, deviceId: null, publicKey: "", deviceCertified: true };
838
- },
839
- async createNamespace(req) {
840
- if (!app.packageName) throw new NotForAccountError("createNamespace without a packageName");
841
- const version = app.packageVersion ?? await latestVersion(app.registryUrl ?? "https://apps.calimero.network", app.packageName);
842
- const { namespaceId, haEnabled, haError } = await found(s, {
843
- defaultCapabilities: 231,
844
- application: { applicationId: req.applicationId, package: app.packageName, version }
845
- });
846
- if (req.name) await group(s, namespaceId, groupMetadataSetOp({ name: req.name }));
847
- return { namespaceId, haEnabled, ...haError !== void 0 ? { haError } : {} };
848
- },
849
- async createGroupInNamespace(namespaceId, req = {}) {
850
- const { op } = await subgroupCreation({ parentId: namespaceId, restricted: req.visibility !== "open", admin: s.account });
851
- const { groupId } = await root(s, namespaceId, op);
852
- rememberGroupNamespace(s.account, groupId, namespaceId);
853
- if (req.groupName) await group(s, groupId, groupMetadataSetOp({ name: req.groupName }));
854
- return { groupId };
855
- },
856
- async addGroupMembers(groupId, req) {
857
- for (const m of req.members) await group(s, groupId, memberAddedOp(m.identity, m.role ?? "Member"));
858
- },
859
- async removeGroupMembers(groupId, req) {
860
- for (const m of req.members) await group(s, groupId, memberRemovedOp(m));
861
- },
862
- async setGroupMetadata(groupId, req) {
863
- await group(s, groupId, groupMetadataSetOp(req));
864
- },
865
- async setMemberMetadata(groupId, identity, req) {
866
- await group(s, groupId, memberMetadataSetOp(identity, req));
867
- },
868
- async setContextMetadata(groupId, contextId, req) {
869
- await group(s, groupId, contextMetadataSetOp(contextId, req));
870
- },
871
- async setDefaultCapabilities(groupId, req) {
872
- await group(s, groupId, defaultCapabilitiesSetOp(req.defaultCapabilities));
873
- },
874
- async setSubgroupVisibility(groupId, req) {
875
- await group(s, groupId, subgroupVisibilitySetOp(req.subgroupVisibility === "open" ? "open" : "restricted"));
876
- },
877
- async setMemberCapabilities(groupId, identity, req) {
878
- await group(s, groupId, memberCapabilitySetOp(identity, req.capabilities));
879
- },
880
- async deleteGroup(groupId) {
881
- await root(s, groupId, groupDeletedOp(groupId));
882
- return { isDeleted: true };
883
- },
884
- async reparentGroup(childGroupId, req) {
885
- await root(s, childGroupId, groupReparentedOp(childGroupId, req.newParentId));
886
- return { reparented: true };
887
- },
888
- async leaveGroup(groupId) {
889
- await group(s, groupId, memberLeftOp(s.account));
890
- },
891
- async leaveNamespace(namespaceId) {
892
- await group(s, namespaceId, memberLeftOp(s.account));
893
- },
894
- // An account runs as itself in every context it can reach (the relay
895
- // executes as the account), so its identity there is the account. Owned
896
- // when its account is a member of the context's group, as on a node a
897
- // context identity is owned once the node has joined.
898
- async getContextIdentitiesOwned(contextId) {
899
- return { identities: await isMemberOfContextGroup(contextId) ? [s.account] : [] };
900
- },
901
- async joinContext(contextId) {
902
- await joinOpen(String(await relay().getContextGroup(contextId)));
903
- return { contextId, memberPublicKey: s.account };
904
- },
905
- async createContext(req) {
906
- const info = await relay().getGroupInfo(req.groupId);
907
- const namespaceId = info.namespaceId ?? req.groupId;
908
- const { contextId } = await createContext2(s, {
909
- namespaceId,
910
- groupId: req.groupId,
911
- applicationId: req.applicationId,
912
- serviceName: req.serviceName,
913
- contextSeed: req.contextSeed,
914
- name: req.name,
915
- initializationParams: req.initializationParams
916
- });
917
- return { contextId, memberPublicKey: "", groupId: req.groupId };
918
- },
919
- async createNamespaceInvitation(namespaceId) {
920
- const [{ members }, info] = await Promise.all([relay().listGroupMembers(namespaceId), relay().getGroupInfo(namespaceId)]);
921
- const relays = members.filter((m) => m.role === "RelayTee").map((m) => m.identity.toLowerCase());
922
- if (routing) {
923
- const named = new Set(
924
- relays.length > 0 ? relays : members.filter((m) => m.role === "Admin").map((m) => m.identity.toLowerCase())
925
- );
926
- let nodes = null;
927
- try {
928
- nodes = (await routing(namespaceId)).nodes;
929
- } catch {
930
- }
931
- if (nodes !== null) {
932
- if (nodes.length === 0) throw new InvitationNotClaimableError(namespaceId, "not-hosted");
933
- if (!nodes.some((n) => n.account !== null && named.has(n.account.toLowerCase()))) {
934
- throw new InvitationNotClaimableError(namespaceId, "no-named-node");
935
- }
936
- }
937
- }
938
- const invitation = await signInvitation({
939
- groupId: namespaceId,
940
- inviterAccount: s.account,
941
- deviceSecret: s.deviceSecret,
942
- ...relays.length > 0 ? { admitters: relays } : {},
943
- members,
944
- applicationId: info.targetApplicationId,
945
- appKey: info.appKey
946
- });
947
- return { invitation };
948
- },
949
- // The relay syncs its own view; an account has nothing to pull.
950
- async syncGroup(groupId) {
951
- return { groupId, synced: true };
952
- },
953
- async syncContext() {
954
- },
955
- joinNamespace,
956
- async updateMemberRole(groupId, identity, req) {
957
- await group(s, groupId, memberRoleSetOp(identity, req.role));
958
- },
959
- // An open subgroup is joined the way `joinContext` joins one: MemberJoinedOpen
960
- // on the subgroup, and nothing to do for a member already in it.
961
- async joinSubgroupInheritance(groupId) {
962
- return { groupId, memberPublicKey: s.account, wasInherited: await joinOpen(groupId) };
963
- },
964
- async detachContextFromGroup(groupId, contextId) {
965
- await group(s, groupId, contextDetachedOp(contextId));
966
- }
967
- };
968
- if (read === null) {
969
- return new Proxy({}, {
970
- get(_target, prop) {
971
- if (typeof prop !== "string") return void 0;
972
- if (prop === "getNodeIdentity") return writes.getNodeIdentity;
973
- if (prop === "joinNamespace") return joinNamespace;
974
- if (prop in EMPTY_READS) return EMPTY_READS[prop];
975
- return async () => {
976
- throw new NoRelayError(prop);
977
- };
978
- }
979
- });
980
- }
981
- return new Proxy(read, {
982
- get(target, prop, receiver) {
983
- if (typeof prop === "string" && prop in writes) return writes[prop];
984
- if (typeof prop === "string" && NODE_ONLY.has(prop)) {
985
- return async () => {
986
- throw new NotForAccountError(prop);
987
- };
988
- }
989
- return Reflect.get(target, prop, receiver);
990
- }
991
- });
992
- }
993
- function explainAdmitFailure(status, body) {
994
- const detail = body ? `: ${body}` : "";
995
- switch (status) {
996
- case 400:
997
- 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.`;
998
- case 403:
999
- 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.`;
1000
- case 409:
1001
- return `That node holds no device of its own, so it cannot endorse anyone (409)${detail}. Another admitter from the same invitation would work.`;
1002
- default:
1003
- return `The join was not published (HTTP ${status})${detail}.`;
1004
- }
1005
- }
1006
- function joinNonce(account) {
1007
- const source = createLocalStorageNonceSource(`calimero.delegated.joinnonce.${account}`);
1008
- return () => source.next();
1009
- }
1010
- function origin(url) {
1011
- return url.replace(/\/+$/, "");
1012
- }
1013
- async function joinWithNode(input) {
1014
- const { account, credential, deviceSecret } = input.credential;
1015
- let signedOp;
1016
- try {
1017
- signedOp = await signMemberJoinOp({
1018
- namespaceId: input.namespaceId,
1019
- member: account,
1020
- invitation: input.invitation,
1021
- credential,
1022
- deviceSecret,
1023
- nonce: await (input.deps?.nonce ?? joinNonce(account))()
1024
- });
1025
- } catch (e) {
1026
- return {
1027
- ok: false,
1028
- step: "sign",
1029
- reason: `The join op could not be signed, so nothing was sent: ${e instanceof Error ? e.message : String(e)}`
1030
- };
1031
- }
1032
- const body = { invitation: input.invitation, signedOp };
1033
- const url = input.admitUrl ?? `${origin(input.nodeUrl)}/admin-api/namespaces/${input.namespaceId}/admit`;
1034
- const doFetch = input.deps?.fetch ?? fetch;
1035
- let response;
1036
- try {
1037
- response = await doFetch(url, {
1038
- method: "POST",
1039
- // No Authorization header and no request proof, deliberately: the route is
1040
- // unauthenticated because the joiner's signature is the authorization.
1041
- headers: { "Content-Type": "application/json", Accept: "application/json" },
1042
- body: JSON.stringify(body)
1043
- });
1044
- } catch (e) {
1045
- return {
1046
- ok: false,
1047
- step: "admit",
1048
- 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.`
1049
- };
1050
- }
1051
- const text = await response.text();
1052
- if (!response.ok) {
1053
- return {
1054
- ok: false,
1055
- step: "admit",
1056
- status: response.status,
1057
- reason: explainAdmitFailure(response.status, text)
1058
- };
1059
- }
1060
- let published = false;
1061
- try {
1062
- const parsed = text ? JSON.parse(text) : {};
1063
- published = parsed.data?.published === true;
1064
- } catch {
1065
- published = false;
1066
- }
1067
- return {
1068
- ok: true,
1069
- published,
1070
- session: { relayUrl: origin(input.nodeUrl), account, credential, deviceSecret }
1071
- };
1072
- }
1073
- function normaliseAccount(account) {
1074
- if (!account) return null;
1075
- const trimmed = account.trim().toLowerCase();
1076
- const bare = trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
1077
- return bare.length > 0 ? bare : null;
1078
- }
1079
- function isInvited(node, invited) {
1080
- if (invited.size === 0) return true;
1081
- const account = normaliseAccount(node.account);
1082
- return account !== null && invited.has(account);
1083
- }
1084
- async function resolveRelayFromInvitation(input) {
1085
- const cloud = input.cloud ?? new CloudClient({
1086
- cloudBaseUrl: input.cloudBaseUrl,
1087
- routingCredential: { credential: input.credential, deviceSecret: input.deviceSecret }
1088
- });
1089
- let nodes;
1090
- let servable;
1091
- try {
1092
- const routing = await cloud.getNamespaceRouting(input.namespaceId);
1093
- nodes = routing.nodes;
1094
- servable = routing.servable;
1095
- } catch (e) {
1096
- return {
1097
- ok: false,
1098
- step: "admitters-lookup",
1099
- 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.`
1100
- };
1101
- }
1102
- if (nodes.length === 0) {
1103
- return {
1104
- ok: false,
1105
- step: "no-nodes",
1106
- 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."
1107
- };
1108
- }
1109
- const invited = new Set(
1110
- (input.admitters ?? []).map(normaliseAccount).filter((a) => a !== null)
1111
- );
1112
- const named = nodes.filter((n) => isInvited(n, invited));
1113
- if (named.length === 0) {
1114
- return {
1115
- ok: false,
1116
- step: "not-invited",
1117
- 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.`
1118
- };
1119
- }
1120
- const usable = named.filter((n) => n.canAdmit);
1121
- const candidates = usable.length > 0 ? usable : named;
1122
- const advisory = usable.length === 0 || !servable;
1123
- const addressable = candidates.filter(
1124
- (n) => typeof n.relayUrl === "string" && n.relayUrl.length > 0
1125
- );
1126
- if (addressable.length === 0) {
1127
- return {
1128
- ok: false,
1129
- step: "no-relay-url",
1130
- 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."
1131
- };
1132
- }
1133
- const chosen = addressable.find((n) => n.canExecute) ?? addressable.find((n) => n.fresh) ?? addressable[0];
1134
- return {
1135
- ok: true,
1136
- relayUrl: chosen.relayUrl,
1137
- // The cloud's ready-made URL when it gave one, so the path is never rebuilt
1138
- // from a guess; the fallback is the documented route on the same origin.
1139
- admitUrl: chosen.admitUrl ?? `${chosen.relayUrl.replace(/\/+$/, "")}/admin-api/namespaces/${input.namespaceId}/admit`,
1140
- admitterAccount: chosen.account,
1141
- peerId: chosen.peerId,
1142
- writable: chosen.canExecute,
1143
- // Stale when the node's own heartbeat lapsed OR when the cloud's summary
1144
- // disagrees with trying it at all. Both mean the same thing to a caller:
1145
- // this was attempted on advisory data, so if the admit fails that is why.
1146
- stale: !chosen.fresh || advisory
1147
- };
1148
- }
1149
-
1150
- // src/delegated/bootstrap-from-invitation.ts
1151
- async function bootstrapFromInvitation(input) {
1152
- const resolve = input.deps?.resolve ?? resolveRelayFromInvitation;
1153
- const join = input.deps?.join ?? joinWithNode;
1154
- let relay = null;
1155
- let nodeUrl = input.nodeUrl;
1156
- let admitUrl;
1157
- if (!nodeUrl) {
1158
- const resolved = await resolve({
1159
- namespaceId: input.namespaceId,
1160
- // The signed list, read off the invitation itself rather than passed
1161
- // separately: two sources for one fact is how an intersection ends up
1162
- // being performed against the wrong list.
1163
- admitters: input.invitation.invitation.admitters,
1164
- credential: input.credential.credential,
1165
- deviceSecret: input.credential.deviceSecret,
1166
- cloudBaseUrl: input.cloudBaseUrl
1167
- });
1168
- if (!resolved.ok) return resolved;
1169
- relay = resolved;
1170
- nodeUrl = resolved.relayUrl;
1171
- admitUrl = resolved.admitUrl;
1172
- }
1173
- const joined = await join({
1174
- nodeUrl,
1175
- admitUrl,
1176
- namespaceId: input.namespaceId,
1177
- invitation: input.invitation,
1178
- credential: input.credential,
1179
- deps: { fetch: input.deps?.fetch, nonce: input.deps?.nonce }
1180
- });
1181
- if (!joined.ok) return joined;
1182
- return { ok: true, published: joined.published, relay, session: joined.session };
1183
- }
1184
-
1185
- // src/delegated/join-as-account.ts
1186
- async function joinAsAccount(session, namespaceId, invitation, opts) {
1187
- const bootstrap = opts.bootstrap ?? bootstrapFromInvitation;
1188
- const outcome = await bootstrap({
1189
- namespaceId,
1190
- invitation,
1191
- credential: { account: session.account, credential: session.credential, deviceSecret: session.deviceSecret },
1192
- cloudBaseUrl: opts.cloudBaseUrl
1193
- });
1194
- if (!outcome.ok) {
1195
- throw Object.assign(new Error(outcome.reason), {
1196
- step: outcome.step,
1197
- ...outcome.status !== void 0 ? { status: outcome.status } : {}
1198
- });
1199
- }
1200
- if (outcome.session.relayUrl) rememberRelay(session.account, outcome.session.relayUrl, { namespaceId });
1201
- opts.onJoined(carryExecutorAccount(session, outcome.session));
1202
- return { namespaceId };
1203
- }
1204
47
 
1205
48
  // src/auth/node-trust.ts
1206
49
  function sameOrigin(a, b) {
@@ -1585,9 +428,9 @@ function MeroProvider({
1585
428
  if (!delegated) return;
1586
429
  const relayUrl = (contextId ? relayForContext(delegated.account, contextId) : null) ?? delegated.relayUrl;
1587
430
  const routed = { ...delegated, relayUrl };
1588
- const client2 = buildDelegatedClient(routed);
1589
- const awaitingKey = Boolean(client2 && relayUrl && !readPinnedRelayNodeKey(relayUrl));
1590
- if (!awaitingKey) setMero(client2);
431
+ const client = buildDelegatedClient(routed, contextId);
432
+ const awaitingKey = Boolean(client && relayUrl && !readPinnedRelayNodeKey(relayUrl));
433
+ if (!awaitingKey) setMero(client);
1591
434
  setIsAuthenticated(true);
1592
435
  setIsOnline(true);
1593
436
  setNodeUrlState(relayUrl);
@@ -1595,11 +438,11 @@ function MeroProvider({
1595
438
  let active = true;
1596
439
  const stop = new AbortController();
1597
440
  (async () => {
1598
- if (!client2 || !relayUrl) return;
441
+ if (!client || !relayUrl) return;
1599
442
  if (awaitingKey) {
1600
443
  const nodeKey = await learnRelayNodeKey(relayUrl, { signal: stop.signal });
1601
444
  if (!active) return;
1602
- setMero(nodeKey ? buildDelegatedClient(routed) ?? client2 : client2);
445
+ setMero(nodeKey ? buildDelegatedClient(routed, contextId) ?? client : client);
1603
446
  setIsLoading(false);
1604
447
  if (!nodeKey) return;
1605
448
  }
@@ -3137,8 +1980,6 @@ function base58ToHex(input) {
3137
1980
  for (let k = 0; k < input.length && input[k] === "1"; k++) bytes.push(0);
3138
1981
  return bytes.reverse().map((b) => b.toString(16).padStart(2, "0")).join("");
3139
1982
  }
3140
-
3141
- // src/hooks/index.ts
3142
1983
  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.";
3143
1984
  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.";
3144
1985
  var REPLAY_RECONCILE_MS = 50;
@@ -5024,6 +3865,6 @@ function useJoinInvitation() {
5024
3865
  return { joinInvitation, joining, memberships, invitationRedeemer };
5025
3866
  }
5026
3867
 
5027
- export { AccountSignInPanel, AppMode, CalimeroLogo, ConnectButton, ConnectButtonAccount, ConnectionType, DEFAULT_MIGRATION_POLL_INTERVAL_MS, HA_ACCOUNT_NOT_LINKED_MESSAGE, HA_REFUSAL_MESSAGES, InvitationNotClaimableError, LoginModal, MERO_CSS_VARS, MeroContext, MeroProvider, MigrationAdminPanel, MigrationPendingBanner, NoRelayError, NotForAccountError, applicationIdForBundle, bootstrapFromInvitation, clearAllStorage, clearApplicationId, clearContextId, clearContextIdentity, clearDelegatedCredential, clearNodeUrl, clearTokenNodeUrl, createAccountAdmin, createDelegatedContext, createNodeAdmin, cssVar, defaultMeroTheme, getApplicationId, getContextId, getContextIdentity, getNodeUrl, getTokenNodeUrl, isFinalInvitationError, isReturningFromWallet, joinWithNode, listDelegatedContexts, localStorageTokenStorage, normaliseAccount, pinRelayNodeKey, readDelegatedCredential, readPinnedRelayNodeKey, readRelayMap, relayForContext, rememberRelay, resolveApplicationIdFromRegistry, resolveMeroTheme, resolveRelayFromInvitation, saveDelegatedCredential, selectLatestBundle, setApplicationId, setContextId, setContextIdentity, setNodeUrl, setTokenNodeUrl, themeToCssVars, useAccountEnrolment, 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 };
3868
+ export { AccountSignInPanel, AppMode, CalimeroLogo, ConnectButton, ConnectButtonAccount, 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, isFinalInvitationError, isReturningFromWallet, localStorageTokenStorage, resolveMeroTheme, setApplicationId, setContextId, setContextIdentity, setNodeUrl, setTokenNodeUrl, themeToCssVars, useAccountEnrolment, 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 };
5028
3869
  //# sourceMappingURL=index.js.map
5029
3870
  //# sourceMappingURL=index.js.map