@calimero-network/mero-react 9.5.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
@@ -1660,7 +1660,85 @@ function themeToCssVars(theme) {
1660
1660
  function cssVar(theme, key) {
1661
1661
  return `var(${MERO_CSS_VARS[key]}, ${theme[key]})`;
1662
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
+ }
1663
1737
  var CUSTOM_SELECTION = "__custom__";
1738
+ var TABS = [
1739
+ { id: "node", label: "Node" },
1740
+ { id: "cloud", label: "Cloud" }
1741
+ ];
1664
1742
  function isValidUrl(urlString) {
1665
1743
  if (!urlString || urlString.trim() === "") {
1666
1744
  return false;
@@ -1896,6 +1974,32 @@ function buildStyles(t) {
1896
1974
  borderRadius: "50%",
1897
1975
  animation: "meroSpin 1s linear infinite"
1898
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
+ },
1899
2003
  spinnerSmall: {
1900
2004
  width: "1.5rem",
1901
2005
  height: "1.5rem",
@@ -1911,8 +2015,19 @@ function LoginModal({
1911
2015
  onClose,
1912
2016
  isOpen,
1913
2017
  theme,
1914
- localNodePorts = DEFAULT_LOCAL_NODE_PORTS
2018
+ localNodePorts = DEFAULT_LOCAL_NODE_PORTS,
2019
+ cloud,
2020
+ initialTab = "node"
1915
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";
1916
2031
  const [selected, setSelected] = useState(CUSTOM_SELECTION);
1917
2032
  const [discovered, setDiscovered] = useState([]);
1918
2033
  const [discovering, setDiscovering] = useState(false);
@@ -2091,6 +2206,76 @@ function LoginModal({
2091
2206
  ) })
2092
2207
  ] });
2093
2208
  };
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
+ }) });
2094
2279
  const modalContent = /* @__PURE__ */ jsxs(Fragment, { children: [
2095
2280
  /* @__PURE__ */ jsx("style", { children: `
2096
2281
  @keyframes meroSpin { to { transform: rotate(360deg); } }
@@ -2103,42 +2288,231 @@ function LoginModal({
2103
2288
  /* @__PURE__ */ jsx(CalimeroLogo, { size: 44, color: cssVar(resolved, "primary") }),
2104
2289
  /* @__PURE__ */ jsx("h1", { style: styles.title, children: "Connect to Calimero" })
2105
2290
  ] }),
2106
- loading ? /* @__PURE__ */ jsxs("div", { style: styles.loading, children: [
2107
- /* @__PURE__ */ jsx("p", { children: "Connecting to node..." }),
2108
- /* @__PURE__ */ jsx("div", { style: styles.spinner })
2109
- ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
2110
- error && /* @__PURE__ */ jsx("p", { style: styles.error, children: error }),
2111
- renderNodeSection(),
2112
- /* @__PURE__ */ jsx("div", { style: styles.buttonGroup, children: /* @__PURE__ */ 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
- ] })
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()
2126
2311
  ] }) })
2127
2312
  ] });
2128
2313
  return createPortal(modalContent, document.body);
2129
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
+ }
2130
2494
  function ConnectButton({
2131
2495
  connectionType = "remote" /* Remote */,
2132
2496
  className,
2133
2497
  style,
2134
2498
  theme,
2135
2499
  logoOnly = false,
2136
- label
2500
+ label,
2501
+ cloud = true,
2502
+ accountDefaults
2137
2503
  }) {
2138
- 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);
2139
2510
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
2140
- const [isModalOpen, setIsModalOpen] = useState(false);
2141
2511
  const dropdownRef = useRef(null);
2512
+ const account = useMemo(
2513
+ () => isAuthenticated && isDelegated ? readDelegatedSession()?.account ?? null : null,
2514
+ [isAuthenticated, isDelegated]
2515
+ );
2142
2516
  const resolvedTheme = useMemo(
2143
2517
  () => theme ? resolveMeroTheme(theme) : null,
2144
2518
  [theme]
@@ -2157,7 +2531,7 @@ function ConnectButton({
2157
2531
  return () => document.removeEventListener("mousedown", handleClickOutside);
2158
2532
  }, []);
2159
2533
  const dashboardUrl = useMemo(() => {
2160
- if (!isAuthenticated || !nodeUrl) return "#";
2534
+ if (!isAuthenticated || !nodeUrl || isDelegated) return "#";
2161
2535
  return new URL("admin-dashboard/", nodeUrl).toString();
2162
2536
  }, [isAuthenticated, nodeUrl]);
2163
2537
  const labels = useMemo(() => {
@@ -2226,8 +2600,13 @@ function ConnectButton({
2226
2600
  }
2227
2601
  ),
2228
2602
  isDropdownOpen && /* @__PURE__ */ jsxs("div", { className: "mero-dropdown", children: [
2229
- /* @__PURE__ */ jsx("div", { className: "mero-dropdown-info", title: nodeUrl || "", children: nodeUrl }),
2230
- /* @__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(
2231
2610
  "a",
2232
2611
  {
2233
2612
  href: dashboardUrl,
@@ -2279,85 +2658,33 @@ function ConnectButton({
2279
2658
  isOpen: isModalOpen,
2280
2659
  onConnect: handleModalConnect,
2281
2660
  onClose: () => setIsModalOpen(false),
2282
- theme: resolvedTheme ?? theme
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"
2283
2671
  }
2284
2672
  )
2285
2673
  ]
2286
2674
  }
2287
2675
  );
2288
2676
  }
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
2677
  function ConnectButtonAccount({
2349
2678
  className,
2350
2679
  style,
2351
2680
  theme,
2352
2681
  defaults = {}
2353
2682
  }) {
2354
- const { isAuthenticated, isOnline, nodeUrl, isDelegated, connectToNode, connectWithAccount, logout, cloudBaseUrl } = useMero();
2683
+ const { isAuthenticated, isOnline, nodeUrl, isDelegated, connectToNode, logout } = useMero();
2355
2684
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
2356
2685
  const [isNodeModalOpen, setIsNodeModalOpen] = useState(false);
2357
2686
  const [isAccountOpen, setIsAccountOpen] = useState(false);
2358
- const [note, setNote] = useState(null);
2359
2687
  const dropdownRef = useRef(null);
2360
- const walletUrl = defaults.walletUrl ?? HOSTED_WALLET;
2361
2688
  const resolvedTheme = useMemo(() => theme ? resolveMeroTheme(theme) : null, [theme]);
2362
2689
  const themeVars = useMemo(
2363
2690
  () => resolvedTheme ? themeToCssVars(resolvedTheme) : void 0,
@@ -2372,98 +2699,7 @@ function ConnectButtonAccount({
2372
2699
  document.addEventListener("mousedown", onOutside);
2373
2700
  return () => document.removeEventListener("mousedown", onOutside);
2374
2701
  }, []);
2375
- const callbackRef = useRef(void 0);
2376
- const callbackErrorRef = useRef(null);
2377
- if (callbackRef.current === void 0 && typeof window !== "undefined") {
2378
- try {
2379
- callbackRef.current = readEnrolmentCallback();
2380
- } catch (e) {
2381
- callbackRef.current = null;
2382
- callbackErrorRef.current = e instanceof Error ? e.message : String(e);
2383
- }
2384
- }
2385
- const completingRef = useRef(false);
2386
- 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 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 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 = 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
- 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]);
2702
+ const { goToWallet, note, walletUrl } = useAccountEnrolment({ walletUrl: defaults.walletUrl });
2467
2703
  if (isAuthenticated && !isOnline) {
2468
2704
  return /* @__PURE__ */ jsx("div", { className: "mero-connect-container", style: { ...themeVars, display: "inline-block" }, children: /* @__PURE__ */ jsxs(
2469
2705
  "button",
@@ -4598,6 +4834,6 @@ function useJoinInvitation() {
4598
4834
  return { joinInvitation, joining, memberships, invitationRedeemer };
4599
4835
  }
4600
4836
 
4601
- 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 };
4602
4838
  //# sourceMappingURL=index.js.map
4603
4839
  //# sourceMappingURL=index.js.map