@calimero-network/mero-react 9.2.0 → 9.3.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.cjs +1384 -41
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +764 -17
- package/dist/index.d.ts +764 -17
- package/dist/index.js +1367 -43
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.cjs
CHANGED
|
@@ -280,6 +280,293 @@ function clearAllStorage() {
|
|
|
280
280
|
localStorage.removeItem(key);
|
|
281
281
|
});
|
|
282
282
|
}
|
|
283
|
+
var KEY = "calimero.delegated.connection";
|
|
284
|
+
var CREDENTIAL_KEY = "calimero.delegated.credential";
|
|
285
|
+
function readDelegatedSession() {
|
|
286
|
+
if (typeof sessionStorage === "undefined") return null;
|
|
287
|
+
try {
|
|
288
|
+
const raw = sessionStorage.getItem(KEY);
|
|
289
|
+
return raw ? JSON.parse(raw) : null;
|
|
290
|
+
} catch {
|
|
291
|
+
return null;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
function saveDelegatedSession(s) {
|
|
295
|
+
try {
|
|
296
|
+
sessionStorage.setItem(KEY, JSON.stringify(s));
|
|
297
|
+
} catch {
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
function clearDelegatedSession() {
|
|
301
|
+
try {
|
|
302
|
+
sessionStorage.removeItem(KEY);
|
|
303
|
+
} catch {
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
function readDelegatedCredential() {
|
|
307
|
+
const session = readDelegatedSession();
|
|
308
|
+
if (session) {
|
|
309
|
+
const { account, credential, deviceSecret } = session;
|
|
310
|
+
return { account, credential, deviceSecret };
|
|
311
|
+
}
|
|
312
|
+
if (typeof sessionStorage === "undefined") return null;
|
|
313
|
+
try {
|
|
314
|
+
const raw = sessionStorage.getItem(CREDENTIAL_KEY);
|
|
315
|
+
if (!raw) return null;
|
|
316
|
+
const parsed = JSON.parse(raw);
|
|
317
|
+
if (!parsed.account || !parsed.credential || !parsed.deviceSecret) return null;
|
|
318
|
+
return parsed;
|
|
319
|
+
} catch {
|
|
320
|
+
return null;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
function saveDelegatedCredential(c) {
|
|
324
|
+
try {
|
|
325
|
+
sessionStorage.setItem(CREDENTIAL_KEY, JSON.stringify(c));
|
|
326
|
+
} catch {
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
function clearDelegatedCredential() {
|
|
330
|
+
try {
|
|
331
|
+
sessionStorage.removeItem(CREDENTIAL_KEY);
|
|
332
|
+
} catch {
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
function persistedNonces(relayUrl, contextId) {
|
|
336
|
+
const key = `calimero.nonce.${relayUrl}.${contextId ?? "no-context"}`;
|
|
337
|
+
return {
|
|
338
|
+
next: async () => {
|
|
339
|
+
let n = 0n;
|
|
340
|
+
try {
|
|
341
|
+
n = BigInt(localStorage.getItem(key) ?? "0");
|
|
342
|
+
} catch {
|
|
343
|
+
n = 0n;
|
|
344
|
+
}
|
|
345
|
+
try {
|
|
346
|
+
localStorage.setItem(key, String(n + 1n));
|
|
347
|
+
} catch {
|
|
348
|
+
}
|
|
349
|
+
return n;
|
|
350
|
+
}
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
function markContextNonceSpent(relayUrl, contextId, nonce) {
|
|
354
|
+
const key = `calimero.nonce.${relayUrl}.${contextId}`;
|
|
355
|
+
try {
|
|
356
|
+
const current = BigInt(localStorage.getItem(key) ?? "0");
|
|
357
|
+
if (current <= nonce) localStorage.setItem(key, String(nonce + 1n));
|
|
358
|
+
} catch {
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
var RELAY_NODE_KEY_PREFIX = "calimero.delegated.relay-node-key.";
|
|
362
|
+
function relayOrigin(relayUrl) {
|
|
363
|
+
return relayUrl.replace(/\/+$/, "");
|
|
364
|
+
}
|
|
365
|
+
function pinRelayNodeKey(relayUrl, nodeKey) {
|
|
366
|
+
localStorage.setItem(RELAY_NODE_KEY_PREFIX + relayOrigin(relayUrl), nodeKey.trim().toLowerCase());
|
|
367
|
+
}
|
|
368
|
+
function readPinnedRelayNodeKey(relayUrl) {
|
|
369
|
+
try {
|
|
370
|
+
const v = localStorage.getItem(RELAY_NODE_KEY_PREFIX + relayOrigin(relayUrl));
|
|
371
|
+
return v && /^[0-9a-f]{64}$/.test(v) ? v : null;
|
|
372
|
+
} catch {
|
|
373
|
+
return null;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
function isLoopback(relayUrl) {
|
|
377
|
+
try {
|
|
378
|
+
const { hostname } = new URL(relayUrl);
|
|
379
|
+
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
|
|
380
|
+
} catch {
|
|
381
|
+
return false;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
var TRUSTED_RELAY_PROFILE = "locked-read-only";
|
|
385
|
+
var MIN_RELAY_RELEASE = "2.3.99";
|
|
386
|
+
var loadedDcap;
|
|
387
|
+
function relayQuoteVerifier(relayUrl) {
|
|
388
|
+
const verify = async (attestation) => {
|
|
389
|
+
loadedDcap ?? (loadedDcap = import('@phala/dcap-qvl').then(
|
|
390
|
+
({ verify: dcapVerify }) => dcapVerify,
|
|
391
|
+
(error) => {
|
|
392
|
+
loadedDcap = void 0;
|
|
393
|
+
throw error;
|
|
394
|
+
}
|
|
395
|
+
));
|
|
396
|
+
return meroJs.createSignedReleaseVerifier({
|
|
397
|
+
dcapVerify: await loadedDcap,
|
|
398
|
+
release: async () => meroJs.fetchNodeRelease(meroJs.cloudNodeReleaseUrl(meroJs.DEFAULT_RELEASE_MIRROR, await meroJs.fetchNodeReleaseVersion(relayUrl))),
|
|
399
|
+
profile: TRUSTED_RELAY_PROFILE,
|
|
400
|
+
minReleaseVersion: MIN_RELAY_RELEASE
|
|
401
|
+
})(attestation);
|
|
402
|
+
};
|
|
403
|
+
return Object.assign(verify, { includeCollateral: true });
|
|
404
|
+
}
|
|
405
|
+
async function resolveRelayNodeKey(relayUrl) {
|
|
406
|
+
const pinned = readPinnedRelayNodeKey(relayUrl);
|
|
407
|
+
if (pinned) return pinned;
|
|
408
|
+
try {
|
|
409
|
+
const local = isLoopback(relayUrl);
|
|
410
|
+
const { nodeKey } = await meroJs.attestRelayNodeKey({
|
|
411
|
+
relayUrl,
|
|
412
|
+
allowMock: local,
|
|
413
|
+
...local ? {} : { verify: relayQuoteVerifier(relayUrl) }
|
|
414
|
+
});
|
|
415
|
+
pinRelayNodeKey(relayUrl, nodeKey);
|
|
416
|
+
return nodeKey;
|
|
417
|
+
} catch (e) {
|
|
418
|
+
console.warn("[mero-react] could not learn the relay node key from its attestation", e);
|
|
419
|
+
return null;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
function jwtExpiryMs(token) {
|
|
423
|
+
try {
|
|
424
|
+
const payload = JSON.parse(atob(token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")));
|
|
425
|
+
return typeof payload.exp === "number" ? payload.exp * 1e3 : null;
|
|
426
|
+
} catch {
|
|
427
|
+
return null;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
function relaySession(s, nodeKey) {
|
|
431
|
+
let token = null;
|
|
432
|
+
let inflight = null;
|
|
433
|
+
return async () => {
|
|
434
|
+
const exp = token ? jwtExpiryMs(token) : null;
|
|
435
|
+
if (token && (exp === null || exp - Date.now() > 3e4)) return token;
|
|
436
|
+
if (!inflight) {
|
|
437
|
+
inflight = meroJs.login({
|
|
438
|
+
nodeUrl: s.relayUrl,
|
|
439
|
+
node: nodeKey,
|
|
440
|
+
deviceSecret: s.deviceSecret,
|
|
441
|
+
accountProof: s.credential,
|
|
442
|
+
audience: meroJs.defaultAudience()
|
|
443
|
+
}).then((minted) => {
|
|
444
|
+
token = minted.accessToken;
|
|
445
|
+
return token;
|
|
446
|
+
}).catch((e) => {
|
|
447
|
+
console.warn("[mero-react] relay login failed", e);
|
|
448
|
+
token = null;
|
|
449
|
+
return void 0;
|
|
450
|
+
}).finally(() => {
|
|
451
|
+
inflight = null;
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
return inflight;
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
function buildDelegatedClient(s, contextId) {
|
|
458
|
+
if (!s.relayUrl) return null;
|
|
459
|
+
const nodeKey = readPinnedRelayNodeKey(s.relayUrl);
|
|
460
|
+
return meroJs.createMeroClient({
|
|
461
|
+
transport: "relay",
|
|
462
|
+
relay: {
|
|
463
|
+
relayUrl: s.relayUrl,
|
|
464
|
+
authorAccount: s.account,
|
|
465
|
+
authorProof: s.credential,
|
|
466
|
+
deviceSecret: s.deviceSecret,
|
|
467
|
+
// The active context, passed in rather than stored on the record: the
|
|
468
|
+
// relay client holds ONE nonce source while `execute` takes a context per
|
|
469
|
+
// call, so the ledger has to be re-keyed when the chosen context changes.
|
|
470
|
+
nonces: persistedNonces(s.relayUrl, contextId)
|
|
471
|
+
},
|
|
472
|
+
// The certificate authenticates the requests too, not just the writes.
|
|
473
|
+
//
|
|
474
|
+
// This is the whole of what reads and events need: the device key signs each
|
|
475
|
+
// request, and the node verifies it against the account's certificate with no
|
|
476
|
+
// store read and no prior relationship. Measured against a node built from
|
|
477
|
+
// core `aecba573b`: `listNamespaces` and `getContexts` answer `200` and are
|
|
478
|
+
// caller-scoped, `/sse` answers `200`, and a real write arrives on the stream
|
|
479
|
+
// as a `StateMutation` frame.
|
|
480
|
+
//
|
|
481
|
+
// What this replaces is a session minted by `login()` plus the relay node's
|
|
482
|
+
// signing key learned out of band — two inputs, one of which the cloud does
|
|
483
|
+
// not publish, for an answer the certificate already gives.
|
|
484
|
+
proof: { credential: s.credential, deviceSecret: s.deviceSecret },
|
|
485
|
+
// A session, when this relay's node key is pinned. A hosted relay's
|
|
486
|
+
// forward-auth accepts a Bearer token and not the proof above, so without
|
|
487
|
+
// one every admin read there is a 401. Given a session the client uses it
|
|
488
|
+
// for every admin call; a relay with no pinned key keeps the proof path.
|
|
489
|
+
session: nodeKey ? relaySession({ ...s, relayUrl: s.relayUrl }, nodeKey) : void 0,
|
|
490
|
+
// Events too. `/sse` on a relay sits behind the same forward-auth, so the
|
|
491
|
+
// proof above gets a 401 there; with the node key the client observes
|
|
492
|
+
// through its own device-certificate login instead.
|
|
493
|
+
observe: nodeKey ? { nodeKey } : void 0
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
var RELAY_MAP_PREFIX = "calimero.delegated.relays.";
|
|
497
|
+
function readRelayMap(account) {
|
|
498
|
+
try {
|
|
499
|
+
const raw = localStorage.getItem(RELAY_MAP_PREFIX + account);
|
|
500
|
+
const parsed = raw ? JSON.parse(raw) : {};
|
|
501
|
+
return { namespaces: parsed.namespaces ?? {}, contexts: parsed.contexts ?? {} };
|
|
502
|
+
} catch {
|
|
503
|
+
return { namespaces: {}, contexts: {} };
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
function writeRelayMap(account, map) {
|
|
507
|
+
try {
|
|
508
|
+
localStorage.setItem(RELAY_MAP_PREFIX + account, JSON.stringify(map));
|
|
509
|
+
} catch {
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
function rememberRelay(account, relayUrl, at) {
|
|
513
|
+
const map = readRelayMap(account);
|
|
514
|
+
const url = relayOrigin(relayUrl);
|
|
515
|
+
if (at.namespaceId) map.namespaces[at.namespaceId] = url;
|
|
516
|
+
if (at.contextId) map.contexts[at.contextId] = url;
|
|
517
|
+
writeRelayMap(account, map);
|
|
518
|
+
}
|
|
519
|
+
function relayForContext(account, contextId) {
|
|
520
|
+
return readRelayMap(account).contexts[contextId] ?? null;
|
|
521
|
+
}
|
|
522
|
+
function knownRelays(s) {
|
|
523
|
+
const map = readRelayMap(s.account);
|
|
524
|
+
const all = [s.relayUrl, ...Object.values(map.namespaces), ...Object.values(map.contexts)].filter((u) => typeof u === "string" && u.length > 0).map(relayOrigin);
|
|
525
|
+
return [...new Set(all)];
|
|
526
|
+
}
|
|
527
|
+
async function listDelegatedContexts(s) {
|
|
528
|
+
const out = [];
|
|
529
|
+
const map = readRelayMap(s.account);
|
|
530
|
+
for (const relayUrl of knownRelays(s)) {
|
|
531
|
+
try {
|
|
532
|
+
if (!await resolveRelayNodeKey(relayUrl)) continue;
|
|
533
|
+
const client2 = buildDelegatedClient({ ...s, relayUrl }, null);
|
|
534
|
+
if (!client2) continue;
|
|
535
|
+
const { contexts } = await client2.admin.getContexts();
|
|
536
|
+
for (const c of contexts ?? []) {
|
|
537
|
+
out.push({ ...c, relayUrl });
|
|
538
|
+
map.contexts[c.id] = relayUrl;
|
|
539
|
+
}
|
|
540
|
+
} catch (e) {
|
|
541
|
+
console.warn(`[mero-react] could not list contexts on ${relayUrl}`, e);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
writeRelayMap(s.account, map);
|
|
545
|
+
return out;
|
|
546
|
+
}
|
|
547
|
+
async function listDelegatedNamespaces(s) {
|
|
548
|
+
var _a, _b;
|
|
549
|
+
const out = [];
|
|
550
|
+
const seen = /* @__PURE__ */ new Set();
|
|
551
|
+
const map = readRelayMap(s.account);
|
|
552
|
+
for (const relayUrl of knownRelays(s)) {
|
|
553
|
+
try {
|
|
554
|
+
if (!await resolveRelayNodeKey(relayUrl)) continue;
|
|
555
|
+
const client2 = buildDelegatedClient({ ...s, relayUrl }, null);
|
|
556
|
+
if (!client2) continue;
|
|
557
|
+
for (const ns of await client2.admin.listNamespaces()) {
|
|
558
|
+
if (seen.has(ns.namespaceId)) continue;
|
|
559
|
+
seen.add(ns.namespaceId);
|
|
560
|
+
out.push({ ...ns, relayUrl });
|
|
561
|
+
(_a = map.namespaces)[_b = ns.namespaceId] ?? (_a[_b] = relayUrl);
|
|
562
|
+
}
|
|
563
|
+
} catch (e) {
|
|
564
|
+
console.warn(`[mero-react] could not list namespaces on ${relayUrl}`, e);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
writeRelayMap(s.account, map);
|
|
568
|
+
return out;
|
|
569
|
+
}
|
|
283
570
|
var MeroContext = react.createContext(null);
|
|
284
571
|
var isBrowser = typeof window !== "undefined";
|
|
285
572
|
function getPermissionsForMode(mode) {
|
|
@@ -326,6 +613,9 @@ function MeroProvider({
|
|
|
326
613
|
[tokenStoreProp]
|
|
327
614
|
);
|
|
328
615
|
const [mero, setMero] = react.useState(null);
|
|
616
|
+
const [delegated, setDelegated] = react.useState(
|
|
617
|
+
() => readDelegatedSession()
|
|
618
|
+
);
|
|
329
619
|
const [isAuthenticated, setIsAuthenticated] = react.useState(false);
|
|
330
620
|
const [isOnline, setIsOnline] = react.useState(true);
|
|
331
621
|
const [isLoading, setIsLoading] = react.useState(true);
|
|
@@ -394,6 +684,12 @@ function MeroProvider({
|
|
|
394
684
|
},
|
|
395
685
|
[mode, packageName, packageVersion, registryUrl]
|
|
396
686
|
);
|
|
687
|
+
const connectWithAccount = react.useCallback((session) => {
|
|
688
|
+
saveDelegatedSession(session);
|
|
689
|
+
const { account, credential, deviceSecret } = session;
|
|
690
|
+
saveDelegatedCredential({ account, credential, deviceSecret });
|
|
691
|
+
setDelegated(session);
|
|
692
|
+
}, []);
|
|
397
693
|
const logout = react.useCallback(() => {
|
|
398
694
|
if (meroRef.current) {
|
|
399
695
|
meroRef.current.clearToken();
|
|
@@ -401,6 +697,9 @@ function MeroProvider({
|
|
|
401
697
|
}
|
|
402
698
|
tokenStore.clear();
|
|
403
699
|
clearAllStorage();
|
|
700
|
+
clearDelegatedSession();
|
|
701
|
+
clearDelegatedCredential();
|
|
702
|
+
setDelegated(null);
|
|
404
703
|
setMero(null);
|
|
405
704
|
setIsAuthenticated(false);
|
|
406
705
|
setNodeUrlState(null);
|
|
@@ -410,6 +709,44 @@ function MeroProvider({
|
|
|
410
709
|
meroRef.current = null;
|
|
411
710
|
}, [tokenStore]);
|
|
412
711
|
react.useEffect(() => {
|
|
712
|
+
if (!delegated) return;
|
|
713
|
+
const relayUrl = (contextId ? relayForContext(delegated.account, contextId) : null) ?? delegated.relayUrl;
|
|
714
|
+
const routed = { ...delegated, relayUrl };
|
|
715
|
+
const client2 = buildDelegatedClient(routed, contextId);
|
|
716
|
+
const awaitingKey = Boolean(client2 && relayUrl && !readPinnedRelayNodeKey(relayUrl));
|
|
717
|
+
if (!awaitingKey) setMero(client2);
|
|
718
|
+
setIsAuthenticated(true);
|
|
719
|
+
setIsOnline(true);
|
|
720
|
+
setNodeUrlState(relayUrl);
|
|
721
|
+
setIsLoading(awaitingKey);
|
|
722
|
+
let active = true;
|
|
723
|
+
(async () => {
|
|
724
|
+
if (!client2 || !relayUrl) return;
|
|
725
|
+
if (awaitingKey) {
|
|
726
|
+
const nodeKey = await resolveRelayNodeKey(relayUrl);
|
|
727
|
+
if (!active) return;
|
|
728
|
+
setMero(nodeKey ? buildDelegatedClient(routed, contextId) ?? client2 : client2);
|
|
729
|
+
setIsLoading(false);
|
|
730
|
+
if (!nodeKey) return;
|
|
731
|
+
}
|
|
732
|
+
try {
|
|
733
|
+
const contexts = await listDelegatedContexts(delegated);
|
|
734
|
+
const apps = [
|
|
735
|
+
...new Set((contexts ?? []).map((c) => c.applicationId).filter(Boolean))
|
|
736
|
+
];
|
|
737
|
+
if (!active) return;
|
|
738
|
+
if (apps.length === 1) {
|
|
739
|
+
setApplicationIdState(apps[0]);
|
|
740
|
+
}
|
|
741
|
+
} catch {
|
|
742
|
+
}
|
|
743
|
+
})();
|
|
744
|
+
return () => {
|
|
745
|
+
active = false;
|
|
746
|
+
};
|
|
747
|
+
}, [delegated, contextId]);
|
|
748
|
+
react.useEffect(() => {
|
|
749
|
+
if (delegated) return;
|
|
413
750
|
let active = true;
|
|
414
751
|
const init = async () => {
|
|
415
752
|
const callback = callbackRef.current;
|
|
@@ -487,7 +824,7 @@ function MeroProvider({
|
|
|
487
824
|
return () => {
|
|
488
825
|
active = false;
|
|
489
826
|
};
|
|
490
|
-
}, [createMeroInstance, checkAuth, allowedNodeUrls, tokenStore]);
|
|
827
|
+
}, [createMeroInstance, checkAuth, allowedNodeUrls, tokenStore, delegated]);
|
|
491
828
|
react.useEffect(() => {
|
|
492
829
|
if (!isAuthenticated || !meroRef.current) return;
|
|
493
830
|
let active = true;
|
|
@@ -498,6 +835,7 @@ function MeroProvider({
|
|
|
498
835
|
const onError = (err) => {
|
|
499
836
|
if (!active) return;
|
|
500
837
|
setIsOnline(false);
|
|
838
|
+
if (delegated) return;
|
|
501
839
|
if (err instanceof meroJs.AuthRevokedError) {
|
|
502
840
|
logout();
|
|
503
841
|
return;
|
|
@@ -541,7 +879,7 @@ function MeroProvider({
|
|
|
541
879
|
sse.off("connect", onConnect);
|
|
542
880
|
sse.off("error", onError);
|
|
543
881
|
};
|
|
544
|
-
}, [isAuthenticated, mero, checkAuth, logout]);
|
|
882
|
+
}, [isAuthenticated, mero, checkAuth, logout, delegated]);
|
|
545
883
|
const contextValue = react.useMemo(
|
|
546
884
|
() => ({
|
|
547
885
|
mero,
|
|
@@ -552,10 +890,14 @@ function MeroProvider({
|
|
|
552
890
|
contextId,
|
|
553
891
|
contextIdentity,
|
|
554
892
|
connectToNode,
|
|
893
|
+
connectWithAccount,
|
|
894
|
+
isDelegated: delegated !== null,
|
|
895
|
+
can: delegated !== null ? { createNamespace: Boolean(packageName), createContext: true, invite: false } : { createNamespace: true, createContext: true, invite: true },
|
|
896
|
+
app: { packageName, packageVersion, registryUrl },
|
|
555
897
|
logout,
|
|
556
898
|
isLoading
|
|
557
899
|
}),
|
|
558
|
-
[mero, isAuthenticated, isOnline, nodeUrl, applicationId, contextId, contextIdentity, connectToNode, logout, isLoading]
|
|
900
|
+
[mero, isAuthenticated, isOnline, nodeUrl, applicationId, contextId, contextIdentity, connectToNode, connectWithAccount, delegated, logout, isLoading, packageName, packageVersion, registryUrl]
|
|
559
901
|
);
|
|
560
902
|
return /* @__PURE__ */ jsxRuntime.jsx(MeroContext.Provider, { value: contextValue, children });
|
|
561
903
|
}
|
|
@@ -1287,6 +1629,314 @@ function ConnectButton({
|
|
|
1287
1629
|
}
|
|
1288
1630
|
);
|
|
1289
1631
|
}
|
|
1632
|
+
var DEVICE_KEY = "calimero.device";
|
|
1633
|
+
var STATE_KEY = "calimero.enrol.state";
|
|
1634
|
+
var HOSTED_WALLET = "https://wallet.cloud.calimero.network/account-enroll";
|
|
1635
|
+
var hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
|
|
1636
|
+
function chooseRelay(relays) {
|
|
1637
|
+
const reachable = relays.filter(
|
|
1638
|
+
(r) => typeof r.relayUrl === "string" && r.relayUrl.length > 0
|
|
1639
|
+
);
|
|
1640
|
+
const fresh = reachable.find((r) => r.fresh);
|
|
1641
|
+
if (fresh) return { relayUrl: fresh.relayUrl, note: null };
|
|
1642
|
+
if (reachable.length > 0) {
|
|
1643
|
+
return {
|
|
1644
|
+
relayUrl: reachable[0].relayUrl,
|
|
1645
|
+
note: "Connected through a relay whose last heartbeat has lapsed \u2014 it may not answer. It was the only one with an address."
|
|
1646
|
+
};
|
|
1647
|
+
}
|
|
1648
|
+
if (relays.length > 0) {
|
|
1649
|
+
return {
|
|
1650
|
+
relayUrl: null,
|
|
1651
|
+
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.`
|
|
1652
|
+
};
|
|
1653
|
+
}
|
|
1654
|
+
return {
|
|
1655
|
+
relayUrl: null,
|
|
1656
|
+
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."
|
|
1657
|
+
};
|
|
1658
|
+
}
|
|
1659
|
+
async function deviceKeys() {
|
|
1660
|
+
const had = localStorage.getItem(DEVICE_KEY);
|
|
1661
|
+
if (had) {
|
|
1662
|
+
const parsed = JSON.parse(had);
|
|
1663
|
+
if (parsed.kemSk && parsed.signSk && parsed.signPk && parsed.kemPk) {
|
|
1664
|
+
return parsed;
|
|
1665
|
+
}
|
|
1666
|
+
localStorage.removeItem(DEVICE_KEY);
|
|
1667
|
+
}
|
|
1668
|
+
const sign = await crypto.subtle.generateKey({ name: "Ed25519" }, true, [
|
|
1669
|
+
"sign",
|
|
1670
|
+
"verify"
|
|
1671
|
+
]);
|
|
1672
|
+
let agree;
|
|
1673
|
+
try {
|
|
1674
|
+
agree = await crypto.subtle.generateKey({ name: "X25519" }, true, [
|
|
1675
|
+
"deriveBits"
|
|
1676
|
+
]);
|
|
1677
|
+
} catch {
|
|
1678
|
+
throw new Error(
|
|
1679
|
+
"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."
|
|
1680
|
+
);
|
|
1681
|
+
}
|
|
1682
|
+
const keys = {
|
|
1683
|
+
signPk: hex(await crypto.subtle.exportKey("raw", sign.publicKey)),
|
|
1684
|
+
signSk: hex((await crypto.subtle.exportKey("pkcs8", sign.privateKey)).slice(16)),
|
|
1685
|
+
kemPk: hex(await crypto.subtle.exportKey("raw", agree.publicKey)),
|
|
1686
|
+
kemSk: hex((await crypto.subtle.exportKey("pkcs8", agree.privateKey)).slice(16))
|
|
1687
|
+
};
|
|
1688
|
+
localStorage.setItem(DEVICE_KEY, JSON.stringify(keys));
|
|
1689
|
+
return keys;
|
|
1690
|
+
}
|
|
1691
|
+
function ConnectButtonAccount({
|
|
1692
|
+
className,
|
|
1693
|
+
style,
|
|
1694
|
+
theme,
|
|
1695
|
+
defaults = {}
|
|
1696
|
+
}) {
|
|
1697
|
+
const { isAuthenticated, isOnline, nodeUrl, isDelegated, connectToNode, connectWithAccount, logout } = useMero();
|
|
1698
|
+
const [isDropdownOpen, setIsDropdownOpen] = react.useState(false);
|
|
1699
|
+
const [isNodeModalOpen, setIsNodeModalOpen] = react.useState(false);
|
|
1700
|
+
const [isAccountOpen, setIsAccountOpen] = react.useState(false);
|
|
1701
|
+
const [note, setNote] = react.useState(null);
|
|
1702
|
+
const dropdownRef = react.useRef(null);
|
|
1703
|
+
const walletUrl = defaults.walletUrl ?? HOSTED_WALLET;
|
|
1704
|
+
const resolvedTheme = react.useMemo(() => theme ? resolveMeroTheme(theme) : null, [theme]);
|
|
1705
|
+
const themeVars = react.useMemo(
|
|
1706
|
+
() => resolvedTheme ? themeToCssVars(resolvedTheme) : void 0,
|
|
1707
|
+
[resolvedTheme]
|
|
1708
|
+
);
|
|
1709
|
+
react.useEffect(() => {
|
|
1710
|
+
const onOutside = (e) => {
|
|
1711
|
+
if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
|
|
1712
|
+
setIsDropdownOpen(false);
|
|
1713
|
+
}
|
|
1714
|
+
};
|
|
1715
|
+
document.addEventListener("mousedown", onOutside);
|
|
1716
|
+
return () => document.removeEventListener("mousedown", onOutside);
|
|
1717
|
+
}, []);
|
|
1718
|
+
const callbackRef = react.useRef(void 0);
|
|
1719
|
+
const callbackErrorRef = react.useRef(null);
|
|
1720
|
+
if (callbackRef.current === void 0 && typeof window !== "undefined") {
|
|
1721
|
+
try {
|
|
1722
|
+
callbackRef.current = meroJs.readEnrolmentCallback();
|
|
1723
|
+
} catch (e) {
|
|
1724
|
+
callbackRef.current = null;
|
|
1725
|
+
callbackErrorRef.current = e instanceof Error ? e.message : String(e);
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
const completingRef = react.useRef(false);
|
|
1729
|
+
react.useEffect(() => {
|
|
1730
|
+
if (callbackErrorRef.current) {
|
|
1731
|
+
setNote(callbackErrorRef.current);
|
|
1732
|
+
callbackErrorRef.current = null;
|
|
1733
|
+
return;
|
|
1734
|
+
}
|
|
1735
|
+
const back = callbackRef.current;
|
|
1736
|
+
if (!back || completingRef.current) return;
|
|
1737
|
+
completingRef.current = true;
|
|
1738
|
+
let cancelled = false;
|
|
1739
|
+
(async () => {
|
|
1740
|
+
try {
|
|
1741
|
+
const keys = await deviceKeys();
|
|
1742
|
+
const sent = (() => {
|
|
1743
|
+
try {
|
|
1744
|
+
return sessionStorage.getItem(STATE_KEY);
|
|
1745
|
+
} catch {
|
|
1746
|
+
return null;
|
|
1747
|
+
}
|
|
1748
|
+
})();
|
|
1749
|
+
try {
|
|
1750
|
+
sessionStorage.removeItem(STATE_KEY);
|
|
1751
|
+
} catch {
|
|
1752
|
+
}
|
|
1753
|
+
if (!sent) {
|
|
1754
|
+
setNote(
|
|
1755
|
+
'This enrolment could not be verified as one this tab started, so it was not accepted. Start again from "Enrol with your account".'
|
|
1756
|
+
);
|
|
1757
|
+
return;
|
|
1758
|
+
}
|
|
1759
|
+
const enrolled = await meroJs.completeDeviceEnrolment({
|
|
1760
|
+
...back,
|
|
1761
|
+
devicePublicKey: keys.signPk,
|
|
1762
|
+
kemPublicKey: keys.kemPk,
|
|
1763
|
+
expectState: sent
|
|
1764
|
+
});
|
|
1765
|
+
saveDelegatedCredential({
|
|
1766
|
+
account: enrolled.account,
|
|
1767
|
+
credential: enrolled.credential,
|
|
1768
|
+
deviceSecret: keys.signSk
|
|
1769
|
+
});
|
|
1770
|
+
const cloud = new meroJs.CloudClient({
|
|
1771
|
+
routingCredential: {
|
|
1772
|
+
credential: enrolled.credential,
|
|
1773
|
+
deviceSecret: keys.signSk
|
|
1774
|
+
}
|
|
1775
|
+
});
|
|
1776
|
+
const chosen = chooseRelay(await cloud.getAccountRelays(enrolled.account));
|
|
1777
|
+
if (chosen.note) setNote(chosen.note);
|
|
1778
|
+
connectWithAccount({
|
|
1779
|
+
relayUrl: chosen.relayUrl,
|
|
1780
|
+
account: enrolled.account,
|
|
1781
|
+
credential: enrolled.credential,
|
|
1782
|
+
deviceSecret: keys.signSk
|
|
1783
|
+
});
|
|
1784
|
+
} catch (e) {
|
|
1785
|
+
if (!cancelled) setNote(e instanceof Error ? e.message : String(e));
|
|
1786
|
+
}
|
|
1787
|
+
})();
|
|
1788
|
+
return () => {
|
|
1789
|
+
cancelled = true;
|
|
1790
|
+
};
|
|
1791
|
+
}, [connectWithAccount]);
|
|
1792
|
+
const goToWallet = react.useCallback(async () => {
|
|
1793
|
+
const keys = await deviceKeys();
|
|
1794
|
+
const state = hex(crypto.getRandomValues(new Uint8Array(16)));
|
|
1795
|
+
try {
|
|
1796
|
+
sessionStorage.setItem(STATE_KEY, state);
|
|
1797
|
+
} catch {
|
|
1798
|
+
}
|
|
1799
|
+
window.location.assign(
|
|
1800
|
+
meroJs.deviceEnrolmentUrl({
|
|
1801
|
+
walletUrl,
|
|
1802
|
+
devicePublicKey: keys.signPk,
|
|
1803
|
+
kemPublicKey: keys.kemPk,
|
|
1804
|
+
returnTo: window.location.origin + window.location.pathname,
|
|
1805
|
+
state
|
|
1806
|
+
})
|
|
1807
|
+
);
|
|
1808
|
+
}, [walletUrl]);
|
|
1809
|
+
if (isAuthenticated && !isOnline) {
|
|
1810
|
+
return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mero-connect-container", style: { ...themeVars, display: "inline-block" }, children: /* @__PURE__ */ jsxRuntime.jsxs(
|
|
1811
|
+
"button",
|
|
1812
|
+
{
|
|
1813
|
+
className: ["mero-connect-button", "mero-reconnecting", className].filter(Boolean).join(" "),
|
|
1814
|
+
style,
|
|
1815
|
+
disabled: true,
|
|
1816
|
+
"aria-label": "Reconnecting...",
|
|
1817
|
+
children: [
|
|
1818
|
+
/* @__PURE__ */ jsxRuntime.jsx(CalimeroLogo, { size: 18, className: "mero-logo" }),
|
|
1819
|
+
"Reconnecting..."
|
|
1820
|
+
]
|
|
1821
|
+
}
|
|
1822
|
+
) });
|
|
1823
|
+
}
|
|
1824
|
+
if (isAuthenticated) {
|
|
1825
|
+
return /* @__PURE__ */ jsxRuntime.jsxs(
|
|
1826
|
+
"div",
|
|
1827
|
+
{
|
|
1828
|
+
ref: dropdownRef,
|
|
1829
|
+
className: "mero-connect-container",
|
|
1830
|
+
style: { ...themeVars, position: "relative", display: "inline-block" },
|
|
1831
|
+
children: [
|
|
1832
|
+
/* @__PURE__ */ jsxRuntime.jsxs(
|
|
1833
|
+
"button",
|
|
1834
|
+
{
|
|
1835
|
+
className: ["mero-connect-button", "mero-connected", className].filter(Boolean).join(" "),
|
|
1836
|
+
style,
|
|
1837
|
+
onClick: () => setIsDropdownOpen((p) => !p),
|
|
1838
|
+
"aria-label": "Connected",
|
|
1839
|
+
children: [
|
|
1840
|
+
/* @__PURE__ */ jsxRuntime.jsx(CalimeroLogo, { size: 18, className: "mero-logo" }),
|
|
1841
|
+
isDelegated ? "Connected (account)" : "Connected"
|
|
1842
|
+
]
|
|
1843
|
+
}
|
|
1844
|
+
),
|
|
1845
|
+
isDropdownOpen && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mero-dropdown", children: [
|
|
1846
|
+
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "mero-dropdown-info", title: nodeUrl || "", children: nodeUrl ?? (isDelegated ? "no relay yet" : null) }),
|
|
1847
|
+
!isDelegated && nodeUrl && /* @__PURE__ */ jsxRuntime.jsx(
|
|
1848
|
+
"a",
|
|
1849
|
+
{
|
|
1850
|
+
href: new URL("admin-dashboard/", nodeUrl).toString(),
|
|
1851
|
+
target: "_blank",
|
|
1852
|
+
rel: "noopener noreferrer",
|
|
1853
|
+
className: "mero-dropdown-item",
|
|
1854
|
+
children: "Dashboard"
|
|
1855
|
+
}
|
|
1856
|
+
),
|
|
1857
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
|
1858
|
+
"button",
|
|
1859
|
+
{
|
|
1860
|
+
className: "mero-dropdown-item",
|
|
1861
|
+
onClick: () => {
|
|
1862
|
+
setIsDropdownOpen(false);
|
|
1863
|
+
logout();
|
|
1864
|
+
},
|
|
1865
|
+
children: "Log out"
|
|
1866
|
+
}
|
|
1867
|
+
)
|
|
1868
|
+
] })
|
|
1869
|
+
]
|
|
1870
|
+
}
|
|
1871
|
+
);
|
|
1872
|
+
}
|
|
1873
|
+
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mero-connect-container", style: { ...themeVars, display: "inline-block" }, children: [
|
|
1874
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { style: { display: "flex", gap: 8, flexWrap: "wrap" }, children: [
|
|
1875
|
+
/* @__PURE__ */ jsxRuntime.jsxs(
|
|
1876
|
+
"button",
|
|
1877
|
+
{
|
|
1878
|
+
className: ["mero-connect-button", className].filter(Boolean).join(" "),
|
|
1879
|
+
style,
|
|
1880
|
+
onClick: () => setIsNodeModalOpen(true),
|
|
1881
|
+
children: [
|
|
1882
|
+
/* @__PURE__ */ jsxRuntime.jsx(CalimeroLogo, { size: 18, className: "mero-logo" }),
|
|
1883
|
+
"I run a node"
|
|
1884
|
+
]
|
|
1885
|
+
}
|
|
1886
|
+
),
|
|
1887
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
|
1888
|
+
"button",
|
|
1889
|
+
{
|
|
1890
|
+
className: ["mero-connect-button", className].filter(Boolean).join(" "),
|
|
1891
|
+
style,
|
|
1892
|
+
onClick: () => setIsAccountOpen((p) => !p),
|
|
1893
|
+
children: "I have an account"
|
|
1894
|
+
}
|
|
1895
|
+
)
|
|
1896
|
+
] }),
|
|
1897
|
+
isAccountOpen && /* @__PURE__ */ jsxRuntime.jsxs(
|
|
1898
|
+
"div",
|
|
1899
|
+
{
|
|
1900
|
+
style: {
|
|
1901
|
+
marginTop: 12,
|
|
1902
|
+
padding: 14,
|
|
1903
|
+
border: "1px solid rgba(127,127,127,.35)",
|
|
1904
|
+
borderRadius: 8,
|
|
1905
|
+
display: "grid",
|
|
1906
|
+
gap: 8,
|
|
1907
|
+
maxWidth: 520,
|
|
1908
|
+
textAlign: "left",
|
|
1909
|
+
font: "13px system-ui, sans-serif"
|
|
1910
|
+
},
|
|
1911
|
+
children: [
|
|
1912
|
+
/* @__PURE__ */ jsxRuntime.jsx("button", { className: "mero-connect-button", onClick: goToWallet, children: "Enrol with your account" }),
|
|
1913
|
+
/* @__PURE__ */ jsxRuntime.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." }),
|
|
1914
|
+
/* @__PURE__ */ jsxRuntime.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." }),
|
|
1915
|
+
defaults.walletUrl && /* Shown only when an app overrode it, so a local rig can see at a
|
|
1916
|
+
glance that it is not enrolling against the hosted wallet. */
|
|
1917
|
+
/* @__PURE__ */ jsxRuntime.jsxs("p", { style: { margin: 0, opacity: 0.6 }, children: [
|
|
1918
|
+
"Enrolling at ",
|
|
1919
|
+
/* @__PURE__ */ jsxRuntime.jsx("code", { children: walletUrl }),
|
|
1920
|
+
", not the hosted wallet."
|
|
1921
|
+
] })
|
|
1922
|
+
]
|
|
1923
|
+
}
|
|
1924
|
+
),
|
|
1925
|
+
note && /* @__PURE__ */ jsxRuntime.jsx("p", { style: { font: "13px system-ui, sans-serif", color: "#b3261e" }, children: note }),
|
|
1926
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
|
1927
|
+
LoginModal,
|
|
1928
|
+
{
|
|
1929
|
+
isOpen: isNodeModalOpen,
|
|
1930
|
+
onConnect: (url) => {
|
|
1931
|
+
setIsNodeModalOpen(false);
|
|
1932
|
+
connectToNode(url);
|
|
1933
|
+
},
|
|
1934
|
+
onClose: () => setIsNodeModalOpen(false),
|
|
1935
|
+
theme: resolvedTheme ?? theme
|
|
1936
|
+
}
|
|
1937
|
+
)
|
|
1938
|
+
] });
|
|
1939
|
+
}
|
|
1290
1940
|
|
|
1291
1941
|
// src/utils/base58.ts
|
|
1292
1942
|
var ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
@@ -1308,6 +1958,159 @@ function base58ToHex(input) {
|
|
|
1308
1958
|
for (let k = 0; k < input.length && input[k] === "1"; k++) bytes.push(0);
|
|
1309
1959
|
return bytes.reverse().map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
1310
1960
|
}
|
|
1961
|
+
function governanceNonce(relay, group) {
|
|
1962
|
+
return { next: async () => nextGovernanceNonce(relay, group) };
|
|
1963
|
+
}
|
|
1964
|
+
function nextGovernanceNonce(relay, group) {
|
|
1965
|
+
const key = `calimero.governance-nonce.${relay}.${group}`;
|
|
1966
|
+
let last = 0n;
|
|
1967
|
+
try {
|
|
1968
|
+
last = BigInt(localStorage.getItem(key) ?? "0");
|
|
1969
|
+
} catch {
|
|
1970
|
+
}
|
|
1971
|
+
const next = [last + 1n, BigInt(Date.now())].reduce((a, b) => a > b ? a : b);
|
|
1972
|
+
try {
|
|
1973
|
+
localStorage.setItem(key, String(next));
|
|
1974
|
+
} catch {
|
|
1975
|
+
}
|
|
1976
|
+
return next;
|
|
1977
|
+
}
|
|
1978
|
+
function relayFor(s, namespaceId) {
|
|
1979
|
+
const url = readRelayMap(s.account).namespaces[namespaceId] ?? s.relayUrl;
|
|
1980
|
+
if (!url) throw new Error("no relay is known for this namespace, so there is nowhere to send this");
|
|
1981
|
+
return url.replace(/\/+$/, "");
|
|
1982
|
+
}
|
|
1983
|
+
function initArgsOf(params) {
|
|
1984
|
+
if (!params || params.length === 0) return {};
|
|
1985
|
+
return JSON.parse(new TextDecoder().decode(Uint8Array.from(params)));
|
|
1986
|
+
}
|
|
1987
|
+
function client(s, relayUrl, nonces, fetch2) {
|
|
1988
|
+
return new meroJs.RelayClient({
|
|
1989
|
+
relayUrl,
|
|
1990
|
+
authorAccount: s.account,
|
|
1991
|
+
authorProof: s.credential,
|
|
1992
|
+
deviceSecret: s.deviceSecret,
|
|
1993
|
+
nonces,
|
|
1994
|
+
fetch: fetch2
|
|
1995
|
+
});
|
|
1996
|
+
}
|
|
1997
|
+
async function createDelegatedContext(s, req, deps = {}) {
|
|
1998
|
+
const relay = relayFor(s, req.namespaceId);
|
|
1999
|
+
const creationNonce = 0n;
|
|
2000
|
+
const created = await client(s, relay, { next: async () => creationNonce }, deps.fetch).createContext({
|
|
2001
|
+
groupId: req.groupId ?? req.namespaceId,
|
|
2002
|
+
applicationId: req.applicationId,
|
|
2003
|
+
initArgs: initArgsOf(req.initializationParams),
|
|
2004
|
+
name: req.name
|
|
2005
|
+
});
|
|
2006
|
+
markContextNonceSpent(relay, created.contextId, creationNonce);
|
|
2007
|
+
rememberRelay(s.account, relay, { namespaceId: req.namespaceId, contextId: created.contextId });
|
|
2008
|
+
return { contextId: created.contextId };
|
|
2009
|
+
}
|
|
2010
|
+
async function delegatedGovernance(s, req, deps = {}) {
|
|
2011
|
+
const relay = relayFor(s, req.namespaceId);
|
|
2012
|
+
return client(s, relay, governanceNonce(relay, req.group), deps.fetch).govern({ groupId: req.group, op: req.op });
|
|
2013
|
+
}
|
|
2014
|
+
async function createDelegatedPrivateContext(s, req, deps = {}) {
|
|
2015
|
+
const { groupId } = await delegatedGovernance(
|
|
2016
|
+
s,
|
|
2017
|
+
{
|
|
2018
|
+
namespaceId: req.namespaceId,
|
|
2019
|
+
group: req.namespaceId,
|
|
2020
|
+
// The id is derived from a fresh salt (core#4244); a node refuses any other.
|
|
2021
|
+
op: (await meroJs.subgroupCreation({ parentId: req.namespaceId, restricted: true, admin: s.account })).op
|
|
2022
|
+
},
|
|
2023
|
+
deps
|
|
2024
|
+
);
|
|
2025
|
+
for (const member of req.members) {
|
|
2026
|
+
await delegatedGovernance(s, { namespaceId: req.namespaceId, group: groupId, op: meroJs.memberAddedOp(member, "Member") }, deps);
|
|
2027
|
+
}
|
|
2028
|
+
const { contextId } = await createDelegatedContext(s, { ...req, groupId }, deps);
|
|
2029
|
+
return { contextId, groupId };
|
|
2030
|
+
}
|
|
2031
|
+
async function foundDelegatedNamespace(s, req = {}, deps = {}) {
|
|
2032
|
+
const relays = knownRelays(s).map((u) => u.replace(/\/+$/, ""));
|
|
2033
|
+
const relay = relays[0];
|
|
2034
|
+
if (!relay) throw new Error("no relay is known for this account, so there is nowhere to found a namespace");
|
|
2035
|
+
const known = Object.entries(readRelayMap(s.account).namespaces).find(
|
|
2036
|
+
([, url]) => url.replace(/\/+$/, "") === relay
|
|
2037
|
+
)?.[0];
|
|
2038
|
+
if (!known) {
|
|
2039
|
+
throw new Error("join a namespace on this relay first: its executor account is learned from one you are in");
|
|
2040
|
+
}
|
|
2041
|
+
const { executorAccount } = await client(s, relay, governanceNonce(relay, known), deps.fetch).describeGovernance(known);
|
|
2042
|
+
let next = BigInt(Date.now());
|
|
2043
|
+
const founded = await client(s, relay, { next: async () => next++ }, deps.fetch).foundNamespace({
|
|
2044
|
+
executorAccount,
|
|
2045
|
+
...req.defaultCapabilities !== void 0 ? { defaultCapabilities: req.defaultCapabilities } : {},
|
|
2046
|
+
...req.application ? { application: req.application } : {}
|
|
2047
|
+
});
|
|
2048
|
+
try {
|
|
2049
|
+
localStorage.setItem(`calimero.governance-nonce.${relay}.${founded.namespaceId}`, String(next));
|
|
2050
|
+
} catch {
|
|
2051
|
+
}
|
|
2052
|
+
rememberRelay(s.account, relay, { namespaceId: founded.namespaceId });
|
|
2053
|
+
if (req.application && founded.applicationSet !== true) {
|
|
2054
|
+
throw new Error(
|
|
2055
|
+
`founded ${founded.namespaceId} but could not give it its application: ${founded.applicationError ?? "unknown reason"}`
|
|
2056
|
+
);
|
|
2057
|
+
}
|
|
2058
|
+
return { namespaceId: founded.namespaceId, teeEnabled: founded.teeEnabled };
|
|
2059
|
+
}
|
|
2060
|
+
async function latestPublishedVersion(registryUrl, pkg, fetchFn = globalThis.fetch) {
|
|
2061
|
+
const url = `${registryUrl.replace(/\/+$/, "")}/api/v2/bundles?package=${encodeURIComponent(pkg)}`;
|
|
2062
|
+
const response = await fetchFn(url, { headers: { Accept: "application/json" } });
|
|
2063
|
+
if (!response.ok) throw new Error(`the registry has no ${pkg} (HTTP ${response.status})`);
|
|
2064
|
+
const bundles = await response.json();
|
|
2065
|
+
const newer = (a, b) => {
|
|
2066
|
+
const [x, y] = [a, b].map((v) => v.split(/[.-]/).map((n) => Number.parseInt(n, 10) || 0));
|
|
2067
|
+
for (let i = 0; i < Math.max(x.length, y.length); i++) {
|
|
2068
|
+
if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0);
|
|
2069
|
+
}
|
|
2070
|
+
return false;
|
|
2071
|
+
};
|
|
2072
|
+
const latest = bundles.map((b) => b.appVersion).filter((v) => typeof v === "string" && v.length > 0).reduce((best, v) => !best || newer(v, best) ? v : best, void 0);
|
|
2073
|
+
if (!latest) throw new Error(`the registry lists no version of ${pkg}`);
|
|
2074
|
+
return latest;
|
|
2075
|
+
}
|
|
2076
|
+
|
|
2077
|
+
// src/delegated/govern.ts
|
|
2078
|
+
var GROUP_NAMESPACE_PREFIX = "calimero.delegated.group-namespace.";
|
|
2079
|
+
function readGroupNamespaces(account) {
|
|
2080
|
+
try {
|
|
2081
|
+
return JSON.parse(localStorage.getItem(GROUP_NAMESPACE_PREFIX + account) ?? "{}");
|
|
2082
|
+
} catch {
|
|
2083
|
+
return {};
|
|
2084
|
+
}
|
|
2085
|
+
}
|
|
2086
|
+
function rememberGroupNamespace(account, groupId, namespaceId) {
|
|
2087
|
+
try {
|
|
2088
|
+
const all = readGroupNamespaces(account);
|
|
2089
|
+
all[groupId] = namespaceId;
|
|
2090
|
+
localStorage.setItem(GROUP_NAMESPACE_PREFIX + account, JSON.stringify(all));
|
|
2091
|
+
} catch {
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
function namespaceOfGroup(s, groupId) {
|
|
2095
|
+
if (readRelayMap(s.account).namespaces[groupId]) return groupId;
|
|
2096
|
+
return readGroupNamespaces(s.account)[groupId];
|
|
2097
|
+
}
|
|
2098
|
+
function requireNamespace(s, groupId) {
|
|
2099
|
+
const ns = namespaceOfGroup(s, groupId);
|
|
2100
|
+
if (!ns) {
|
|
2101
|
+
throw new Error(
|
|
2102
|
+
`the namespace of group ${groupId} is not known to this account: it can manage only groups in namespaces it joined or subgroups it created`
|
|
2103
|
+
);
|
|
2104
|
+
}
|
|
2105
|
+
return ns;
|
|
2106
|
+
}
|
|
2107
|
+
async function governGroup(s, groupId, op) {
|
|
2108
|
+
return delegatedGovernance(s, { namespaceId: requireNamespace(s, groupId), group: groupId, op });
|
|
2109
|
+
}
|
|
2110
|
+
async function governRoot(s, groupId, op) {
|
|
2111
|
+
const namespaceId = requireNamespace(s, groupId);
|
|
2112
|
+
return delegatedGovernance(s, { namespaceId, group: namespaceId, op });
|
|
2113
|
+
}
|
|
1311
2114
|
|
|
1312
2115
|
// src/hooks/index.ts
|
|
1313
2116
|
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.";
|
|
@@ -1605,7 +2408,7 @@ function extractAliasContextId(value) {
|
|
|
1605
2408
|
return null;
|
|
1606
2409
|
}
|
|
1607
2410
|
function useExecute(contextId, executorId) {
|
|
1608
|
-
const { mero } = useMero();
|
|
2411
|
+
const { mero, isDelegated } = useMero();
|
|
1609
2412
|
const [loading, setLoading] = react.useState(false);
|
|
1610
2413
|
const [error, setError] = react.useState(null);
|
|
1611
2414
|
const mountedRef = react.useRef(true);
|
|
@@ -1618,7 +2421,13 @@ function useExecute(contextId, executorId) {
|
|
|
1618
2421
|
const execute = react.useCallback(
|
|
1619
2422
|
async (method, params) => {
|
|
1620
2423
|
if (!mero || !contextId || !executorId) {
|
|
1621
|
-
if (mountedRef.current)
|
|
2424
|
+
if (mountedRef.current) {
|
|
2425
|
+
setError(
|
|
2426
|
+
new Error(
|
|
2427
|
+
!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"
|
|
2428
|
+
)
|
|
2429
|
+
);
|
|
2430
|
+
}
|
|
1622
2431
|
return null;
|
|
1623
2432
|
}
|
|
1624
2433
|
if (mountedRef.current) {
|
|
@@ -1641,7 +2450,7 @@ function useExecute(contextId, executorId) {
|
|
|
1641
2450
|
if (mountedRef.current) setLoading(false);
|
|
1642
2451
|
}
|
|
1643
2452
|
},
|
|
1644
|
-
[mero, contextId, executorId]
|
|
2453
|
+
[mero, contextId, executorId, isDelegated]
|
|
1645
2454
|
);
|
|
1646
2455
|
return { execute, loading, error };
|
|
1647
2456
|
}
|
|
@@ -1669,14 +2478,22 @@ function useSubscription(input, callback) {
|
|
|
1669
2478
|
}, [mero, contextIdsKey, groupIdsKey]);
|
|
1670
2479
|
}
|
|
1671
2480
|
function useContexts(applicationId) {
|
|
1672
|
-
const { mero } = useMero();
|
|
2481
|
+
const { mero, isDelegated } = useMero();
|
|
1673
2482
|
const { data, loading, error, refetch } = useAsyncResource(
|
|
1674
2483
|
mero ? async () => {
|
|
2484
|
+
if (isDelegated) {
|
|
2485
|
+
const session = readDelegatedSession();
|
|
2486
|
+
const listed = session ? await listDelegatedContexts(session) : [];
|
|
2487
|
+
const own = listed.filter(
|
|
2488
|
+
(c) => !applicationId || c.applicationId === applicationId
|
|
2489
|
+
);
|
|
2490
|
+
return mapApplicationContexts(own);
|
|
2491
|
+
}
|
|
1675
2492
|
const response = applicationId ? await mero.admin.getContextsForApplication(applicationId) : await mero.admin.getContexts();
|
|
1676
2493
|
return mapApplicationContexts(response.contexts ?? []);
|
|
1677
2494
|
} : null,
|
|
1678
2495
|
[],
|
|
1679
|
-
[mero, applicationId]
|
|
2496
|
+
[mero, applicationId, isDelegated]
|
|
1680
2497
|
);
|
|
1681
2498
|
return { contexts: data, loading, error, refetch };
|
|
1682
2499
|
}
|
|
@@ -1908,17 +2725,58 @@ function useContextDiscovery(options) {
|
|
|
1908
2725
|
return { context, loading, error, discover, reset };
|
|
1909
2726
|
}
|
|
1910
2727
|
function useCreateContext() {
|
|
1911
|
-
const { mero } = useMero();
|
|
2728
|
+
const { mero, isDelegated } = useMero();
|
|
1912
2729
|
const { loading, error, run } = useAsyncMutation();
|
|
1913
2730
|
const createContext2 = react.useCallback(
|
|
1914
2731
|
async (request) => {
|
|
2732
|
+
if (isDelegated) {
|
|
2733
|
+
const session = readDelegatedSession();
|
|
2734
|
+
if (!session || !request.groupId) return null;
|
|
2735
|
+
return run(
|
|
2736
|
+
() => createDelegatedContext(session, {
|
|
2737
|
+
namespaceId: request.groupId,
|
|
2738
|
+
applicationId: request.applicationId,
|
|
2739
|
+
initializationParams: request.initializationParams
|
|
2740
|
+
})
|
|
2741
|
+
);
|
|
2742
|
+
}
|
|
1915
2743
|
if (!mero) return null;
|
|
1916
2744
|
return run(() => mero.admin.createContext(request));
|
|
1917
2745
|
},
|
|
1918
|
-
[mero, run]
|
|
2746
|
+
[mero, run, isDelegated]
|
|
1919
2747
|
);
|
|
1920
2748
|
return { createContext: createContext2, loading, error };
|
|
1921
2749
|
}
|
|
2750
|
+
function useCreatePrivateContext() {
|
|
2751
|
+
const { mero, isDelegated } = useMero();
|
|
2752
|
+
const { loading, error, run } = useAsyncMutation();
|
|
2753
|
+
const createPrivateContext = react.useCallback(
|
|
2754
|
+
async (request) => {
|
|
2755
|
+
if (isDelegated) {
|
|
2756
|
+
const session = readDelegatedSession();
|
|
2757
|
+
if (!session) return null;
|
|
2758
|
+
return run(() => createDelegatedPrivateContext(session, request));
|
|
2759
|
+
}
|
|
2760
|
+
if (!mero) return null;
|
|
2761
|
+
return run(async () => {
|
|
2762
|
+
const { groupId } = await mero.admin.createGroupInNamespace(request.namespaceId, {
|
|
2763
|
+
visibility: "restricted"
|
|
2764
|
+
});
|
|
2765
|
+
await mero.admin.addGroupMembers(groupId, {
|
|
2766
|
+
members: request.members.map((identity) => ({ identity, role: "Member" }))
|
|
2767
|
+
});
|
|
2768
|
+
const { contextId } = await mero.admin.createContext({
|
|
2769
|
+
applicationId: request.applicationId,
|
|
2770
|
+
groupId,
|
|
2771
|
+
initializationParams: request.initializationParams
|
|
2772
|
+
});
|
|
2773
|
+
return { contextId };
|
|
2774
|
+
});
|
|
2775
|
+
},
|
|
2776
|
+
[mero, run, isDelegated]
|
|
2777
|
+
);
|
|
2778
|
+
return { createPrivateContext, loading, error };
|
|
2779
|
+
}
|
|
1922
2780
|
function useDeleteContext() {
|
|
1923
2781
|
const { mero } = useMero();
|
|
1924
2782
|
const { loading, error, run } = useAsyncMutation();
|
|
@@ -1944,14 +2802,23 @@ function useJoinContext(options = {}) {
|
|
|
1944
2802
|
return { joinContext, loading, error, failure };
|
|
1945
2803
|
}
|
|
1946
2804
|
function useJoinSubgroupInheritance() {
|
|
1947
|
-
const { mero } = useMero();
|
|
2805
|
+
const { mero, isDelegated } = useMero();
|
|
1948
2806
|
const { loading, error, run } = useAsyncMutation();
|
|
1949
2807
|
const joinSubgroupInheritance = react.useCallback(
|
|
1950
2808
|
async (groupId) => {
|
|
2809
|
+
if (isDelegated) {
|
|
2810
|
+
const session = readDelegatedSession();
|
|
2811
|
+
if (!session) return null;
|
|
2812
|
+
return run(async () => {
|
|
2813
|
+
await governRoot(session, groupId, meroJs.memberJoinedOpenOp({ member: session.account, groupId, credential: session.credential }));
|
|
2814
|
+
const { publicKey } = await meroJs.signerFromSecret(session.deviceSecret);
|
|
2815
|
+
return { groupId, memberPublicKey: publicKey, wasInherited: false };
|
|
2816
|
+
});
|
|
2817
|
+
}
|
|
1951
2818
|
if (!mero) return null;
|
|
1952
2819
|
return run(() => mero.admin.joinSubgroupInheritance(groupId));
|
|
1953
2820
|
},
|
|
1954
|
-
[mero, run]
|
|
2821
|
+
[mero, run, isDelegated]
|
|
1955
2822
|
);
|
|
1956
2823
|
return { joinSubgroupInheritance, loading, error };
|
|
1957
2824
|
}
|
|
@@ -1974,14 +2841,19 @@ function useGroupInfo(groupId) {
|
|
|
1974
2841
|
return { groupInfo: data, loading, error, refetch };
|
|
1975
2842
|
}
|
|
1976
2843
|
function useDeleteGroup() {
|
|
1977
|
-
const { mero } = useMero();
|
|
2844
|
+
const { mero, isDelegated } = useMero();
|
|
1978
2845
|
const { loading, error, run } = useAsyncMutation();
|
|
1979
2846
|
const deleteGroup = react.useCallback(
|
|
1980
2847
|
async (groupId) => {
|
|
2848
|
+
if (isDelegated) {
|
|
2849
|
+
const session = readDelegatedSession();
|
|
2850
|
+
if (!session) return null;
|
|
2851
|
+
return run(() => governRoot(session, groupId, meroJs.groupDeletedOp(groupId)));
|
|
2852
|
+
}
|
|
1981
2853
|
if (!mero) return null;
|
|
1982
2854
|
return run(() => mero.admin.deleteGroup(groupId));
|
|
1983
2855
|
},
|
|
1984
|
-
[mero, run]
|
|
2856
|
+
[mero, run, isDelegated]
|
|
1985
2857
|
);
|
|
1986
2858
|
return { deleteGroup, loading, error };
|
|
1987
2859
|
}
|
|
@@ -1998,26 +2870,42 @@ function useSyncGroup() {
|
|
|
1998
2870
|
return { syncGroup, loading, error };
|
|
1999
2871
|
}
|
|
2000
2872
|
function useAddGroupMembers() {
|
|
2001
|
-
const { mero } = useMero();
|
|
2873
|
+
const { mero, isDelegated } = useMero();
|
|
2002
2874
|
const { loading, error, run } = useAsyncMutation();
|
|
2003
2875
|
const addGroupMembers = react.useCallback(
|
|
2004
2876
|
async (groupId, request) => {
|
|
2877
|
+
if (isDelegated) {
|
|
2878
|
+
const session = readDelegatedSession();
|
|
2879
|
+
if (!session) return null;
|
|
2880
|
+
return run(async () => {
|
|
2881
|
+
for (const m of request.members) {
|
|
2882
|
+
await governGroup(session, groupId, meroJs.memberAddedOp(m.identity, m.role));
|
|
2883
|
+
}
|
|
2884
|
+
});
|
|
2885
|
+
}
|
|
2005
2886
|
if (!mero) return null;
|
|
2006
2887
|
return run(() => mero.admin.addGroupMembers(groupId, request));
|
|
2007
2888
|
},
|
|
2008
|
-
[mero, run]
|
|
2889
|
+
[mero, run, isDelegated]
|
|
2009
2890
|
);
|
|
2010
2891
|
return { addGroupMembers, loading, error };
|
|
2011
2892
|
}
|
|
2012
2893
|
function useRemoveGroupMembers() {
|
|
2013
|
-
const { mero } = useMero();
|
|
2894
|
+
const { mero, isDelegated } = useMero();
|
|
2014
2895
|
const { loading, error, run } = useAsyncMutation();
|
|
2015
2896
|
const removeGroupMembers = react.useCallback(
|
|
2016
2897
|
async (groupId, request) => {
|
|
2898
|
+
if (isDelegated) {
|
|
2899
|
+
const session = readDelegatedSession();
|
|
2900
|
+
if (!session) return null;
|
|
2901
|
+
return run(async () => {
|
|
2902
|
+
for (const member of request.members) await governGroup(session, groupId, meroJs.memberRemovedOp(member));
|
|
2903
|
+
});
|
|
2904
|
+
}
|
|
2017
2905
|
if (!mero) return null;
|
|
2018
2906
|
return run(() => mero.admin.removeGroupMembers(groupId, request));
|
|
2019
2907
|
},
|
|
2020
|
-
[mero, run]
|
|
2908
|
+
[mero, run, isDelegated]
|
|
2021
2909
|
);
|
|
2022
2910
|
return { removeGroupMembers, loading, error };
|
|
2023
2911
|
}
|
|
@@ -2058,23 +2946,43 @@ function useNamespaceIdentity(namespaceId) {
|
|
|
2058
2946
|
return { identity: data, loading, error, refetch };
|
|
2059
2947
|
}
|
|
2060
2948
|
function useNamespacesForApplication(applicationId) {
|
|
2061
|
-
const { mero } = useMero();
|
|
2949
|
+
const { mero, isDelegated } = useMero();
|
|
2062
2950
|
const { data, loading, error, refetch } = useAsyncResource(
|
|
2063
|
-
mero && applicationId ?
|
|
2951
|
+
mero && applicationId ? isDelegated ? async () => {
|
|
2952
|
+
const session = readDelegatedSession();
|
|
2953
|
+
const listed = session ? await listDelegatedNamespaces(session) : [];
|
|
2954
|
+
return listed.filter((ns) => ns.targetApplicationId === applicationId);
|
|
2955
|
+
} : () => mero.admin.listNamespacesForApplication(applicationId) : null,
|
|
2064
2956
|
[],
|
|
2065
|
-
[mero, applicationId]
|
|
2957
|
+
[mero, applicationId, isDelegated]
|
|
2066
2958
|
);
|
|
2067
2959
|
return { namespaces: data, loading, error, refetch };
|
|
2068
2960
|
}
|
|
2961
|
+
var DEFAULT_REGISTRY_URL = "https://apps.calimero.network";
|
|
2069
2962
|
function useCreateNamespace() {
|
|
2070
|
-
const { mero } = useMero();
|
|
2963
|
+
const { mero, isDelegated, app } = useMero();
|
|
2071
2964
|
const { loading, error, run } = useAsyncMutation();
|
|
2072
2965
|
const createNamespace = react.useCallback(
|
|
2073
2966
|
async (request) => {
|
|
2967
|
+
if (isDelegated) {
|
|
2968
|
+
const session = readDelegatedSession();
|
|
2969
|
+
if (!session) return null;
|
|
2970
|
+
const pkg = app.packageName;
|
|
2971
|
+
return run(async () => {
|
|
2972
|
+
if (!pkg) {
|
|
2973
|
+
throw new Error("this app names no registry package, so a founded namespace could not be given its application");
|
|
2974
|
+
}
|
|
2975
|
+
const version = app.packageVersion ?? await latestPublishedVersion(app.registryUrl ?? DEFAULT_REGISTRY_URL, pkg);
|
|
2976
|
+
return foundDelegatedNamespace(session, {
|
|
2977
|
+
defaultCapabilities: 231,
|
|
2978
|
+
application: { applicationId: request.applicationId, package: pkg, version }
|
|
2979
|
+
});
|
|
2980
|
+
});
|
|
2981
|
+
}
|
|
2074
2982
|
if (!mero) return null;
|
|
2075
2983
|
return run(() => mero.admin.createNamespace(request));
|
|
2076
2984
|
},
|
|
2077
|
-
[mero, run]
|
|
2985
|
+
[mero, run, isDelegated, app]
|
|
2078
2986
|
);
|
|
2079
2987
|
return { createNamespace, loading, error };
|
|
2080
2988
|
}
|
|
@@ -2139,14 +3047,32 @@ function useRedeemInvitation() {
|
|
|
2139
3047
|
return { redeem, outcome, loading };
|
|
2140
3048
|
}
|
|
2141
3049
|
function useCreateGroupInNamespace() {
|
|
2142
|
-
const { mero } = useMero();
|
|
3050
|
+
const { mero, isDelegated } = useMero();
|
|
2143
3051
|
const { loading, error, run } = useAsyncMutation();
|
|
2144
3052
|
const createGroupInNamespace = react.useCallback(
|
|
2145
3053
|
async (namespaceId, request) => {
|
|
3054
|
+
if (isDelegated) {
|
|
3055
|
+
const session = readDelegatedSession();
|
|
3056
|
+
if (!session) return null;
|
|
3057
|
+
return run(async () => {
|
|
3058
|
+
const { groupId } = await governRoot(
|
|
3059
|
+
session,
|
|
3060
|
+
namespaceId,
|
|
3061
|
+
// The id is derived from a fresh salt (core#4244); a node refuses any other.
|
|
3062
|
+
(await meroJs.subgroupCreation({
|
|
3063
|
+
parentId: namespaceId,
|
|
3064
|
+
restricted: request?.visibility !== "open",
|
|
3065
|
+
admin: session.account
|
|
3066
|
+
})).op
|
|
3067
|
+
);
|
|
3068
|
+
rememberGroupNamespace(session.account, groupId, namespaceId);
|
|
3069
|
+
return { groupId };
|
|
3070
|
+
});
|
|
3071
|
+
}
|
|
2146
3072
|
if (!mero) return null;
|
|
2147
3073
|
return run(() => mero.admin.createGroupInNamespace(namespaceId, request));
|
|
2148
3074
|
},
|
|
2149
|
-
[mero, run]
|
|
3075
|
+
[mero, run, isDelegated]
|
|
2150
3076
|
);
|
|
2151
3077
|
return { createGroupInNamespace, loading, error };
|
|
2152
3078
|
}
|
|
@@ -2160,38 +3086,55 @@ function useNamespaceGroups(namespaceId) {
|
|
|
2160
3086
|
return { groups: data, loading, error, refetch };
|
|
2161
3087
|
}
|
|
2162
3088
|
function useUpdateMemberRole() {
|
|
2163
|
-
const { mero } = useMero();
|
|
3089
|
+
const { mero, isDelegated } = useMero();
|
|
2164
3090
|
const { loading, error, run } = useAsyncMutation();
|
|
2165
3091
|
const updateMemberRole = react.useCallback(
|
|
2166
3092
|
async (groupId, identity, request) => {
|
|
3093
|
+
if (isDelegated) {
|
|
3094
|
+
const session = readDelegatedSession();
|
|
3095
|
+
if (!session) return null;
|
|
3096
|
+
return run(() => governGroup(session, groupId, meroJs.memberRoleSetOp(identity, request.role)));
|
|
3097
|
+
}
|
|
2167
3098
|
if (!mero) return null;
|
|
2168
3099
|
return run(() => mero.admin.updateMemberRole(groupId, identity, request));
|
|
2169
3100
|
},
|
|
2170
|
-
[mero, run]
|
|
3101
|
+
[mero, run, isDelegated]
|
|
2171
3102
|
);
|
|
2172
3103
|
return { updateMemberRole, loading, error };
|
|
2173
3104
|
}
|
|
2174
3105
|
function useSetDefaultCapabilities() {
|
|
2175
|
-
const { mero } = useMero();
|
|
3106
|
+
const { mero, isDelegated } = useMero();
|
|
2176
3107
|
const { loading, error, run } = useAsyncMutation();
|
|
2177
3108
|
const setDefaultCapabilities = react.useCallback(
|
|
2178
3109
|
async (groupId, request) => {
|
|
3110
|
+
if (isDelegated) {
|
|
3111
|
+
const session = readDelegatedSession();
|
|
3112
|
+
if (!session) return null;
|
|
3113
|
+
return run(() => governGroup(session, groupId, meroJs.defaultCapabilitiesSetOp(request.defaultCapabilities)));
|
|
3114
|
+
}
|
|
2179
3115
|
if (!mero) return null;
|
|
2180
3116
|
return run(() => mero.admin.setDefaultCapabilities(groupId, request));
|
|
2181
3117
|
},
|
|
2182
|
-
[mero, run]
|
|
3118
|
+
[mero, run, isDelegated]
|
|
2183
3119
|
);
|
|
2184
3120
|
return { setDefaultCapabilities, loading, error };
|
|
2185
3121
|
}
|
|
2186
3122
|
function useSetSubgroupVisibility() {
|
|
2187
|
-
const { mero } = useMero();
|
|
3123
|
+
const { mero, isDelegated } = useMero();
|
|
2188
3124
|
const { loading, error, run } = useAsyncMutation();
|
|
2189
3125
|
const setSubgroupVisibility = react.useCallback(
|
|
2190
3126
|
async (groupId, request) => {
|
|
3127
|
+
if (isDelegated) {
|
|
3128
|
+
const session = readDelegatedSession();
|
|
3129
|
+
if (!session) return null;
|
|
3130
|
+
return run(
|
|
3131
|
+
() => governGroup(session, groupId, meroJs.subgroupVisibilitySetOp(request.subgroupVisibility === "open" ? "open" : "restricted"))
|
|
3132
|
+
);
|
|
3133
|
+
}
|
|
2191
3134
|
if (!mero) return null;
|
|
2192
3135
|
return run(() => mero.admin.setSubgroupVisibility(groupId, request));
|
|
2193
3136
|
},
|
|
2194
|
-
[mero, run]
|
|
3137
|
+
[mero, run, isDelegated]
|
|
2195
3138
|
);
|
|
2196
3139
|
return { setSubgroupVisibility, loading, error };
|
|
2197
3140
|
}
|
|
@@ -2226,38 +3169,53 @@ function useSetTeeAdmissionPolicy() {
|
|
|
2226
3169
|
return { setTeeAdmissionPolicy, loading, error };
|
|
2227
3170
|
}
|
|
2228
3171
|
function useSetGroupMetadata() {
|
|
2229
|
-
const { mero } = useMero();
|
|
3172
|
+
const { mero, isDelegated } = useMero();
|
|
2230
3173
|
const { loading, error, run } = useAsyncMutation();
|
|
2231
3174
|
const setGroupMetadata = react.useCallback(
|
|
2232
3175
|
async (groupId, request) => {
|
|
3176
|
+
if (isDelegated) {
|
|
3177
|
+
const session = readDelegatedSession();
|
|
3178
|
+
if (!session) return null;
|
|
3179
|
+
return run(() => governGroup(session, groupId, meroJs.groupMetadataSetOp(request)));
|
|
3180
|
+
}
|
|
2233
3181
|
if (!mero) return null;
|
|
2234
3182
|
return run(() => mero.admin.setGroupMetadata(groupId, request));
|
|
2235
3183
|
},
|
|
2236
|
-
[mero, run]
|
|
3184
|
+
[mero, run, isDelegated]
|
|
2237
3185
|
);
|
|
2238
3186
|
return { setGroupMetadata, loading, error };
|
|
2239
3187
|
}
|
|
2240
3188
|
function useSetMemberMetadata() {
|
|
2241
|
-
const { mero } = useMero();
|
|
3189
|
+
const { mero, isDelegated } = useMero();
|
|
2242
3190
|
const { loading, error, run } = useAsyncMutation();
|
|
2243
3191
|
const setMemberMetadata = react.useCallback(
|
|
2244
3192
|
async (groupId, identity, request) => {
|
|
3193
|
+
if (isDelegated) {
|
|
3194
|
+
const session = readDelegatedSession();
|
|
3195
|
+
if (!session) return null;
|
|
3196
|
+
return run(() => governGroup(session, groupId, meroJs.memberMetadataSetOp(identity, request)));
|
|
3197
|
+
}
|
|
2245
3198
|
if (!mero) return null;
|
|
2246
3199
|
return run(() => mero.admin.setMemberMetadata(groupId, identity, request));
|
|
2247
3200
|
},
|
|
2248
|
-
[mero, run]
|
|
3201
|
+
[mero, run, isDelegated]
|
|
2249
3202
|
);
|
|
2250
3203
|
return { setMemberMetadata, loading, error };
|
|
2251
3204
|
}
|
|
2252
3205
|
function useSetContextMetadata() {
|
|
2253
|
-
const { mero } = useMero();
|
|
3206
|
+
const { mero, isDelegated } = useMero();
|
|
2254
3207
|
const { loading, error, run } = useAsyncMutation();
|
|
2255
3208
|
const setContextMetadata = react.useCallback(
|
|
2256
3209
|
async (groupId, contextId, request) => {
|
|
3210
|
+
if (isDelegated) {
|
|
3211
|
+
const session = readDelegatedSession();
|
|
3212
|
+
if (!session) return null;
|
|
3213
|
+
return run(() => governGroup(session, groupId, meroJs.contextMetadataSetOp(contextId, request)));
|
|
3214
|
+
}
|
|
2257
3215
|
if (!mero) return null;
|
|
2258
3216
|
return run(() => mero.admin.setContextMetadata(groupId, contextId, request));
|
|
2259
3217
|
},
|
|
2260
|
-
[mero, run]
|
|
3218
|
+
[mero, run, isDelegated]
|
|
2261
3219
|
);
|
|
2262
3220
|
return { setContextMetadata, loading, error };
|
|
2263
3221
|
}
|
|
@@ -2416,14 +3374,22 @@ function useRetryGroupUpgrade() {
|
|
|
2416
3374
|
return { retryGroupUpgrade, loading, error };
|
|
2417
3375
|
}
|
|
2418
3376
|
function useReparentGroup() {
|
|
2419
|
-
const { mero } = useMero();
|
|
3377
|
+
const { mero, isDelegated } = useMero();
|
|
2420
3378
|
const { loading, error, run } = useAsyncMutation();
|
|
2421
3379
|
const reparentGroup = react.useCallback(
|
|
2422
3380
|
async (childGroupId, request) => {
|
|
3381
|
+
if (isDelegated) {
|
|
3382
|
+
const session = readDelegatedSession();
|
|
3383
|
+
if (!session) return null;
|
|
3384
|
+
return run(async () => {
|
|
3385
|
+
await governRoot(session, childGroupId, meroJs.groupReparentedOp(childGroupId, request.newParentId));
|
|
3386
|
+
return { reparented: true };
|
|
3387
|
+
});
|
|
3388
|
+
}
|
|
2423
3389
|
if (!mero) return null;
|
|
2424
3390
|
return run(() => mero.admin.reparentGroup(childGroupId, request));
|
|
2425
3391
|
},
|
|
2426
|
-
[mero, run]
|
|
3392
|
+
[mero, run, isDelegated]
|
|
2427
3393
|
);
|
|
2428
3394
|
return { reparentGroup, loading, error };
|
|
2429
3395
|
}
|
|
@@ -2437,14 +3403,19 @@ function useSubgroups(groupId) {
|
|
|
2437
3403
|
return { subgroups: data, loading, error, refetch };
|
|
2438
3404
|
}
|
|
2439
3405
|
function useDetachContextFromGroup() {
|
|
2440
|
-
const { mero } = useMero();
|
|
3406
|
+
const { mero, isDelegated } = useMero();
|
|
2441
3407
|
const { loading, error, run } = useAsyncMutation();
|
|
2442
3408
|
const detachContextFromGroup = react.useCallback(
|
|
2443
3409
|
async (groupId, contextId) => {
|
|
3410
|
+
if (isDelegated) {
|
|
3411
|
+
const session = readDelegatedSession();
|
|
3412
|
+
if (!session) return null;
|
|
3413
|
+
return run(() => governGroup(session, groupId, meroJs.contextDetachedOp(contextId)));
|
|
3414
|
+
}
|
|
2444
3415
|
if (!mero) return null;
|
|
2445
3416
|
return run(() => mero.admin.detachContextFromGroup(groupId, contextId));
|
|
2446
3417
|
},
|
|
2447
|
-
[mero, run]
|
|
3418
|
+
[mero, run, isDelegated]
|
|
2448
3419
|
);
|
|
2449
3420
|
return { detachContextFromGroup, loading, error };
|
|
2450
3421
|
}
|
|
@@ -2956,6 +3927,359 @@ function MigrationAdminPanel({ namespaceId, pollIntervalMs, className }) {
|
|
|
2956
3927
|
] })
|
|
2957
3928
|
] });
|
|
2958
3929
|
}
|
|
3930
|
+
function normaliseAccount(account) {
|
|
3931
|
+
if (!account) return null;
|
|
3932
|
+
const trimmed = account.trim().toLowerCase();
|
|
3933
|
+
const bare = trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
|
|
3934
|
+
return bare.length > 0 ? bare : null;
|
|
3935
|
+
}
|
|
3936
|
+
function isInvited(node, invited) {
|
|
3937
|
+
if (invited.size === 0) return true;
|
|
3938
|
+
const account = normaliseAccount(node.account);
|
|
3939
|
+
return account !== null && invited.has(account);
|
|
3940
|
+
}
|
|
3941
|
+
async function resolveRelayFromInvitation(input) {
|
|
3942
|
+
const cloud = input.cloud ?? new meroJs.CloudClient({
|
|
3943
|
+
cloudBaseUrl: input.cloudBaseUrl,
|
|
3944
|
+
routingCredential: { credential: input.credential, deviceSecret: input.deviceSecret }
|
|
3945
|
+
});
|
|
3946
|
+
let nodes;
|
|
3947
|
+
let servable;
|
|
3948
|
+
try {
|
|
3949
|
+
const routing = await cloud.getNamespaceRouting(input.namespaceId);
|
|
3950
|
+
nodes = routing.nodes;
|
|
3951
|
+
servable = routing.servable;
|
|
3952
|
+
} catch (e) {
|
|
3953
|
+
return {
|
|
3954
|
+
ok: false,
|
|
3955
|
+
step: "admitters-lookup",
|
|
3956
|
+
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.`
|
|
3957
|
+
};
|
|
3958
|
+
}
|
|
3959
|
+
if (nodes.length === 0) {
|
|
3960
|
+
return {
|
|
3961
|
+
ok: false,
|
|
3962
|
+
step: "no-nodes",
|
|
3963
|
+
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."
|
|
3964
|
+
};
|
|
3965
|
+
}
|
|
3966
|
+
const invited = new Set(
|
|
3967
|
+
(input.admitters ?? []).map(normaliseAccount).filter((a) => a !== null)
|
|
3968
|
+
);
|
|
3969
|
+
const named = nodes.filter((n) => isInvited(n, invited));
|
|
3970
|
+
if (named.length === 0) {
|
|
3971
|
+
return {
|
|
3972
|
+
ok: false,
|
|
3973
|
+
step: "not-invited",
|
|
3974
|
+
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.`
|
|
3975
|
+
};
|
|
3976
|
+
}
|
|
3977
|
+
const usable = named.filter((n) => n.canAdmit);
|
|
3978
|
+
const candidates = usable.length > 0 ? usable : named;
|
|
3979
|
+
const advisory = usable.length === 0 || !servable;
|
|
3980
|
+
const addressable = candidates.filter(
|
|
3981
|
+
(n) => typeof n.relayUrl === "string" && n.relayUrl.length > 0
|
|
3982
|
+
);
|
|
3983
|
+
if (addressable.length === 0) {
|
|
3984
|
+
return {
|
|
3985
|
+
ok: false,
|
|
3986
|
+
step: "no-relay-url",
|
|
3987
|
+
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."
|
|
3988
|
+
};
|
|
3989
|
+
}
|
|
3990
|
+
const chosen = addressable.find((n) => n.canExecute) ?? addressable.find((n) => n.fresh) ?? addressable[0];
|
|
3991
|
+
return {
|
|
3992
|
+
ok: true,
|
|
3993
|
+
relayUrl: chosen.relayUrl,
|
|
3994
|
+
// The cloud's ready-made URL when it gave one, so the path is never rebuilt
|
|
3995
|
+
// from a guess; the fallback is the documented route on the same origin.
|
|
3996
|
+
admitUrl: chosen.admitUrl ?? `${chosen.relayUrl.replace(/\/+$/, "")}/admin-api/namespaces/${input.namespaceId}/admit`,
|
|
3997
|
+
admitterAccount: chosen.account,
|
|
3998
|
+
peerId: chosen.peerId,
|
|
3999
|
+
writable: chosen.canExecute,
|
|
4000
|
+
// Stale when the node's own heartbeat lapsed OR when the cloud's summary
|
|
4001
|
+
// disagrees with trying it at all. Both mean the same thing to a caller:
|
|
4002
|
+
// this was attempted on advisory data, so if the admit fails that is why.
|
|
4003
|
+
stale: !chosen.fresh || advisory
|
|
4004
|
+
};
|
|
4005
|
+
}
|
|
4006
|
+
function explainAdmitFailure(status, body) {
|
|
4007
|
+
const detail = body ? `: ${body}` : "";
|
|
4008
|
+
switch (status) {
|
|
4009
|
+
case 400:
|
|
4010
|
+
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.`;
|
|
4011
|
+
case 403:
|
|
4012
|
+
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.`;
|
|
4013
|
+
case 409:
|
|
4014
|
+
return `That node holds no device of its own, so it cannot endorse anyone (409)${detail}. Another admitter from the same invitation would work.`;
|
|
4015
|
+
default:
|
|
4016
|
+
return `The join was not published (HTTP ${status})${detail}.`;
|
|
4017
|
+
}
|
|
4018
|
+
}
|
|
4019
|
+
function joinNonce(account) {
|
|
4020
|
+
const source = meroJs.createLocalStorageNonceSource(`calimero.delegated.joinnonce.${account}`);
|
|
4021
|
+
return () => source.next();
|
|
4022
|
+
}
|
|
4023
|
+
function origin(url) {
|
|
4024
|
+
return url.replace(/\/+$/, "");
|
|
4025
|
+
}
|
|
4026
|
+
async function joinWithNode(input) {
|
|
4027
|
+
const { account, credential, deviceSecret } = input.credential;
|
|
4028
|
+
let signedOp;
|
|
4029
|
+
try {
|
|
4030
|
+
signedOp = await meroJs.signMemberJoinOp({
|
|
4031
|
+
namespaceId: input.namespaceId,
|
|
4032
|
+
member: account,
|
|
4033
|
+
invitation: input.invitation,
|
|
4034
|
+
credential,
|
|
4035
|
+
deviceSecret,
|
|
4036
|
+
nonce: await (input.deps?.nonce ?? joinNonce(account))()
|
|
4037
|
+
});
|
|
4038
|
+
} catch (e) {
|
|
4039
|
+
return {
|
|
4040
|
+
ok: false,
|
|
4041
|
+
step: "sign",
|
|
4042
|
+
reason: `The join op could not be signed, so nothing was sent: ${e instanceof Error ? e.message : String(e)}`
|
|
4043
|
+
};
|
|
4044
|
+
}
|
|
4045
|
+
const body = { invitation: input.invitation, signedOp };
|
|
4046
|
+
const url = input.admitUrl ?? `${origin(input.nodeUrl)}/admin-api/namespaces/${input.namespaceId}/admit`;
|
|
4047
|
+
const doFetch = input.deps?.fetch ?? fetch;
|
|
4048
|
+
let response;
|
|
4049
|
+
try {
|
|
4050
|
+
response = await doFetch(url, {
|
|
4051
|
+
method: "POST",
|
|
4052
|
+
// No Authorization header and no request proof, deliberately: the route is
|
|
4053
|
+
// unauthenticated because the joiner's signature is the authorization.
|
|
4054
|
+
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
4055
|
+
body: JSON.stringify(body)
|
|
4056
|
+
});
|
|
4057
|
+
} catch (e) {
|
|
4058
|
+
return {
|
|
4059
|
+
ok: false,
|
|
4060
|
+
step: "admit",
|
|
4061
|
+
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.`
|
|
4062
|
+
};
|
|
4063
|
+
}
|
|
4064
|
+
const text = await response.text();
|
|
4065
|
+
if (!response.ok) {
|
|
4066
|
+
return {
|
|
4067
|
+
ok: false,
|
|
4068
|
+
step: "admit",
|
|
4069
|
+
status: response.status,
|
|
4070
|
+
reason: explainAdmitFailure(response.status, text)
|
|
4071
|
+
};
|
|
4072
|
+
}
|
|
4073
|
+
let published = false;
|
|
4074
|
+
try {
|
|
4075
|
+
const parsed = text ? JSON.parse(text) : {};
|
|
4076
|
+
published = parsed.data?.published === true;
|
|
4077
|
+
} catch {
|
|
4078
|
+
published = false;
|
|
4079
|
+
}
|
|
4080
|
+
return {
|
|
4081
|
+
ok: true,
|
|
4082
|
+
published,
|
|
4083
|
+
session: { relayUrl: origin(input.nodeUrl), account, credential, deviceSecret }
|
|
4084
|
+
};
|
|
4085
|
+
}
|
|
4086
|
+
|
|
4087
|
+
// src/delegated/bootstrap-from-invitation.ts
|
|
4088
|
+
async function bootstrapFromInvitation(input) {
|
|
4089
|
+
const resolve = input.deps?.resolve ?? resolveRelayFromInvitation;
|
|
4090
|
+
const join = input.deps?.join ?? joinWithNode;
|
|
4091
|
+
let relay = null;
|
|
4092
|
+
let nodeUrl = input.nodeUrl;
|
|
4093
|
+
let admitUrl;
|
|
4094
|
+
if (!nodeUrl) {
|
|
4095
|
+
const resolved = await resolve({
|
|
4096
|
+
namespaceId: input.namespaceId,
|
|
4097
|
+
// The signed list, read off the invitation itself rather than passed
|
|
4098
|
+
// separately: two sources for one fact is how an intersection ends up
|
|
4099
|
+
// being performed against the wrong list.
|
|
4100
|
+
admitters: input.invitation.invitation.admitters,
|
|
4101
|
+
credential: input.credential.credential,
|
|
4102
|
+
deviceSecret: input.credential.deviceSecret,
|
|
4103
|
+
cloudBaseUrl: input.cloudBaseUrl
|
|
4104
|
+
});
|
|
4105
|
+
if (!resolved.ok) return resolved;
|
|
4106
|
+
relay = resolved;
|
|
4107
|
+
nodeUrl = resolved.relayUrl;
|
|
4108
|
+
admitUrl = resolved.admitUrl;
|
|
4109
|
+
}
|
|
4110
|
+
const joined = await join({
|
|
4111
|
+
nodeUrl,
|
|
4112
|
+
admitUrl,
|
|
4113
|
+
namespaceId: input.namespaceId,
|
|
4114
|
+
invitation: input.invitation,
|
|
4115
|
+
credential: input.credential,
|
|
4116
|
+
deps: { fetch: input.deps?.fetch, nonce: input.deps?.nonce }
|
|
4117
|
+
});
|
|
4118
|
+
if (!joined.ok) return joined;
|
|
4119
|
+
return { ok: true, published: joined.published, relay, session: joined.session };
|
|
4120
|
+
}
|
|
4121
|
+
function useDelegatedBootstrap(options = {}) {
|
|
4122
|
+
const { connectWithAccount } = useMero();
|
|
4123
|
+
const [running, setRunning] = react.useState(false);
|
|
4124
|
+
const [result, setResult] = react.useState(null);
|
|
4125
|
+
const credential = readDelegatedCredential();
|
|
4126
|
+
const relayUrl = readDelegatedSession()?.relayUrl ?? null;
|
|
4127
|
+
const { cloudBaseUrl } = options;
|
|
4128
|
+
const bootstrap = react.useCallback(
|
|
4129
|
+
async (input) => {
|
|
4130
|
+
const held = readDelegatedCredential();
|
|
4131
|
+
if (!held) {
|
|
4132
|
+
const failure = {
|
|
4133
|
+
ok: false,
|
|
4134
|
+
step: "no-credential",
|
|
4135
|
+
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."
|
|
4136
|
+
};
|
|
4137
|
+
setResult(failure);
|
|
4138
|
+
return failure;
|
|
4139
|
+
}
|
|
4140
|
+
setRunning(true);
|
|
4141
|
+
try {
|
|
4142
|
+
const outcome = await bootstrapFromInvitation({
|
|
4143
|
+
namespaceId: input.namespaceId,
|
|
4144
|
+
invitation: input.invitation,
|
|
4145
|
+
credential: held,
|
|
4146
|
+
nodeUrl: input.nodeUrl,
|
|
4147
|
+
cloudBaseUrl
|
|
4148
|
+
});
|
|
4149
|
+
setResult(outcome);
|
|
4150
|
+
if (outcome.ok) {
|
|
4151
|
+
if (outcome.session.relayUrl) {
|
|
4152
|
+
rememberRelay(held.account, outcome.session.relayUrl, {
|
|
4153
|
+
namespaceId: input.namespaceId,
|
|
4154
|
+
contextId: input.contextId
|
|
4155
|
+
});
|
|
4156
|
+
}
|
|
4157
|
+
connectWithAccount(outcome.session);
|
|
4158
|
+
}
|
|
4159
|
+
return outcome;
|
|
4160
|
+
} finally {
|
|
4161
|
+
setRunning(false);
|
|
4162
|
+
}
|
|
4163
|
+
},
|
|
4164
|
+
[cloudBaseUrl, connectWithAccount]
|
|
4165
|
+
);
|
|
4166
|
+
return {
|
|
4167
|
+
credential,
|
|
4168
|
+
needsBootstrap: credential !== null && relayUrl === null,
|
|
4169
|
+
running,
|
|
4170
|
+
result,
|
|
4171
|
+
bootstrap
|
|
4172
|
+
};
|
|
4173
|
+
}
|
|
4174
|
+
function statusOf(err) {
|
|
4175
|
+
if (!err || typeof err !== "object") return void 0;
|
|
4176
|
+
const e = err;
|
|
4177
|
+
for (const c of [e.status, e.response?.status, e.statusCode]) {
|
|
4178
|
+
if (typeof c === "number" && Number.isFinite(c)) return c;
|
|
4179
|
+
}
|
|
4180
|
+
return void 0;
|
|
4181
|
+
}
|
|
4182
|
+
var STEP_LABEL = {
|
|
4183
|
+
"no-credential": "No enrolled account",
|
|
4184
|
+
"admitters-lookup": "Admitters lookup failed",
|
|
4185
|
+
"no-nodes": "No hosted node serves this namespace",
|
|
4186
|
+
"not-invited": "This invitation names none of the serving nodes",
|
|
4187
|
+
"invited-unreachable": "The invited admitter cannot take a join right now",
|
|
4188
|
+
"no-relay-url": "The invited admitter has no address yet",
|
|
4189
|
+
sign: "The join could not be signed",
|
|
4190
|
+
admit: "The admitter refused the join"
|
|
4191
|
+
};
|
|
4192
|
+
function accountJoinIsFinal(failure) {
|
|
4193
|
+
if (failure.step === "admit") return failure.status === 400 || failure.status === 403;
|
|
4194
|
+
return failure.step === "not-invited" || failure.step === "sign";
|
|
4195
|
+
}
|
|
4196
|
+
function isFinalInvitationError(message) {
|
|
4197
|
+
if (!message) return false;
|
|
4198
|
+
const m = message.toLowerCase();
|
|
4199
|
+
return [
|
|
4200
|
+
"invitation expired",
|
|
4201
|
+
"expired invitation",
|
|
4202
|
+
"invalid invitation",
|
|
4203
|
+
"invitation is invalid",
|
|
4204
|
+
"malformed invitation",
|
|
4205
|
+
"malformed payload",
|
|
4206
|
+
"invalid signature",
|
|
4207
|
+
"signature verification failed",
|
|
4208
|
+
"not admin",
|
|
4209
|
+
"revoked",
|
|
4210
|
+
"already a member"
|
|
4211
|
+
].some((t) => m.includes(t));
|
|
4212
|
+
}
|
|
4213
|
+
function useJoinInvitation() {
|
|
4214
|
+
const { mero, isDelegated } = useMero();
|
|
4215
|
+
const { credential, bootstrap } = useDelegatedBootstrap();
|
|
4216
|
+
const [joining, setJoining] = react.useState(false);
|
|
4217
|
+
const joinInvitation = react.useCallback(
|
|
4218
|
+
async (input) => {
|
|
4219
|
+
setJoining(true);
|
|
4220
|
+
try {
|
|
4221
|
+
const asAccount = isDelegated || credential !== null && mero === null;
|
|
4222
|
+
if (asAccount) {
|
|
4223
|
+
const outcome = await bootstrap({
|
|
4224
|
+
namespaceId: input.namespaceId,
|
|
4225
|
+
invitation: input.invitation,
|
|
4226
|
+
contextId: input.contextId
|
|
4227
|
+
});
|
|
4228
|
+
if (outcome.ok) return { ok: true };
|
|
4229
|
+
return {
|
|
4230
|
+
ok: false,
|
|
4231
|
+
step: outcome.step,
|
|
4232
|
+
reason: `${STEP_LABEL[outcome.step]}. ${outcome.reason}`,
|
|
4233
|
+
final: accountJoinIsFinal(outcome),
|
|
4234
|
+
...outcome.status !== void 0 ? { status: outcome.status } : {}
|
|
4235
|
+
};
|
|
4236
|
+
}
|
|
4237
|
+
if (!mero) {
|
|
4238
|
+
return { ok: false, step: "node-join", reason: "Not connected to a node.", final: false };
|
|
4239
|
+
}
|
|
4240
|
+
await mero.admin.joinNamespace(input.namespaceId, { invitation: input.invitation });
|
|
4241
|
+
await mero.admin.joinContext(input.contextId);
|
|
4242
|
+
return { ok: true };
|
|
4243
|
+
} catch (e) {
|
|
4244
|
+
const reason = e instanceof Error ? e.message : String(e);
|
|
4245
|
+
const status = statusOf(e);
|
|
4246
|
+
return {
|
|
4247
|
+
ok: false,
|
|
4248
|
+
step: "node-join",
|
|
4249
|
+
reason,
|
|
4250
|
+
final: isFinalInvitationError(reason),
|
|
4251
|
+
...status !== void 0 ? { status } : {}
|
|
4252
|
+
};
|
|
4253
|
+
} finally {
|
|
4254
|
+
setJoining(false);
|
|
4255
|
+
}
|
|
4256
|
+
},
|
|
4257
|
+
[mero, isDelegated, credential, bootstrap]
|
|
4258
|
+
);
|
|
4259
|
+
const memberships = react.useCallback(async () => {
|
|
4260
|
+
const asAccount = isDelegated || credential !== null && mero === null;
|
|
4261
|
+
const ids = (list) => list.map((n) => n.namespaceId ?? n.groupId ?? n.id ?? "").filter(Boolean);
|
|
4262
|
+
if (asAccount) {
|
|
4263
|
+
const session = readDelegatedSession();
|
|
4264
|
+
return session ? ids(await listDelegatedNamespaces(session)) : [];
|
|
4265
|
+
}
|
|
4266
|
+
if (!mero) return [];
|
|
4267
|
+
return ids(await mero.admin.listNamespaces());
|
|
4268
|
+
}, [mero, isDelegated, credential]);
|
|
4269
|
+
const invitationRedeemer = react.useCallback(
|
|
4270
|
+
(input) => ({
|
|
4271
|
+
join: async () => {
|
|
4272
|
+
const outcome = await joinInvitation(input);
|
|
4273
|
+
if (!outcome.ok) {
|
|
4274
|
+
throw Object.assign(new Error(outcome.reason), outcome.status !== void 0 ? { status: outcome.status } : {});
|
|
4275
|
+
}
|
|
4276
|
+
},
|
|
4277
|
+
memberships
|
|
4278
|
+
}),
|
|
4279
|
+
[joinInvitation, memberships]
|
|
4280
|
+
);
|
|
4281
|
+
return { joinInvitation, joining, memberships, invitationRedeemer };
|
|
4282
|
+
}
|
|
2959
4283
|
|
|
2960
4284
|
Object.defineProperty(exports, "CAPABILITIES", {
|
|
2961
4285
|
enumerable: true,
|
|
@@ -2996,6 +4320,7 @@ Object.defineProperty(exports, "withoutCap", {
|
|
|
2996
4320
|
exports.AppMode = AppMode;
|
|
2997
4321
|
exports.CalimeroLogo = CalimeroLogo;
|
|
2998
4322
|
exports.ConnectButton = ConnectButton;
|
|
4323
|
+
exports.ConnectButtonAccount = ConnectButtonAccount;
|
|
2999
4324
|
exports.ConnectionType = ConnectionType;
|
|
3000
4325
|
exports.DEFAULT_MIGRATION_POLL_INTERVAL_MS = DEFAULT_MIGRATION_POLL_INTERVAL_MS;
|
|
3001
4326
|
exports.LoginModal = LoginModal;
|
|
@@ -3004,12 +4329,15 @@ exports.MeroContext = MeroContext;
|
|
|
3004
4329
|
exports.MeroProvider = MeroProvider;
|
|
3005
4330
|
exports.MigrationAdminPanel = MigrationAdminPanel;
|
|
3006
4331
|
exports.MigrationPendingBanner = MigrationPendingBanner;
|
|
4332
|
+
exports.bootstrapFromInvitation = bootstrapFromInvitation;
|
|
3007
4333
|
exports.clearAllStorage = clearAllStorage;
|
|
3008
4334
|
exports.clearApplicationId = clearApplicationId;
|
|
3009
4335
|
exports.clearContextId = clearContextId;
|
|
3010
4336
|
exports.clearContextIdentity = clearContextIdentity;
|
|
4337
|
+
exports.clearDelegatedCredential = clearDelegatedCredential;
|
|
3011
4338
|
exports.clearNodeUrl = clearNodeUrl;
|
|
3012
4339
|
exports.clearTokenNodeUrl = clearTokenNodeUrl;
|
|
4340
|
+
exports.createDelegatedContext = createDelegatedContext;
|
|
3013
4341
|
exports.cssVar = cssVar;
|
|
3014
4342
|
exports.defaultMeroTheme = defaultMeroTheme;
|
|
3015
4343
|
exports.getApplicationId = getApplicationId;
|
|
@@ -3017,8 +4345,20 @@ exports.getContextId = getContextId;
|
|
|
3017
4345
|
exports.getContextIdentity = getContextIdentity;
|
|
3018
4346
|
exports.getNodeUrl = getNodeUrl;
|
|
3019
4347
|
exports.getTokenNodeUrl = getTokenNodeUrl;
|
|
4348
|
+
exports.isFinalInvitationError = isFinalInvitationError;
|
|
4349
|
+
exports.joinWithNode = joinWithNode;
|
|
4350
|
+
exports.listDelegatedContexts = listDelegatedContexts;
|
|
3020
4351
|
exports.localStorageTokenStorage = localStorageTokenStorage;
|
|
4352
|
+
exports.normaliseAccount = normaliseAccount;
|
|
4353
|
+
exports.pinRelayNodeKey = pinRelayNodeKey;
|
|
4354
|
+
exports.readDelegatedCredential = readDelegatedCredential;
|
|
4355
|
+
exports.readPinnedRelayNodeKey = readPinnedRelayNodeKey;
|
|
4356
|
+
exports.readRelayMap = readRelayMap;
|
|
4357
|
+
exports.relayForContext = relayForContext;
|
|
4358
|
+
exports.rememberRelay = rememberRelay;
|
|
3021
4359
|
exports.resolveMeroTheme = resolveMeroTheme;
|
|
4360
|
+
exports.resolveRelayFromInvitation = resolveRelayFromInvitation;
|
|
4361
|
+
exports.saveDelegatedCredential = saveDelegatedCredential;
|
|
3022
4362
|
exports.setApplicationId = setApplicationId;
|
|
3023
4363
|
exports.setContextId = setContextId;
|
|
3024
4364
|
exports.setContextIdentity = setContextIdentity;
|
|
@@ -3037,7 +4377,9 @@ exports.useCreateContext = useCreateContext;
|
|
|
3037
4377
|
exports.useCreateGroupInNamespace = useCreateGroupInNamespace;
|
|
3038
4378
|
exports.useCreateNamespace = useCreateNamespace;
|
|
3039
4379
|
exports.useCreateNamespaceInvitation = useCreateNamespaceInvitation;
|
|
4380
|
+
exports.useCreatePrivateContext = useCreatePrivateContext;
|
|
3040
4381
|
exports.useDefaultCapabilities = useDefaultCapabilities;
|
|
4382
|
+
exports.useDelegatedBootstrap = useDelegatedBootstrap;
|
|
3041
4383
|
exports.useDeleteContext = useDeleteContext;
|
|
3042
4384
|
exports.useDeleteGroup = useDeleteGroup;
|
|
3043
4385
|
exports.useDeleteNamespace = useDeleteNamespace;
|
|
@@ -3055,6 +4397,7 @@ exports.useGroupUpgradeStatus = useGroupUpgradeStatus;
|
|
|
3055
4397
|
exports.useInstallFromRegistry = useInstallFromRegistry;
|
|
3056
4398
|
exports.useJoinContext = useJoinContext;
|
|
3057
4399
|
exports.useJoinGroup = useJoinGroup;
|
|
4400
|
+
exports.useJoinInvitation = useJoinInvitation;
|
|
3058
4401
|
exports.useJoinNamespace = useJoinNamespace;
|
|
3059
4402
|
exports.useJoinSubgroupInheritance = useJoinSubgroupInheritance;
|
|
3060
4403
|
exports.useLatestVersion = useLatestVersion;
|