@calimero-network/mero-react 9.5.0 → 9.6.1

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 CHANGED
@@ -494,14 +494,17 @@ function createNodeAdmin(input, deps = {}) {
494
494
 
495
495
  // src/delegated/govern.ts
496
496
  var GROUP_NAMESPACE_PREFIX = "calimero.delegated.group-namespace.";
497
+ var learned = /* @__PURE__ */ new Map();
497
498
  function readGroupNamespaces(account) {
499
+ let stored = {};
498
500
  try {
499
- return JSON.parse(localStorage.getItem(GROUP_NAMESPACE_PREFIX + account) ?? "{}");
501
+ stored = JSON.parse(localStorage.getItem(GROUP_NAMESPACE_PREFIX + account) ?? "{}");
500
502
  } catch {
501
- return {};
502
503
  }
504
+ return { ...stored, ...learned.get(account) };
503
505
  }
504
506
  function rememberGroupNamespace(account, groupId, namespaceId) {
507
+ learned.set(account, { ...learned.get(account), [groupId]: namespaceId });
505
508
  try {
506
509
  const all = readGroupNamespaces(account);
507
510
  all[groupId] = namespaceId;
@@ -579,8 +582,8 @@ var NODE_ONLY = /* @__PURE__ */ new Set([
579
582
  ]);
580
583
  function createAccountAdmin(input, deps = {}) {
581
584
  const { session: s, read, app } = input;
582
- const group = deps.govern?.group ?? governGroup;
583
- const root = deps.govern?.root ?? governRoot;
585
+ const governGroupOp = deps.govern?.group ?? governGroup;
586
+ const governRootOp = deps.govern?.root ?? governRoot;
584
587
  const createContext2 = deps.createContext ?? createDelegatedContext;
585
588
  const found = deps.found ?? foundDelegatedNamespace;
586
589
  const latestVersion = deps.latestVersion ?? latestPublishedVersion;
@@ -594,6 +597,19 @@ function createAccountAdmin(input, deps = {}) {
594
597
  if (read === null) throw new NoRelayError("this call");
595
598
  return read;
596
599
  };
600
+ async function knowNamespaceOf(groupId) {
601
+ if (namespaceOfGroup(s, groupId)) return;
602
+ const info = await relay().getGroupInfo(groupId);
603
+ rememberGroupNamespace(s.account, groupId, info.namespaceId ?? groupId);
604
+ }
605
+ const group = async (session, groupId, op) => {
606
+ await knowNamespaceOf(groupId);
607
+ return governGroupOp(session, groupId, op);
608
+ };
609
+ const root = async (session, groupId, op) => {
610
+ await knowNamespaceOf(groupId);
611
+ return governRootOp(session, groupId, op);
612
+ };
597
613
  async function isMemberOfContextGroup(contextId, knownGroupId) {
598
614
  const groupId = knownGroupId ?? String(await relay().getContextGroup(contextId));
599
615
  const { members } = await relay().listGroupMembers(groupId);
@@ -1221,6 +1237,7 @@ function getPermissionsForMode(mode) {
1221
1237
  case "multi-context" /* MultiContext */:
1222
1238
  return [
1223
1239
  "context:create",
1240
+ "context:delete",
1224
1241
  "context:list",
1225
1242
  "context:execute",
1226
1243
  "context:subscribe",
@@ -1660,7 +1677,85 @@ function themeToCssVars(theme) {
1660
1677
  function cssVar(theme, key) {
1661
1678
  return `var(${MERO_CSS_VARS[key]}, ${theme[key]})`;
1662
1679
  }
1680
+ function AccountSignInPanel({
1681
+ onEnrol,
1682
+ note,
1683
+ walletUrl,
1684
+ customWallet = false,
1685
+ theme
1686
+ }) {
1687
+ const styles = react.useMemo(() => {
1688
+ const t = resolveMeroTheme(theme);
1689
+ const radius = cssVar(t, "radius");
1690
+ const error = cssVar(t, "error");
1691
+ return {
1692
+ root: { display: "flex", flexDirection: "column", gap: "1rem" },
1693
+ info: {
1694
+ color: cssVar(t, "textSecondary"),
1695
+ textAlign: "center",
1696
+ fontSize: "0.875rem",
1697
+ margin: 0
1698
+ },
1699
+ hint: {
1700
+ color: cssVar(t, "textSecondary"),
1701
+ textAlign: "center",
1702
+ fontSize: "0.8125rem",
1703
+ margin: 0,
1704
+ opacity: 0.8,
1705
+ overflowWrap: "anywhere"
1706
+ },
1707
+ note: {
1708
+ color: error,
1709
+ backgroundColor: `color-mix(in srgb, ${error} 10%, transparent)`,
1710
+ border: `1px solid color-mix(in srgb, ${error} 30%, transparent)`,
1711
+ borderRadius: radius,
1712
+ padding: "0.75rem",
1713
+ fontSize: "0.875rem",
1714
+ textAlign: "center",
1715
+ margin: 0
1716
+ },
1717
+ buttonGroup: { display: "flex", justifyContent: "center" },
1718
+ button: {
1719
+ padding: "0.75rem 2rem",
1720
+ borderRadius: radius,
1721
+ border: "none",
1722
+ fontSize: "0.875rem",
1723
+ fontWeight: 600,
1724
+ cursor: "pointer",
1725
+ backgroundColor: cssVar(t, "primary"),
1726
+ color: cssVar(t, "primaryText"),
1727
+ transition: "all 0.15s ease"
1728
+ }
1729
+ };
1730
+ }, [theme]);
1731
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { style: styles.root, "data-testid": "account-sign-in-panel", children: [
1732
+ note && /* @__PURE__ */ jsxRuntime.jsx("p", { style: styles.note, role: "status", "data-testid": "account-note", children: note }),
1733
+ /* @__PURE__ */ jsxRuntime.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." }),
1734
+ /* @__PURE__ */ jsxRuntime.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." }),
1735
+ /* @__PURE__ */ jsxRuntime.jsx("div", { style: styles.buttonGroup, children: /* @__PURE__ */ jsxRuntime.jsx(
1736
+ "button",
1737
+ {
1738
+ type: "button",
1739
+ style: styles.button,
1740
+ onClick: onEnrol,
1741
+ "data-testid": "enrol-button",
1742
+ children: "Enrol with your account"
1743
+ }
1744
+ ) }),
1745
+ customWallet && walletUrl && /* Shown only when an app overrode it, so a local rig can see at a
1746
+ glance that it is not enrolling against the hosted wallet. */
1747
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { style: styles.hint, children: [
1748
+ "Enrolling at ",
1749
+ /* @__PURE__ */ jsxRuntime.jsx("code", { children: walletUrl }),
1750
+ ", not the hosted wallet."
1751
+ ] })
1752
+ ] });
1753
+ }
1663
1754
  var CUSTOM_SELECTION = "__custom__";
1755
+ var TABS = [
1756
+ { id: "node", label: "Node" },
1757
+ { id: "cloud", label: "Cloud" }
1758
+ ];
1664
1759
  function isValidUrl(urlString) {
1665
1760
  if (!urlString || urlString.trim() === "") {
1666
1761
  return false;
@@ -1896,6 +1991,32 @@ function buildStyles(t) {
1896
1991
  borderRadius: "50%",
1897
1992
  animation: "meroSpin 1s linear infinite"
1898
1993
  },
1994
+ tabList: {
1995
+ display: "flex",
1996
+ gap: "0.25rem",
1997
+ padding: "0.25rem",
1998
+ marginBottom: "1.5rem",
1999
+ borderRadius: radius,
2000
+ border: `1px solid ${border}`,
2001
+ backgroundColor: bgSecondary
2002
+ },
2003
+ tab: {
2004
+ flex: 1,
2005
+ padding: "0.5rem 1rem",
2006
+ borderRadius: radius,
2007
+ border: "1px solid transparent",
2008
+ backgroundColor: "transparent",
2009
+ color: textSecondary,
2010
+ fontSize: "0.875rem",
2011
+ fontWeight: 600,
2012
+ cursor: "pointer",
2013
+ transition: "all 0.15s ease"
2014
+ },
2015
+ tabActive: {
2016
+ border: `1px solid ${accent}`,
2017
+ backgroundColor: accentGlow,
2018
+ color: text
2019
+ },
1899
2020
  spinnerSmall: {
1900
2021
  width: "1.5rem",
1901
2022
  height: "1.5rem",
@@ -1911,8 +2032,19 @@ function LoginModal({
1911
2032
  onClose,
1912
2033
  isOpen,
1913
2034
  theme,
1914
- localNodePorts = meroJs.DEFAULT_LOCAL_NODE_PORTS
2035
+ localNodePorts = meroJs.DEFAULT_LOCAL_NODE_PORTS,
2036
+ cloud,
2037
+ initialTab = "node"
1915
2038
  }) {
2039
+ const [tab, setTab] = react.useState(initialTab);
2040
+ react.useEffect(() => {
2041
+ if (isOpen) setTab(initialTab);
2042
+ }, [isOpen, initialTab]);
2043
+ const tabRefs = react.useRef({
2044
+ node: null,
2045
+ cloud: null
2046
+ });
2047
+ const activeTab = cloud ? tab : "node";
1916
2048
  const [selected, setSelected] = react.useState(CUSTOM_SELECTION);
1917
2049
  const [discovered, setDiscovered] = react.useState([]);
1918
2050
  const [discovering, setDiscovering] = react.useState(false);
@@ -2091,6 +2223,76 @@ function LoginModal({
2091
2223
  ) })
2092
2224
  ] });
2093
2225
  };
2226
+ const renderNodeBody = () => {
2227
+ const body = loading ? /* @__PURE__ */ jsxRuntime.jsxs("div", { style: styles.loading, children: [
2228
+ /* @__PURE__ */ jsxRuntime.jsx("p", { children: "Connecting to node..." }),
2229
+ /* @__PURE__ */ jsxRuntime.jsx("div", { style: styles.spinner })
2230
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2231
+ error && /* @__PURE__ */ jsxRuntime.jsx("p", { style: styles.error, children: error }),
2232
+ renderNodeSection(),
2233
+ /* @__PURE__ */ jsxRuntime.jsx("div", { style: styles.buttonGroup, children: /* @__PURE__ */ jsxRuntime.jsx(
2234
+ "button",
2235
+ {
2236
+ onClick: handleConnect,
2237
+ disabled: !canConnect,
2238
+ style: {
2239
+ ...styles.button,
2240
+ ...!canConnect ? styles.buttonDisabled : {}
2241
+ },
2242
+ "data-testid": "connect-button",
2243
+ children: "Connect"
2244
+ }
2245
+ ) })
2246
+ ] });
2247
+ if (!cloud) return body;
2248
+ return /* @__PURE__ */ jsxRuntime.jsx(
2249
+ "div",
2250
+ {
2251
+ role: "tabpanel",
2252
+ id: "mero-login-panel-node",
2253
+ "aria-labelledby": "mero-login-tab-node",
2254
+ children: body
2255
+ }
2256
+ );
2257
+ };
2258
+ const selectTab = (id) => {
2259
+ setTab(id);
2260
+ tabRefs.current[id]?.focus();
2261
+ };
2262
+ const onTabKeyDown = (e) => {
2263
+ const i = TABS.findIndex((t) => t.id === activeTab);
2264
+ let next = null;
2265
+ if (e.key === "ArrowRight") next = (i + 1) % TABS.length;
2266
+ else if (e.key === "ArrowLeft") next = (i - 1 + TABS.length) % TABS.length;
2267
+ else if (e.key === "Home") next = 0;
2268
+ else if (e.key === "End") next = TABS.length - 1;
2269
+ if (next === null) return;
2270
+ e.preventDefault();
2271
+ selectTab(TABS[next].id);
2272
+ };
2273
+ const renderTabs = () => /* @__PURE__ */ jsxRuntime.jsx("div", { role: "tablist", "aria-label": "How to connect", style: styles.tabList, children: TABS.map((t) => {
2274
+ const selected2 = activeTab === t.id;
2275
+ return /* @__PURE__ */ jsxRuntime.jsx(
2276
+ "button",
2277
+ {
2278
+ ref: (el) => {
2279
+ tabRefs.current[t.id] = el;
2280
+ },
2281
+ type: "button",
2282
+ role: "tab",
2283
+ id: `mero-login-tab-${t.id}`,
2284
+ "aria-selected": selected2,
2285
+ "aria-controls": `mero-login-panel-${t.id}`,
2286
+ tabIndex: selected2 ? 0 : -1,
2287
+ onClick: () => setTab(t.id),
2288
+ onKeyDown: onTabKeyDown,
2289
+ style: { ...styles.tab, ...selected2 ? styles.tabActive : {} },
2290
+ "data-testid": `login-tab-${t.id}`,
2291
+ children: t.label
2292
+ },
2293
+ t.id
2294
+ );
2295
+ }) });
2094
2296
  const modalContent = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2095
2297
  /* @__PURE__ */ jsxRuntime.jsx("style", { children: `
2096
2298
  @keyframes meroSpin { to { transform: rotate(360deg); } }
@@ -2103,42 +2305,231 @@ function LoginModal({
2103
2305
  /* @__PURE__ */ jsxRuntime.jsx(CalimeroLogo, { size: 44, color: cssVar(resolved, "primary") }),
2104
2306
  /* @__PURE__ */ jsxRuntime.jsx("h1", { style: styles.title, children: "Connect to Calimero" })
2105
2307
  ] }),
2106
- loading ? /* @__PURE__ */ jsxRuntime.jsxs("div", { style: styles.loading, children: [
2107
- /* @__PURE__ */ jsxRuntime.jsx("p", { children: "Connecting to node..." }),
2108
- /* @__PURE__ */ jsxRuntime.jsx("div", { style: styles.spinner })
2109
- ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2110
- error && /* @__PURE__ */ jsxRuntime.jsx("p", { style: styles.error, children: error }),
2111
- renderNodeSection(),
2112
- /* @__PURE__ */ jsxRuntime.jsx("div", { style: styles.buttonGroup, children: /* @__PURE__ */ jsxRuntime.jsx(
2113
- "button",
2114
- {
2115
- onClick: handleConnect,
2116
- disabled: !canConnect,
2117
- style: {
2118
- ...styles.button,
2119
- ...!canConnect ? styles.buttonDisabled : {}
2120
- },
2121
- "data-testid": "connect-button",
2122
- children: "Connect"
2123
- }
2124
- ) })
2125
- ] })
2308
+ cloud && renderTabs(),
2309
+ activeTab === "cloud" && cloud ? /* @__PURE__ */ jsxRuntime.jsx(
2310
+ "div",
2311
+ {
2312
+ role: "tabpanel",
2313
+ id: "mero-login-panel-cloud",
2314
+ "aria-labelledby": "mero-login-tab-cloud",
2315
+ tabIndex: 0,
2316
+ children: /* @__PURE__ */ jsxRuntime.jsx(
2317
+ AccountSignInPanel,
2318
+ {
2319
+ onEnrol: cloud.onEnrol,
2320
+ note: cloud.note,
2321
+ walletUrl: cloud.walletUrl,
2322
+ customWallet: cloud.customWallet,
2323
+ theme
2324
+ }
2325
+ )
2326
+ }
2327
+ ) : renderNodeBody()
2126
2328
  ] }) })
2127
2329
  ] });
2128
2330
  return reactDom.createPortal(modalContent, document.body);
2129
2331
  }
2332
+ var DEVICE_KEY = "calimero.device";
2333
+ var STATE_KEY = "calimero.enrol.state";
2334
+ var HOSTED_WALLET = "https://wallet.cloud.calimero.network/account-enroll";
2335
+ var hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
2336
+ function chooseRelay(relays) {
2337
+ const reachable = relays.filter(
2338
+ (r) => typeof r.relayUrl === "string" && r.relayUrl.length > 0
2339
+ );
2340
+ const fresh = reachable.find((r) => r.fresh);
2341
+ if (fresh) return { relayUrl: fresh.relayUrl, note: null };
2342
+ if (reachable.length > 0) {
2343
+ return {
2344
+ relayUrl: reachable[0].relayUrl,
2345
+ note: "Connected through a relay whose last heartbeat has lapsed \u2014 it may not answer. It was the only one with an address."
2346
+ };
2347
+ }
2348
+ if (relays.length > 0) {
2349
+ return {
2350
+ relayUrl: null,
2351
+ 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.`
2352
+ };
2353
+ }
2354
+ return {
2355
+ relayUrl: null,
2356
+ 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."
2357
+ };
2358
+ }
2359
+ async function deviceKeys() {
2360
+ const had = localStorage.getItem(DEVICE_KEY);
2361
+ if (had) {
2362
+ const parsed = JSON.parse(had);
2363
+ if (parsed.kemSk && parsed.signSk && parsed.signPk && parsed.kemPk) {
2364
+ return parsed;
2365
+ }
2366
+ localStorage.removeItem(DEVICE_KEY);
2367
+ }
2368
+ const sign = await crypto.subtle.generateKey({ name: "Ed25519" }, true, [
2369
+ "sign",
2370
+ "verify"
2371
+ ]);
2372
+ let agree;
2373
+ try {
2374
+ agree = await crypto.subtle.generateKey({ name: "X25519" }, true, [
2375
+ "deriveBits"
2376
+ ]);
2377
+ } catch {
2378
+ throw new Error(
2379
+ "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."
2380
+ );
2381
+ }
2382
+ const keys = {
2383
+ signPk: hex(await crypto.subtle.exportKey("raw", sign.publicKey)),
2384
+ signSk: hex((await crypto.subtle.exportKey("pkcs8", sign.privateKey)).slice(16)),
2385
+ kemPk: hex(await crypto.subtle.exportKey("raw", agree.publicKey)),
2386
+ kemSk: hex((await crypto.subtle.exportKey("pkcs8", agree.privateKey)).slice(16))
2387
+ };
2388
+ localStorage.setItem(DEVICE_KEY, JSON.stringify(keys));
2389
+ return keys;
2390
+ }
2391
+ function useAccountEnrolment({
2392
+ walletUrl: walletOverride,
2393
+ enabled = true
2394
+ } = {}) {
2395
+ const { connectWithAccount, cloudBaseUrl } = useMero();
2396
+ const [note, setNote] = react.useState(null);
2397
+ const walletUrl = walletOverride ?? HOSTED_WALLET;
2398
+ const callbackRef = react.useRef(void 0);
2399
+ const callbackErrorRef = react.useRef(null);
2400
+ if (enabled && callbackRef.current === void 0 && typeof window !== "undefined") {
2401
+ try {
2402
+ callbackRef.current = meroJs.readEnrolmentCallback();
2403
+ } catch (e) {
2404
+ callbackRef.current = null;
2405
+ callbackErrorRef.current = e instanceof Error ? e.message : String(e);
2406
+ }
2407
+ }
2408
+ const returningRef = react.useRef(null);
2409
+ if (returningRef.current === null && callbackRef.current !== void 0) {
2410
+ returningRef.current = callbackRef.current !== null || callbackErrorRef.current !== null;
2411
+ }
2412
+ const completingRef = react.useRef(false);
2413
+ react.useEffect(() => {
2414
+ if (callbackErrorRef.current) {
2415
+ setNote(callbackErrorRef.current);
2416
+ callbackErrorRef.current = null;
2417
+ return;
2418
+ }
2419
+ const back = callbackRef.current;
2420
+ if (!back || completingRef.current) return;
2421
+ completingRef.current = true;
2422
+ let cancelled = false;
2423
+ (async () => {
2424
+ try {
2425
+ const keys = await deviceKeys();
2426
+ const sent = (() => {
2427
+ try {
2428
+ return sessionStorage.getItem(STATE_KEY);
2429
+ } catch {
2430
+ return null;
2431
+ }
2432
+ })();
2433
+ try {
2434
+ sessionStorage.removeItem(STATE_KEY);
2435
+ } catch {
2436
+ }
2437
+ if (!sent) {
2438
+ setNote(
2439
+ 'This enrolment could not be verified as one this tab started, so it was not accepted. Start again from "Enrol with your account".'
2440
+ );
2441
+ return;
2442
+ }
2443
+ const enrolled = await meroJs.completeDeviceEnrolment({
2444
+ ...back,
2445
+ devicePublicKey: keys.signPk,
2446
+ kemPublicKey: keys.kemPk,
2447
+ expectState: sent
2448
+ });
2449
+ saveDelegatedCredential({
2450
+ account: enrolled.account,
2451
+ credential: enrolled.credential,
2452
+ deviceSecret: keys.signSk
2453
+ });
2454
+ const cloud = new meroJs.CloudClient({
2455
+ cloudBaseUrl,
2456
+ routingCredential: {
2457
+ credential: enrolled.credential,
2458
+ deviceSecret: keys.signSk
2459
+ }
2460
+ });
2461
+ const chosen = chooseRelay(await cloud.getAccountRelays(enrolled.account));
2462
+ if (chosen.note) setNote(chosen.note);
2463
+ connectWithAccount({
2464
+ relayUrl: chosen.relayUrl,
2465
+ account: enrolled.account,
2466
+ credential: enrolled.credential,
2467
+ deviceSecret: keys.signSk
2468
+ });
2469
+ } catch (e) {
2470
+ if (!cancelled) setNote(e instanceof Error ? e.message : String(e));
2471
+ }
2472
+ })();
2473
+ return () => {
2474
+ cancelled = true;
2475
+ };
2476
+ }, [connectWithAccount, cloudBaseUrl]);
2477
+ const goToWallet = react.useCallback(async () => {
2478
+ let keys;
2479
+ try {
2480
+ keys = await deviceKeys();
2481
+ } catch (e) {
2482
+ setNote(e instanceof Error ? e.message : String(e));
2483
+ return;
2484
+ }
2485
+ const state = hex(crypto.getRandomValues(new Uint8Array(16)));
2486
+ try {
2487
+ sessionStorage.setItem(STATE_KEY, state);
2488
+ } catch {
2489
+ }
2490
+ window.location.assign(
2491
+ meroJs.deviceEnrolmentUrl({
2492
+ walletUrl,
2493
+ devicePublicKey: keys.signPk,
2494
+ kemPublicKey: keys.kemPk,
2495
+ returnTo: window.location.origin + window.location.pathname,
2496
+ state
2497
+ })
2498
+ );
2499
+ }, [walletUrl]);
2500
+ return {
2501
+ goToWallet,
2502
+ note,
2503
+ returning: returningRef.current === true,
2504
+ walletUrl,
2505
+ customWallet: walletOverride !== void 0
2506
+ };
2507
+ }
2508
+ function shortAccount(account) {
2509
+ return account.length > 14 ? `${account.slice(0, 6)}\u2026${account.slice(-6)}` : account;
2510
+ }
2130
2511
  function ConnectButton({
2131
2512
  connectionType = "remote" /* Remote */,
2132
2513
  className,
2133
2514
  style,
2134
2515
  theme,
2135
2516
  logoOnly = false,
2136
- label
2517
+ label,
2518
+ cloud = true,
2519
+ accountDefaults
2137
2520
  }) {
2138
- const { isAuthenticated, connectToNode, logout, nodeUrl, isOnline } = useMero();
2521
+ const { isAuthenticated, connectToNode, logout, nodeUrl, isOnline, isDelegated } = useMero();
2522
+ const enrolment = useAccountEnrolment({
2523
+ walletUrl: accountDefaults?.walletUrl,
2524
+ enabled: cloud
2525
+ });
2526
+ const [isModalOpen, setIsModalOpen] = react.useState(() => cloud && enrolment.returning);
2139
2527
  const [isDropdownOpen, setIsDropdownOpen] = react.useState(false);
2140
- const [isModalOpen, setIsModalOpen] = react.useState(false);
2141
2528
  const dropdownRef = react.useRef(null);
2529
+ const account = react.useMemo(
2530
+ () => isAuthenticated && isDelegated ? readDelegatedSession()?.account ?? null : null,
2531
+ [isAuthenticated, isDelegated]
2532
+ );
2142
2533
  const resolvedTheme = react.useMemo(
2143
2534
  () => theme ? resolveMeroTheme(theme) : null,
2144
2535
  [theme]
@@ -2157,7 +2548,7 @@ function ConnectButton({
2157
2548
  return () => document.removeEventListener("mousedown", handleClickOutside);
2158
2549
  }, []);
2159
2550
  const dashboardUrl = react.useMemo(() => {
2160
- if (!isAuthenticated || !nodeUrl) return "#";
2551
+ if (!isAuthenticated || !nodeUrl || isDelegated) return "#";
2161
2552
  return new URL("admin-dashboard/", nodeUrl).toString();
2162
2553
  }, [isAuthenticated, nodeUrl]);
2163
2554
  const labels = react.useMemo(() => {
@@ -2226,8 +2617,13 @@ function ConnectButton({
2226
2617
  }
2227
2618
  ),
2228
2619
  isDropdownOpen && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mero-dropdown", children: [
2229
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mero-dropdown-info", title: nodeUrl || "", children: nodeUrl }),
2230
- /* @__PURE__ */ jsxRuntime.jsx(
2620
+ isDelegated && account && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mero-dropdown-info", title: account, "data-testid": "connected-account", children: [
2621
+ "Account ",
2622
+ shortAccount(account)
2623
+ ] }),
2624
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mero-dropdown-info", title: nodeUrl || "", children: nodeUrl ?? (isDelegated ? "no relay yet" : null) }),
2625
+ isDelegated && enrolment.note && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mero-dropdown-info", "data-testid": "connected-note", children: enrolment.note }),
2626
+ !isDelegated && /* @__PURE__ */ jsxRuntime.jsx(
2231
2627
  "a",
2232
2628
  {
2233
2629
  href: dashboardUrl,
@@ -2279,85 +2675,33 @@ function ConnectButton({
2279
2675
  isOpen: isModalOpen,
2280
2676
  onConnect: handleModalConnect,
2281
2677
  onClose: () => setIsModalOpen(false),
2282
- theme: resolvedTheme ?? theme
2678
+ theme: resolvedTheme ?? theme,
2679
+ cloud: cloud ? {
2680
+ onEnrol: () => {
2681
+ void enrolment.goToWallet();
2682
+ },
2683
+ note: enrolment.note,
2684
+ walletUrl: enrolment.walletUrl,
2685
+ customWallet: enrolment.customWallet
2686
+ } : void 0,
2687
+ initialTab: cloud && enrolment.returning ? "cloud" : "node"
2283
2688
  }
2284
2689
  )
2285
2690
  ]
2286
2691
  }
2287
2692
  );
2288
2693
  }
2289
- var DEVICE_KEY = "calimero.device";
2290
- var STATE_KEY = "calimero.enrol.state";
2291
- var HOSTED_WALLET = "https://wallet.cloud.calimero.network/account-enroll";
2292
- var hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
2293
- function chooseRelay(relays) {
2294
- const reachable = relays.filter(
2295
- (r) => typeof r.relayUrl === "string" && r.relayUrl.length > 0
2296
- );
2297
- const fresh = reachable.find((r) => r.fresh);
2298
- if (fresh) return { relayUrl: fresh.relayUrl, note: null };
2299
- if (reachable.length > 0) {
2300
- return {
2301
- relayUrl: reachable[0].relayUrl,
2302
- note: "Connected through a relay whose last heartbeat has lapsed \u2014 it may not answer. It was the only one with an address."
2303
- };
2304
- }
2305
- if (relays.length > 0) {
2306
- return {
2307
- relayUrl: null,
2308
- 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.`
2309
- };
2310
- }
2311
- return {
2312
- relayUrl: null,
2313
- 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."
2314
- };
2315
- }
2316
- async function deviceKeys() {
2317
- const had = localStorage.getItem(DEVICE_KEY);
2318
- if (had) {
2319
- const parsed = JSON.parse(had);
2320
- if (parsed.kemSk && parsed.signSk && parsed.signPk && parsed.kemPk) {
2321
- return parsed;
2322
- }
2323
- localStorage.removeItem(DEVICE_KEY);
2324
- }
2325
- const sign = await crypto.subtle.generateKey({ name: "Ed25519" }, true, [
2326
- "sign",
2327
- "verify"
2328
- ]);
2329
- let agree;
2330
- try {
2331
- agree = await crypto.subtle.generateKey({ name: "X25519" }, true, [
2332
- "deriveBits"
2333
- ]);
2334
- } catch {
2335
- throw new Error(
2336
- "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."
2337
- );
2338
- }
2339
- const keys = {
2340
- signPk: hex(await crypto.subtle.exportKey("raw", sign.publicKey)),
2341
- signSk: hex((await crypto.subtle.exportKey("pkcs8", sign.privateKey)).slice(16)),
2342
- kemPk: hex(await crypto.subtle.exportKey("raw", agree.publicKey)),
2343
- kemSk: hex((await crypto.subtle.exportKey("pkcs8", agree.privateKey)).slice(16))
2344
- };
2345
- localStorage.setItem(DEVICE_KEY, JSON.stringify(keys));
2346
- return keys;
2347
- }
2348
2694
  function ConnectButtonAccount({
2349
2695
  className,
2350
2696
  style,
2351
2697
  theme,
2352
2698
  defaults = {}
2353
2699
  }) {
2354
- const { isAuthenticated, isOnline, nodeUrl, isDelegated, connectToNode, connectWithAccount, logout, cloudBaseUrl } = useMero();
2700
+ const { isAuthenticated, isOnline, nodeUrl, isDelegated, connectToNode, logout } = useMero();
2355
2701
  const [isDropdownOpen, setIsDropdownOpen] = react.useState(false);
2356
2702
  const [isNodeModalOpen, setIsNodeModalOpen] = react.useState(false);
2357
2703
  const [isAccountOpen, setIsAccountOpen] = react.useState(false);
2358
- const [note, setNote] = react.useState(null);
2359
2704
  const dropdownRef = react.useRef(null);
2360
- const walletUrl = defaults.walletUrl ?? HOSTED_WALLET;
2361
2705
  const resolvedTheme = react.useMemo(() => theme ? resolveMeroTheme(theme) : null, [theme]);
2362
2706
  const themeVars = react.useMemo(
2363
2707
  () => resolvedTheme ? themeToCssVars(resolvedTheme) : void 0,
@@ -2372,98 +2716,7 @@ function ConnectButtonAccount({
2372
2716
  document.addEventListener("mousedown", onOutside);
2373
2717
  return () => document.removeEventListener("mousedown", onOutside);
2374
2718
  }, []);
2375
- const callbackRef = react.useRef(void 0);
2376
- const callbackErrorRef = react.useRef(null);
2377
- if (callbackRef.current === void 0 && typeof window !== "undefined") {
2378
- try {
2379
- callbackRef.current = meroJs.readEnrolmentCallback();
2380
- } catch (e) {
2381
- callbackRef.current = null;
2382
- callbackErrorRef.current = e instanceof Error ? e.message : String(e);
2383
- }
2384
- }
2385
- const completingRef = react.useRef(false);
2386
- react.useEffect(() => {
2387
- if (callbackErrorRef.current) {
2388
- setNote(callbackErrorRef.current);
2389
- callbackErrorRef.current = null;
2390
- return;
2391
- }
2392
- const back = callbackRef.current;
2393
- if (!back || completingRef.current) return;
2394
- completingRef.current = true;
2395
- let cancelled = false;
2396
- (async () => {
2397
- try {
2398
- const keys = await deviceKeys();
2399
- const sent = (() => {
2400
- try {
2401
- return sessionStorage.getItem(STATE_KEY);
2402
- } catch {
2403
- return null;
2404
- }
2405
- })();
2406
- try {
2407
- sessionStorage.removeItem(STATE_KEY);
2408
- } catch {
2409
- }
2410
- if (!sent) {
2411
- setNote(
2412
- 'This enrolment could not be verified as one this tab started, so it was not accepted. Start again from "Enrol with your account".'
2413
- );
2414
- return;
2415
- }
2416
- const enrolled = await meroJs.completeDeviceEnrolment({
2417
- ...back,
2418
- devicePublicKey: keys.signPk,
2419
- kemPublicKey: keys.kemPk,
2420
- expectState: sent
2421
- });
2422
- saveDelegatedCredential({
2423
- account: enrolled.account,
2424
- credential: enrolled.credential,
2425
- deviceSecret: keys.signSk
2426
- });
2427
- const cloud = new meroJs.CloudClient({
2428
- cloudBaseUrl,
2429
- routingCredential: {
2430
- credential: enrolled.credential,
2431
- deviceSecret: keys.signSk
2432
- }
2433
- });
2434
- const chosen = chooseRelay(await cloud.getAccountRelays(enrolled.account));
2435
- if (chosen.note) setNote(chosen.note);
2436
- connectWithAccount({
2437
- relayUrl: chosen.relayUrl,
2438
- account: enrolled.account,
2439
- credential: enrolled.credential,
2440
- deviceSecret: keys.signSk
2441
- });
2442
- } catch (e) {
2443
- if (!cancelled) setNote(e instanceof Error ? e.message : String(e));
2444
- }
2445
- })();
2446
- return () => {
2447
- cancelled = true;
2448
- };
2449
- }, [connectWithAccount, cloudBaseUrl]);
2450
- const goToWallet = react.useCallback(async () => {
2451
- const keys = await deviceKeys();
2452
- const state = hex(crypto.getRandomValues(new Uint8Array(16)));
2453
- try {
2454
- sessionStorage.setItem(STATE_KEY, state);
2455
- } catch {
2456
- }
2457
- window.location.assign(
2458
- meroJs.deviceEnrolmentUrl({
2459
- walletUrl,
2460
- devicePublicKey: keys.signPk,
2461
- kemPublicKey: keys.kemPk,
2462
- returnTo: window.location.origin + window.location.pathname,
2463
- state
2464
- })
2465
- );
2466
- }, [walletUrl]);
2719
+ const { goToWallet, note, walletUrl } = useAccountEnrolment({ walletUrl: defaults.walletUrl });
2467
2720
  if (isAuthenticated && !isOnline) {
2468
2721
  return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mero-connect-container", style: { ...themeVars, display: "inline-block" }, children: /* @__PURE__ */ jsxRuntime.jsxs(
2469
2722
  "button",
@@ -4634,6 +4887,7 @@ Object.defineProperty(exports, "withoutCap", {
4634
4887
  enumerable: true,
4635
4888
  get: function () { return meroJs.withoutCap; }
4636
4889
  });
4890
+ exports.AccountSignInPanel = AccountSignInPanel;
4637
4891
  exports.AppMode = AppMode;
4638
4892
  exports.CalimeroLogo = CalimeroLogo;
4639
4893
  exports.ConnectButton = ConnectButton;
@@ -4686,6 +4940,7 @@ exports.setContextIdentity = setContextIdentity;
4686
4940
  exports.setNodeUrl = setNodeUrl;
4687
4941
  exports.setTokenNodeUrl = setTokenNodeUrl;
4688
4942
  exports.themeToCssVars = themeToCssVars;
4943
+ exports.useAccountEnrolment = useAccountEnrolment;
4689
4944
  exports.useAddGroupMembers = useAddGroupMembers;
4690
4945
  exports.useAppVersion = useAppVersion;
4691
4946
  exports.useApplicationContexts = useApplicationContexts;