@calimero-network/mero-react 9.4.0 → 9.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createContext, useMemo, useState, useRef, useCallback, useEffect, useContext } from 'react';
2
- import { signGroupInvitation, LocalStorageTokenStore, parseAuthCallback, MeroJs, buildAuthLoginUrl, DEFAULT_LOCAL_NODE_PORTS, discoverLocalNodes, nodeEndpoint, readEnrolmentCallback, completeDeviceEnrolment, CloudClient, deviceEnrolmentUrl, memberJoinedOpenOp, signerFromSecret, groupDeletedOp, memberAddedOp, memberRemovedOp, subgroupCreation, memberRoleSetOp, defaultCapabilitiesSetOp, subgroupVisibilitySetOp, groupMetadataSetOp, memberMetadataSetOp, contextMetadataSetOp, groupReparentedOp, contextDetachedOp, compareSemver, signMemberJoinOp, AuthRevokedError, HTTPError, memberLeftOp, memberCapabilitySetOp, attestRelayNodeKey, createMeroClient, RelayClient, classifyError, createLocalStorageNonceSource, login, defaultAudience, createSignedReleaseVerifier, fetchNodeRelease, cloudNodeReleaseUrl, DEFAULT_RELEASE_MIRROR, fetchNodeReleaseVersion } from '@calimero-network/mero-js';
2
+ import { signGroupInvitation, signMemberJoinOp, CloudClient, LocalStorageTokenStore, parseAuthCallback, MeroJs, buildAuthLoginUrl, DEFAULT_LOCAL_NODE_PORTS, discoverLocalNodes, nodeEndpoint, readEnrolmentCallback, completeDeviceEnrolment, deviceEnrolmentUrl, memberJoinedOpenOp, signerFromSecret, groupDeletedOp, memberAddedOp, memberRemovedOp, subgroupCreation, memberRoleSetOp, defaultCapabilitiesSetOp, subgroupVisibilitySetOp, groupMetadataSetOp, memberMetadataSetOp, contextMetadataSetOp, groupReparentedOp, contextDetachedOp, compareSemver, AuthRevokedError, HTTPError, memberLeftOp, memberCapabilitySetOp, attestRelayNodeKey, createMeroClient, RelayClient, createLocalStorageNonceSource, classifyError, login, defaultAudience, createSignedReleaseVerifier, fetchNodeRelease, cloudNodeReleaseUrl, DEFAULT_RELEASE_MIRROR, fetchNodeReleaseVersion } from '@calimero-network/mero-js';
3
3
  export * from '@calimero-network/mero-js';
4
4
  export { CAPABILITIES, DEFAULT_LOCAL_NODE_PORTS, discoverLocalNodes, hasCap, localNodeUrl, nodeEndpoint, probeNodeHealth, withCap, withoutCap } from '@calimero-network/mero-js';
5
5
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
@@ -559,8 +559,23 @@ var NODE_ONLY = /* @__PURE__ */ new Set([
559
559
  "uninstallApplication",
560
560
  "generateContextIdentity",
561
561
  "deleteContext",
562
- "createAlias",
563
- "deleteAlias"
562
+ "createContextAlias",
563
+ "createApplicationAlias",
564
+ "createDeviceAlias",
565
+ "deleteContextAlias",
566
+ "deleteApplicationAlias",
567
+ "deleteDeviceAlias",
568
+ "deleteNamespace",
569
+ "createGroupInvitation",
570
+ "joinGroup",
571
+ "setTeeAdmissionPolicy",
572
+ "getTeeAdmissionPolicy",
573
+ "deleteBlob",
574
+ "listAccountDevices",
575
+ "revokeAccountDevice",
576
+ "getGroupUpgradeStatus",
577
+ "getMigrationStatus",
578
+ "getCascadeStatus"
564
579
  ]);
