@calimero-network/mero-react 9.9.0 → 9.10.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/README.md CHANGED
@@ -335,7 +335,30 @@ Helpers: `defaultMeroTheme` (the full default palette), `resolveMeroTheme(partia
335
335
  | `cloud` | `boolean` | `true` | The modal has two tabs: **Node** (discovery + URL, default) and **Cloud** (sign in with a Calimero account by enrolling at the wallet). `false` removes the Cloud tab. A page coming back from the wallet opens the modal on Cloud automatically. |
336
336
  | `accountDefaults` | `{ walletUrl?: string }` | — | Local development only: enrol at a wallet other than the hosted one. |
337
337
 
338
- The account flow without the button is `useAccountEnrolment()` (returns `goToWallet`, `note`, `returning`, `walletUrl`, `customWallet`); its UI is `<AccountSignInPanel>`, and `<LoginModal cloud={...} initialTab="cloud">` renders both tabs.
338
+ ### `<LoginModal>` and the Cloud tab
339
+
340
+ An app that mounts the modal itself gets the same two tabs with nothing wired: by default `LoginModal` sources its Cloud tab from `useAccountEnrolment()` internally, so "Enrol with your account" works and a page coming back from the wallet is completed (and lands on the Cloud tab) whether or not the modal is open. It must sit inside `MeroProvider`.
341
+
342
+ ```tsx
343
+ // Node + Cloud tabs, account sign-in included (default)
344
+ <LoginModal isOpen={open} onConnect={connectToNode} onClose={() => setOpen(false)} />
345
+
346
+ // Node dialog only, no tabs — the pre-Cloud behaviour
347
+ <LoginModal cloud={false} isOpen={open} onConnect={connectToNode} onClose={() => setOpen(false)} />
348
+
349
+ // Your own enrolment (what ConnectButton does): the object is used verbatim
350
+ <LoginModal cloud={{ onEnrol, note, walletUrl, customWallet }} initialTab="cloud" ... />
351
+ ```
352
+
353
+ | `cloud` | Cloud tab | Enrolment callback read by |
354
+ |---------|-----------|----------------------------|
355
+ | omitted | shown, sourced by the modal | the modal |
356
+ | `false` | none (no tabs) | nobody here |
357
+ | object | shown, the caller's values | the caller |
358
+
359
+ `initialTab` defaults to `'node'`; with `cloud` omitted it defaults to `'cloud'` on the load coming back from the wallet. An explicit `initialTab` wins.
360
+
361
+ The caller owns `isOpen`. To have the modal open by itself on the way back from the wallet (as `ConnectButton` does), seed its open state with `isReturningFromWallet()`, which peeks at the fragment without consuming it: `const [open, setOpen] = useState(isReturningFromWallet);`. The account flow without any of these is `useAccountEnrolment()` (returns `goToWallet`, `note`, `returning`, `walletUrl`, `customWallet`); its UI is `<AccountSignInPanel>`.
339
362
 
340
363
  ## Enums
341
364
 
package/dist/index.cjs CHANGED
@@ -170,41 +170,120 @@ function dcapVerifyFrom(mod) {
170
170
  }
171
171
  return verify;
172
172
  }
173
- function relayQuoteVerifier(relayUrl) {
173
+ var RelayKeyTransportError = class extends Error {
174
+ constructor(step, cause) {
175
+ super(`${step}: ${cause instanceof Error ? cause.message : String(cause)}`);
176
+ this.step = step;
177
+ this.cause = cause;
178
+ this.name = "RelayKeyTransportError";
179
+ }
180
+ };
181
+ async function transport(step, run) {
182
+ try {
183
+ return await run();
184
+ } catch (e) {
185
+ throw e instanceof RelayKeyTransportError ? e : new RelayKeyTransportError(step, e);
186
+ }
187
+ }
188
+ function relayFetch(marked) {
189
+ return async (input, init) => {
190
+ let response;
191
+ try {
192
+ response = await globalThis.fetch(input, init);
193
+ } catch (e) {
194
+ marked.failure = e;
195
+ throw new RelayKeyTransportError(`reaching ${String(input)}`, e);
196
+ }
197
+ if (!response.ok) marked.failure ?? (marked.failure = new Error(`${String(input)} answered HTTP ${response.status}`));
198
+ return response;
199
+ };
200
+ }
201
+ function relayQuoteVerifier(relayUrl, fetchRelay) {
174
202
  const verify = async (attestation) => {
175
- loadedDcap ?? (loadedDcap = import('@phala/dcap-qvl').then(
176
- (mod) => dcapVerifyFrom(mod),
177
- (error) => {
178
- loadedDcap = void 0;
179
- throw error;
180
- }
181
- ));
203
+ const dcapVerify = await transport("loading the quote verifier", () => {
204
+ loadedDcap ?? (loadedDcap = import('@phala/dcap-qvl').then(
205
+ (mod) => dcapVerifyFrom(mod),
206
+ (error) => {
207
+ loadedDcap = void 0;
208
+ throw error;
209
+ }
210
+ ));
211
+ return loadedDcap;
212
+ });
182
213
  return meroJs.createSignedReleaseVerifier({
183
- dcapVerify: await loadedDcap,
184
- release: async () => meroJs.fetchNodeRelease(meroJs.cloudNodeReleaseUrl(meroJs.DEFAULT_RELEASE_MIRROR, await meroJs.fetchNodeReleaseVersion(relayUrl))),
214
+ dcapVerify,
215
+ // Fetched only. Its signature, its version and the quote's registers are
216
+ // all checked by the verifier after this returns, and none of that is a
217
+ // transport question.
218
+ release: () => transport(
219
+ "fetching the release the relay runs",
220
+ async () => meroJs.fetchNodeRelease(
221
+ meroJs.cloudNodeReleaseUrl(meroJs.DEFAULT_RELEASE_MIRROR, await meroJs.fetchNodeReleaseVersion(relayUrl, { fetch: fetchRelay }))
222
+ )
223
+ ),
185
224
  profile: TRUSTED_RELAY_PROFILE,
186
225
  minReleaseVersion: MIN_RELAY_RELEASE
187
226
  })(attestation);
188
227
  };
189
228
  return Object.assign(verify, { includeCollateral: true });
190
229
  }
191
- async function resolveRelayNodeKey(relayUrl) {
230
+ async function attemptRelayNodeKey(relayUrl) {
192
231
  const pinned = readPinnedRelayNodeKey(relayUrl);
193
- if (pinned) return pinned;
232
+ if (pinned) return { kind: "learned", nodeKey: pinned };
233
+ const marked = { failure: null };
234
+ const fetchRelay = relayFetch(marked);
194
235
  try {
195
236
  const local = isLoopback(relayUrl);
196
237
  const { nodeKey } = await meroJs.attestRelayNodeKey({
197
238
  relayUrl,
198
239
  allowMock: local,
199
- ...local ? {} : { verify: relayQuoteVerifier(relayUrl) }
240
+ fetch: fetchRelay,
241
+ ...local ? {} : { verify: relayQuoteVerifier(relayUrl, fetchRelay) }
200
242
  });
201
243
  pinRelayNodeKey(relayUrl, nodeKey);
202
- return nodeKey;
244
+ return { kind: "learned", nodeKey };
203
245
  } catch (e) {
204
- console.warn("[mero-react] could not learn the relay node key from its attestation", e);
205
- return null;
246
+ if (e instanceof RelayKeyTransportError || marked.failure) return { kind: "unavailable", error: e };
247
+ return { kind: "refused", error: e };
206
248
  }
207
249
  }
250
+ async function resolveRelayNodeKey(relayUrl) {
251
+ const attempt = await attemptRelayNodeKey(relayUrl);
252
+ if (attempt.kind === "learned") return attempt.nodeKey;
253
+ console.warn("[mero-react] could not learn the relay node key from its attestation", attempt.error);
254
+ return null;
255
+ }
256
+ var RELAY_NODE_KEY_RETRY_MS = [1e3, 2e3, 5e3, 1e4, 3e4];
257
+ function pause(ms, signal) {
258
+ return new Promise((resolve) => {
259
+ if (signal?.aborted) return resolve();
260
+ const timer = setTimeout(done, ms);
261
+ function done() {
262
+ clearTimeout(timer);
263
+ signal?.removeEventListener("abort", done);
264
+ resolve();
265
+ }
266
+ signal?.addEventListener("abort", done);
267
+ });
268
+ }
269
+ async function learnRelayNodeKey(relayUrl, options = {}) {
270
+ const { signal } = options;
271
+ for (let failures = 0; !signal?.aborted; failures += 1) {
272
+ const attempt = await attemptRelayNodeKey(relayUrl);
273
+ if (attempt.kind === "learned") return attempt.nodeKey;
274
+ if (attempt.kind === "refused") {
275
+ console.warn("[mero-react] refusing the relay's attestation; its node key stays unknown", attempt.error);
276
+ return null;
277
+ }
278
+ const wait = RELAY_NODE_KEY_RETRY_MS[Math.min(failures, RELAY_NODE_KEY_RETRY_MS.length - 1)];
279
+ console.warn(
280
+ `[mero-react] could not reach what proves the relay's node key; retrying in ${wait / 1e3} s`,
281
+ attempt.error
282
+ );
283
+ await pause(wait, signal);
284
+ }
285
+ return null;
286
+ }
208
287
  function jwtExpiryMs(token) {
209
288
  try {
210
289
  const payload = JSON.parse(atob(token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")));
@@ -1470,10 +1549,11 @@ function MeroProvider({
1470
1549
  setNodeUrlState(relayUrl);
1471
1550
  setIsLoading(awaitingKey);
1472
1551
  let active = true;
1552
+ const stop = new AbortController();
1473
1553
  (async () => {
1474
1554
  if (!client2 || !relayUrl) return;
1475
1555
  if (awaitingKey) {
1476
- const nodeKey = await resolveRelayNodeKey(relayUrl);
1556
+ const nodeKey = await learnRelayNodeKey(relayUrl, { signal: stop.signal });
1477
1557
  if (!active) return;
1478
1558
  setMero(nodeKey ? buildDelegatedClient(routed) ?? client2 : client2);
1479
1559
  setIsLoading(false);
@@ -1493,6 +1573,7 @@ function MeroProvider({
1493
1573
  })();
1494
1574
  return () => {
1495
1575
  active = false;
1576
+ stop.abort();
1496
1577
  };
1497
1578
  }, [delegated, contextId]);
1498
1579
  react.useEffect(() => {
@@ -1852,6 +1933,196 @@ function AccountSignInPanel({
1852
1933
  ] })
1853
1934
  ] });
1854
1935
  }
1936
+ var DEVICE_KEY = "calimero.device";
1937
+ var STATE_KEY = "calimero.enrol.state";
1938
+ var HOSTED_WALLET = "https://wallet.cloud.calimero.network/account-enroll";
1939
+ var hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
1940
+ function executorOf(relay) {
1941
+ const value = relay.executorAccount;
1942
+ return typeof value === "string" && /^[0-9a-f]{64}$/.test(value) ? value : null;
1943
+ }
1944
+ function chooseRelay(relays) {
1945
+ const reachable = relays.filter(
1946
+ (r) => typeof r.relayUrl === "string" && r.relayUrl.length > 0
1947
+ );
1948
+ const fresh = reachable.find((r) => r.fresh);
1949
+ if (fresh) return { relayUrl: fresh.relayUrl, executorAccount: executorOf(fresh), note: null };
1950
+ if (reachable.length > 0) {
1951
+ return {
1952
+ relayUrl: reachable[0].relayUrl,
1953
+ executorAccount: executorOf(reachable[0]),
1954
+ note: "Connected through a relay whose last heartbeat has lapsed \u2014 it may not answer. It was the only one with an address."
1955
+ };
1956
+ }
1957
+ if (relays.length > 0) {
1958
+ return {
1959
+ relayUrl: null,
1960
+ executorAccount: null,
1961
+ 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.`
1962
+ };
1963
+ }
1964
+ return {
1965
+ relayUrl: null,
1966
+ executorAccount: null,
1967
+ 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."
1968
+ };
1969
+ }
1970
+ async function deviceKeys() {
1971
+ const had = localStorage.getItem(DEVICE_KEY);
1972
+ if (had) {
1973
+ const parsed = JSON.parse(had);
1974
+ if (parsed.kemSk && parsed.signSk && parsed.signPk && parsed.kemPk) {
1975
+ return parsed;
1976
+ }
1977
+ localStorage.removeItem(DEVICE_KEY);
1978
+ }
1979
+ const sign = await crypto.subtle.generateKey({ name: "Ed25519" }, true, [
1980
+ "sign",
1981
+ "verify"
1982
+ ]);
1983
+ let agree;
1984
+ try {
1985
+ agree = await crypto.subtle.generateKey({ name: "X25519" }, true, [
1986
+ "deriveBits"
1987
+ ]);
1988
+ } catch {
1989
+ throw new Error(
1990
+ "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."
1991
+ );
1992
+ }
1993
+ const keys = {
1994
+ signPk: hex(await crypto.subtle.exportKey("raw", sign.publicKey)),
1995
+ signSk: hex((await crypto.subtle.exportKey("pkcs8", sign.privateKey)).slice(16)),
1996
+ kemPk: hex(await crypto.subtle.exportKey("raw", agree.publicKey)),
1997
+ kemSk: hex((await crypto.subtle.exportKey("pkcs8", agree.privateKey)).slice(16))
1998
+ };
1999
+ localStorage.setItem(DEVICE_KEY, JSON.stringify(keys));
2000
+ return keys;
2001
+ }
2002
+ function isReturningFromWallet(location = typeof window === "undefined" ? void 0 : window.location) {
2003
+ if (!location) return false;
2004
+ const params = new URLSearchParams(location.hash.replace(/^#/, ""));
2005
+ if (params.get("error")) return true;
2006
+ return Boolean(params.get("credential") && params.get("account") && params.get("device"));
2007
+ }
2008
+ function useAccountEnrolment({
2009
+ walletUrl: walletOverride,
2010
+ enabled = true
2011
+ } = {}) {
2012
+ const { connectWithAccount, cloudBaseUrl } = useMero();
2013
+ const [note, setNote] = react.useState(null);
2014
+ const walletUrl = walletOverride ?? HOSTED_WALLET;
2015
+ const callbackRef = react.useRef(void 0);
2016
+ const callbackErrorRef = react.useRef(null);
2017
+ if (enabled && callbackRef.current === void 0 && typeof window !== "undefined") {
2018
+ try {
2019
+ callbackRef.current = meroJs.readEnrolmentCallback();
2020
+ } catch (e) {
2021
+ callbackRef.current = null;
2022
+ callbackErrorRef.current = e instanceof Error ? e.message : String(e);
2023
+ }
2024
+ }
2025
+ const returningRef = react.useRef(null);
2026
+ if (returningRef.current === null && callbackRef.current !== void 0) {
2027
+ returningRef.current = callbackRef.current !== null || callbackErrorRef.current !== null;
2028
+ }
2029
+ const completingRef = react.useRef(false);
2030
+ react.useEffect(() => {
2031
+ if (callbackErrorRef.current) {
2032
+ setNote(callbackErrorRef.current);
2033
+ callbackErrorRef.current = null;
2034
+ return;
2035
+ }
2036
+ const back = callbackRef.current;
2037
+ if (!back || completingRef.current) return;
2038
+ completingRef.current = true;
2039
+ let cancelled = false;
2040
+ (async () => {
2041
+ try {
2042
+ const keys = await deviceKeys();
2043
+ const sent = (() => {
2044
+ try {
2045
+ return sessionStorage.getItem(STATE_KEY);
2046
+ } catch {
2047
+ return null;
2048
+ }
2049
+ })();
2050
+ try {
2051
+ sessionStorage.removeItem(STATE_KEY);
2052
+ } catch {
2053
+ }
2054
+ if (!sent) {
2055
+ setNote(
2056
+ 'This enrolment could not be verified as one this tab started, so it was not accepted. Start again from "Enrol with your account".'
2057
+ );
2058
+ return;
2059
+ }
2060
+ const enrolled = await meroJs.completeDeviceEnrolment({
2061
+ ...back,
2062
+ devicePublicKey: keys.signPk,
2063
+ kemPublicKey: keys.kemPk,
2064
+ expectState: sent
2065
+ });
2066
+ saveDelegatedCredential({
2067
+ account: enrolled.account,
2068
+ credential: enrolled.credential,
2069
+ deviceSecret: keys.signSk
2070
+ });
2071
+ const cloud = new meroJs.CloudClient({
2072
+ cloudBaseUrl,
2073
+ routingCredential: {
2074
+ credential: enrolled.credential,
2075
+ deviceSecret: keys.signSk
2076
+ }
2077
+ });
2078
+ const chosen = chooseRelay(await cloud.getAccountRelays(enrolled.account));
2079
+ if (chosen.note) setNote(chosen.note);
2080
+ connectWithAccount({
2081
+ relayUrl: chosen.relayUrl,
2082
+ account: enrolled.account,
2083
+ credential: enrolled.credential,
2084
+ deviceSecret: keys.signSk,
2085
+ ...chosen.executorAccount ? { executorAccount: chosen.executorAccount } : {}
2086
+ });
2087
+ } catch (e) {
2088
+ if (!cancelled) setNote(e instanceof Error ? e.message : String(e));
2089
+ }
2090
+ })();
2091
+ return () => {
2092
+ cancelled = true;
2093
+ };
2094
+ }, [connectWithAccount, cloudBaseUrl]);
2095
+ const goToWallet = react.useCallback(async () => {
2096
+ let keys;
2097
+ try {
2098
+ keys = await deviceKeys();
2099
+ } catch (e) {
2100
+ setNote(e instanceof Error ? e.message : String(e));
2101
+ return;
2102
+ }
2103
+ const state = hex(crypto.getRandomValues(new Uint8Array(16)));
2104
+ try {
2105
+ sessionStorage.setItem(STATE_KEY, state);
2106
+ } catch {
2107
+ }
2108
+ window.location.assign(
2109
+ meroJs.deviceEnrolmentUrl({
2110
+ walletUrl,
2111
+ devicePublicKey: keys.signPk,
2112
+ kemPublicKey: keys.kemPk,
2113
+ returnTo: window.location.origin + window.location.pathname,
2114
+ state
2115
+ })
2116
+ );
2117
+ }, [walletUrl]);
2118
+ return {
2119
+ goToWallet,
2120
+ note,
2121
+ returning: returningRef.current === true,
2122
+ walletUrl,
2123
+ customWallet: walletOverride !== void 0
2124
+ };
2125
+ }
1855
2126
  var CUSTOM_SELECTION = "__custom__";
1856
2127
  var TABS = [
1857
2128
  { id: "node", label: "Node" },
@@ -2135,8 +2406,21 @@ function LoginModal({
2135
2406
  theme,
2136
2407
  localNodePorts = meroJs.DEFAULT_LOCAL_NODE_PORTS,
2137
2408
  cloud,
2138
- initialTab = "node"
2409
+ initialTab: initialTabProp
2139
2410
  }) {
2411
+ const own = useAccountEnrolment({ enabled: cloud === void 0 });
2412
+ const cloudTab = react.useMemo(
2413
+ () => cloud === void 0 ? {
2414
+ onEnrol: () => {
2415
+ void own.goToWallet();
2416
+ },
2417
+ note: own.note,
2418
+ walletUrl: own.walletUrl,
2419
+ customWallet: own.customWallet
2420
+ } : cloud || null,
2421
+ [cloud, own.goToWallet, own.note, own.walletUrl, own.customWallet]
2422
+ );
2423
+ const initialTab = initialTabProp ?? (cloud === void 0 && own.returning ? "cloud" : "node");
2140
2424
  const [tab, setTab] = react.useState(initialTab);
2141
2425
  react.useEffect(() => {
2142
2426
  if (isOpen) setTab(initialTab);
@@ -2145,7 +2429,7 @@ function LoginModal({
2145
2429
  node: null,
2146
2430
  cloud: null
2147
2431
  });
2148
- const activeTab = cloud ? tab : "node";
2432
+ const activeTab = cloudTab ? tab : "node";
2149
2433
  const [selected, setSelected] = react.useState(CUSTOM_SELECTION);
2150
2434
  const [discovered, setDiscovered] = react.useState([]);
2151
2435
  const [discovering, setDiscovering] = react.useState(false);
@@ -2345,7 +2629,7 @@ function LoginModal({
2345
2629
  }
2346
2630
  ) })
2347
2631
  ] });
2348
- if (!cloud) return body;
2632
+ if (!cloudTab) return body;
2349
2633
  return /* @__PURE__ */ jsxRuntime.jsx(
2350
2634
  "div",
2351
2635
  {
@@ -2406,8 +2690,8 @@ function LoginModal({
2406
2690
  /* @__PURE__ */ jsxRuntime.jsx(CalimeroLogo, { size: 44, color: cssVar(resolved, "primary") }),
2407
2691
  /* @__PURE__ */ jsxRuntime.jsx("h1", { style: styles.title, children: "Connect to Calimero" })
2408
2692
  ] }),
2409
- cloud && renderTabs(),
2410
- activeTab === "cloud" && cloud ? /* @__PURE__ */ jsxRuntime.jsx(
2693
+ cloudTab && renderTabs(),
2694
+ activeTab === "cloud" && cloudTab ? /* @__PURE__ */ jsxRuntime.jsx(
2411
2695
  "div",
2412
2696
  {
2413
2697
  role: "tabpanel",
@@ -2417,10 +2701,10 @@ function LoginModal({
2417
2701
  children: /* @__PURE__ */ jsxRuntime.jsx(
2418
2702
  AccountSignInPanel,
2419
2703
  {
2420
- onEnrol: cloud.onEnrol,
2421
- note: cloud.note,
2422
- walletUrl: cloud.walletUrl,
2423
- customWallet: cloud.customWallet,
2704
+ onEnrol: cloudTab.onEnrol,
2705
+ note: cloudTab.note,
2706
+ walletUrl: cloudTab.walletUrl,
2707
+ customWallet: cloudTab.customWallet,
2424
2708
  theme
2425
2709
  }
2426
2710
  )
@@ -2430,190 +2714,6 @@ function LoginModal({
2430
2714
  ] });
2431
2715
  return reactDom.createPortal(modalContent, document.body);
2432
2716
  }
2433
- var DEVICE_KEY = "calimero.device";
2434
- var STATE_KEY = "calimero.enrol.state";
2435
- var HOSTED_WALLET = "https://wallet.cloud.calimero.network/account-enroll";
2436
- var hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
2437
- function executorOf(relay) {
2438
- const value = relay.executorAccount;
2439
- return typeof value === "string" && /^[0-9a-f]{64}$/.test(value) ? value : null;
2440
- }
2441
- function chooseRelay(relays) {
2442
- const reachable = relays.filter(
2443
- (r) => typeof r.relayUrl === "string" && r.relayUrl.length > 0
2444
- );
2445
- const fresh = reachable.find((r) => r.fresh);
2446
- if (fresh) return { relayUrl: fresh.relayUrl, executorAccount: executorOf(fresh), note: null };
2447
- if (reachable.length > 0) {
2448
- return {
2449
- relayUrl: reachable[0].relayUrl,
2450
- executorAccount: executorOf(reachable[0]),
2451
- note: "Connected through a relay whose last heartbeat has lapsed \u2014 it may not answer. It was the only one with an address."
2452
- };
2453
- }
2454
- if (relays.length > 0) {
2455
- return {
2456
- relayUrl: null,
2457
- executorAccount: null,
2458
- 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.`
2459
- };
2460
- }
2461
- return {
2462
- relayUrl: null,
2463
- executorAccount: null,
2464
- 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."
2465
- };
2466
- }
2467
- async function deviceKeys() {
2468
- const had = localStorage.getItem(DEVICE_KEY);
2469
- if (had) {
2470
- const parsed = JSON.parse(had);
2471
- if (parsed.kemSk && parsed.signSk && parsed.signPk && parsed.kemPk) {
2472
- return parsed;
2473
- }
2474
- localStorage.removeItem(DEVICE_KEY);
2475
- }
2476
- const sign = await crypto.subtle.generateKey({ name: "Ed25519" }, true, [
2477
- "sign",
2478
- "verify"
2479
- ]);
2480
- let agree;
2481
- try {
2482
- agree = await crypto.subtle.generateKey({ name: "X25519" }, true, [
2483
- "deriveBits"
2484
- ]);
2485
- } catch {
2486
- throw new Error(
2487
- "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."
2488
- );
2489
- }
2490
- const keys = {
2491
- signPk: hex(await crypto.subtle.exportKey("raw", sign.publicKey)),
2492
- signSk: hex((await crypto.subtle.exportKey("pkcs8", sign.privateKey)).slice(16)),
2493
- kemPk: hex(await crypto.subtle.exportKey("raw", agree.publicKey)),
2494
- kemSk: hex((await crypto.subtle.exportKey("pkcs8", agree.privateKey)).slice(16))
2495
- };
2496
- localStorage.setItem(DEVICE_KEY, JSON.stringify(keys));
2497
- return keys;
2498
- }
2499
- function useAccountEnrolment({
2500
- walletUrl: walletOverride,
2501
- enabled = true
2502
- } = {}) {
2503
- const { connectWithAccount, cloudBaseUrl } = useMero();
2504
- const [note, setNote] = react.useState(null);
2505
- const walletUrl = walletOverride ?? HOSTED_WALLET;
2506
- const callbackRef = react.useRef(void 0);
2507
- const callbackErrorRef = react.useRef(null);
2508
- if (enabled && callbackRef.current === void 0 && typeof window !== "undefined") {
2509
- try {
2510
- callbackRef.current = meroJs.readEnrolmentCallback();
2511
- } catch (e) {
2512
- callbackRef.current = null;
2513
- callbackErrorRef.current = e instanceof Error ? e.message : String(e);
2514
- }
2515
- }
2516
- const returningRef = react.useRef(null);
2517
- if (returningRef.current === null && callbackRef.current !== void 0) {
2518
- returningRef.current = callbackRef.current !== null || callbackErrorRef.current !== null;
2519
- }
2520
- const completingRef = react.useRef(false);
2521
- react.useEffect(() => {
2522
- if (callbackErrorRef.current) {
2523
- setNote(callbackErrorRef.current);
2524
- callbackErrorRef.current = null;
2525
- return;
2526
- }
2527
- const back = callbackRef.current;
2528
- if (!back || completingRef.current) return;
2529
- completingRef.current = true;
2530
- let cancelled = false;
2531
- (async () => {
2532
- try {
2533
- const keys = await deviceKeys();
2534
- const sent = (() => {
2535
- try {
2536
- return sessionStorage.getItem(STATE_KEY);
2537
- } catch {
2538
- return null;
2539
- }
2540
- })();
2541
- try {
2542
- sessionStorage.removeItem(STATE_KEY);
2543
- } catch {
2544
- }
2545
- if (!sent) {
2546
- setNote(
2547
- 'This enrolment could not be verified as one this tab started, so it was not accepted. Start again from "Enrol with your account".'
2548
- );
2549
- return;
2550
- }
2551
- const enrolled = await meroJs.completeDeviceEnrolment({
2552
- ...back,
2553
- devicePublicKey: keys.signPk,
2554
- kemPublicKey: keys.kemPk,
2555
- expectState: sent
2556
- });
2557
- saveDelegatedCredential({
2558
- account: enrolled.account,
2559
- credential: enrolled.credential,
2560
- deviceSecret: keys.signSk
2561
- });
2562
- const cloud = new meroJs.CloudClient({
2563
- cloudBaseUrl,
2564
- routingCredential: {
2565
- credential: enrolled.credential,
2566
- deviceSecret: keys.signSk
2567
- }
2568
- });
2569
- const chosen = chooseRelay(await cloud.getAccountRelays(enrolled.account));
2570
- if (chosen.note) setNote(chosen.note);
2571
- connectWithAccount({
2572
- relayUrl: chosen.relayUrl,
2573
- account: enrolled.account,
2574
- credential: enrolled.credential,
2575
- deviceSecret: keys.signSk,
2576
- ...chosen.executorAccount ? { executorAccount: chosen.executorAccount } : {}
2577
- });
2578
- } catch (e) {
2579
- if (!cancelled) setNote(e instanceof Error ? e.message : String(e));
2580
- }
2581
- })();
2582
- return () => {
2583
- cancelled = true;
2584
- };
2585
- }, [connectWithAccount, cloudBaseUrl]);
2586
- const goToWallet = react.useCallback(async () => {
2587
- let keys;
2588
- try {
2589
- keys = await deviceKeys();
2590
- } catch (e) {
2591
- setNote(e instanceof Error ? e.message : String(e));
2592
- return;
2593
- }
2594
- const state = hex(crypto.getRandomValues(new Uint8Array(16)));
2595
- try {
2596
- sessionStorage.setItem(STATE_KEY, state);
2597
- } catch {
2598
- }
2599
- window.location.assign(
2600
- meroJs.deviceEnrolmentUrl({
2601
- walletUrl,
2602
- devicePublicKey: keys.signPk,
2603
- kemPublicKey: keys.kemPk,
2604
- returnTo: window.location.origin + window.location.pathname,
2605
- state
2606
- })
2607
- );
2608
- }, [walletUrl]);
2609
- return {
2610
- goToWallet,
2611
- note,
2612
- returning: returningRef.current === true,
2613
- walletUrl,
2614
- customWallet: walletOverride !== void 0
2615
- };
2616
- }
2617
2717
  function shortAccount(account) {
2618
2718
  return account.length > 14 ? `${account.slice(0, 6)}\u2026${account.slice(-6)}` : account;
2619
2719
  }
@@ -2792,7 +2892,7 @@ function ConnectButton({
2792
2892
  note: enrolment.note,
2793
2893
  walletUrl: enrolment.walletUrl,
2794
2894
  customWallet: enrolment.customWallet
2795
- } : void 0,
2895
+ } : false,
2796
2896
  initialTab: cloud && enrolment.returning ? "cloud" : "node"
2797
2897
  }
2798
2898
  )
@@ -2952,7 +3052,8 @@ function ConnectButtonAccount({
2952
3052
  connectToNode(url);
2953
3053
  },
2954
3054
  onClose: () => setIsNodeModalOpen(false),
2955
- theme: resolvedTheme ?? theme
3055
+ theme: resolvedTheme ?? theme,
3056
+ cloud: false
2956
3057
  }
2957
3058
  )
2958
3059
  ] });
@@ -5037,6 +5138,7 @@ exports.getContextIdentity = getContextIdentity;
5037
5138
  exports.getNodeUrl = getNodeUrl;
5038
5139
  exports.getTokenNodeUrl = getTokenNodeUrl;
5039
5140
  exports.isFinalInvitationError = isFinalInvitationError;
5141
+ exports.isReturningFromWallet = isReturningFromWallet;
5040
5142
  exports.joinWithNode = joinWithNode;
5041
5143
  exports.listDelegatedContexts = listDelegatedContexts;
5042
5144
  exports.localStorageTokenStorage = localStorageTokenStorage;