565
580
  function createAccountAdmin(input, deps = {}) {
566
581
  const { session: s, read, app } = input;
@@ -570,6 +585,11 @@ function createAccountAdmin(input, deps = {}) {
570
585
  const found = deps.found ?? foundDelegatedNamespace;
571
586
  const latestVersion = deps.latestVersion ?? latestPublishedVersion;
572
587
  const signInvitation = deps.signInvitation ?? signGroupInvitation;
588
+ const join = deps.join;
589
+ async function joinNamespace(namespaceId, req) {
590
+ if (!join) throw new NotForAccountError("joinNamespace without a join handler");
591
+ return join(namespaceId, req.invitation);
592
+ }
573
593
  const relay = () => {
574
594
  if (read === null) throw new NoRelayError("this call");
575
595
  return read;
@@ -692,6 +712,25 @@ function createAccountAdmin(input, deps = {}) {
692
712
  // The relay syncs its own view; an account has nothing to pull.
693
713
  async syncGroup(groupId) {
694
714
  return { groupId, synced: true };
715
+ },
716
+ async syncContext() {
717
+ },
718
+ joinNamespace,
719
+ async updateMemberRole(groupId, identity, req) {
720
+ await group(s, groupId, memberRoleSetOp(identity, req.role));
721
+ },
722
+ // An open subgroup is joined the way `joinContext` joins one: MemberJoinedOpen
723
+ // on the subgroup, and nothing to do for a member already in it.
724
+ async joinSubgroupInheritance(groupId) {
725
+ const { members } = await relay().listGroupMembers(groupId);
726
+ if (members.some((m) => m.identity.toLowerCase() === s.account.toLowerCase())) {
727
+ return { groupId, memberPublicKey: s.account, wasInherited: false };
728
+ }
729
+ await root(s, groupId, memberJoinedOpenOp({ member: s.account, groupId, credential: s.credential }));
730
+ return { groupId, memberPublicKey: s.account, wasInherited: true };
731
+ },
732
+ async detachContextFromGroup(groupId, contextId) {
733
+ await group(s, groupId, contextDetachedOp(contextId));
695
734
  }
696
735
  };
697
736
  if (read === null) {
@@ -699,6 +738,7 @@ function createAccountAdmin(input, deps = {}) {
699
738
  get(_target, prop) {
700
739
  if (typeof prop !== "string") return void 0;
701
740
  if (prop === "getNodeIdentity") return writes.getNodeIdentity;
741
+ if (prop === "joinNamespace") return joinNamespace;
702
742
  if (prop in EMPTY_READS) return EMPTY_READS[prop];
703
743
  return async () => {
704
744
  throw new NoRelayError(prop);
@@ -718,6 +758,217 @@ function createAccountAdmin(input, deps = {}) {
718
758
  }
719
759
  });
720
760
  }
761
+ function explainAdmitFailure(status, body) {
762
+ const detail = body ? `: ${body}` : "";
763
+ switch (status) {
764
+ case 400:
765
+ 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.`;
766
+ case 403:
767
+ 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.`;
768
+ case 409:
769
+ return `That node holds no device of its own, so it cannot endorse anyone (409)${detail}. Another admitter from the same invitation would work.`;
770
+ default:
771
+ return `The join was not published (HTTP ${status})${detail}.`;
772
+ }
773
+ }
774
+ function joinNonce(account) {
775
+ const source = createLocalStorageNonceSource(`calimero.delegated.joinnonce.${account}`);
776
+ return () => source.next();
777
+ }
778
+ function origin(url) {
779
+ return url.replace(/\/+$/, "");
780
+ }
781
+ async function joinWithNode(input) {
782
+ const { account, credential, deviceSecret } = input.credential;
783
+ let signedOp;
784
+ try {
785
+ signedOp = await signMemberJoinOp({
786
+ namespaceId: input.namespaceId,
787
+ member: account,
788
+ invitation: input.invitation,
789
+ credential,
790
+ deviceSecret,
791
+ nonce: await (input.deps?.nonce ?? joinNonce(account))()
792
+ });
793
+ } catch (e) {
794
+ return {
795
+ ok: false,
796
+ step: "sign",
797
+ reason: `The join op could not be signed, so nothing was sent: ${e instanceof Error ? e.message : String(e)}`
798
+ };
799
+ }
800
+ const body = { invitation: input.invitation, signedOp };
801
+ const url = input.admitUrl ?? `${origin(input.nodeUrl)}/admin-api/namespaces/${input.namespaceId}/admit`;
802
+ const doFetch = input.deps?.fetch ?? fetch;
803
+ let response;
804
+ try {
805
+ response = await doFetch(url, {
806
+ method: "POST",
807
+ // No Authorization header and no request proof, deliberately: the route is
808
+ // unauthenticated because the joiner's signature is the authorization.
809
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
810
+ body: JSON.stringify(body)
811
+ });
812
+ } catch (e) {
813
+ return {
814
+ ok: false,
815
+ step: "admit",
816
+ 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.`
817
+ };
818
+ }
819
+ const text = await response.text();
820
+ if (!response.ok) {
821
+ return {
822
+ ok: false,
823
+ step: "admit",
824
+ status: response.status,
825
+ reason: explainAdmitFailure(response.status, text)
826
+ };
827
+ }
828
+ let published = false;
829
+ try {
830
+ const parsed = text ? JSON.parse(text) : {};
831
+ published = parsed.data?.published === true;
832
+ } catch {
833
+ published = false;
834
+ }
835
+ return {
836
+ ok: true,
837
+ published,
838
+ session: { relayUrl: origin(input.nodeUrl), account, credential, deviceSecret }
839
+ };
840
+ }
841
+ function normaliseAccount(account) {
842
+ if (!account) return null;
843
+ const trimmed = account.trim().toLowerCase();
844
+ const bare = trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
845
+ return bare.length > 0 ? bare : null;
846
+ }
847
+ function isInvited(node, invited) {
848
+ if (invited.size === 0) return true;
849
+ const account = normaliseAccount(node.account);
850
+ return account !== null && invited.has(account);
851
+ }
852
+ async function resolveRelayFromInvitation(input) {
853
+ const cloud = input.cloud ?? new CloudClient({
854
+ cloudBaseUrl: input.cloudBaseUrl,
855
+ routingCredential: { credential: input.credential, deviceSecret: input.deviceSecret }
856
+ });
857
+ let nodes;
858
+ let servable;
859
+ try {
860
+ const routing = await cloud.getNamespaceRouting(input.namespaceId);
861
+ nodes = routing.nodes;
862
+ servable = routing.servable;
863
+ } catch (e) {
864
+ return {
865
+ ok: false,
866
+ step: "admitters-lookup",
867
+ 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.`
868
+ };
869
+ }
870
+ if (nodes.length === 0) {
871
+ return {
872
+ ok: false,
873
+ step: "no-nodes",
874
+ 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."
875
+ };
876
+ }
877
+ const invited = new Set(
878
+ (input.admitters ?? []).map(normaliseAccount).filter((a) => a !== null)
879
+ );
880
+ const named = nodes.filter((n) => isInvited(n, invited));
881
+ if (named.length === 0) {
882
+ return {
883
+ ok: false,
884
+ step: "not-invited",
885
+ 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.`
886
+ };
887
+ }
888
+ const usable = named.filter((n) => n.canAdmit);
889
+ const candidates = usable.length > 0 ? usable : named;
890
+ const advisory = usable.length === 0 || !servable;
891
+ const addressable = candidates.filter(
892
+ (n) => typeof n.relayUrl === "string" && n.relayUrl.length > 0
893
+ );
894
+ if (addressable.length === 0) {
895
+ return {
896
+ ok: false,
897
+ step: "no-relay-url",
898
+ 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."
899
+ };
900
+ }
901
+ const chosen = addressable.find((n) => n.canExecute) ?? addressable.find((n) => n.fresh) ?? addressable[0];
902
+ return {
903
+ ok: true,
904
+ relayUrl: chosen.relayUrl,
905
+ // The cloud's ready-made URL when it gave one, so the path is never rebuilt
906
+ // from a guess; the fallback is the documented route on the same origin.
907
+ admitUrl: chosen.admitUrl ?? `${chosen.relayUrl.replace(/\/+$/, "")}/admin-api/namespaces/${input.namespaceId}/admit`,
908
+ admitterAccount: chosen.account,
909
+ peerId: chosen.peerId,
910
+ writable: chosen.canExecute,
911
+ // Stale when the node's own heartbeat lapsed OR when the cloud's summary
912
+ // disagrees with trying it at all. Both mean the same thing to a caller:
913
+ // this was attempted on advisory data, so if the admit fails that is why.
914
+ stale: !chosen.fresh || advisory
915
+ };
916
+ }
917
+
918
+ // src/delegated/bootstrap-from-invitation.ts
919
+ async function bootstrapFromInvitation(input) {
920
+ const resolve = input.deps?.resolve ?? resolveRelayFromInvitation;
921
+ const join = input.deps?.join ?? joinWithNode;
922
+ let relay = null;
923
+ let nodeUrl = input.nodeUrl;
924
+ let admitUrl;
925
+ if (!nodeUrl) {
926
+ const resolved = await resolve({
927
+ namespaceId: input.namespaceId,
928
+ // The signed list, read off the invitation itself rather than passed
929
+ // separately: two sources for one fact is how an intersection ends up
930
+ // being performed against the wrong list.
931
+ admitters: input.invitation.invitation.admitters,
932
+ credential: input.credential.credential,
933
+ deviceSecret: input.credential.deviceSecret,
934
+ cloudBaseUrl: input.cloudBaseUrl
935
+ });
936
+ if (!resolved.ok) return resolved;
937
+ relay = resolved;
938
+ nodeUrl = resolved.relayUrl;
939
+ admitUrl = resolved.admitUrl;
940
+ }
941
+ const joined = await join({
942
+ nodeUrl,
943
+ admitUrl,
944
+ namespaceId: input.namespaceId,
945
+ invitation: input.invitation,
946
+ credential: input.credential,
947
+ deps: { fetch: input.deps?.fetch, nonce: input.deps?.nonce }
948
+ });
949
+ if (!joined.ok) return joined;
950
+ return { ok: true, published: joined.published, relay, session: joined.session };
951
+ }
952
+
953
+ // src/delegated/join-as-account.ts
954
+ async function joinAsAccount(session, namespaceId, invitation, opts) {
955
+ const bootstrap = opts.bootstrap ?? bootstrapFromInvitation;
956
+ const outcome = await bootstrap({
957
+ namespaceId,
958
+ invitation,
959
+ credential: { account: session.account, credential: session.credential, deviceSecret: session.deviceSecret },
960
+ cloudBaseUrl: opts.cloudBaseUrl
961
+ });
962
+ if (!outcome.ok) {
963
+ throw Object.assign(new Error(outcome.reason), {
964
+ step: outcome.step,
965
+ ...outcome.status !== void 0 ? { status: outcome.status } : {}
966
+ });
967
+ }
968
+ if (outcome.session.relayUrl) rememberRelay(session.account, outcome.session.relayUrl, { namespaceId });
969
+ opts.onJoined(outcome.session);
970
+ return { namespaceId };
971
+ }
721
972
 
722
973
  // src/auth/node-trust.ts
723
974
  function sameOrigin(a, b) {
@@ -1271,13 +1522,19 @@ function MeroProvider({
1271
1522
  const admin = useMemo(() => {
1272
1523
  const app = { packageName, packageVersion, registryUrl };
1273
1524
  if (delegated !== null) {
1274
- if (delegated.relayUrl === null) return createAccountAdmin({ session: delegated, read: null, app });
1525
+ const deps = {
1526
+ join: (namespaceId, invitation) => joinAsAccount(delegated, namespaceId, invitation, { cloudBaseUrl, onJoined: connectWithAccount })
1527
+ };
1528
+ if (delegated.relayUrl === null) return createAccountAdmin({ session: delegated, read: null, app }, deps);
1275
1529
  if (!mero) return null;
1276
- return createAccountAdmin({ session: delegated, read: mero.admin, app });
1530
+ return createAccountAdmin(
1531
+ { session: delegated, read: mero.admin, app },
1532
+ deps
1533
+ );
1277
1534
  }
1278
1535
  const nodeAdmin = mero?.admin;
1279
1536
  return nodeAdmin ? createNodeAdmin({ admin: nodeAdmin, app }) : null;
1280
- }, [mero, delegated, packageName, packageVersion, registryUrl]);
1537
+ }, [mero, delegated, packageName, packageVersion, registryUrl, cloudBaseUrl, connectWithAccount]);
1281
1538
  const contextValue = useMemo(
1282
1539
  () => ({
1283
1540
  mero,
@@ -1403,7 +1660,85 @@ function themeToCssVars(theme) {
1403
1660
  function cssVar(theme, key) {
1404
1661
  return `var(${MERO_CSS_VARS[key]}, ${theme[key]})`;
1405
1662
  }
1663
+ function AccountSignInPanel({
1664
+ onEnrol,
1665
+ note,
1666
+ walletUrl,
1667
+ customWallet = false,
1668
+ theme
1669
+ }) {
1670
+ const styles = useMemo(() => {
1671
+ const t = resolveMeroTheme(theme);
1672
+ const radius = cssVar(t, "radius");
1673
+ const error = cssVar(t, "error");
1674
+ return {
1675
+ root: { display: "flex", flexDirection: "column", gap: "1rem" },
1676
+ info: {
1677
+ color: cssVar(t, "textSecondary"),
1678
+ textAlign: "center",
1679
+ fontSize: "0.875rem",
1680
+ margin: 0
1681
+ },
1682
+ hint: {
1683
+ color: cssVar(t, "textSecondary"),
1684
+ textAlign: "center",
1685
+ fontSize: "0.8125rem",
1686
+ margin: 0,
1687
+ opacity: 0.8,
1688
+ overflowWrap: "anywhere"
1689
+ },
1690
+ note: {
1691
+ color: error,
1692
+ backgroundColor: `color-mix(in srgb, ${error} 10%, transparent)`,
1693
+ border: `1px solid color-mix(in srgb, ${error} 30%, transparent)`,
1694
+ borderRadius: radius,
1695
+ padding: "0.75rem",
1696
+ fontSize: "0.875rem",
1697
+ textAlign: "center",
1698
+ margin: 0
1699
+ },
1700
+ buttonGroup: { display: "flex", justifyContent: "center" },
1701
+ button: {
1702
+ padding: "0.75rem 2rem",
1703
+ borderRadius: radius,
1704
+ border: "none",
1705
+ fontSize: "0.875rem",
1706
+ fontWeight: 600,
1707
+ cursor: "pointer",
1708
+ backgroundColor: cssVar(t, "primary"),
1709
+ color: cssVar(t, "primaryText"),
1710
+ transition: "all 0.15s ease"
1711
+ }
1712
+ };
1713
+ }, [theme]);
1714
+ return /* @__PURE__ */ jsxs("div", { style: styles.root, "data-testid": "account-sign-in-panel", children: [
1715
+ note && /* @__PURE__ */ jsx("p", { style: styles.note, role: "status", "data-testid": "account-note", children: note }),
1716
+ /* @__PURE__ */ jsx("p", { style: styles.info, 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." }),
1717
+ /* @__PURE__ */ jsx("p", { style: styles.info, 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." }),
1718
+ /* @__PURE__ */ jsx("div", { style: styles.buttonGroup, children: /* @__PURE__ */ jsx(
1719
+ "button",
1720
+ {
1721
+ type: "button",
1722
+ style: styles.button,
1723
+ onClick: onEnrol,
1724
+ "data-testid": "enrol-button",
1725
+ children: "Enrol with your account"
1726
+ }
1727
+ ) }),
1728
+ customWallet && walletUrl && /* Shown only when an app overrode it, so a local rig can see at a
1729
+ glance that it is not enrolling against the hosted wallet. */
1730
+ /* @__PURE__ */ jsxs("p", { style: styles.hint, children: [
1731
+ "Enrolling at ",
1732
+ /* @__PURE__ */ jsx("code", { children: walletUrl }),
1733
+ ", not the hosted wallet."
1734
+ ] })
1735
+ ] });
1736
+ }
1406
1737
  var CUSTOM_SELECTION = "__custom__";
1738
+ var TABS = [
1739
+ { id: "node", label: "Node" },
1740
+ { id: "cloud", label: "Cloud" }
1741
+ ];
1407
1742
  function isValidUrl(urlString) {
1408
1743
  if (!urlString || urlString.trim() === "") {
1409
1744
  return false;
@@ -1639,6 +1974,32 @@ function buildStyles(t) {
1639
1974
  borderRadius: "50%",
1640
1975
  animation: "meroSpin 1s linear infinite"
1641
1976
  },
1977
+ tabList: {
1978
+ display: "flex",
1979
+ gap: "0.25rem",
1980
+ padding: "0.25rem",
1981
+ marginBottom: "1.5rem",
1982
+ borderRadius: radius,
1983
+ border: `1px solid ${border}`,
1984
+ backgroundColor: bgSecondary
1985
+ },
1986
+ tab: {
1987
+ flex: 1,
1988
+ padding: "0.5rem 1rem",
1989
+ borderRadius: radius,
1990
+ border: "1px solid transparent",
1991
+ backgroundColor: "transparent",
1992
+ color: textSecondary,
1993
+ fontSize: "0.875rem",
1994
+ fontWeight: 600,
1995
+ cursor: "pointer",
1996
+ transition: "all 0.15s ease"
1997
+ },
1998
+ tabActive: {
1999
+ border: `1px solid ${accent}`,
2000
+ backgroundColor: accentGlow,
2001
+ color: text
2002
+ },
1642
2003
  spinnerSmall: {
1643
2004
  width: "1.5rem",
1644
2005
  height: "1.5rem",
@@ -1654,8 +2015,19 @@ function LoginModal({
1654
2015
  onClose,
1655
2016
  isOpen,
1656
2017
  theme,
1657
- localNodePorts = DEFAULT_LOCAL_NODE_PORTS
2018
+ localNodePorts = DEFAULT_LOCAL_NODE_PORTS,
2019
+ cloud,
2020
+ initialTab = "node"
1658
2021
  }) {
2022
+ const [tab, setTab] = useState(initialTab);
2023
+ useEffect(() => {
2024
+ if (isOpen) setTab(initialTab);
2025
+ }, [isOpen, initialTab]);
2026
+ const tabRefs = useRef({
2027
+ node: null,
2028
+ cloud: null
2029
+ });
2030
+ const activeTab = cloud ? tab : "node";
1659
2031
  const [selected, setSelected] = useState(CUSTOM_SELECTION);
1660
2032
  const [discovered, setDiscovered] = useState([]);
1661
2033
  const [discovering, setDiscovering] = useState(false);
@@ -1834,54 +2206,313 @@ function LoginModal({
1834
2206
  ) })
1835
2207
  ] });
1836
2208
  };
1837
- const modalContent = /* @__PURE__ */ jsxs(Fragment, { children: [
1838
- /* @__PURE__ */ jsx("style", { children: `
1839
- @keyframes meroSpin { to { transform: rotate(360deg); } }
1840
- @keyframes meroFadeIn { from { opacity: 0; } to { opacity: 1; } }
1841
- @keyframes meroSlideIn { from { transform: translateY(-12px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
1842
- ` }),
1843
- /* @__PURE__ */ jsx("div", { style: { ...themeVars, ...styles.overlay }, onClick: onClose, children: /* @__PURE__ */ jsxs("div", { style: styles.content, onClick: (e) => e.stopPropagation(), children: [
1844
- /* @__PURE__ */ jsx("button", { style: styles.closeButton, onClick: onClose, "aria-label": "Close", children: "\xD7" }),
1845
- /* @__PURE__ */ jsxs("div", { style: styles.header, children: [
1846
- /* @__PURE__ */ jsx(CalimeroLogo, { size: 44, color: cssVar(resolved, "primary") }),
1847
- /* @__PURE__ */ jsx("h1", { style: styles.title, children: "Connect to Calimero" })
1848
- ] }),
1849
- loading ? /* @__PURE__ */ jsxs("div", { style: styles.loading, children: [
1850
- /* @__PURE__ */ jsx("p", { children: "Connecting to node..." }),
1851
- /* @__PURE__ */ jsx("div", { style: styles.spinner })
1852
- ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
1853
- error && /* @__PURE__ */ jsx("p", { style: styles.error, children: error }),
1854
- renderNodeSection(),
1855
- /* @__PURE__ */ jsx("div", { style: styles.buttonGroup, children: /* @__PURE__ */ jsx(
1856
- "button",
1857
- {
1858
- onClick: handleConnect,
1859
- disabled: !canConnect,
1860
- style: {
1861
- ...styles.button,
1862
- ...!canConnect ? styles.buttonDisabled : {}
1863
- },
1864
- "data-testid": "connect-button",
1865
- children: "Connect"
1866
- }
1867
- ) })
1868
- ] })
1869
- ] }) })
2209
+ const renderNodeBody = () => {
2210
+ const body = loading ? /* @__PURE__ */ jsxs("div", { style: styles.loading, children: [
2211
+ /* @__PURE__ */ jsx("p", { children: "Connecting to node..." }),
2212
+ /* @__PURE__ */ jsx("div", { style: styles.spinner })
2213
+ ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
2214
+ error && /* @__PURE__ */ jsx("p", { style: styles.error, children: error }),
2215
+ renderNodeSection(),
2216
+ /* @__PURE__ */ jsx("div", { style: styles.buttonGroup, children: /* @__PURE__ */ jsx(
2217
+ "button",
2218
+ {
2219
+ onClick: handleConnect,
2220
+ disabled: !canConnect,
2221
+ style: {
2222
+ ...styles.button,
2223
+ ...!canConnect ? styles.buttonDisabled : {}
2224
+ },
2225
+ "data-testid": "connect-button",
2226
+ children: "Connect"
2227
+ }
2228
+ ) })
2229
+ ] });
2230
+ if (!cloud) return body;
2231
+ return /* @__PURE__ */ jsx(
2232
+ "div",
2233
+ {
2234
+ role: "tabpanel",
2235
+ id: "mero-login-panel-node",
2236
+ "aria-labelledby": "mero-login-tab-node",
2237
+ children: body
2238
+ }
2239
+ );
2240
+ };
2241
+ const selectTab = (id) => {
2242
+ setTab(id);
2243
+ tabRefs.current[id]?.focus();
2244
+ };
2245
+ const onTabKeyDown = (e) => {
2246
+ const i = TABS.findIndex((t) => t.id === activeTab);
2247
+ let next = null;
2248
+ if (e.key === "ArrowRight") next = (i + 1) % TABS.length;
2249
+ else if (e.key === "ArrowLeft") next = (i - 1 + TABS.length) % TABS.length;
2250
+ else if (e.key === "Home") next = 0;
2251
+ else if (e.key === "End") next = TABS.length - 1;
2252
+ if (next === null) return;
2253
+ e.preventDefault();
2254
+ selectTab(TABS[next].id);
2255
+ };
2256
+ const renderTabs = () => /* @__PURE__ */ jsx("div", { role: "tablist", "aria-label": "How to connect", style: styles.tabList, children: TABS.map((t) => {
2257
+ const selected2 = activeTab === t.id;
2258
+ return /* @__PURE__ */ jsx(
2259
+ "button",
2260
+ {
2261
+ ref: (el) => {
2262
+ tabRefs.current[t.id] = el;
2263
+ },
2264
+ type: "button",
2265
+ role: "tab",
2266
+ id: `mero-login-tab-${t.id}`,
2267
+ "aria-selected": selected2,
2268
+ "aria-controls": `mero-login-panel-${t.id}`,
2269
+ tabIndex: selected2 ? 0 : -1,
2270
+ onClick: () => setTab(t.id),
2271
+ onKeyDown: onTabKeyDown,
2272
+ style: { ...styles.tab, ...selected2 ? styles.tabActive : {} },
2273
+ "data-testid": `login-tab-${t.id}`,
2274
+ children: t.label
2275
+ },
2276
+ t.id
2277
+ );
2278
+ }) });
2279
+ const modalContent = /* @__PURE__ */ jsxs(Fragment, { children: [
2280
+ /* @__PURE__ */ jsx("style", { children: `
2281
+ @keyframes meroSpin { to { transform: rotate(360deg); } }
2282
+ @keyframes meroFadeIn { from { opacity: 0; } to { opacity: 1; } }
2283
+ @keyframes meroSlideIn { from { transform: translateY(-12px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
2284
+ ` }),
2285
+ /* @__PURE__ */ jsx("div", { style: { ...themeVars, ...styles.overlay }, onClick: onClose, children: /* @__PURE__ */ jsxs("div", { style: styles.content, onClick: (e) => e.stopPropagation(), children: [
2286
+ /* @__PURE__ */ jsx("button", { style: styles.closeButton, onClick: onClose, "aria-label": "Close", children: "\xD7" }),
2287
+ /* @__PURE__ */ jsxs("div", { style: styles.header, children: [
2288
+ /* @__PURE__ */ jsx(CalimeroLogo, { size: 44, color: cssVar(resolved, "primary") }),
2289
+ /* @__PURE__ */ jsx("h1", { style: styles.title, children: "Connect to Calimero" })
2290
+ ] }),
2291
+ cloud && renderTabs(),
2292
+ activeTab === "cloud" && cloud ? /* @__PURE__ */ jsx(
2293
+ "div",
2294
+ {
2295
+ role: "tabpanel",
2296
+ id: "mero-login-panel-cloud",
2297
+ "aria-labelledby": "mero-login-tab-cloud",
2298
+ tabIndex: 0,
2299
+ children: /* @__PURE__ */ jsx(
2300
+ AccountSignInPanel,
2301
+ {
2302
+ onEnrol: cloud.onEnrol,
2303
+ note: cloud.note,
2304
+ walletUrl: cloud.walletUrl,
2305
+ customWallet: cloud.customWallet,
2306
+ theme
2307
+ }
2308
+ )
2309
+ }
2310
+ ) : renderNodeBody()
2311
+ ] }) })
1870
2312
  ] });
1871
2313
  return createPortal(modalContent, document.body);
1872
2314
  }
2315
+ var DEVICE_KEY = "calimero.device";
2316
+ var STATE_KEY = "calimero.enrol.state";
2317
+ var HOSTED_WALLET = "https://wallet.cloud.calimero.network/account-enroll";
2318
+ var hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
2319
+ function chooseRelay(relays) {
2320
+ const reachable = relays.filter(
2321
+ (r) => typeof r.relayUrl === "string" && r.relayUrl.length > 0
2322
+ );
2323
+ const fresh = reachable.find((r) => r.fresh);
2324
+ if (fresh) return { relayUrl: fresh.relayUrl, note: null };
2325
+ if (reachable.length > 0) {
2326
+ return {
2327
+ relayUrl: reachable[0].relayUrl,
2328
+ note: "Connected through a relay whose last heartbeat has lapsed \u2014 it may not answer. It was the only one with an address."
2329
+ };
2330
+ }
2331
+ if (relays.length > 0) {
2332
+ return {
2333
+ relayUrl: null,
2334
+ 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.`
2335
+ };
2336
+ }
2337
+ return {
2338
+ relayUrl: null,
2339
+ 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."
2340
+ };
2341
+ }
2342
+ async function deviceKeys() {
2343
+ const had = localStorage.getItem(DEVICE_KEY);
2344
+ if (had) {
2345
+ const parsed = JSON.parse(had);
2346
+ if (parsed.kemSk && parsed.signSk && parsed.signPk && parsed.kemPk) {
2347
+ return parsed;
2348
+ }
2349
+ localStorage.removeItem(DEVICE_KEY);
2350
+ }
2351
+ const sign = await crypto.subtle.generateKey({ name: "Ed25519" }, true, [
2352
+ "sign",
2353
+ "verify"
2354
+ ]);
2355
+ let agree;
2356
+ try {
2357
+ agree = await crypto.subtle.generateKey({ name: "X25519" }, true, [
2358
+ "deriveBits"
2359
+ ]);
2360
+ } catch {
2361
+ throw new Error(
2362
+ "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."
2363
+ );
2364
+ }
2365
+ const keys = {
2366
+ signPk: hex(await crypto.subtle.exportKey("raw", sign.publicKey)),
2367
+ signSk: hex((await crypto.subtle.exportKey("pkcs8", sign.privateKey)).slice(16)),
2368
+ kemPk: hex(await crypto.subtle.exportKey("raw", agree.publicKey)),
2369
+ kemSk: hex((await crypto.subtle.exportKey("pkcs8", agree.privateKey)).slice(16))
2370
+ };
2371
+ localStorage.setItem(DEVICE_KEY, JSON.stringify(keys));
2372
+ return keys;
2373
+ }
2374
+ function useAccountEnrolment({
2375
+ walletUrl: walletOverride,
2376
+ enabled = true
2377
+ } = {}) {
2378
+ const { connectWithAccount, cloudBaseUrl } = useMero();
2379
+ const [note, setNote] = useState(null);
2380
+ const walletUrl = walletOverride ?? HOSTED_WALLET;
2381
+ const callbackRef = useRef(void 0);
2382
+ const callbackErrorRef = useRef(null);
2383
+ if (enabled && callbackRef.current === void 0 && typeof window !== "undefined") {
2384
+ try {
2385
+ callbackRef.current = readEnrolmentCallback();
2386
+ } catch (e) {
2387
+ callbackRef.current = null;
2388
+ callbackErrorRef.current = e instanceof Error ? e.message : String(e);
2389
+ }
2390
+ }
2391
+ const returningRef = useRef(null);
2392
+ if (returningRef.current === null && callbackRef.current !== void 0) {
2393
+ returningRef.current = callbackRef.current !== null || callbackErrorRef.current !== null;
2394
+ }
2395
+ const completingRef = useRef(false);
2396
+ useEffect(() => {
2397
+ if (callbackErrorRef.current) {
2398
+ setNote(callbackErrorRef.current);
2399
+ callbackErrorRef.current = null;
2400
+ return;
2401
+ }
2402
+ const back = callbackRef.current;
2403
+ if (!back || completingRef.current) return;
2404
+ completingRef.current = true;
2405
+ let cancelled = false;
2406
+ (async () => {
2407
+ try {
2408
+ const keys = await deviceKeys();
2409
+ const sent = (() => {
2410
+ try {
2411
+ return sessionStorage.getItem(STATE_KEY);
2412
+ } catch {
2413
+ return null;
2414
+ }
2415
+ })();
2416
+ try {
2417
+ sessionStorage.removeItem(STATE_KEY);
2418
+ } catch {
2419
+ }
2420
+ if (!sent) {
2421
+ setNote(
2422
+ 'This enrolment could not be verified as one this tab started, so it was not accepted. Start again from "Enrol with your account".'
2423
+ );
2424
+ return;
2425
+ }
2426
+ const enrolled = await completeDeviceEnrolment({
2427
+ ...back,
2428
+ devicePublicKey: keys.signPk,
2429
+ kemPublicKey: keys.kemPk,
2430
+ expectState: sent
2431
+ });
2432
+ saveDelegatedCredential({
2433
+ account: enrolled.account,
2434
+ credential: enrolled.credential,
2435
+ deviceSecret: keys.signSk
2436
+ });
2437
+ const cloud = new CloudClient({
2438
+ cloudBaseUrl,
2439
+ routingCredential: {
2440
+ credential: enrolled.credential,
2441
+ deviceSecret: keys.signSk
2442
+ }
2443
+ });
2444
+ const chosen = chooseRelay(await cloud.getAccountRelays(enrolled.account));
2445
+ if (chosen.note) setNote(chosen.note);
2446
+ connectWithAccount({
2447
+ relayUrl: chosen.relayUrl,
2448
+ account: enrolled.account,
2449
+ credential: enrolled.credential,
2450
+ deviceSecret: keys.signSk
2451
+ });
2452
+ } catch (e) {
2453
+ if (!cancelled) setNote(e instanceof Error ? e.message : String(e));
2454
+ }
2455
+ })();
2456
+ return () => {
2457
+ cancelled = true;
2458
+ };
2459
+ }, [connectWithAccount, cloudBaseUrl]);
2460
+ const goToWallet = useCallback(async () => {
2461
+ let keys;
2462
+ try {
2463
+ keys = await deviceKeys();
2464
+ } catch (e) {
2465
+ setNote(e instanceof Error ? e.message : String(e));
2466
+ return;
2467
+ }
2468
+ const state = hex(crypto.getRandomValues(new Uint8Array(16)));
2469
+ try {
2470
+ sessionStorage.setItem(STATE_KEY, state);
2471
+ } catch {
2472
+ }
2473
+ window.location.assign(
2474
+ deviceEnrolmentUrl({
2475
+ walletUrl,
2476
+ devicePublicKey: keys.signPk,
2477
+ kemPublicKey: keys.kemPk,
2478
+ returnTo: window.location.origin + window.location.pathname,
2479
+ state
2480
+ })
2481
+ );
2482
+ }, [walletUrl]);
2483
+ return {
2484
+ goToWallet,
2485
+ note,
2486
+ returning: returningRef.current === true,
2487
+ walletUrl,
2488
+ customWallet: walletOverride !== void 0
2489
+ };
2490
+ }
2491
+ function shortAccount(account) {
2492
+ return account.length > 14 ? `${account.slice(0, 6)}\u2026${account.slice(-6)}` : account;
2493
+ }
1873
2494
  function ConnectButton({
1874
2495
  connectionType = "remote" /* Remote */,
1875
2496
  className,
1876
2497
  style,
1877
2498
  theme,
1878
2499
  logoOnly = false,
1879
- label
2500
+ label,
2501
+ cloud = true,
2502
+ accountDefaults
1880
2503
  }) {
1881
- const { isAuthenticated, connectToNode, logout, nodeUrl, isOnline } = useMero();
2504
+ const { isAuthenticated, connectToNode, logout, nodeUrl, isOnline, isDelegated } = useMero();
2505
+ const enrolment = useAccountEnrolment({
2506
+ walletUrl: accountDefaults?.walletUrl,
2507
+ enabled: cloud
2508
+ });
2509
+ const [isModalOpen, setIsModalOpen] = useState(() => cloud && enrolment.returning);
1882
2510
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
1883
- const [isModalOpen, setIsModalOpen] = useState(false);
1884
2511
  const dropdownRef = useRef(null);
2512
+ const account = useMemo(
2513
+ () => isAuthenticated && isDelegated ? readDelegatedSession()?.account ?? null : null,
2514
+ [isAuthenticated, isDelegated]
2515
+ );
1885
2516
  const resolvedTheme = useMemo(
1886
2517
  () => theme ? resolveMeroTheme(theme) : null,
1887
2518
  [theme]
@@ -1900,7 +2531,7 @@ function ConnectButton({
1900
2531
  return () => document.removeEventListener("mousedown", handleClickOutside);
1901
2532
  }, []);
1902
2533
  const dashboardUrl = useMemo(() => {
1903
- if (!isAuthenticated || !nodeUrl) return "#";
2534
+ if (!isAuthenticated || !nodeUrl || isDelegated) return "#";
1904
2535
  return new URL("admin-dashboard/", nodeUrl).toString();
1905
2536
  }, [isAuthenticated, nodeUrl]);
1906
2537
  const labels = useMemo(() => {
@@ -1969,8 +2600,13 @@ function ConnectButton({
1969
2600
  }
1970
2601
  ),
1971
2602
  isDropdownOpen && /* @__PURE__ */ jsxs("div", { className: "mero-dropdown", children: [
1972
- /* @__PURE__ */ jsx("div", { className: "mero-dropdown-info", title: nodeUrl || "", children: nodeUrl }),
1973
- /* @__PURE__ */ jsx(
2603
+ isDelegated && account && /* @__PURE__ */ jsxs("div", { className: "mero-dropdown-info", title: account, "data-testid": "connected-account", children: [
2604
+ "Account ",
2605
+ shortAccount(account)
2606
+ ] }),
2607
+ /* @__PURE__ */ jsx("div", { className: "mero-dropdown-info", title: nodeUrl || "", children: nodeUrl ?? (isDelegated ? "no relay yet" : null) }),
2608
+ isDelegated && enrolment.note && /* @__PURE__ */ jsx("div", { className: "mero-dropdown-info", "data-testid": "connected-note", children: enrolment.note }),
2609
+ !isDelegated && /* @__PURE__ */ jsx(
1974
2610
  "a",
1975
2611
  {
1976
2612
  href: dashboardUrl,
@@ -2015,198 +2651,55 @@ function ConnectButton({
2015
2651
  !logoOnly && labels.connect
2016
2652
  ]
2017
2653
  }
2018
- ),
2019
- /* @__PURE__ */ jsx(
2020
- LoginModal,
2021
- {
2022
- isOpen: isModalOpen,
2023
- onConnect: handleModalConnect,
2024
- onClose: () => setIsModalOpen(false),
2025
- theme: resolvedTheme ?? theme
2026
- }
2027
- )
2028
- ]
2029
- }
2030
- );
2031
- }
2032
- var DEVICE_KEY = "calimero.device";
2033
- var STATE_KEY = "calimero.enrol.state";
2034
- var HOSTED_WALLET = "https://wallet.cloud.calimero.network/account-enroll";
2035
- var hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
2036
- function chooseRelay(relays) {
2037
- const reachable = relays.filter(
2038
- (r) => typeof r.relayUrl === "string" && r.relayUrl.length > 0
2039
- );
2040
- const fresh = reachable.find((r) => r.fresh);
2041
- if (fresh) return { relayUrl: fresh.relayUrl, note: null };
2042
- if (reachable.length > 0) {
2043
- return {
2044
- relayUrl: reachable[0].relayUrl,
2045
- note: "Connected through a relay whose last heartbeat has lapsed \u2014 it may not answer. It was the only one with an address."
2046
- };
2047
- }
2048
- if (relays.length > 0) {
2049
- return {
2050
- relayUrl: null,
2051
- note: `Signed in. Your account has ${relays.length} relay${relays.length === 1 ? "" : "s"} assigned, but the cloud knows no address for any of them yet, so there is nowhere to write through for the moment. Reads and writes resume as soon as one reports in.`
2052
- };
2053
- }
2054
- return {
2055
- relayUrl: null,
2056
- note: "Signed in, with nowhere to write yet: a new account is a member of nothing, so no node serves it. Redeeming an invitation admits this account to a namespace and gives it a relay \u2014 that is the normal first step, not an error."
2057
- };
2058
- }
2059
- async function deviceKeys() {
2060
- const had = localStorage.getItem(DEVICE_KEY);
2061
- if (had) {
2062
- const parsed = JSON.parse(had);
2063
- if (parsed.kemSk && parsed.signSk && parsed.signPk && parsed.kemPk) {
2064
- return parsed;
2065
- }
2066
- localStorage.removeItem(DEVICE_KEY);
2067
- }
2068
- const sign = await crypto.subtle.generateKey({ name: "Ed25519" }, true, [
2069
- "sign",
2070
- "verify"
2071
- ]);
2072
- let agree;
2073
- try {
2074
- agree = await crypto.subtle.generateKey({ name: "X25519" }, true, [
2075
- "deriveBits"
2076
- ]);
2077
- } catch {
2078
- throw new Error(
2079
- "this browser cannot generate an X25519 key, so it cannot receive wrapped scope keys. Chrome 133+ and Safari 17+ support it; enrolling without one would certify a delivery key nothing holds the secret for."
2080
- );
2081
- }
2082
- const keys = {
2083
- signPk: hex(await crypto.subtle.exportKey("raw", sign.publicKey)),
2084
- signSk: hex((await crypto.subtle.exportKey("pkcs8", sign.privateKey)).slice(16)),
2085
- kemPk: hex(await crypto.subtle.exportKey("raw", agree.publicKey)),
2086
- kemSk: hex((await crypto.subtle.exportKey("pkcs8", agree.privateKey)).slice(16))
2087
- };
2088
- localStorage.setItem(DEVICE_KEY, JSON.stringify(keys));
2089
- return keys;
2090
- }
2091
- function ConnectButtonAccount({
2092
- className,
2093
- style,
2094
- theme,
2095
- defaults = {}
2096
- }) {
2097
- const { isAuthenticated, isOnline, nodeUrl, isDelegated, connectToNode, connectWithAccount, logout, cloudBaseUrl } = useMero();
2098
- const [isDropdownOpen, setIsDropdownOpen] = useState(false);
2099
- const [isNodeModalOpen, setIsNodeModalOpen] = useState(false);
2100
- const [isAccountOpen, setIsAccountOpen] = useState(false);
2101
- const [note, setNote] = useState(null);
2102
- const dropdownRef = useRef(null);
2103
- const walletUrl = defaults.walletUrl ?? HOSTED_WALLET;
2104
- const resolvedTheme = useMemo(() => theme ? resolveMeroTheme(theme) : null, [theme]);
2105
- const themeVars = useMemo(
2106
- () => resolvedTheme ? themeToCssVars(resolvedTheme) : void 0,
2107
- [resolvedTheme]
2108
- );
2109
- useEffect(() => {
2110
- const onOutside = (e) => {
2111
- if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
2112
- setIsDropdownOpen(false);
2113
- }
2114
- };
2115
- document.addEventListener("mousedown", onOutside);
2116
- return () => document.removeEventListener("mousedown", onOutside);
2117
- }, []);
2118
- const callbackRef = useRef(void 0);
2119
- const callbackErrorRef = useRef(null);
2120
- if (callbackRef.current === void 0 && typeof window !== "undefined") {
2121
- try {
2122
- callbackRef.current = readEnrolmentCallback();
2123
- } catch (e) {
2124
- callbackRef.current = null;
2125
- callbackErrorRef.current = e instanceof Error ? e.message : String(e);
2126
- }
2127
- }
2128
- const completingRef = useRef(false);
2129
- useEffect(() => {
2130
- if (callbackErrorRef.current) {
2131
- setNote(callbackErrorRef.current);
2132
- callbackErrorRef.current = null;
2133
- return;
2134
- }
2135
- const back = callbackRef.current;
2136
- if (!back || completingRef.current) return;
2137
- completingRef.current = true;
2138
- let cancelled = false;
2139
- (async () => {
2140
- try {
2141
- const keys = await deviceKeys();
2142
- const sent = (() => {
2143
- try {
2144
- return sessionStorage.getItem(STATE_KEY);
2145
- } catch {
2146
- return null;
2147
- }
2148
- })();
2149
- try {
2150
- sessionStorage.removeItem(STATE_KEY);
2151
- } catch {
2152
- }
2153
- if (!sent) {
2154
- setNote(
2155
- 'This enrolment could not be verified as one this tab started, so it was not accepted. Start again from "Enrol with your account".'
2156
- );
2157
- return;
2158
- }
2159
- const enrolled = await completeDeviceEnrolment({
2160
- ...back,
2161
- devicePublicKey: keys.signPk,
2162
- kemPublicKey: keys.kemPk,
2163
- expectState: sent
2164
- });
2165
- saveDelegatedCredential({
2166
- account: enrolled.account,
2167
- credential: enrolled.credential,
2168
- deviceSecret: keys.signSk
2169
- });
2170
- const cloud = new CloudClient({
2171
- cloudBaseUrl,
2172
- routingCredential: {
2173
- credential: enrolled.credential,
2174
- deviceSecret: keys.signSk
2654
+ ),
2655
+ /* @__PURE__ */ jsx(
2656
+ LoginModal,
2657
+ {
2658
+ isOpen: isModalOpen,
2659
+ onConnect: handleModalConnect,
2660
+ onClose: () => setIsModalOpen(false),
2661
+ theme: resolvedTheme ?? theme,
2662
+ cloud: cloud ? {
2663
+ onEnrol: () => {
2664
+ void enrolment.goToWallet();
2665
+ },
2666
+ note: enrolment.note,
2667
+ walletUrl: enrolment.walletUrl,
2668
+ customWallet: enrolment.customWallet
2669
+ } : void 0,
2670
+ initialTab: cloud && enrolment.returning ? "cloud" : "node"
2175
2671
  }
2176
- });
2177
- const chosen = chooseRelay(await cloud.getAccountRelays(enrolled.account));
2178
- if (chosen.note) setNote(chosen.note);
2179
- connectWithAccount({
2180
- relayUrl: chosen.relayUrl,
2181
- account: enrolled.account,
2182
- credential: enrolled.credential,
2183
- deviceSecret: keys.signSk
2184
- });
2185
- } catch (e) {
2186
- if (!cancelled) setNote(e instanceof Error ? e.message : String(e));
2672
+ )
2673
+ ]
2674
+ }
2675
+ );
2676
+ }
2677
+ function ConnectButtonAccount({
2678
+ className,
2679
+ style,
2680
+ theme,
2681
+ defaults = {}
2682
+ }) {
2683
+ const { isAuthenticated, isOnline, nodeUrl, isDelegated, connectToNode, logout } = useMero();
2684
+ const [isDropdownOpen, setIsDropdownOpen] = useState(false);
2685
+ const [isNodeModalOpen, setIsNodeModalOpen] = useState(false);
2686
+ const [isAccountOpen, setIsAccountOpen] = useState(false);
2687
+ const dropdownRef = useRef(null);
2688
+ const resolvedTheme = useMemo(() => theme ? resolveMeroTheme(theme) : null, [theme]);
2689
+ const themeVars = useMemo(
2690
+ () => resolvedTheme ? themeToCssVars(resolvedTheme) : void 0,
2691
+ [resolvedTheme]
2692
+ );
2693
+ useEffect(() => {
2694
+ const onOutside = (e) => {
2695
+ if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
2696
+ setIsDropdownOpen(false);
2187
2697
  }
2188
- })();
2189
- return () => {
2190
- cancelled = true;
2191
2698
  };
2192
- }, [connectWithAccount, cloudBaseUrl]);
2193
- const goToWallet = useCallback(async () => {
2194
- const keys = await deviceKeys();
2195
- const state = hex(crypto.getRandomValues(new Uint8Array(16)));
2196
- try {
2197
- sessionStorage.setItem(STATE_KEY, state);
2198
- } catch {
2199
- }
2200
- window.location.assign(
2201
- deviceEnrolmentUrl({
2202
- walletUrl,
2203
- devicePublicKey: keys.signPk,
2204
- kemPublicKey: keys.kemPk,
2205
- returnTo: window.location.origin + window.location.pathname,
2206
- state
2207
- })
2208
- );
2209
- }, [walletUrl]);
2699
+ document.addEventListener("mousedown", onOutside);
2700
+ return () => document.removeEventListener("mousedown", onOutside);
2701
+ }, []);
2702
+ const { goToWallet, note, walletUrl } = useAccountEnrolment({ walletUrl: defaults.walletUrl });
2210
2703
  if (isAuthenticated && !isOnline) {
2211
2704
  return /* @__PURE__ */ jsx("div", { className: "mero-connect-container", style: { ...themeVars, display: "inline-block" }, children: /* @__PURE__ */ jsxs(
2212
2705
  "button",
@@ -4173,197 +4666,6 @@ function MigrationAdminPanel({ namespaceId, pollIntervalMs, className }) {
4173
4666
  ] })
4174
4667
  ] });
4175
4668
  }
4176
- function normaliseAccount(account) {
4177
- if (!account) return null;
4178
- const trimmed = account.trim().toLowerCase();
4179
- const bare = trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
4180
- return bare.length > 0 ? bare : null;
4181
- }
4182
- function isInvited(node, invited) {
4183
- if (invited.size === 0) return true;
4184
- const account = normaliseAccount(node.account);
4185
- return account !== null && invited.has(account);
4186
- }
4187
- async function resolveRelayFromInvitation(input) {
4188
- const cloud = input.cloud ?? new CloudClient({
4189
- cloudBaseUrl: input.cloudBaseUrl,
4190
- routingCredential: { credential: input.credential, deviceSecret: input.deviceSecret }
4191
- });
4192
- let nodes;
4193
- let servable;
4194
- try {
4195
- const routing = await cloud.getNamespaceRouting(input.namespaceId);
4196
- nodes = routing.nodes;
4197
- servable = routing.servable;
4198
- } catch (e) {
4199
- return {
4200
- ok: false,
4201
- step: "admitters-lookup",
4202
- reason: `The cloud could not be asked which nodes serve namespace ${input.namespaceId}: ${e instanceof Error ? e.message : String(e)}. Nothing is known about the invitation yet \u2014 this is the lookup failing, not the invitation.`
4203
- };
4204
- }
4205
- if (nodes.length === 0) {
4206
- return {
4207
- ok: false,
4208
- step: "no-nodes",
4209
- reason: "The cloud lists no nodes serving this namespace, so there is no hosted node to be admitted through. The namespace has no fleet assignment \u2014 whoever invited you is running their own node, and admission has to go through a node the cloud routes to."
4210
- };
4211
- }
4212
- const invited = new Set(
4213
- (input.admitters ?? []).map(normaliseAccount).filter((a) => a !== null)
4214
- );
4215
- const named = nodes.filter((n) => isInvited(n, invited));
4216
- if (named.length === 0) {
4217
- return {
4218
- ok: false,
4219
- step: "not-invited",
4220
- reason: `${nodes.length} node${nodes.length === 1 ? "" : "s"} serve this namespace, but your invitation names none of them. The signed admitter list is a snapshot from when the invitation was minted, so a node assigned since is healthy and will still refuse the claim. Ask for a fresh invitation.`
4221
- };
4222
- }
4223
- const usable = named.filter((n) => n.canAdmit);
4224
- const candidates = usable.length > 0 ? usable : named;
4225
- const advisory = usable.length === 0 || !servable;
4226
- const addressable = candidates.filter(
4227
- (n) => typeof n.relayUrl === "string" && n.relayUrl.length > 0
4228
- );
4229
- if (addressable.length === 0) {
4230
- return {
4231
- ok: false,
4232
- step: "no-relay-url",
4233
- reason: "A node your invitation names can admit you, but the cloud knows no address for it yet, so there would be nothing to connect through afterwards. Try again shortly."
4234
- };
4235
- }
4236
- const chosen = addressable.find((n) => n.canExecute) ?? addressable.find((n) => n.fresh) ?? addressable[0];
4237
- return {
4238
- ok: true,
4239
- relayUrl: chosen.relayUrl,
4240
- // The cloud's ready-made URL when it gave one, so the path is never rebuilt
4241
- // from a guess; the fallback is the documented route on the same origin.
4242
- admitUrl: chosen.admitUrl ?? `${chosen.relayUrl.replace(/\/+$/, "")}/admin-api/namespaces/${input.namespaceId}/admit`,
4243
- admitterAccount: chosen.account,
4244
- peerId: chosen.peerId,
4245
- writable: chosen.canExecute,
4246
- // Stale when the node's own heartbeat lapsed OR when the cloud's summary
4247
- // disagrees with trying it at all. Both mean the same thing to a caller:
4248
- // this was attempted on advisory data, so if the admit fails that is why.
4249
- stale: !chosen.fresh || advisory
4250
- };
4251
- }
4252
- function explainAdmitFailure(status, body) {
4253
- const detail = body ? `: ${body}` : "";
4254
- switch (status) {
4255
- case 400:
4256
- return `The node refused the join as malformed (400)${detail}. The signature covers the invitation exactly as sent, so an edited or re-serialised invitation fails here \u2014 as does a namespace id that is not the invitation's own group.`;
4257
- case 403:
4258
- return `The node refused to carry this join (403)${detail}. Either it is not in the invitation's signed admitters list \u2014 being live and listed by the cloud is not the same thing \u2014 or the invitation itself was rejected as expired or not the inviter\u2019s to issue.`;
4259
- case 409:
4260
- return `That node holds no device of its own, so it cannot endorse anyone (409)${detail}. Another admitter from the same invitation would work.`;
4261
- default:
4262
- return `The join was not published (HTTP ${status})${detail}.`;
4263
- }
4264
- }
4265
- function joinNonce(account) {
4266
- const source = createLocalStorageNonceSource(`calimero.delegated.joinnonce.${account}`);
4267
- return () => source.next();
4268
- }
4269
- function origin(url) {
4270
- return url.replace(/\/+$/, "");
4271
- }
4272
- async function joinWithNode(input) {
4273
- const { account, credential, deviceSecret } = input.credential;
4274
- let signedOp;
4275
- try {
4276
- signedOp = await signMemberJoinOp({
4277
- namespaceId: input.namespaceId,
4278
- member: account,
4279
- invitation: input.invitation,
4280
- credential,
4281
- deviceSecret,
4282
- nonce: await (input.deps?.nonce ?? joinNonce(account))()
4283
- });
4284
- } catch (e) {
4285
- return {
4286
- ok: false,
4287
- step: "sign",
4288
- reason: `The join op could not be signed, so nothing was sent: ${e instanceof Error ? e.message : String(e)}`
4289
- };
4290
- }
4291
- const body = { invitation: input.invitation, signedOp };
4292
- const url = input.admitUrl ?? `${origin(input.nodeUrl)}/admin-api/namespaces/${input.namespaceId}/admit`;
4293
- const doFetch = input.deps?.fetch ?? fetch;
4294
- let response;
4295
- try {
4296
- response = await doFetch(url, {
4297
- method: "POST",
4298
- // No Authorization header and no request proof, deliberately: the route is
4299
- // unauthenticated because the joiner's signature is the authorization.
4300
- headers: { "Content-Type": "application/json", Accept: "application/json" },
4301
- body: JSON.stringify(body)
4302
- });
4303
- } catch (e) {
4304
- return {
4305
- ok: false,
4306
- step: "admit",
4307
- reason: `The admitter at ${input.nodeUrl} could not be reached: ${e instanceof Error ? e.message : String(e)}. The invitation is untouched \u2014 this is the node being unreachable, not a refusal.`
4308
- };
4309
- }
4310
- const text = await response.text();
4311
- if (!response.ok) {
4312
- return {
4313
- ok: false,
4314
- step: "admit",
4315
- status: response.status,
4316
- reason: explainAdmitFailure(response.status, text)
4317
- };
4318
- }
4319
- let published = false;
4320
- try {
4321
- const parsed = text ? JSON.parse(text) : {};
4322
- published = parsed.data?.published === true;
4323
- } catch {
4324
- published = false;
4325
- }
4326
- return {
4327
- ok: true,
4328
- published,
4329
- session: { relayUrl: origin(input.nodeUrl), account, credential, deviceSecret }
4330
- };
4331
- }
4332
-
4333
- // src/delegated/bootstrap-from-invitation.ts
4334
- async function bootstrapFromInvitation(input) {
4335
- const resolve = input.deps?.resolve ?? resolveRelayFromInvitation;
4336
- const join = input.deps?.join ?? joinWithNode;
4337
- let relay = null;
4338
- let nodeUrl = input.nodeUrl;
4339
- let admitUrl;
4340
- if (!nodeUrl) {
4341
- const resolved = await resolve({
4342
- namespaceId: input.namespaceId,
4343
- // The signed list, read off the invitation itself rather than passed
4344
- // separately: two sources for one fact is how an intersection ends up
4345
- // being performed against the wrong list.
4346
- admitters: input.invitation.invitation.admitters,
4347
- credential: input.credential.credential,
4348
- deviceSecret: input.credential.deviceSecret,
4349
- cloudBaseUrl: input.cloudBaseUrl
4350
- });
4351
- if (!resolved.ok) return resolved;
4352
- relay = resolved;
4353
- nodeUrl = resolved.relayUrl;
4354
- admitUrl = resolved.admitUrl;
4355
- }
4356
- const joined = await join({
4357
- nodeUrl,
4358
- admitUrl,
4359
- namespaceId: input.namespaceId,
4360
- invitation: input.invitation,
4361
- credential: input.credential,
4362
- deps: { fetch: input.deps?.fetch, nonce: input.deps?.nonce }
4363
- });
4364
- if (!joined.ok) return joined;
4365
- return { ok: true, published: joined.published, relay, session: joined.session };
4366
- }
4367
4669
  function useDelegatedBootstrap(options = {}) {
4368
4670
  const { connectWithAccount, cloudBaseUrl: providerCloud } = useMero();
4369
4671
  const [running, setRunning] = useState(false);
@@ -4532,6 +4834,6 @@ function useJoinInvitation() {
4532
4834
  return { joinInvitation, joining, memberships, invitationRedeemer };
4533
4835
  }
4534
4836
 
4535
- export { AppMode, CalimeroLogo, ConnectButton, ConnectButtonAccount, ConnectionType, DEFAULT_MIGRATION_POLL_INTERVAL_MS, LoginModal, MERO_CSS_VARS, MeroContext, MeroProvider, MigrationAdminPanel, MigrationPendingBanner, NoRelayError, NotForAccountError, bootstrapFromInvitation, clearAllStorage, clearApplicationId, clearContextId, clearContextIdentity, clearDelegatedCredential, clearNodeUrl, clearTokenNodeUrl, createAccountAdmin, createDelegatedContext, createNodeAdmin, cssVar, defaultMeroTheme, getApplicationId, getContextId, getContextIdentity, getNodeUrl, getTokenNodeUrl, isFinalInvitationError, joinWithNode, listDelegatedContexts, localStorageTokenStorage, normaliseAccount, pinRelayNodeKey, readDelegatedCredential, readPinnedRelayNodeKey, readRelayMap, relayForContext, rememberRelay, resolveMeroTheme, resolveRelayFromInvitation, saveDelegatedCredential, setApplicationId, setContextId, setContextIdentity, setNodeUrl, setTokenNodeUrl, themeToCssVars, useAddGroupMembers, useAppVersion, useApplicationContexts, useBlobInfo, useBlobUrl, useContextDiscovery, useContextGroup, useContexts, useCreateContext, useCreateGroupInNamespace, useCreateNamespace, useCreateNamespaceInvitation, useCreatePrivateContext, useDefaultCapabilities, useDelegatedBootstrap, useDeleteContext, useDeleteGroup, useDeleteNamespace, useDetachContextFromGroup, useEphemeral, useExecute, useGroupAppVersion, useGroupCapabilities, useGroupContexts, useGroupInfo, useGroupInvitations, useGroupMembers, useGroupMetadata, useGroupUpgradeStatus, useInstallFromRegistry, useJoinContext, useJoinGroup, useJoinInvitation, useJoinNamespace, useJoinSubgroupInheritance, useLatestVersion, useMemberMetadata, useMero, useMigrationEvents, useMigrationStatus, useMyAuthoredMigration, useNamespace, useNamespaceGroups, useNamespaceIdentity, useNamespaces, useNamespacesForApplication, useNodeIdentity, useRedeemInvitation, useRemoveGroupMembers, useReparentGroup, useResyncContext, useRetryGroupUpgrade, useSetContextMetadata, useSetDefaultCapabilities, useSetGroupMetadata, useSetMemberMetadata, useSetSubgroupVisibility, useSetTeeAdmissionPolicy, useSubgroupVisibility, useSubgroups, useSubscription, useSyncGroup, useUpdateMemberRole, useUpgradeGroup, useUploadBlob };
4837
+ export { AccountSignInPanel, AppMode, CalimeroLogo, ConnectButton, ConnectButtonAccount, ConnectionType, DEFAULT_MIGRATION_POLL_INTERVAL_MS, LoginModal, MERO_CSS_VARS, MeroContext, MeroProvider, MigrationAdminPanel, MigrationPendingBanner, NoRelayError, NotForAccountError, bootstrapFromInvitation, clearAllStorage, clearApplicationId, clearContextId, clearContextIdentity, clearDelegatedCredential, clearNodeUrl, clearTokenNodeUrl, createAccountAdmin, createDelegatedContext, createNodeAdmin, cssVar, defaultMeroTheme, getApplicationId, getContextId, getContextIdentity, getNodeUrl, getTokenNodeUrl, isFinalInvitationError, joinWithNode, listDelegatedContexts, localStorageTokenStorage, normaliseAccount, pinRelayNodeKey, readDelegatedCredential, readPinnedRelayNodeKey, readRelayMap, relayForContext, rememberRelay, resolveMeroTheme, resolveRelayFromInvitation, saveDelegatedCredential, setApplicationId, setContextId, setContextIdentity, setNodeUrl, setTokenNodeUrl, themeToCssVars, 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 };
4536
4838
  //# sourceMappingURL=index.js.map
4537
4839
  //# sourceMappingURL=index.js.map