@calimero-network/mero-react 9.1.3 → 9.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/index.cjs +1423 -52
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +814 -19
- package/dist/index.d.ts +814 -19
- package/dist/index.js +1405 -54
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["#style-inject:#style-inject","../src/components/styles.css","../src/types.ts","../src/auth/node-trust.ts","../src/auth/token-adoption.ts","../src/storage/index.ts","../src/context/MeroContext.tsx","../src/components/CalimeroLogo.tsx","../src/theme.ts","../src/components/LoginModal.tsx","../src/components/ConnectButton.tsx","../src/utils/base58.ts","../src/hooks/index.ts","../src/components/MigrationPendingBanner.tsx","../src/components/MigrationAdminPanel.tsx"],"names":["AppMode","ConnectionType","refreshToken","createContext","useMemo","LocalStorageTokenStore","useState","useRef","parseAuthCallback","useCallback","MeroJs","buildAuthLoginUrl","useEffect","AuthRevokedError","HTTPError","useContext","jsxs","jsx","DEFAULT_LOCAL_NODE_PORTS","discoverLocalNodes","nodeEndpoint","Fragment","createPortal","compareSemver"],"mappings":";;;;;;;;AACyB,SAAR,YAA6B,GAAA,EAAK,EAAE,QAAA,EAAS,GAAI,EAAC,EAAG;AAC1D,EAAA,IAAY,OAAO,QAAA,KAAa,WAAA,EAAa;AAE7C,EAAA,MAAM,OAAO,QAAA,CAAS,IAAA,IAAQ,SAAS,oBAAA,CAAqB,MAAM,EAAE,CAAC,CAAA;AACrE,EAAA,MAAM,KAAA,GAAQ,QAAA,CAAS,aAAA,CAAc,OAAO,CAAA;AAC5C,EAAA,KAAA,CAAM,IAAA,GAAO,UAAA;AAEb,EAAA,IAAI,aAAa,KAAA,EAAO;AACtB,IAAA,IAAI,KAAK,UAAA,EAAY;AACnB,MAAA,IAAA,CAAK,Y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QAAG,QAAA,EAAA,MAAA,EAAI,CAAA;AAAA,wBAAKA,cAAAA,CAAC,IAAA,EAAA,EAAG,QAAA,EAAA,OAAA,EAAK,CAAA;AAAA,wBAAKA,cAAAA,CAAC,IAAA,EAAA,EAAG,QAAA,EAAA,QAAA,EAAM,CAAA;AAAA,wBAAKA,cAAAA,CAAC,IAAA,EAAA,EAAG,QAAA,EAAA,SAAA,EAAO,CAAA;AAAA,wBAAKA,cAAAA,CAAC,IAAA,EAAA,EAAG,QAAA,EAAA,QAAA,EAAM;AAAA,OAAA,EAAK,CAAA,EAC/E,CAAA;AAAA,sBACAA,cAAAA,CAAC,OAAA,EAAA,EACE,QAAA,EAAA,OAAA,CAAQ,GAAA,CAAI,CAAC,CAAA,qBACZD,eAAAA,CAAC,IAAA,EAAA,EAAgB,aAAA,EAAY,sBAAA,EAC3B,QAAA,EAAA;AAAA,wBAAAC,cAAAA,CAAC,IAAA,EAAA,EAAI,QAAA,EAAA,CAAA,CAAE,IAAA,EAAK,CAAA;AAAA,wBACZA,cAAAA,CAAC,IAAA,EAAA,EAAI,QAAA,EAAA,CAAA,CAAE,KAAA,EAAM,CAAA;AAAA,wBACbA,cAAAA,CAAC,IAAA,EAAA,EAAI,QAAA,EAAA,CAAA,CAAE,MAAA,EAAQ,iBAAiB,QAAA,EAAI,CAAA;AAAA,wBACpCA,cAAAA,CAAC,IAAA,EAAA,EAAI,QAAA,EAAA,CAAA,CAAE,MAAA,EAAQ,qBAAqB,QAAA,EAAI,CAAA;AAAA,wBACxCA,cAAAA,CAAC,IAAA,EAAA,EAAI,QAAA,EAAA,CAAA,CAAE,MAAA,EAAQ,mBAAmB,QAAA,EAAI;AAAA,OAAA,EAAA,EAL/B,CAAA,CAAE,IAMX,CACD,CAAA,EACH;AAAA,KAAA,EACF;AAAA,GAAA,EACF,CAAA;AAEJ","file":"index.cjs","sourcesContent":["\n export default function styleInject(css, { insertAt } = {}) {\n if (!css || typeof document === 'undefined') return\n \n const head = document.head || document.getElementsByTagName('head')[0]\n const style = document.createElement('style')\n style.type = 'text/css'\n \n if (insertAt === 'top') {\n if (head.firstChild) {\n head.insertBefore(style, head.firstChild)\n } else {\n head.appendChild(style)\n }\n } else {\n head.appendChild(style)\n }\n \n if (style.styleSheet) {\n style.styleSheet.cssText = css\n } else {\n style.appendChild(document.createTextNode(css))\n }\n }\n ","import styleInject from '#style-inject';styleInject(\":root {\\n --mero-bg: #0d1117;\\n --mero-bg-secondary: #161b22;\\n --mero-bg-tertiary: #1c2128;\\n --mero-text: #e6edf3;\\n --mero-text-secondary: #8b949e;\\n --mero-accent: #a5ff11;\\n --mero-accent-hover: #8ed40d;\\n --mero-on-primary: #0d1117;\\n --mero-error: #ff6b6b;\\n --mero-border: #30363d;\\n --mero-disabled: #555555;\\n --mero-shadow: rgba(0, 0, 0, 0.5);\\n --mero-overlay: rgba(0, 0, 0, 0.75);\\n --mero-radius: 8px;\\n}\\n.mero-connect-button {\\n display: inline-flex;\\n align-items: center;\\n justify-content: center;\\n gap: 8px;\\n padding: 10px 20px;\\n background-color: var(--mero-accent);\\n border: 1px solid var(--mero-accent);\\n border-radius: var(--mero-radius);\\n cursor: pointer;\\n font-size: 14px;\\n font-weight: 600;\\n letter-spacing: 0.01em;\\n color: var(--mero-on-primary);\\n transition:\\n background-color 0.15s ease,\\n border-color 0.15s ease,\\n box-shadow 0.15s ease,\\n transform 0.1s ease;\\n min-width: 140px;\\n box-sizing: border-box;\\n font-family:\\n \\\"Inter\\\",\\n -apple-system,\\n BlinkMacSystemFont,\\n \\\"Segoe UI\\\",\\n Roboto,\\n Oxygen,\\n Ubuntu,\\n sans-serif;\\n -webkit-font-smoothing: antialiased;\\n -moz-osx-font-smoothing: grayscale;\\n line-height: 1;\\n}\\n.mero-connect-button:hover:not(.mero-connected):not(.mero-reconnecting) {\\n background-color: var(--mero-accent-hover);\\n border-color: var(--mero-accent-hover);\\n box-shadow: 0 0 0 4px rgba(165, 255, 17, 0.18);\\n box-shadow: 0 0 0 4px color-mix(in srgb, var(--mero-accent) 18%, transparent);\\n}\\n.mero-connect-button:active:not(.mero-connected):not(.mero-reconnecting) {\\n transform: translateY(1px);\\n}\\n.mero-connect-button:focus-visible {\\n outline: none;\\n box-shadow: 0 0 0 3px rgba(165, 255, 17, 0.45);\\n box-shadow: 0 0 0 3px color-mix(in srgb, var(--mero-accent) 45%, transparent);\\n}\\n.mero-connect-button.mero-logo-only {\\n min-width: 0;\\n width: 40px;\\n height: 40px;\\n padding: 0;\\n gap: 0;\\n}\\n.mero-connect-button.mero-connected {\\n background-color: var(--mero-accent);\\n color: var(--mero-on-primary);\\n border-color: var(--mero-accent);\\n}\\n.mero-connect-button.mero-connected:hover {\\n background-color: var(--mero-accent-hover);\\n border-color: var(--mero-accent-hover);\\n}\\n.mero-connect-button.mero-reconnecting {\\n background-color: var(--mero-bg-secondary);\\n color: var(--mero-text-secondary);\\n border-color: var(--mero-border);\\n cursor: not-allowed;\\n}\\n.mero-connect-container {\\n position: relative;\\n display: inline-block;\\n}\\n.mero-dropdown {\\n position: absolute;\\n top: 100%;\\n left: 0;\\n background-color: var(--mero-bg-secondary);\\n border: 1px solid var(--mero-border);\\n border-radius: var(--mero-radius);\\n margin-top: 6px;\\n padding: 0;\\n z-index: 1001;\\n width: 100%;\\n min-width: 180px;\\n overflow: hidden;\\n box-shadow: 0 8px 24px var(--mero-shadow);\\n}\\n.mero-dropdown-info {\\n padding: 10px 16px;\\n color: var(--mero-text-secondary);\\n font-size: 13px;\\n border-bottom: 1px solid var(--mero-border);\\n white-space: nowrap;\\n overflow: hidden;\\n text-overflow: ellipsis;\\n max-width: 220px;\\n}\\n.mero-dropdown-item {\\n display: block;\\n width: 100%;\\n padding: 10px 16px;\\n background: none;\\n border: none;\\n color: var(--mero-text);\\n text-align: left;\\n cursor: pointer;\\n font-size: 14px;\\n text-decoration: none;\\n font-family: inherit;\\n}\\n.mero-dropdown-item:hover {\\n background-color: var(--mero-accent);\\n color: var(--mero-on-primary);\\n}\\n.mero-logo {\\n width: 24px;\\n height: 24px;\\n color: currentColor;\\n}\\n@keyframes meroFadeIn {\\n from {\\n opacity: 0;\\n }\\n to {\\n opacity: 1;\\n }\\n}\\n@keyframes meroSlideIn {\\n from {\\n transform: translateY(-12px);\\n opacity: 0;\\n }\\n to {\\n transform: translateY(0);\\n opacity: 1;\\n }\\n}\\n@keyframes meroSpin {\\n to {\\n transform: rotate(360deg);\\n }\\n}\\n\")","/**\n * Types for mero-react\n */\n\nimport type { MeroJs, TokenStore } from '@calimero-network/mero-js';\n\n/**\n * Application mode determines the permission scope\n */\nexport enum AppMode {\n /**\n * @deprecated since 2.1.0 — SingleContext is no longer supported and will\n * be removed in 3.0.0. Auth-frontend no longer drives\n * context/namespace/group selection; the auth callback returns only\n * `access_token`, `refresh_token`, `application_id`, and `node_url`.\n * Switch to {@link AppMode.MultiContext} and have your app manage\n * context selection itself.\n *\n * Migration: see `example/app/src/pages/context/SelectContext.tsx` for a\n * reference implementation. It uses `useContexts` /\n * `useNamespacesForApplication` for listing, then calls\n * `mero.admin.createNamespace` / `createGroupInNamespace` /\n * `createContext` directly (rather than the `useCreate*` hooks) so the\n * underlying server error surfaces to the user instead of being\n * swallowed by `useAsyncMutation`.\n */\n SingleContext = 'single-context',\n /** Multi-context: user can manage multiple contexts */\n MultiContext = 'multi-context',\n /** Admin: full administrative access */\n Admin = 'admin',\n}\n\n/**\n * Connection type for the login modal\n */\nexport enum ConnectionType {\n /**\n * @deprecated The login modal no longer has Local/Remote tabs — it always\n * shows node discovery + manual URL entry. Behaves the same as `Remote`.\n */\n RemoteAndLocal = 'remote-and-local',\n /** Open the login modal (node discovery + manual URL entry) */\n Remote = 'remote',\n /**\n * @deprecated The hardcoded default-local-node view was removed. Behaves\n * the same as `Remote`.\n */\n Local = 'local',\n /** Custom URL (skip modal) */\n Custom = 'custom',\n}\n\n/**\n * Custom connection configuration\n */\nexport interface CustomConnectionConfig {\n type: ConnectionType.Custom;\n url: string;\n}\n\n/**\n * Context for an application\n */\nexport interface AppContext {\n contextId: string;\n executorId: string;\n applicationId: string;\n}\n\n/**\n * Result of an RPC execution\n */\nexport interface ExecutionResult<T = unknown> {\n success: boolean;\n result?: T;\n error?: string;\n}\n\nexport interface ApplicationContextRecord {\n contextId: string;\n applicationId: string;\n}\n\nexport interface ContextDiscoveryOptions {\n applicationId: string;\n knownContextIds?: string[];\n targetAlias?: string;\n pollIntervalMs?: number;\n timeoutMs?: number;\n}\n\nexport interface ContextDiscoveryState {\n context: ApplicationContextRecord | null;\n loading: boolean;\n error: Error | null;\n discover: () => Promise<ApplicationContextRecord | null>;\n reset: () => void;\n}\n\n/**\n * Mero context value exposed by useMero hook\n */\nexport interface MeroContextValue {\n /** The MeroJs instance (null if not connected) */\n mero: MeroJs | null;\n /** Whether the user is authenticated */\n isAuthenticated: boolean;\n /** Whether the connection is online */\n isOnline: boolean;\n /** The current node URL */\n nodeUrl: string | null;\n /** The application ID */\n applicationId: string | null;\n /** The context ID (from auth flow) */\n contextId: string | null;\n /** The context identity / executor public key (from auth flow) */\n contextIdentity: string | null;\n /** Connect to a node URL and start auth flow */\n connectToNode: (url: string) => void;\n /** Logout and clear tokens */\n logout: () => void;\n /** Loading state */\n isLoading: boolean;\n}\n\n/**\n * MeroProvider configuration\n */\nexport interface MeroProviderConfig {\n /** Application mode */\n mode: AppMode;\n /** Package name (for registry-based apps) */\n packageName?: string;\n /** Package version (optional, defaults to latest) */\n packageVersion?: string;\n /** Registry URL (optional) */\n registryUrl?: string;\n /** Request timeout in milliseconds */\n timeoutMs?: number;\n /**\n * Origins the OAuth callback is allowed to authenticate against. Defends\n * against a malicious `node_url` in the callback URL (token exfiltration):\n * the node login was initiated with is always trusted, and this allowlist\n * additionally permits direct-callback entry to known nodes. When neither is\n * available (no initiated node and no allowlist) a callback node_url is\n * rejected and a security error is logged.\n */\n allowedNodeUrls?: string[];\n /**\n * Token store for access/refresh tokens. Defaults to a localStorage-backed\n * store that persists across reloads.\n *\n * SECURITY: localStorage tokens — including the refresh token — are readable\n * by any script on the page, so an XSS bug can exfiltrate them. For sensitive\n * deployments pass a `MemoryTokenStore` (session-only) or a store backed by an\n * HttpOnly cookie set by your auth service.\n */\n tokenStore?: TokenStore;\n}\n","/**\n * Trust decision for the node URL an OAuth callback wants us to authenticate\n * against.\n *\n * The auth flow redirects the browser to a node's auth UI and back to the app\n * with `access_token` / `refresh_token` / `node_url` in the callback URL. That\n * URL is attacker-influenceable, so a malicious `node_url` would otherwise make\n * the SDK send the freshly-minted tokens to an attacker's node (exfiltration).\n *\n * Defense: only authenticate against a node we can independently trust — the\n * node login was *initiated* with (saved before the redirect), or an\n * app-configured allowlist.\n */\n\n/** True iff both URLs parse and share the same origin (scheme + host + port). */\nexport function sameOrigin(a: string, b: string): boolean {\n try {\n return new URL(a).origin === new URL(b).origin;\n } catch {\n return false;\n }\n}\n\nexport interface ResolveTrustedNodeParams {\n /** `node_url` from the OAuth callback (untrusted, attacker-influenceable). */\n candidate: string | null | undefined;\n /** Node URL login was initiated with, saved before the redirect (trusted). */\n initiated: string | null;\n /** Additional trusted origins, for direct-callback entry without an initiated node. */\n allowedNodeUrls?: string[];\n}\n\nexport interface TrustedNodeResult {\n /** The node URL that is safe to authenticate against, or null. */\n url: string | null;\n /** A candidate node_url was present but could not be trusted (likely an attack). */\n rejected: boolean;\n}\n\n/**\n * Decide which node URL, if any, is safe to authenticate against.\n *\n * - No candidate → fall back to the initiated node.\n * - Candidate + initiated node → must share the initiated node's origin, else reject.\n * - Candidate + no initiated node + allowlist → must be in the allowlist, else reject.\n * - Candidate + no trust anchor (no initiated node and no allowlist) → reject. There is\n * nothing to validate the attacker-influenceable callback against, so refusing is the\n * safe default. The normal flow always records the initiated node (via `connectToNode`)\n * before redirecting; configure `allowedNodeUrls` to permit direct-callback entry.\n */\nexport function resolveTrustedNodeUrl(params: ResolveTrustedNodeParams): TrustedNodeResult {\n const { candidate, initiated, allowedNodeUrls } = params;\n\n if (!candidate) {\n return { url: initiated ?? null, rejected: false };\n }\n\n if (initiated) {\n return sameOrigin(candidate, initiated)\n ? { url: candidate, rejected: false }\n : { url: null, rejected: true };\n }\n\n if (allowedNodeUrls && allowedNodeUrls.length > 0) {\n return allowedNodeUrls.some((u) => sameOrigin(candidate, u))\n ? { url: candidate, rejected: false }\n : { url: null, rejected: true };\n }\n\n return { url: null, rejected: true };\n}\n","/**\n * Decide whether the token bundle carried in an SSO callback hash may replace\n * the bundle already in the token store.\n *\n * Since core 0.11.0 (calimero-network/core#3083) refresh tokens are SINGLE-USE:\n * every `POST /auth/refresh` consumes the presented refresh token and returns a\n * new one. Re-presenting a consumed refresh token is treated as theft — the node\n * answers 401 `x-auth-error: token_reuse` and revokes the whole token family, so\n * *every* holder is hard-logged-out.\n *\n * That makes an unconditional `tokenStore.setTokens(callbackBundle)` on the SSO\n * callback path actively dangerous. A desktop host (or any SSO initiator) hands\n * the app a token bundle in the URL hash; if mero-js has already rotated the\n * stored refresh token, writing the hash bundle over it resurrects a *consumed*\n * refresh token. The next refresh presents it → `token_reuse` → family revoked.\n *\n * So the hash bundle is adopted only when it is safe:\n * - there is no stored bundle (a genuinely fresh login), or\n * - the node changed (the stored bundle belongs to a different node), or\n * - the hash tokens are genuinely NEWER than what is stored, or\n * - the stored bundle is missing a refresh token that the hash can supply.\n *\n * Anything else — a stale hash, or a hash replaying the access token we already\n * hold — is ignored, leaving the live (possibly rotated) bundle untouched.\n */\n\nimport type { TokenData } from '@calimero-network/mero-js';\nimport { sameOrigin } from './node-trust';\n\nconst HOUR_MS = 3_600_000;\n\ninterface JwtClaims {\n /** Issued-at (seconds). The authoritative rotation-order signal when present. */\n iat?: number;\n /** Expiry (seconds). */\n exp?: number;\n}\n\n/**\n * Decode a JWT's payload claims without verifying the signature.\n *\n * Verification is the node's job — we only need the ordering claims to decide\n * which of two bundles is newer, and both bundles are already node-trusted by\n * the time we get here (see `resolveTrustedNodeUrl`).\n *\n * Returns null for anything that is not a decodable three-part JWT (opaque\n * tokens, test fixtures, garbage).\n */\nexport function decodeJwtClaims(token: string): JwtClaims | null {\n try {\n const parts = token.split('.');\n if (parts.length !== 3) return null;\n let b64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');\n while (b64.length % 4) b64 += '=';\n const payload: unknown = JSON.parse(atob(b64));\n if (!payload || typeof payload !== 'object') return null;\n const { iat, exp } = payload as JwtClaims;\n return {\n iat: typeof iat === 'number' && iat > 0 ? iat : undefined,\n exp: typeof exp === 'number' && exp > 0 ? exp : undefined,\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Absolute expiry (ms) of an access token, from its `exp` claim.\n *\n * Mirrors mero-js's internal `expiresAtFromJwt` (which it does not export —\n * checked against mero-js 6.1.0), including the \"assume one hour\" fallback for\n * tokens whose expiry we cannot read.\n */\nexport function expiresAtFromJwt(token: string, fallbackMs: number = Date.now() + HOUR_MS): number {\n const exp = decodeJwtClaims(token)?.exp;\n return exp ? exp * 1000 : fallbackMs;\n}\n\n/**\n * Is the callback's access token newer than the one we already hold?\n *\n * Prefers `iat` (issued-at) — the direct rotation-order signal — and falls back\n * to `exp`, then to the stored bundle's recorded `expires_at`. When the answer\n * cannot be established the token is NOT considered newer: refusing to adopt\n * costs a redundant login at worst, whereas adopting a stale bundle burns the\n * whole token family.\n */\nfunction isCallbackNewer(callbackAccessToken: string, stored: TokenData): boolean {\n const incoming = decodeJwtClaims(callbackAccessToken);\n if (!incoming) return false;\n\n const current = decodeJwtClaims(stored.access_token);\n if (current) {\n if (incoming.iat !== undefined && current.iat !== undefined && incoming.iat !== current.iat) {\n return incoming.iat > current.iat;\n }\n if (incoming.exp !== undefined && current.exp !== undefined && incoming.exp !== current.exp) {\n return incoming.exp > current.exp;\n }\n // Same claims (a replay of the token we already hold), or nothing to compare\n // on — either way the callback brings nothing new.\n return false;\n }\n\n // Stored access token is not a decodable JWT — compare against the expiry the\n // store recorded for it.\n return incoming.exp !== undefined && incoming.exp * 1000 > stored.expires_at;\n}\n\n/** Why the SSO hash bundle was (or was not) written to the token store. */\nexport type TokenAdoptionReason =\n /** No stored bundle — a genuinely fresh login. Seed from the hash. */\n | 'fresh-login'\n /** The stored bundle belongs to a different node. Re-seed from the hash. */\n | 'node-changed'\n /** The hash tokens are genuinely newer than the stored ones. */\n | 'newer'\n /** Same session, but the stored bundle has no refresh token and the hash does. */\n | 'fill-refresh'\n /** The hash tokens are stale, or replay the access token we already hold. */\n | 'stale';\n\nexport type TokenAdoptionDecision =\n | { adopt: true; tokens: TokenData; reason: Exclude<TokenAdoptionReason, 'stale'> }\n | { adopt: false; reason: 'stale' };\n\nexport interface ResolveTokenAdoptionParams {\n /** Access token from the callback hash. Always present (mero-js returns null otherwise). */\n callbackAccessToken: string;\n /**\n * Refresh token from the callback hash. `parseAuthCallback` yields `''` when the\n * hash carries no `refresh_token` — hosts are moving to access-only bundles\n * precisely so they cannot hand back a rotated-away refresh token.\n */\n callbackRefreshToken: string;\n /** Trusted node URL the callback resolved to (see `resolveTrustedNodeUrl`). */\n callbackNodeUrl: string;\n /** Bundle currently in the token store — mero-js may have rotated it already. */\n stored: TokenData | null;\n /** Node URL the stored bundle was issued by, i.e. the node URL before this callback. */\n storedNodeUrl: string | null;\n}\n\n/**\n * Decide what (if anything) to write to the token store for an SSO callback.\n *\n * Never returns a bundle with an empty `refresh_token` when a refresh token for\n * the same node is already stored: an access-only hash bundle is MERGED over the\n * stored one, so adopting a fresher access token cannot strip the session's\n * ability to refresh.\n */\nexport function resolveTokenAdoption(params: ResolveTokenAdoptionParams): TokenAdoptionDecision {\n const { callbackAccessToken, callbackRefreshToken, callbackNodeUrl, stored, storedNodeUrl } =\n params;\n\n const bundle = (refreshToken: string): TokenData => ({\n access_token: callbackAccessToken,\n refresh_token: refreshToken,\n expires_at: expiresAtFromJwt(callbackAccessToken),\n });\n\n // Fresh login — nothing to protect.\n if (!stored?.access_token) {\n return { adopt: true, tokens: bundle(callbackRefreshToken), reason: 'fresh-login' };\n }\n\n // Different node — the stored bundle is for someone else's token family, and\n // its refresh token is meaningless here, so it must NOT be carried over.\n const sameNode = !!storedNodeUrl && sameOrigin(callbackNodeUrl, storedNodeUrl);\n if (!sameNode) {\n return { adopt: true, tokens: bundle(callbackRefreshToken), reason: 'node-changed' };\n }\n\n // Same node, live bundle. Keep the stored refresh token unless the hash carries\n // one — the hash's refresh token may be a copy that mero-js has already rotated\n // away, but an *empty* one would strip refresh from the session entirely.\n const refreshToken = callbackRefreshToken || stored.refresh_token;\n\n if (isCallbackNewer(callbackAccessToken, stored)) {\n return { adopt: true, tokens: bundle(refreshToken), reason: 'newer' };\n }\n\n // The access token is not newer, but the stored bundle cannot refresh and the\n // hash can repair that. Keep the *stored* access token (it is at least as new).\n if (!stored.refresh_token && callbackRefreshToken) {\n return {\n adopt: true,\n tokens: { ...stored, refresh_token: callbackRefreshToken },\n reason: 'fill-refresh',\n };\n }\n\n // Stale (or a replay of the bundle we already hold). Writing it would resurrect\n // a consumed refresh token → `token_reuse` → the node revokes the whole family.\n return { adopt: false, reason: 'stale' };\n}\n","/**\n * Storage utilities for mero-react\n * \n * Provides localStorage-based token storage and other persistence utilities.\n */\n\nimport type { TokenData } from '@calimero-network/mero-js';\n\n// Storage keys\nconst STORAGE_KEYS = {\n ACCESS_TOKEN: 'mero:access_token',\n REFRESH_TOKEN: 'mero:refresh_token',\n EXPIRES_AT: 'mero:expires_at',\n NODE_URL: 'mero:node_url',\n // The node the token bundle currently in the TokenStore was issued by. Distinct\n // from NODE_URL, which `connectToNode` overwrites with the *target* node before\n // redirecting to login — so at callback time NODE_URL names where we are going,\n // not who minted the tokens we still hold. Telling those apart is what lets the\n // SSO callback re-seed on a node change without mistaking a different node's\n // bundle for a rotated one (see auth/token-adoption.ts).\n TOKEN_NODE_URL: 'mero:token_node_url',\n APPLICATION_ID: 'mero:application_id',\n CONTEXT_ID: 'mero:context_id',\n CONTEXT_IDENTITY: 'mero:context_identity',\n} as const;\n\nlet _storageAvailable: boolean | null = null;\n\nfunction isLocalStorageAvailable(): boolean {\n if (_storageAvailable !== null) return _storageAvailable;\n try {\n if (typeof window === 'undefined' || !window.localStorage) {\n _storageAvailable = false;\n return false;\n }\n const testKey = '__mero_test__';\n localStorage.setItem(testKey, 'test');\n localStorage.removeItem(testKey);\n _storageAvailable = true;\n } catch {\n _storageAvailable = false;\n }\n return _storageAvailable;\n}\n\nexport const localStorageTokenStorage = {\n async get(): Promise<TokenData | null> {\n if (!isLocalStorageAvailable()) {\n return null;\n }\n\n try {\n const accessToken = localStorage.getItem(STORAGE_KEYS.ACCESS_TOKEN);\n const refreshToken = localStorage.getItem(STORAGE_KEYS.REFRESH_TOKEN);\n const expiresAt = localStorage.getItem(STORAGE_KEYS.EXPIRES_AT);\n\n if (!accessToken || !refreshToken) {\n return null;\n }\n\n return {\n access_token: accessToken,\n refresh_token: refreshToken,\n expires_at: expiresAt ? parseInt(expiresAt, 10) : Date.now() + 3600000,\n };\n } catch (e) {\n console.error('[mero-react] Failed to get token from storage:', e);\n return null;\n }\n },\n\n async set(token: TokenData): Promise<void> {\n if (!isLocalStorageAvailable()) {\n return;\n }\n\n try {\n localStorage.setItem(STORAGE_KEYS.ACCESS_TOKEN, token.access_token);\n localStorage.setItem(STORAGE_KEYS.REFRESH_TOKEN, token.refresh_token);\n localStorage.setItem(STORAGE_KEYS.EXPIRES_AT, token.expires_at.toString());\n } catch (e) {\n console.error('[mero-react] Failed to save token to storage:', e);\n }\n },\n\n async clear(): Promise<void> {\n if (!isLocalStorageAvailable()) {\n return;\n }\n\n try {\n localStorage.removeItem(STORAGE_KEYS.ACCESS_TOKEN);\n localStorage.removeItem(STORAGE_KEYS.REFRESH_TOKEN);\n localStorage.removeItem(STORAGE_KEYS.EXPIRES_AT);\n } catch (e) {\n console.error('[mero-react] Failed to clear token from storage:', e);\n }\n },\n};\n\n/**\n * Get the stored node URL\n */\nexport function getNodeUrl(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.NODE_URL);\n}\n\n/**\n * Set the node URL\n */\nexport function setNodeUrl(url: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.NODE_URL, url);\n}\n\n/**\n * Clear the node URL\n */\nexport function clearNodeUrl(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.NODE_URL);\n}\n\n/**\n * Get the node URL that minted the token bundle currently in the TokenStore.\n */\nexport function getTokenNodeUrl(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.TOKEN_NODE_URL);\n}\n\n/**\n * Record the node URL that minted the token bundle now in the TokenStore.\n */\nexport function setTokenNodeUrl(url: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.TOKEN_NODE_URL, url);\n}\n\n/**\n * Clear the token bundle's node URL\n */\nexport function clearTokenNodeUrl(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.TOKEN_NODE_URL);\n}\n\n/**\n * Get the stored application ID\n */\nexport function getApplicationId(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.APPLICATION_ID);\n}\n\n/**\n * Set the application ID\n */\nexport function setApplicationId(id: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.APPLICATION_ID, id);\n}\n\n/**\n * Clear the application ID\n */\nexport function clearApplicationId(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.APPLICATION_ID);\n}\n\n/**\n * Get the stored context ID\n */\nexport function getContextId(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.CONTEXT_ID);\n}\n\n/**\n * Set the context ID\n */\nexport function setContextId(id: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.CONTEXT_ID, id);\n}\n\n/**\n * Clear the context ID\n */\nexport function clearContextId(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.CONTEXT_ID);\n}\n\n/**\n * Get the stored context identity\n */\nexport function getContextIdentity(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.CONTEXT_IDENTITY);\n}\n\n/**\n * Set the context identity\n */\nexport function setContextIdentity(id: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.CONTEXT_IDENTITY, id);\n}\n\n/**\n * Clear the context identity\n */\nexport function clearContextIdentity(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.CONTEXT_IDENTITY);\n}\n\n/**\n * Clear all mero-react storage\n */\nexport function clearAllStorage(): void {\n if (!isLocalStorageAvailable()) return;\n Object.values(STORAGE_KEYS).forEach((key) => {\n localStorage.removeItem(key);\n });\n}\n","import React, {\n createContext,\n useContext,\n useState,\n useEffect,\n useCallback,\n useRef,\n useMemo,\n} from 'react';\nimport {\n MeroJs,\n LocalStorageTokenStore,\n parseAuthCallback,\n buildAuthLoginUrl,\n AuthRevokedError,\n HTTPError,\n} from '@calimero-network/mero-js';\nimport { AppMode } from '../types';\nimport type { AuthCallbackResult, TokenStore } from '@calimero-network/mero-js';\nimport { resolveTrustedNodeUrl } from '../auth/node-trust';\nimport { resolveTokenAdoption } from '../auth/token-adoption';\nimport {\n getNodeUrl,\n setNodeUrl,\n getTokenNodeUrl,\n setTokenNodeUrl,\n getApplicationId,\n setApplicationId,\n getContextId,\n setContextId,\n getContextIdentity,\n setContextIdentity,\n clearAllStorage,\n} from '../storage';\nimport type { MeroContextValue, MeroProviderConfig } from '../types';\n\nconst MeroContext = createContext<MeroContextValue | null>(null);\n\nconst isBrowser = typeof window !== 'undefined';\n\n/**\n * Permission grants requested for the client token at login.\n *\n * Cores since 0.11.0-rc.9 default-deny admin-api routes the token holds no\n * scope for; cores >=0.11.0-rc.11 map the governance/blob/alias routes to the\n * client-grantable `namespace` / `group` / `blob` / `context:alias`\n * permissions, so app tokens must request them here or every workspace,\n * group, blob and context-alias call 403s.\n *\n * `context:list` is included even in single-context mode because every app\n * calls GET /admin-api/contexts/:id/identities-owned right after login, which\n * maps to a `context:list` requirement.\n *\n * `context:subscribe` is what `/sse`, `/sse/subscription` and `/ws` require\n * (core's `PermissionValidator`, `validator.rs`, maps all three to\n * `Context(Subscribe(Global))`). Without it every event stream an app opens is\n * refused `403` + `X-Auth-Error: permission_denied`, so the app renders, reads\n * and writes, and simply never receives a live update. Only `AppMode.Admin`\n * escaped, because `admin` covers every route.\n *\n * MEASURED against merod 0.11.0-rc.41 (build 88e323b): a client key minted with\n * the MultiContext list below minus `context:subscribe` gets `403` on\n * `GET /sse`; the same list with it gets `200`.\n *\n * Exported for tests.\n */\nexport function getPermissionsForMode(mode: AppMode): string[] {\n switch (mode) {\n case AppMode.SingleContext:\n return [\n 'context:execute',\n 'context:list',\n 'context:subscribe',\n 'application:list',\n 'blob',\n 'context:alias',\n ];\n case AppMode.MultiContext:\n return [\n 'context:create',\n 'context:list',\n 'context:execute',\n 'context:subscribe',\n 'application:list',\n 'namespace',\n 'group',\n 'blob',\n 'context:alias',\n ];\n case AppMode.Admin:\n return ['admin'];\n default:\n throw new Error(`Unsupported application mode: ${mode}`);\n }\n}\n\nexport interface MeroProviderProps extends MeroProviderConfig {\n children: React.ReactNode;\n}\n\nexport function MeroProvider({\n children,\n mode,\n packageName,\n packageVersion,\n registryUrl,\n timeoutMs = 30000,\n allowedNodeUrls,\n tokenStore: tokenStoreProp,\n}: MeroProviderProps) {\n const tokenStore = useMemo<TokenStore>(\n () => tokenStoreProp ?? new LocalStorageTokenStore(),\n [tokenStoreProp],\n );\n const [mero, setMero] = useState<MeroJs | null>(null);\n const [isAuthenticated, setIsAuthenticated] = useState(false);\n const [isOnline, setIsOnline] = useState(true);\n const [isLoading, setIsLoading] = useState(true);\n const [nodeUrl, setNodeUrlState] = useState<string | null>(() => getNodeUrl());\n const [applicationId, setApplicationIdState] = useState<string | null>(\n () => getApplicationId() || null,\n );\n const [contextId, setContextIdState] = useState<string | null>(() => getContextId());\n const [contextIdentity, setContextIdentityState] = useState<string | null>(() => getContextIdentity());\n\n const meroRef = useRef<MeroJs | null>(null);\n // Guards the SSE 401 recovery below, so a burst of reconnect failures can't\n // stack concurrent validate/refresh attempts over one single-use refresh token.\n const recoveringRef = useRef(false);\n\n // Parse auth callback ONCE in a ref (StrictMode-safe: refs persist across unmount/remount)\n const callbackRef = useRef<AuthCallbackResult | null | undefined>(undefined);\n if (callbackRef.current === undefined && isBrowser) {\n callbackRef.current = parseAuthCallback(window.location.href);\n }\n\n const createMeroInstance = useCallback(\n (url: string): MeroJs => {\n if (meroRef.current) {\n meroRef.current.close();\n }\n const instance = new MeroJs({\n baseUrl: url,\n tokenStore,\n timeoutMs,\n });\n meroRef.current = instance;\n return instance;\n },\n [timeoutMs, tokenStore],\n );\n\n const checkAuth = useCallback(\n async (instance: MeroJs): Promise<boolean> => {\n // Validate the session via /auth/validate (signature, revocation, node\n // binding — no permission requirement) instead of probing\n // GET /admin-api/contexts. Since core 0.11.0-rc.9 the node enforces\n // token permission scopes, and /admin-api/contexts requires Global\n // `context:list` — which single-context tokens (execute-only) and\n // app-scoped tokens don't hold, so probing it 403'd valid sessions and\n // bounced every app straight back to the login page.\n const accessToken = tokenStore.getTokens()?.access_token;\n if (!accessToken) return false;\n\n const validate = async (token: string): Promise<boolean> => {\n try {\n const { valid } = await instance.auth.validateToken(token);\n return valid;\n } catch {\n return false;\n }\n };\n\n if (await validate(accessToken)) return true;\n\n // An expired access token does NOT mean the session is over: refresh\n // tokens last 30 days against core's 1-hour access TTL, so on any reload\n // more than an hour after login we land here holding a perfectly good\n // refresh token.\n //\n // `validateToken` has in fact already spent it. It pins the token under\n // test into an explicit `Authorization` header, and mero-js's init\n // headers override the transport's own token (mero-js\n // http-client/web-client.js `buildHeaders`). So the 401 + `x-auth-error:\n // token_expired` trips the transport's refresh hook — rotating the stored\n // bundle — and then the retry re-sends the SAME stale header, 401s again,\n // and reports `valid: false`. The session was silently renewed and thrown\n // away, and the app bounced to login; a second reload would then \"fix\"\n // itself, which is exactly how this reads as a random logout.\n //\n // So: re-read the store, and if the transport rotated it underneath us,\n // judge the session on the token we ACTUALLY hold now. We never call\n // /auth/refresh ourselves — doing so would race mero-js's single-flight\n // lock over a single-use refresh token and get the whole family revoked\n // (calimero-network/core#3083).\n const rotated = tokenStore.getTokens()?.access_token;\n if (!rotated || rotated === accessToken) return false;\n return validate(rotated);\n },\n [tokenStore],\n );\n\n const connectToNode = useCallback(\n (url: string) => {\n if (!isBrowser) return;\n setNodeUrl(url);\n setNodeUrlState(url);\n\n const callbackUrl = new URL(window.location.href);\n callbackUrl.hash = '';\n\n const loginUrl = buildAuthLoginUrl(url, {\n callbackUrl: callbackUrl.toString(),\n permissions: getPermissionsForMode(mode),\n mode,\n packageName,\n packageVersion,\n registryUrl,\n });\n\n window.location.href = loginUrl;\n },\n [mode, packageName, packageVersion, registryUrl],\n );\n\n const logout = useCallback(() => {\n if (meroRef.current) {\n meroRef.current.clearToken();\n meroRef.current.close();\n }\n // Always clear the token store, even when not connected (meroRef is null) —\n // otherwise the access/refresh tokens persist in storage after logout.\n tokenStore.clear();\n clearAllStorage();\n setMero(null);\n setIsAuthenticated(false);\n setNodeUrlState(null);\n setApplicationIdState(null);\n setContextIdState(null);\n setContextIdentityState(null);\n meroRef.current = null;\n }, [tokenStore]);\n\n // Initialization effect\n useEffect(() => {\n let active = true;\n\n const init = async () => {\n const callback = callbackRef.current;\n let nodeFromCallback: string | null = null;\n\n if (callback) {\n // Read BEFORE the callback overwrites either of them.\n // - initiatedNodeUrl: the node login was initiated with — the trust anchor.\n // - tokenNodeUrl: the node that minted the bundle currently in the store.\n // They differ exactly when the user is switching nodes: `connectToNode`\n // points NODE_URL at the *target* node before redirecting, while the store\n // still holds the *previous* node's bundle. Falling back to the initiated\n // node keeps sessions that predate TOKEN_NODE_URL working.\n const initiatedNodeUrl = getNodeUrl();\n const tokenNodeUrl = getTokenNodeUrl() ?? initiatedNodeUrl;\n\n // The callback URL is attacker-influenceable, so validate its node_url\n // BEFORE storing tokens or connecting — otherwise a malicious node_url\n // would receive the freshly-minted tokens (exfiltration).\n const { url, rejected } = resolveTrustedNodeUrl({\n candidate: callback.nodeUrl,\n initiated: initiatedNodeUrl,\n allowedNodeUrls,\n });\n\n // Always strip the callback params (tokens + node_url) from the address\n // bar and consume the parsed callback, whatever the trust outcome.\n if (isBrowser) {\n window.history.replaceState({}, '', window.location.pathname + window.location.search);\n }\n callbackRef.current = null;\n\n if (rejected) {\n // Untrusted node_url — likely a token-exfiltration attempt. Drop the\n // callback's tokens, but DON'T return: fall through to restore any\n // existing session from storage so a tampered callback can't log a\n // legitimately authenticated user out.\n console.error(\n '[MeroProvider] OAuth callback node_url is not trusted (it does not match the node ' +\n 'login was initiated with, nor `allowedNodeUrls`). Ignoring the callback; no tokens stored.',\n );\n } else if (url) {\n // Trusted node → the callback's tokens MAY be persisted. Whether they\n // SHOULD be is a separate question: refresh tokens are single-use since\n // core 0.11.0 (calimero-network/core#3083), so blindly writing the hash\n // bundle over a bundle mero-js has already rotated resurrects a consumed\n // refresh token — the node reads that as theft (`x-auth-error:\n // token_reuse`) and revokes the entire token family, hard-logging out\n // every holder. Adopt only a fresh, newer, or different-node bundle, and\n // merge rather than replace so an access-only hash (hosts are dropping\n // `refresh_token` from the hash) can never strip a live refresh token.\n const decision = resolveTokenAdoption({\n callbackAccessToken: callback.accessToken,\n callbackRefreshToken: callback.refreshToken,\n callbackNodeUrl: url,\n stored: tokenStore.getTokens(),\n storedNodeUrl: tokenNodeUrl,\n });\n\n if (decision.adopt) {\n tokenStore.setTokens(decision.tokens);\n setTokenNodeUrl(url);\n } else {\n console.warn(\n '[MeroProvider] Ignoring the SSO callback token bundle: it is stale (not newer than ' +\n 'the tokens already stored for this node). Adopting it would replay an already-rotated ' +\n 'refresh token, which the node revokes the whole token family for.',\n );\n }\n\n if (callback.applicationId) {\n setApplicationId(callback.applicationId);\n if (active) setApplicationIdState(callback.applicationId);\n }\n if (callback.contextId) {\n setContextId(callback.contextId);\n if (active) setContextIdState(callback.contextId);\n }\n if (callback.contextIdentity) {\n setContextIdentity(callback.contextIdentity);\n if (active) setContextIdentityState(callback.contextIdentity);\n }\n\n setNodeUrl(url);\n if (active) setNodeUrlState(url);\n nodeFromCallback = url;\n }\n // url === null && !rejected → callback had no node to bind to; ignore it.\n }\n\n const savedUrl = nodeFromCallback || getNodeUrl();\n if (!savedUrl) {\n if (active) setIsLoading(false);\n return;\n }\n\n const instance = createMeroInstance(savedUrl);\n const authed = await checkAuth(instance);\n\n if (!active) return;\n\n if (authed) {\n setMero(instance);\n setIsAuthenticated(true);\n setIsOnline(true);\n } else if (nodeFromCallback) {\n setMero(instance);\n }\n\n setIsLoading(false);\n };\n\n init().catch((err) => {\n console.error('[MeroProvider] Initialization failed:', err);\n if (active) setIsLoading(false);\n });\n\n return () => {\n active = false;\n };\n }, [createMeroInstance, checkAuth, allowedNodeUrls, tokenStore]);\n\n // SSE connection for online/offline detection — no polling.\n useEffect(() => {\n if (!isAuthenticated || !meroRef.current) return;\n\n let active = true;\n const sse = meroRef.current.events;\n\n const onConnect = () => { if (active) setIsOnline(true); };\n const onError = (err: Error) => {\n if (!active) return;\n setIsOnline(false);\n\n // ── Which stream failures are worth acting on ──────────────────────────\n //\n // This used to be `if (!err.message.includes('401')) return;`, and the\n // comment under it explained that mero-js threw a bare\n // `SSE connection failed: <status>`, so nothing better was available.\n // That stopped being true in mero-js 19.14.1 (#166): the SSE path now\n // throws the same typed errors the request path does, carrying the\n // status and the `x-auth-error` header.\n //\n // Matching on '401' was not merely coarse, it was aimed at the wrong\n // number. Core answers a dead or under-scoped token on `/sse` with\n // **403**, not 401 — `token_expired` is the only 401 a stream sees. So\n // every failure that actually needed acting on was the one this gate\n // dropped, and the app sat at `isOnline = false` with no way back and no\n // prompt to log in again.\n //\n // Three cases now, because they need three different answers.\n\n // 1. The token family is gone (403 `token_revoked`, or a 401\n // `token_reuse`). mero-js has already STOPPED reconnecting — every\n // retry re-sends the same dead credential — so nothing will reopen\n // this stream, and there is no refresh token left to spend either.\n if (err instanceof AuthRevokedError) {\n logout();\n return;\n }\n\n if (err instanceof HTTPError && err.status === 403) {\n // 2. The token is live but was minted without `context:subscribe`.\n // Core requires that grant for `/sse`, `/sse/subscription` and\n // `/ws`, and the grant set is baked in at MINT time — so a refresh\n // re-issues the same unusable token and the stream 403s again,\n // forever. mero-react 9.1.2 (#73) fixed what we ASK for; a client\n // key minted before it can only be replaced by a fresh login.\n // `checkAuth` would return true here and reconnect us into that\n // loop, which is why this case must not go through it.\n if (err.headers?.get('x-auth-error') === 'permission_denied') {\n console.warn(\n '[MeroProvider] This session cannot open an event stream ' +\n '(403 permission_denied): its token predates the context:subscribe ' +\n 'grant. Logging out — a fresh login mints a key that can subscribe.',\n );\n logout();\n return;\n }\n // 3. Any other 403 is core refusing this caller for a reason a new\n // token would not change — \"Forbidden: not the session owner\". Not\n // an auth-token problem, so do not spend the session on it.\n return;\n }\n\n // A 401 is NOT proof the session is over, and it used to be treated as\n // such: `logout()` wipes the token store, so an expired access token cost\n // the user their still-valid 30-day refresh token and forced a real\n // re-login.\n //\n // The stream authenticates only at connect time (an open stream survives\n // expiry), so this fires on the first reconnect after the access token\n // ages out — a sleep/wake, a network blip, a PWA resume, a node restart.\n // Routine events, all of them. Ask `checkAuth`, which recovers a\n // merely-expired token via the transport's refresh and returns false only\n // when the session is genuinely dead.\n //\n // The string check stays as a fallback: not every caller is on 19.14.1,\n // and an older mero-js still reports this as `SSE connection failed: 401`.\n const status = err instanceof HTTPError ? err.status : null;\n if (status !== 401 && !err.message.includes('401')) return;\n\n if (recoveringRef.current) return;\n recoveringRef.current = true;\n void (async () => {\n try {\n const instance = meroRef.current;\n if (!instance) return;\n if (await checkAuth(instance)) {\n // Renewed. mero-js's `onTokenRefresh` hook has already updated the\n // instance's in-memory token, so the SseClient's `getAuthToken`\n // hands the reconnect the new one.\n if (active) await instance.events.connect().catch(() => {});\n return;\n }\n if (active) logout();\n } finally {\n recoveringRef.current = false;\n }\n })();\n };\n\n sse.on('connect', onConnect);\n sse.on('error', onError);\n sse.connect().catch(() => { if (active) setIsOnline(false); });\n\n return () => {\n active = false;\n sse.off('connect', onConnect);\n sse.off('error', onError);\n };\n // `checkAuth` and `logout` are both useCallback-stable (they close over the\n // memoized `tokenStore`), so listing them does not re-subscribe the stream.\n }, [isAuthenticated, mero, checkAuth, logout]);\n\n const contextValue = useMemo<MeroContextValue>(\n () => ({\n mero,\n isAuthenticated,\n isOnline,\n nodeUrl,\n applicationId,\n contextId,\n contextIdentity,\n connectToNode,\n logout,\n isLoading,\n }),\n [mero, isAuthenticated, isOnline, nodeUrl, applicationId, contextId, contextIdentity, connectToNode, logout, isLoading],\n );\n\n return (\n <MeroContext.Provider value={contextValue}>\n {children}\n </MeroContext.Provider>\n );\n}\n\nexport function useMero(): MeroContextValue {\n const context = useContext(MeroContext);\n if (!context) {\n throw new Error('useMero must be used within a MeroProvider');\n }\n return context;\n}\n\nexport { MeroContext };\n","/**\n * CalimeroLogo - the official Calimero emblem.\n *\n * Uses `currentColor` for fills so the consumer can theme it with `color`,\n * a `style.color` override, or by passing `color` directly.\n */\n\nimport React from 'react';\n\nexport interface CalimeroLogoProps extends React.SVGAttributes<SVGSVGElement> {\n /** Width / height shorthand (applied to both). Default: 24. */\n size?: number | string;\n}\n\nexport function CalimeroLogo({\n size = 24,\n color,\n style,\n ...rest\n}: CalimeroLogoProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 193 193\"\n fill={color ?? 'currentColor'}\n style={style}\n xmlns=\"http://www.w3.org/2000/svg\"\n aria-hidden=\"true\"\n {...rest}\n >\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M13.5969 23.2235C63.4924 -4.81833 123.53 2.55678 148.374 10.0273C153.006 11.4201 155.606 16.2198 154.181 20.7478C152.757 25.2758 147.846 27.8173 143.214 26.4245C120.866 19.7045 66.3988 13.3369 22.3442 38.0961C21.3748 38.6409 20.8298 39.6384 20.8808 40.6778C22.5544 74.7376 40.6646 139.735 103.059 173.709C107.293 176.015 108.813 181.238 106.455 185.377C104.096 189.516 98.7523 191.002 94.5186 188.696C24.7767 150.721 5.18199 78.7606 3.35124 41.5008C2.98177 33.9812 6.96683 26.9496 13.5969 23.2235Z\"\n />\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M180.214 22.5271C185.054 22.2785 189.183 25.9121 189.437 30.6429C192.776 92.7591 159.782 138.316 138.517 157.587C133.185 162.419 125.221 164.303 117.934 161.241C102.817 154.887 88.1835 141.52 76.3001 128.189C64.2403 114.66 54.1712 100.2 48.3006 90.492C45.8345 86.4139 47.2173 81.1537 51.3891 78.743C55.561 76.3323 60.9421 77.684 63.4082 81.7621C68.803 90.6832 78.2588 104.272 89.5315 116.919C100.981 129.763 113.488 140.698 124.866 145.48C125.179 145.612 125.851 145.671 126.586 145.006C145.206 128.132 174.903 87.1988 171.912 31.5431C171.657 26.8122 175.374 22.7756 180.214 22.5271Z\"\n />\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M85.9137 55.4487C70.263 57.0264 57.2007 60.7039 50.4014 63.4262C45.9168 65.2218 40.7922 63.1236 38.9553 58.7397C37.1184 54.3559 39.2649 49.3464 43.7495 47.5508C52.2083 44.164 66.9167 40.1173 84.1135 38.3837C101.323 36.649 121.62 37.1693 140.947 43.4423C149.244 46.1351 155.088 53.9217 154.482 62.8728C153.225 81.429 144.514 100.403 127.158 122.145C124.177 125.88 118.663 126.546 114.842 123.631C111.021 120.717 110.341 115.327 113.322 111.592C129.481 91.3484 136.032 75.6017 136.971 61.7394C137.02 61.0029 136.547 60.0904 135.417 59.7238C119.18 54.4537 101.552 53.8722 85.9137 55.4487Z\"\n />\n </svg>\n );\n}\n\nexport default CalimeroLogo;\n","/**\n * Theme tokens for mero-react components.\n *\n * Defaults match the green palette used across Calimero apps (admin-dashboard,\n * tauri-app, app-registry). Pass a partial `MeroTheme` to `ConnectButton` or\n * `LoginModal` to override any token.\n */\n\nimport type { CSSProperties } from 'react';\n\nexport interface MeroTheme {\n /** Primary accent / CTA color */\n primary?: string;\n /** Primary accent on hover */\n primaryHover?: string;\n /** Text color rendered on top of `primary` (e.g. inside the Connect button when connected) */\n primaryText?: string;\n /** Main surface color (modal background, button background) */\n background?: string;\n /** Secondary surface color (input fields, info chips) */\n backgroundSecondary?: string;\n /** Tertiary surface color (subtle elevation) */\n backgroundTertiary?: string;\n /** Border color */\n border?: string;\n /** Primary text color */\n text?: string;\n /** Muted / secondary text color */\n textSecondary?: string;\n /** Error / danger color */\n error?: string;\n /** Modal backdrop color */\n overlay?: string;\n /** Border radius (any CSS length) */\n radius?: string;\n}\n\nexport type ResolvedMeroTheme = Required<MeroTheme>;\n\nexport const defaultMeroTheme: Readonly<ResolvedMeroTheme> = Object.freeze({\n primary: '#a5ff11',\n primaryHover: '#8ed40d',\n primaryText: '#0d1117',\n background: '#0d1117',\n backgroundSecondary: '#161b22',\n backgroundTertiary: '#1c2128',\n border: '#30363d',\n text: '#e6edf3',\n textSecondary: '#8b949e',\n error: '#ff6b6b',\n overlay: 'rgba(0, 0, 0, 0.75)',\n radius: '8px',\n});\n\n/**\n * Merge a partial theme with the defaults.\n *\n * Filtering rules — values that fall back to the default:\n * - `undefined` (the prop key wasn't set, or was set to `undefined`)\n * - empty string `''`\n * - whitespace-only strings (e.g. `' '`)\n *\n * These are dropped because they're invalid CSS and would produce\n * invisible elements (transparent backgrounds, missing borders, etc.).\n * If you genuinely want the browser default for a token, omit the key\n * from the theme prop rather than passing an empty string.\n *\n * Any other non-empty string is forwarded as-is — CSS syntax itself\n * is NOT validated.\n */\nexport function resolveMeroTheme(theme?: MeroTheme): ResolvedMeroTheme {\n if (!theme) return { ...defaultMeroTheme };\n const filtered = Object.fromEntries(\n Object.entries(theme).filter(\n ([, v]) => v !== undefined && typeof v === 'string' && v.trim() !== '',\n ),\n ) as Partial<MeroTheme>;\n return { ...defaultMeroTheme, ...filtered };\n}\n\n/**\n * Single source of truth mapping each `MeroTheme` token name to the CSS\n * custom-property name it surfaces as. Used by `themeToCssVars` to emit the\n * inline-style map and by component code (e.g. `LoginModal`) to read the\n * variable in inline styles via `var(--mero-*, fallback)`.\n *\n * Adding a new token? Add it here, in `MeroTheme`, and in `defaultMeroTheme`,\n * and the rest of the system picks it up automatically.\n */\nexport const MERO_CSS_VARS: Record<keyof MeroTheme, string> = {\n background: '--mero-bg',\n backgroundSecondary: '--mero-bg-secondary',\n backgroundTertiary: '--mero-bg-tertiary',\n text: '--mero-text',\n textSecondary: '--mero-text-secondary',\n primary: '--mero-accent',\n primaryHover: '--mero-accent-hover',\n primaryText: '--mero-on-primary',\n border: '--mero-border',\n error: '--mero-error',\n overlay: '--mero-overlay',\n radius: '--mero-radius',\n};\n\n/**\n * Build a `style` object that exposes a resolved theme as CSS variables, so\n * descendant CSS rules (e.g. those in `styles.css`) pick up the overrides.\n */\nexport function themeToCssVars(theme: ResolvedMeroTheme): CSSProperties {\n const vars: Record<string, string> = {};\n for (const key of Object.keys(MERO_CSS_VARS) as Array<keyof MeroTheme>) {\n vars[MERO_CSS_VARS[key]] = theme[key];\n }\n return vars as CSSProperties;\n}\n\n/**\n * Returns a `var(--mero-*, fallback)` reference for a theme token, suitable\n * for inline styles in portal-rendered components where descendant CSS\n * variables also need to support global `:root` overrides.\n */\nexport function cssVar(theme: ResolvedMeroTheme, key: keyof MeroTheme): string {\n return `var(${MERO_CSS_VARS[key]}, ${theme[key]})`;\n}\n","/**\n * LoginModal - Modal for connecting to a Calimero node\n *\n * A single section: the modal auto-discovers nodes on the well-known local\n * ports (see `nodeDiscovery`) and offers whatever is running as radio choices,\n * plus an always-available \"enter URL manually\" option. With nothing found it\n * falls straight through to manual URL entry.\n *\n * The old Local/Remote tabs are gone — the \"Local\" tab pointed at a hardcoded\n * default node (`node1.127.0.0.1.nip.io`) that doesn't resolve in most setups;\n * discovery + manual entry covers both cases properly.\n */\n\nimport { useMemo, useState, useEffect, useCallback, useRef } from 'react';\nimport { createPortal } from 'react-dom';\nimport { CalimeroLogo } from './CalimeroLogo';\nimport type { ConnectionType, CustomConnectionConfig } from '../types';\nimport {\n discoverLocalNodes,\n nodeEndpoint,\n DEFAULT_LOCAL_NODE_PORTS,\n} from '@calimero-network/mero-js';\nimport {\n cssVar,\n resolveMeroTheme,\n themeToCssVars,\n type MeroTheme,\n type ResolvedMeroTheme,\n} from '../theme';\n\n/** Sentinel selection value for the manual \"enter a URL\" option. */\nconst CUSTOM_SELECTION = '__custom__';\n\nexport interface LoginModalProps {\n /** Callback when user connects */\n onConnect: (url: string) => void;\n /** Callback when modal is closed */\n onClose: () => void;\n /**\n * @deprecated Ignored. The modal always shows node discovery + manual URL\n * entry; the old hardcoded-default \"Local\" view was removed. Kept so\n * existing call sites keep compiling.\n */\n connectionType?: ConnectionType | CustomConnectionConfig;\n /** Whether the modal is open */\n isOpen: boolean;\n /** Theme overrides — accepts any subset of `MeroTheme` tokens */\n theme?: MeroTheme;\n /**\n * Ports probed when discovering local nodes. Defaults to the well-known\n * Calimero dev ports (2428, 2429, 2528, 2529). Mostly an escape hatch for\n * non-standard setups and tests.\n */\n localNodePorts?: readonly number[];\n}\n\n/**\n * Validate URL format\n */\nfunction isValidUrl(urlString: string): boolean {\n if (!urlString || urlString.trim() === '') {\n return false;\n }\n\n try {\n const urlToTest =\n urlString.startsWith('http://') || urlString.startsWith('https://')\n ? urlString\n : `https://${urlString}`;\n\n const url = new URL(urlToTest);\n\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n return false;\n }\n\n if (!url.hostname) {\n return false;\n }\n\n const hostname = url.hostname;\n\n // Allow localhost\n if (hostname === 'localhost') {\n return true;\n }\n\n // Check for valid IP address\n const ipv4Regex = /^(\\d{1,3}\\.){3}\\d{1,3}$/;\n if (ipv4Regex.test(hostname)) {\n const octets = hostname.split('.').map(Number);\n return octets.every((octet) => octet >= 0 && octet <= 255);\n }\n\n // Check for valid domain name\n const domainRegex =\n /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n return domainRegex.test(hostname);\n } catch {\n return false;\n }\n}\n\n/** Strip the scheme for a compact node label (e.g. `localhost:2428`). */\nfunction displayNodeUrl(url: string): string {\n return url.replace(/^https?:\\/\\//, '').replace(/\\/+$/, '');\n}\n\n/**\n * Mix a color with transparent using CSS `color-mix`. Works for any valid CSS\n * color value (hex of any length, rgb(), hsl(), named colors, var(...)) — not\n * just 6-digit hex.\n */\nfunction tint(color: string, percent: number): string {\n return `color-mix(in srgb, ${color} ${percent}%, transparent)`;\n}\n\n/**\n * Build the inline-style map from a resolved theme. Each value is emitted as\n * `var(--mero-*, fallback)` so a global `:root { --mero-* }` rule reaches the\n * portal-rendered modal; the fallback ensures the modal still renders correctly\n * if the consumer hasn't imported `styles.css`.\n */\nfunction buildStyles(t: ResolvedMeroTheme) {\n const bg = cssVar(t, 'background');\n const bgSecondary = cssVar(t, 'backgroundSecondary');\n const text = cssVar(t, 'text');\n const textSecondary = cssVar(t, 'textSecondary');\n const accent = cssVar(t, 'primary');\n const onPrimary = cssVar(t, 'primaryText');\n const border = cssVar(t, 'border');\n const error = cssVar(t, 'error');\n const overlay = cssVar(t, 'overlay');\n const radius = cssVar(t, 'radius');\n\n const errorBg = tint(error, 10);\n const errorBorder = tint(error, 30);\n const accentGlow = tint(accent, 15);\n\n return {\n overlay: {\n position: 'fixed' as const,\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n backgroundColor: overlay,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n zIndex: 10000,\n padding: '1rem',\n animation: 'meroFadeIn 0.2s ease-out',\n },\n content: {\n backgroundColor: bg,\n borderRadius: radius,\n padding: '2rem',\n maxWidth: '420px',\n width: '100%',\n position: 'relative' as const,\n border: `1px solid ${border}`,\n boxShadow: `0 25px 50px -12px rgba(0, 0, 0, 0.6), 0 0 0 1px ${accentGlow}`,\n animation: 'meroSlideIn 0.25s ease-out',\n color: text,\n },\n closeButton: {\n position: 'absolute' as const,\n top: '0.75rem',\n right: '0.75rem',\n background: 'none',\n border: 'none',\n fontSize: '1.5rem',\n color: textSecondary,\n cursor: 'pointer',\n padding: '0.25rem',\n lineHeight: 1,\n },\n header: {\n display: 'flex',\n flexDirection: 'column' as const,\n alignItems: 'center',\n gap: '0.75rem',\n marginBottom: '1.5rem',\n },\n title: {\n fontSize: '1.25rem',\n fontWeight: 600,\n color: text,\n margin: 0,\n },\n info: {\n color: textSecondary,\n textAlign: 'center' as const,\n marginBottom: '1.5rem',\n fontSize: '0.875rem',\n },\n error: {\n color: error,\n backgroundColor: errorBg,\n border: `1px solid ${errorBorder}`,\n borderRadius: radius,\n padding: '0.75rem',\n marginBottom: '1rem',\n fontSize: '0.875rem',\n textAlign: 'center' as const,\n },\n radioList: {\n display: 'flex',\n flexDirection: 'column' as const,\n gap: '0.5rem',\n marginBottom: '1rem',\n },\n radioItem: {\n display: 'flex',\n alignItems: 'center',\n gap: '0.625rem',\n color: text,\n cursor: 'pointer',\n padding: '0.75rem 1rem',\n borderRadius: radius,\n border: `1px solid ${border}`,\n backgroundColor: bgSecondary,\n transition: 'all 0.15s ease',\n fontSize: '0.875rem',\n },\n radioItemActive: {\n // Override the full `border` shorthand (not just borderColor) so React\n // never has to mix shorthand + longhand on the same element.\n border: `1px solid ${accent}`,\n backgroundColor: accentGlow,\n color: text,\n },\n radioIndicator: {\n flexShrink: 0,\n width: '1rem',\n height: '1rem',\n borderRadius: '50%',\n border: `2px solid ${border}`,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n },\n radioIndicatorActive: {\n border: `2px solid ${accent}`,\n },\n radioDot: {\n width: '0.5rem',\n height: '0.5rem',\n borderRadius: '50%',\n backgroundColor: accent,\n },\n nodeMeta: {\n marginLeft: 'auto',\n fontSize: '0.75rem',\n color: textSecondary,\n },\n input: {\n width: '100%',\n padding: '0.75rem 1rem',\n borderRadius: radius,\n border: `1px solid ${border}`,\n backgroundColor: bgSecondary,\n color: text,\n fontSize: '0.875rem',\n outline: 'none',\n marginBottom: '1rem',\n boxSizing: 'border-box' as const,\n },\n toolbar: {\n display: 'flex',\n justifyContent: 'center',\n marginBottom: '1rem',\n },\n rescan: {\n background: 'none',\n border: 'none',\n color: accent,\n cursor: 'pointer',\n fontSize: '0.8125rem',\n padding: '0.25rem 0.5rem',\n },\n buttonGroup: {\n display: 'flex',\n justifyContent: 'center',\n },\n button: {\n padding: '0.75rem 2rem',\n borderRadius: radius,\n border: 'none',\n fontSize: '0.875rem',\n fontWeight: 600,\n cursor: 'pointer',\n backgroundColor: accent,\n color: onPrimary,\n transition: 'all 0.15s ease',\n },\n buttonDisabled: {\n opacity: 0.5,\n cursor: 'not-allowed',\n },\n loading: {\n display: 'flex',\n flexDirection: 'column' as const,\n alignItems: 'center',\n gap: '1rem',\n padding: '2rem',\n color: textSecondary,\n },\n discovering: {\n display: 'flex',\n flexDirection: 'column' as const,\n alignItems: 'center',\n gap: '0.75rem',\n padding: '1rem',\n color: textSecondary,\n fontSize: '0.875rem',\n },\n spinner: {\n width: '2rem',\n height: '2rem',\n border: `3px solid ${border}`,\n borderTopColor: accent,\n borderRadius: '50%',\n animation: 'meroSpin 1s linear infinite',\n },\n spinnerSmall: {\n width: '1.5rem',\n height: '1.5rem',\n border: `3px solid ${border}`,\n borderTopColor: accent,\n borderRadius: '50%',\n animation: 'meroSpin 1s linear infinite',\n },\n };\n}\n\n/**\n * LoginModal - Connection modal component\n */\nexport function LoginModal({\n onConnect,\n onClose,\n isOpen,\n theme,\n localNodePorts = DEFAULT_LOCAL_NODE_PORTS,\n}: LoginModalProps) {\n // `selected` is a discovered node URL or CUSTOM.\n const [selected, setSelected] = useState<string>(CUSTOM_SELECTION);\n const [discovered, setDiscovered] = useState<string[]>([]);\n const [discovering, setDiscovering] = useState<boolean>(false);\n const [customUrl, setCustomUrl] = useState<string>('');\n\n const [loading, setLoading] = useState<boolean>(false);\n const [error, setError] = useState<string | null>(null);\n\n const resolved = useMemo(() => resolveMeroTheme(theme), [theme]);\n const styles = useMemo(() => buildStyles(resolved), [resolved]);\n // Only emit inline `--mero-*` variables when a `theme` prop was actually\n // provided. Without a prop, we let global `:root { --mero-* }` rules cascade\n // through to the portal-rendered modal (with `var()` fallbacks in buildStyles\n // covering the case where no global rules are loaded).\n const themeVars = useMemo(\n () => (theme ? themeToCssVars(resolved) : undefined),\n [theme, resolved],\n );\n\n // Load saved URL into the manual field\n useEffect(() => {\n const savedUrl = localStorage.getItem('mero:node_url');\n if (savedUrl) {\n setCustomUrl(savedUrl);\n }\n }, []);\n\n // Probe local ports whenever the modal is open; a bumpable nonce lets the\n // user trigger a re-scan.\n const [scanNonce, setScanNonce] = useState(0);\n const portsKey = useMemo(() => localNodePorts.join(','), [localNodePorts]);\n\n useEffect(() => {\n if (!isOpen) {\n return;\n }\n\n const controller = new AbortController();\n let active = true;\n setDiscovering(true);\n // Clear any prior results so a re-scan never shows stale nodes.\n setDiscovered([]);\n setError(null);\n\n discoverLocalNodes({ ports: localNodePorts, signal: controller.signal })\n .then((nodes) => {\n if (!active) return;\n setDiscovered(nodes);\n // Default to the first discovered node, else fall through to manual.\n setSelected(nodes.length > 0 ? nodes[0] : CUSTOM_SELECTION);\n })\n // discoverLocalNodes is designed never to reject; the catch is purely\n // defensive so a future change can't surface an unhandled rejection.\n .catch(() => {\n if (active) setSelected(CUSTOM_SELECTION);\n })\n .finally(() => {\n if (active) setDiscovering(false);\n });\n\n return () => {\n active = false;\n controller.abort();\n };\n // portsKey captures localNodePorts content; scanNonce forces a re-scan.\n }, [isOpen, portsKey, scanNonce]);\n\n const isCustom = selected === CUSTOM_SELECTION;\n const hasDiscovered = discovered.length > 0;\n\n // Whether the connect button can fire in the current state.\n const canConnect =\n !loading && !discovering && (isCustom ? isValidUrl(customUrl) : true);\n\n // Keep a ref so the input's keydown handler always sees current validity.\n const canConnectRef = useRef(canConnect);\n canConnectRef.current = canConnect;\n\n const handleConnect = useCallback(async () => {\n const usingDiscovered = selected !== CUSTOM_SELECTION;\n const targetUrl = usingDiscovered ? selected : customUrl;\n\n // Manual URLs must look valid before we try them.\n if (!usingDiscovered && !isValidUrl(targetUrl)) {\n return;\n }\n\n const normalizedUrl = targetUrl.replace(/\\/+$/, '');\n\n // A discovered node already answered a health check — connect straight away.\n if (usingDiscovered) {\n onConnect(normalizedUrl);\n return;\n }\n\n // Manually entered URLs are verified via is-authed.\n setLoading(true);\n setError(null);\n\n try {\n const response = await fetch(\n nodeEndpoint(normalizedUrl, 'admin-api/is-authed'),\n );\n\n if (response.ok || response.status === 401) {\n setLoading(false);\n onConnect(normalizedUrl);\n } else {\n throw new Error(`Connection failed: ${response.statusText}`);\n }\n } catch (err) {\n console.error('Connection failed:', err);\n setError('Failed to connect. Please check the URL and try again.');\n setLoading(false);\n }\n }, [selected, customUrl, onConnect]);\n\n if (!isOpen) {\n return null;\n }\n\n const showManualInput = isCustom;\n const renderRadio = (value: string, label: string, meta?: string) => {\n const active = selected === value;\n return (\n // Selection is driven solely by the radio input's `onChange` — clicking\n // anywhere on the wrapping label forwards to the input, and keyboard\n // users can tab to / arrow through the (visually hidden but focusable)\n // input. A label `onClick` here would double-fire `setSelected`.\n <label\n key={value}\n data-testid={`node-option-${value === CUSTOM_SELECTION ? 'custom' : displayNodeUrl(value)}`}\n style={{\n ...styles.radioItem,\n ...(active ? styles.radioItemActive : {}),\n }}\n >\n <input\n type=\"radio\"\n name=\"mero-node\"\n value={value}\n checked={active}\n onChange={() => setSelected(value)}\n style={{ position: 'absolute', opacity: 0 }}\n />\n <span\n style={{\n ...styles.radioIndicator,\n ...(active ? styles.radioIndicatorActive : {}),\n }}\n >\n {active && <span style={styles.radioDot} />}\n </span>\n {label}\n {meta && <span style={styles.nodeMeta}>{meta}</span>}\n </label>\n );\n };\n\n const renderNodeSection = () => {\n if (discovering) {\n return (\n <div style={styles.discovering} data-testid=\"node-discovering\">\n <div style={styles.spinnerSmall} />\n <p>Searching for local nodes...</p>\n </div>\n );\n }\n\n return (\n <>\n <p style={styles.info}>\n {hasDiscovered\n ? 'Select your Calimero node to continue.'\n : 'No local node found. Enter a node URL to continue.'}\n </p>\n\n {hasDiscovered && (\n <div\n style={styles.radioList}\n role=\"radiogroup\"\n aria-label=\"Available nodes\"\n >\n {discovered.map((url) =>\n renderRadio(url, displayNodeUrl(url), 'local'),\n )}\n {/* Manual entry is always offered alongside discovered nodes. */}\n {renderRadio(CUSTOM_SELECTION, 'Enter node URL manually')}\n </div>\n )}\n\n {showManualInput && (\n <input\n type=\"text\"\n value={customUrl}\n onChange={(e) => setCustomUrl(e.target.value)}\n placeholder=\"https://your-node-url.calimero.network\"\n style={styles.input}\n data-testid=\"node-url-input\"\n autoFocus={!hasDiscovered}\n onKeyDown={(e) => {\n if (e.key === 'Enter' && canConnectRef.current) {\n handleConnect();\n }\n }}\n />\n )}\n\n <div style={styles.toolbar}>\n <button\n type=\"button\"\n style={styles.rescan}\n onClick={() => setScanNonce((n) => n + 1)}\n data-testid=\"rescan-button\"\n >\n ↻ Rescan local nodes\n </button>\n </div>\n </>\n );\n };\n\n const modalContent = (\n <>\n <style>{`\n @keyframes meroSpin { to { transform: rotate(360deg); } }\n @keyframes meroFadeIn { from { opacity: 0; } to { opacity: 1; } }\n @keyframes meroSlideIn { from { transform: translateY(-12px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }\n `}</style>\n <div style={{ ...themeVars, ...styles.overlay }} onClick={onClose}>\n <div style={styles.content} onClick={(e) => e.stopPropagation()}>\n <button style={styles.closeButton} onClick={onClose} aria-label=\"Close\">\n ×\n </button>\n\n <div style={styles.header}>\n <CalimeroLogo size={44} color={cssVar(resolved, 'primary')} />\n <h1 style={styles.title}>Connect to Calimero</h1>\n </div>\n\n {loading ? (\n <div style={styles.loading}>\n <p>Connecting to node...</p>\n <div style={styles.spinner} />\n </div>\n ) : (\n <>\n {error && <p style={styles.error}>{error}</p>}\n\n {renderNodeSection()}\n\n <div style={styles.buttonGroup}>\n <button\n onClick={handleConnect}\n disabled={!canConnect}\n style={{\n ...styles.button,\n ...(!canConnect ? styles.buttonDisabled : {}),\n }}\n data-testid=\"connect-button\"\n >\n Connect\n </button>\n </div>\n </>\n )}\n </div>\n </div>\n </>\n );\n\n return createPortal(modalContent, document.body);\n}\n\nexport default LoginModal;\n","/**\n * ConnectButton - A button component for connecting to Calimero\n *\n * Shows connection status and provides login/logout functionality.\n * Includes built-in LoginModal for node selection.\n */\n\nimport React, { useState, useEffect, useRef, useMemo } from 'react';\nimport { useMero } from '../context';\nimport { LoginModal } from './LoginModal';\nimport { CalimeroLogo } from './CalimeroLogo';\nimport type { ConnectionType, CustomConnectionConfig } from '../types';\nimport { ConnectionType as ConnectionTypeEnum } from '../types';\nimport { resolveMeroTheme, themeToCssVars, type MeroTheme } from '../theme';\n\nexport interface ConnectButtonProps {\n /**\n * Connection behaviour. `Custom` (object form) connects straight to the\n * given URL, skipping the modal; every other value opens the LoginModal,\n * which always shows node discovery + manual URL entry.\n */\n connectionType?: ConnectionType | CustomConnectionConfig;\n /** Custom class name */\n className?: string;\n /** Custom styles */\n style?: React.CSSProperties;\n /** Theme overrides — accepts any subset of `MeroTheme` tokens */\n theme?: MeroTheme;\n /**\n * Render only the Calimero logo, no text. Produces a square 40×40 icon\n * button. The label is still announced to screen readers via `aria-label`.\n * Default: false.\n */\n logoOnly?: boolean;\n /**\n * Override the default labels per state. A bare string is shorthand for\n * `{ connect: '<string>' }`. The connected and reconnecting states keep\n * their defaults unless explicitly overridden.\n */\n label?:\n | string\n | { connect?: string; connected?: string; reconnecting?: string };\n}\n\n/**\n * ConnectButton - Displays connection status and handles login/logout\n */\nexport function ConnectButton({\n connectionType = ConnectionTypeEnum.Remote,\n className,\n style,\n theme,\n logoOnly = false,\n label,\n}: ConnectButtonProps) {\n const { isAuthenticated, connectToNode, logout, nodeUrl, isOnline } = useMero();\n const [isDropdownOpen, setIsDropdownOpen] = useState(false);\n const [isModalOpen, setIsModalOpen] = useState(false);\n const dropdownRef = useRef<HTMLDivElement>(null);\n\n // Resolve once. Inline CSS variables are only emitted when a theme prop is\n // provided — otherwise we leave the cascade alone so global `:root { --mero-* }`\n // overrides take effect.\n const resolvedTheme = useMemo(\n () => (theme ? resolveMeroTheme(theme) : null),\n [theme],\n );\n const themeVars = useMemo(\n () => (resolvedTheme ? themeToCssVars(resolvedTheme) : undefined),\n [resolvedTheme],\n );\n\n // Close dropdown when clicking outside\n useEffect(() => {\n const handleClickOutside = (event: MouseEvent) => {\n if (\n dropdownRef.current &&\n !dropdownRef.current.contains(event.target as Node)\n ) {\n setIsDropdownOpen(false);\n }\n };\n document.addEventListener('mousedown', handleClickOutside);\n return () => document.removeEventListener('mousedown', handleClickOutside);\n }, []);\n\n const dashboardUrl = useMemo(() => {\n if (!isAuthenticated || !nodeUrl) return '#';\n return new URL('admin-dashboard/', nodeUrl).toString();\n }, [isAuthenticated, nodeUrl]);\n\n const labels = useMemo(() => {\n const overrides = typeof label === 'string' ? { connect: label } : label;\n return {\n connect: overrides?.connect ?? 'Connect',\n connected: overrides?.connected ?? 'Connected',\n reconnecting: overrides?.reconnecting ?? 'Reconnecting...',\n };\n }, [label]);\n\n const buttonClassName = logoOnly ? 'mero-logo-only' : '';\n\n const handleConnect = () => {\n // If Custom type with URL, connect directly\n if (\n typeof connectionType === 'object' &&\n connectionType.type === ConnectionTypeEnum.Custom\n ) {\n connectToNode(connectionType.url);\n return;\n }\n\n // Otherwise, open modal\n setIsModalOpen(true);\n };\n\n const handleModalConnect = (url: string) => {\n setIsModalOpen(false);\n connectToNode(url);\n };\n\n // Reconnecting state\n if (isAuthenticated && !isOnline) {\n return (\n <div\n className=\"mero-connect-container\"\n style={{ ...themeVars, display: 'inline-block' }}\n >\n <button\n className={['mero-connect-button', 'mero-reconnecting', buttonClassName, className].filter(Boolean).join(' ')}\n style={style}\n disabled\n aria-label={labels.reconnecting}\n title={logoOnly ? labels.reconnecting : undefined}\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n {!logoOnly && labels.reconnecting}\n </button>\n </div>\n );\n }\n\n // Connected state\n if (isAuthenticated) {\n return (\n <div\n ref={dropdownRef}\n className=\"mero-connect-container\"\n style={{ ...themeVars, position: 'relative', display: 'inline-block' }}\n >\n <button\n className={['mero-connect-button', 'mero-connected', buttonClassName, className].filter(Boolean).join(' ')}\n style={style}\n onClick={() => setIsDropdownOpen((prev) => !prev)}\n aria-label={labels.connected}\n title={logoOnly ? labels.connected : undefined}\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n {!logoOnly && labels.connected}\n </button>\n {isDropdownOpen && (\n <div className=\"mero-dropdown\">\n <div className=\"mero-dropdown-info\" title={nodeUrl || ''}>\n {nodeUrl}\n </div>\n <a\n href={dashboardUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"mero-dropdown-item\"\n >\n Dashboard\n </a>\n <button\n className=\"mero-dropdown-item\"\n onClick={() => {\n setIsDropdownOpen(false);\n logout();\n }}\n >\n Log out\n </button>\n </div>\n )}\n </div>\n );\n }\n\n // Disconnected state\n return (\n <div\n className=\"mero-connect-container\"\n style={{ ...themeVars, display: 'inline-block' }}\n >\n <button\n className={['mero-connect-button', buttonClassName, className].filter(Boolean).join(' ')}\n style={style}\n onClick={handleConnect}\n aria-label={labels.connect}\n title={logoOnly ? labels.connect : undefined}\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n {!logoOnly && labels.connect}\n </button>\n <LoginModal\n isOpen={isModalOpen}\n onConnect={handleModalConnect}\n onClose={() => setIsModalOpen(false)}\n theme={resolvedTheme ?? theme}\n />\n </div>\n );\n}\n\nexport default ConnectButton;\n","/**\n * Minimal Base58 (Bitcoin alphabet) decoder.\n *\n * Blob ids come back from the admin API Base58-encoded, while a namespace's\n * `appKey` is a hex string, so comparing \"what's installed\" to \"what the group\n * targets\" needs one side converted. Decoding Base58 to canonical lowercase hex\n * is the smaller, encoding-agnostic conversion.\n */\n\nconst ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Decode a Base58 string to a lowercase hex string (no `0x` prefix). Leading\n * `1` characters map to leading zero bytes, so the byte width is preserved.\n * Throws on any character outside the Base58 alphabet.\n */\nexport function base58ToHex(input: string): string {\n const bytes: number[] = [];\n for (const char of input) {\n let carry = ALPHABET.indexOf(char);\n if (carry === -1) throw new Error(`invalid base58 character: ${char}`);\n for (let i = 0; i < bytes.length; i++) {\n carry += bytes[i] * 58;\n bytes[i] = carry & 0xff;\n carry >>= 8;\n }\n while (carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n for (let k = 0; k < input.length && input[k] === '1'; k++) bytes.push(0);\n return bytes\n .reverse()\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n","import { useState, useCallback, useEffect, useMemo, useRef } from 'react';\nimport { compareSemver } from '@calimero-network/mero-js';\nimport { useMero } from '../context';\nimport { base58ToHex } from '../utils/base58';\nimport type {\n Codec,\n EphemeralClient,\n Context,\n CreateContextRequest,\n CreateGroupInvitationRequest,\n CreateGroupInNamespaceRequest,\n CreateNamespaceInvitationRequest,\n CreateNamespaceInvitationResponseData,\n CreateNamespaceRequest,\n CreateRecursiveInvitationResponseData,\n GetBlobInfoResponseData,\n GroupContextEntry,\n GroupInfo,\n GroupUpgradeStatusResponseData,\n MetadataRecord,\n JoinGroupRequest,\n JoinNamespaceRequest,\n ListGroupMembersResponseData,\n Namespace,\n NamespaceIdentity,\n NodeIdentity,\n ReparentGroupRequest,\n AddGroupMembersRequest,\n RemoveGroupMembersRequest,\n SetDefaultCapabilitiesRequest,\n SetMetadataRequest,\n SetSubgroupVisibilityRequest,\n SetTeeAdmissionPolicyRequest,\n SubgroupEntry,\n SseEventData,\n UpdateMemberRoleRequest,\n UpgradeGroupRequest,\n UploadBlobRequest,\n ResyncContextRequest,\n MigrationStatus,\n MemberMigrationStatusEntry,\n MigrationStatusRollup,\n MigrateMyEntriesSummary,\n AppVersionChangedEvent,\n GroupMembershipEventData,\n GroupMigrationEventData,\n} from '@calimero-network/mero-js';\nimport type {\n ApplicationContextRecord,\n ContextDiscoveryOptions,\n ContextDiscoveryState,\n} from '../types';\n\nexport { useMero } from '../context';\n\n/**\n * The presence types come straight from `mero-js` now — `Codec` and\n * `EphemeralEntry` are its own declarations, and `EphemeralClient` is the type\n * of the class behind `mero.ephemeral`, so a drift between what this hook\n * assumes and what the SDK does is a compile error rather than a runtime\n * surprise.\n *\n * Re-exported under the same names this package has always exported, so\n * consumers importing `Codec` / `EphemeralEntry` / `EphemeralClient` from\n * `@calimero-network/mero-react` keep compiling — they now simply get the\n * nominal `mero-js` types instead of structural copies of them.\n *\n * On `EphemeralEntry.ageMs`: it is ABSENT on a live delta and PRESENT on a\n * replayed seed entry, reporting how stale that entry already was (bounded by\n * the node's presence TTL). Absent and `0` are different — a `0` means \"the\n * node replayed this and it is brand new\", not \"no age information\". Read it\n * with `?? 0`, never with a truthiness check.\n */\nexport type { Codec, EphemeralEntry, EphemeralClient } from '@calimero-network/mero-js';\n\nexport interface UseEphemeralOptions<T> {\n /** Encoding for the presence slice. Defaults to JSON. */\n codec?: Codec<T>;\n /** Base value for the first `setPresence` merge. */\n initial?: T;\n /** Minimum ms between publishes. Trailing edge — the latest value wins. */\n throttleMs?: number;\n /** Include your own echoed presence in `peers`. Default false. */\n includeSelf?: boolean;\n}\n\n/** Shape returned by {@link useEphemeral}. */\nexport interface UseEphemeralResult<T> {\n peers: Map<string, T>;\n setPresence: (partial: Partial<T>) => void;\n ageOf: (author: string) => number | undefined;\n error: Error | null;\n}\n\n/**\n * Which asynchronous producer currently owns the latched error slot.\n *\n * Only genuinely ASYNCHRONOUS failures are latched — an event happened once,\n * in the past, and nothing about the current render can re-derive it. Anything\n * that is a standing property of the current props/client (notably \"this\n * client has no `mero.ephemeral` surface\") is NOT latched: it is recomputed\n * every render, so it can neither go stale nor be accidentally cleared.\n *\n * The slot is shared, so each producer only clears what it itself raised.\n */\ntype ErrorSource = 'identity' | 'publish';\n\n/**\n * The latched async error, tagged with its producer AND with the context it\n * belongs to.\n *\n * `contextKey` is what makes cross-context leaks structurally impossible\n * rather than a matter of remembering to clear: a write whose key is no longer\n * the current context is dropped on the way in (a publish that was in flight\n * across a context switch), and a latch whose key no longer matches is not\n * read on the way out. Neither path depends on some other effect having run a\n * clear first.\n */\ninterface LatchedEphemeralError {\n contextKey: string | null;\n source: ErrorSource;\n error: Error;\n}\n\nconst NO_EPHEMERAL_SURFACE_MESSAGE =\n 'useEphemeral: this client has no `mero.ephemeral` surface. Ephemeral ' +\n 'presence requires @calimero-network/mero-js >= 9.1.0; upgrade the ' +\n 'installed @calimero-network/mero-js (and any lockfile pin) to use it.';\n\nconst COULD_NOT_RESOLVE_IDENTITY_MESSAGE =\n 'useEphemeral: could not resolve a local context identity, so your own ' +\n 'presence cannot be filtered out. Pass includeSelf: true to accept this.';\n\n/**\n * How long after the last replayed entry (one carrying `ageMs`) the replay\n * window stays open before `peers` is reconciled down to what the replay\n * contained. Long enough to absorb a replay burst split across several SSE\n * frames/ticks, short enough that a swept peer does not linger.\n */\nconst REPLAY_RECONCILE_MS = 50;\n\n/**\n * Observe and publish ephemeral presence (cursors, typing, online) for a\n * context.\n *\n * ONE read path: the subscription. When a client subscribes, the node replays\n * that context's current presence to that connection as ordinary entries\n * before the live deltas start, so seeding and updating share a single shape\n * ({@link EphemeralEntry}) and a reconnect — `SseClient` auto-reconnects and\n * re-subscribes — re-seeds itself. There is no snapshot fetch and no\n * client-side reconciliation pass.\n *\n * Freshness is computed entirely from local clock deltas: a replayed entry is\n * current as of `Date.now() - ageMs`, a live delta as of `Date.now()`. No\n * cross-machine clock comparison is ever performed.\n *\n * No client-side TTL or heartbeat: the node sweeps at 7s and emits removals,\n * and re-publishes on your behalf every 2.5s. A replay is treated as\n * AUTHORITATIVE — see the replay-reconcile pass in the read effect — so a peer\n * swept while the SSE connection was down does not survive the reconnect.\n *\n * `error` is derived, not accumulated: standing conditions (no `ephemeral`\n * surface) are recomputed every render, one-shot async failures are latched\n * keyed by the context they happened in, and whether a latched failure is even\n * relevant (an unresolved identity when `includeSelf` is true) is decided at\n * read time. Nothing survives a context switch.\n */\nexport function useEphemeral<T>(\n contextId: string | null,\n options: UseEphemeralOptions<T> = {},\n): UseEphemeralResult<T> {\n const { includeSelf = false } = options;\n const { mero } = useMero();\n // Cast: the installed mero-js's `MeroJs` type predates `ephemeral` (see\n // `EphemeralClient` above), though it exists at runtime.\n const ephemeral = mero\n ? ((mero as unknown as { ephemeral?: EphemeralClient }).ephemeral ?? null)\n : null;\n\n const [peers, setPeers] = useState<Map<string, T>>(new Map());\n // The one latched async error (see `LatchedEphemeralError`). Not read\n // directly — `error` below derives what is actually reported from it.\n const [latchedError, setLatchedError] = useState<LatchedEphemeralError | null>(null);\n // The context the CURRENT render targets. Read by `setSourceError` so a\n // callback that resolves after a context switch can tell that its result is\n // no longer wanted without closing over anything but its own captured key.\n const contextKeyRef = useRef<string | null>(contextId);\n contextKeyRef.current = contextId;\n // `key` is the contextId captured when the failing operation was STARTED,\n // not when it settled. A late write from a context we have already left is\n // dropped here rather than being written and then hopefully cleared.\n const setSourceError = useCallback(\n (source: ErrorSource, err: Error, key: string | null) => {\n if (key !== contextKeyRef.current) return;\n setLatchedError({ contextKey: key, source, error: err });\n },\n [],\n );\n const clearSourceError = useCallback((source: ErrorSource, key: string | null) => {\n setLatchedError(prev =>\n prev && prev.source === source && prev.contextKey === key ? null : prev,\n );\n }, []);\n\n // DERIVED, never latched: \"this client has no `mero.ephemeral` surface\" is a\n // standing property of the current client, not an event. Recomputing it every\n // render is what makes it impossible to (a) leave it set after an upgraded\n // client arrives or (b) lose it to some other effect's clear — a context\n // switch, for instance, cannot hide a client that still has no surface.\n // Memoised only so the Error identity is stable while the condition holds.\n const surfaceError = useMemo(\n () => (mero && !ephemeral ? new Error(NO_EPHEMERAL_SURFACE_MESSAGE) : null),\n [mero, ephemeral],\n );\n\n // A latch is reported only if it belongs to the context being rendered, and\n // only if it is still MEANINGFUL: an unresolved local identity is an error\n // solely because self-filtering needs it, so opting into `includeSelf` makes\n // it a non-event — decided here, at read time, rather than by racing an\n // effect to clear it.\n const error =\n surfaceError ??\n (latchedError &&\n latchedError.contextKey === contextId &&\n !(latchedError.source === 'identity' && includeSelf)\n ? latchedError.error\n : null);\n // author -> local ms timestamp the entry is considered current as of.\n const receivedAtRef = useRef<Map<string, number>>(new Map());\n // `codec` and `initial` are held in refs, never in a dependency array:\n // `jsonCodec()` is a FACTORY, so `{ codec: jsonCodec() }` at the call site is\n // a fresh identity every render. As a dep it would tear down and re-create\n // the subscription on every render — and since every applied entry sets a\n // new Map (a new render), that is an unbounded resubscribe storm, each\n // resubscribe pulling a fresh presence replay. A codec swapped mid-flight is\n // not a real use case.\n const codecRef = useRef<Codec<T> | undefined>(options.codec);\n codecRef.current = options.codec;\n const initialRef = useRef<T | undefined>(options.initial);\n initialRef.current = options.initial;\n // This node's own context member key (device-level), resolved async. Never\n // compare this against an account id — that comparison silently never\n // matches, which is the classic self-echo bug.\n const selfRef = useRef<string | null>(null);\n const lastLocalRef = useRef<T | undefined>(options.initial);\n const pendingRef = useRef<T | undefined>(undefined);\n const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n // Seeded to the mount time (not 0) so an isolated call shortly after mount\n // is correctly treated as part of the initial \"burst\" and trailing-edge\n // throttled, rather than bypassing the throttle because it looks like it's\n // arriving long after a (nonexistent) previous publish.\n const lastSentAtRef = useRef<number>(Date.now());\n // Open replay window: the authors seen since a replayed entry (one carrying\n // `ageMs`) last arrived. Null when no replay is in progress.\n const replaySeenRef = useRef<Set<string> | null>(null);\n const replayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const ageOf = useCallback((author: string): number | undefined => {\n const at = receivedAtRef.current.get(author);\n return at === undefined ? undefined : Date.now() - at;\n }, []);\n\n // Clear ALL per-context state synchronously the instant the target context\n // changes. Read state, so a previous context's peers don't keep rendering\n // until the new context's replay arrives — and write state, because a\n // queued publish would otherwise fire into the PREVIOUS context (its\n // `setTimeout` closure captured the old `publish`), and `lastLocalRef` would\n // shallow-merge the old context's fields into the first slice published in\n // the new one. Presence is app-defined data (cursor position, typing target),\n // so both are genuine cross-context writes, not cosmetic leaks.\n //\n // The latched error is dropped here as well, but purely as housekeeping (it\n // is what makes A -> B -> A not resurrect A's old failure). Correctness does\n // not rest on it: the latch carries its own `contextKey`, so an error from a\n // context we have left is neither written nor read regardless of whether this\n // effect ran. The standing surface condition is untouched — it is derived, so\n // it re-reports itself on the very next render if it is still true.\n useEffect(() => {\n setPeers(new Map());\n receivedAtRef.current = new Map();\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n timerRef.current = null;\n }\n if (replayTimerRef.current) {\n clearTimeout(replayTimerRef.current);\n replayTimerRef.current = null;\n }\n replaySeenRef.current = null;\n pendingRef.current = undefined;\n lastLocalRef.current = initialRef.current;\n selfRef.current = null;\n setLatchedError(null);\n }, [contextId]);\n\n // Resolve THIS node's context member key — the same value the node stamps\n // as `author` on ephemeral entries.\n useEffect(() => {\n if (!mero || !contextId) return;\n // Captured at START. Everything this effect reports is tagged with it, so\n // a slow lookup that lands after a context switch cannot write into the\n // context we switched to.\n const key = contextId;\n let cancelled = false;\n mero.admin\n .getContextIdentitiesOwned(contextId)\n .then(res => {\n if (cancelled) return;\n const self = res.identities?.[0] ?? null;\n selfRef.current = self;\n if (!self) {\n // Latched unconditionally — `includeSelf` is NOT consulted here.\n // Whether an unresolved identity matters is a question about the\n // CURRENT props, so it is answered where `error` is derived; asking\n // it here is what previously left the error stranded when\n // `includeSelf` flipped to true while resolution still failed.\n setSourceError('identity', new Error(COULD_NOT_RESOLVE_IDENTITY_MESSAGE), key);\n return;\n }\n // A later run of this effect (contextId change, includeSelf toggle)\n // resolved a self identity where an earlier run didn't — clear the\n // \"could not resolve\" error this effect itself raised.\n clearSourceError('identity', key);\n // Ordering race: the identity lookup and the subscription's presence\n // replay land independently, so a self entry can already be seeded in\n // `peers`. Retroactively drop it now that we know who \"self\" is.\n if (!includeSelf) {\n receivedAtRef.current.delete(self);\n setPeers(prev => {\n if (!prev.has(self)) return prev;\n const next = new Map(prev);\n next.delete(self);\n return next;\n });\n }\n })\n .catch((err: unknown) => {\n if (!cancelled) {\n setSourceError('identity', toError(err), key);\n }\n });\n return () => { cancelled = true; };\n // `mero` itself is a dep on purpose: a real MeroProvider memoizes its\n // context value, so `mero` only changes identity when the underlying\n // client is actually replaced (e.g. `allowedNodeUrls` changes) — and\n // that replacement is exactly when this effect must re-resolve the\n // local identity against the new client. Keying on presence alone\n // (`Boolean(mero)`) would silently keep resolving against a closed,\n // stale client instance.\n }, [mero, contextId, includeSelf, setSourceError, clearSourceError]);\n\n // The single read path. Subscribing makes the node replay this context's\n // current presence to this connection as ordinary entries, then stream live\n // deltas — so this one handler both seeds and updates, and an SSE reconnect\n // (which re-subscribes) re-seeds without any extra machinery.\n //\n // A REPLAY IS AUTHORITATIVE. The node replays exactly who is present right\n // now; anything we still hold that the replay does not mention is gone.\n // Without reconciling against it, a peer swept while the connection was down\n // is a permanent ghost: its removal event was delivered to nobody, and the\n // replay — which lists only survivors — will never mention it again. That\n // sweep happens inside `SseClient`'s auto-reconnect, so it does NOT re-run\n // this effect; reconciliation has to be driven by the entries themselves,\n // which is why it keys off `ageMs` (present only on replayed entries) rather\n // than off subscribe/unsubscribe. Clearing `peers` eagerly on subscribe would\n // also miss the reconnect case entirely — and would blank the UI on every\n // `includeSelf` toggle.\n //\n // The window closes `REPLAY_RECONCILE_MS` after the last replayed entry, and\n // live entries arriving while it is open count as present too, so a peer that\n // publishes mid-replay is never swept. A replayed entry that somehow arrives\n // after the window closed re-adds its author immediately — the failure mode\n // is a flicker, never a resurrected ghost or a permanent loss.\n useEffect(() => {\n if (!ephemeral || !contextId) return;\n\n const closeReplayWindow = () => {\n replayTimerRef.current = null;\n const seen = replaySeenRef.current;\n replaySeenRef.current = null;\n if (!seen) return;\n setPeers(prev => {\n let next: Map<string, T> | null = null;\n for (const author of prev.keys()) {\n if (seen.has(author)) continue;\n if (!next) next = new Map(prev);\n next.delete(author);\n receivedAtRef.current.delete(author);\n }\n return next ?? prev;\n });\n };\n\n const unsubscribe = ephemeral.subscribe<T>(\n contextId,\n entry => {\n const { author, state } = entry;\n if (entry.ageMs !== undefined) {\n // A replayed entry: (re)open the reconcile window and debounce its\n // close, so a replay burst split across frames counts as one replay.\n if (!replaySeenRef.current) replaySeenRef.current = new Set();\n if (replayTimerRef.current) clearTimeout(replayTimerRef.current);\n replayTimerRef.current = setTimeout(closeReplayWindow, REPLAY_RECONCILE_MS);\n }\n if (entry.removed || state === undefined) {\n replaySeenRef.current?.delete(author);\n receivedAtRef.current.delete(author);\n setPeers(prev => {\n if (!prev.has(author)) return prev;\n const next = new Map(prev);\n next.delete(author);\n return next;\n });\n return;\n }\n if (!includeSelf && author === selfRef.current) return;\n replaySeenRef.current?.add(author);\n // `ageMs` is absent on a live delta (current as of now) and present on\n // a replayed entry (current as of `now - ageMs`). `?? 0` — never a\n // truthiness test: an `ageMs` of 0 is a real, meaningful value.\n receivedAtRef.current.set(author, Date.now() - (entry.ageMs ?? 0));\n setPeers(prev => new Map(prev).set(author, state));\n },\n codecRef.current,\n );\n\n return () => {\n if (replayTimerRef.current) {\n clearTimeout(replayTimerRef.current);\n replayTimerRef.current = null;\n }\n replaySeenRef.current = null;\n unsubscribe();\n };\n // `ephemeral` itself is a dep on purpose — see the identity-resolution\n // effect above. A replaced client must re-subscribe against the new\n // client, not keep reading/writing through the old (possibly closed)\n // one. `codec` is deliberately NOT a dep — see `codecRef`.\n }, [ephemeral, contextId, includeSelf]);\n\n const publish = useCallback((value: T) => {\n if (!ephemeral || !contextId) return;\n // Captured at START, like the identity lookup's `key`: `ephemeral.set` is\n // not cancellable, so a rejection can land long after a context switch.\n // Tagging the write with the context it was issued for is what keeps that\n // failure out of the new context's error slot.\n const key = contextId;\n lastSentAtRef.current = Date.now();\n void ephemeral.set<T>(key, value, codecRef.current).then(\n () => clearSourceError('publish', key),\n (err: unknown) => setSourceError('publish', toError(err), key),\n );\n }, [ephemeral, contextId, setSourceError, clearSourceError]);\n\n /**\n * Publish your own presence.\n *\n * SHALLOW merge over the last locally-set value (starting from `initial`):\n * presence is one slot per author, so fields are not independent channels\n * and a bare replace would silently drop whatever you did not mention.\n * Nested objects are replaced wholesale, not deep-merged —\n * `setPresence({ cursor: { x: 1 } })` DROPS `cursor.y` if it was set\n * separately.\n *\n * Throttled on the trailing edge: rapid calls collapse into one publish\n * carrying the newest value, never the oldest queued one.\n */\n const setPresence = useCallback((partial: Partial<T>) => {\n const next = { ...(lastLocalRef.current ?? ({} as T)), ...partial } as T;\n lastLocalRef.current = next;\n\n const throttleMs = options.throttleMs ?? 30;\n if (throttleMs <= 0) {\n publish(next);\n return;\n }\n\n pendingRef.current = next;\n if (timerRef.current) return;\n const elapsed = Date.now() - lastSentAtRef.current;\n const delay = Math.max(throttleMs - elapsed, 0);\n timerRef.current = setTimeout(() => {\n timerRef.current = null;\n const queued = pendingRef.current;\n pendingRef.current = undefined;\n if (queued !== undefined) publish(queued);\n }, delay);\n }, [publish, options.throttleMs]);\n\n // Cancel a queued publish on unmount.\n useEffect(() => () => {\n if (timerRef.current) clearTimeout(timerRef.current);\n }, []);\n\n return { peers, setPresence, ageOf, error };\n}\n\n/**\n * Shape accepted by the metadata-setter hooks — re-exported from mero-js so\n * callers have one canonical type. A `set*Metadata` call **replaces the whole\n * record**: `data` defaults to `{}` and wholly replaces the stored map; omit\n * `name` to keep the current name.\n */\nexport type SetMetadataInput = SetMetadataRequest;\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction mapApplicationContexts(contexts: Context[]): ApplicationContextRecord[] {\n return contexts.map((context) => ({\n contextId: context.id,\n applicationId: context.applicationId,\n }));\n}\n\nfunction useMountedRef() {\n const mountedRef = useRef(true);\n\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n return mountedRef;\n}\n\nfunction useAsyncMutation() {\n const mountedRef = useMountedRef();\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const run = useCallback(\n async <T,>(action: () => Promise<T>): Promise<T | null> => {\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n return await action();\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current) {\n setError(errorValue);\n }\n return null;\n } finally {\n if (mountedRef.current) {\n setLoading(false);\n }\n }\n },\n [mountedRef],\n );\n\n return { loading, error, run, setError };\n}\n\n/**\n * Generic read resource: fetch + loading/error/data with a latest-request-wins\n * guard. `fetcher` is null when the read is disabled (missing args) — the\n * resource resets to `initialValue` and nothing is fetched. `deps` drive both\n * the refetch and a synchronous reset when they change, so a slow earlier\n * request can never overwrite a newer one. This is the staleness guard the read\n * hooks used to hand-roll (and mostly lacked), now in one place.\n */\nfunction useAsyncResource<T>(\n fetcher: (() => Promise<T>) | null,\n initialValue: T,\n deps: readonly unknown[],\n): { data: T; loading: boolean; error: Error | null; refetch: () => Promise<void> } {\n const mountedRef = useMountedRef();\n const [data, setData] = useState<T>(initialValue);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const reqRef = useRef(0);\n\n // fetcherRef is refreshed every render so refetch() always calls the latest\n // closure; initialRef captures the (per-hook constant) initial value once.\n // Neither is a dependency — adding them would break latest-request-wins.\n const fetcherRef = useRef(fetcher);\n fetcherRef.current = fetcher;\n const initialRef = useRef(initialValue);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n const fn = fetcherRef.current;\n if (!fn) {\n if (mountedRef.current && seq === reqRef.current) {\n setData(initialRef.current);\n setError(null);\n setLoading(false);\n }\n return;\n }\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n try {\n const result = await fn();\n if (mountedRef.current && seq === reqRef.current) setData(result);\n } catch (err) {\n if (mountedRef.current && seq === reqRef.current) setError(toError(err));\n } finally {\n if (mountedRef.current && seq === reqRef.current) setLoading(false);\n }\n }, deps);\n\n // Invalidate any in-flight request and drop the previous key's data DURING\n // RENDER, not in an effect. An effect leaves one render where `data` still\n // answers for the old inputs, and a consumer that persists what it sees\n // (a \"this member already has a name\" marker, say) makes that transient\n // staleness permanent.\n const prevDeps = useRef(deps);\n if (\n deps.length !== prevDeps.current.length ||\n deps.some((d, i) => !Object.is(d, prevDeps.current[i]))\n ) {\n prevDeps.current = deps;\n reqRef.current += 1;\n setData(initialRef.current);\n setError(null);\n }\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nfunction extractAliasContextId(value: unknown): string | null {\n if (typeof value === 'string') {\n return value;\n }\n\n if (!value || typeof value !== 'object') {\n return null;\n }\n\n if ('value' in value && typeof value.value === 'string') {\n return value.value;\n }\n\n if ('contextId' in value && typeof value.contextId === 'string') {\n return value.contextId;\n }\n\n return null;\n}\n\n/**\n * Execute RPC methods against a context.\n * Tracks loading/error state. Unmount-safe.\n */\nexport function useExecute(contextId: string | null, executorId: string | null) {\n const { mero } = useMero();\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useRef(true);\n\n useEffect(() => {\n mountedRef.current = true;\n return () => { mountedRef.current = false; };\n }, []);\n\n const execute = useCallback(\n async <T = unknown>(method: string, params?: Record<string, unknown>): Promise<T | null> => {\n if (!mero || !contextId || !executorId) {\n if (mountedRef.current) setError(new Error('Not connected'));\n return null;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n try {\n const result = await mero.rpc.execute<T>({\n contextId,\n method,\n argsJson: params,\n executorPublicKey: executorId,\n });\n return result;\n } catch (err) {\n const e = err instanceof Error ? err : new Error(String(err));\n if (mountedRef.current) setError(e);\n return null;\n } finally {\n if (mountedRef.current) setLoading(false);\n }\n },\n [mero, contextId, executorId],\n );\n\n return { execute, loading, error };\n}\n\n/** Event payload delivered to a `useSubscription` callback. */\nexport type SubscriptionEventData =\n | SseEventData\n | GroupMembershipEventData\n | GroupMigrationEventData;\n\n/** Ids to subscribe to. Either can be omitted, but not both. */\nexport interface SubscriptionInput {\n contextIds?: string[];\n groupIds?: string[];\n}\n\n/**\n * Subscribe to SSE events for context and/or group IDs.\n * StrictMode-safe: tracks the SseClient instance in a ref to avoid\n * double-connect on mount/unmount/remount cycles.\n */\nexport function useSubscription(\n contextIds: string[],\n callback: (event: SubscriptionEventData) => void,\n): void;\nexport function useSubscription(\n input: SubscriptionInput,\n callback: (event: SubscriptionEventData) => void,\n): void;\nexport function useSubscription(\n input: string[] | SubscriptionInput,\n callback: (event: SubscriptionEventData) => void,\n) {\n const { mero } = useMero();\n const callbackRef = useRef(callback);\n callbackRef.current = callback;\n\n const { contextIds = [], groupIds = [] } = Array.isArray(input)\n ? { contextIds: input, groupIds: [] as string[] }\n : input;\n\n const contextIdsKey = JSON.stringify(contextIds);\n const groupIdsKey = JSON.stringify(groupIds);\n\n useEffect(() => {\n if (!mero || (contextIds.length === 0 && groupIds.length === 0)) return;\n\n const sse = mero.events;\n\n const handler = (event: SubscriptionEventData) => {\n callbackRef.current(event);\n };\n\n sse.on('event', handler);\n sse.connect().catch(() => {});\n sse.subscribe({ contextIds, groupIds }).catch(() => {});\n\n return () => {\n sse.off('event', handler);\n };\n }, [mero, contextIdsKey, groupIdsKey]);\n}\n\n/**\n * Fetch contexts for the current node, optionally filtered by application ID.\n */\nexport function useContexts(applicationId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<ApplicationContextRecord[]>(\n mero\n ? async () => {\n const response = applicationId\n ? await mero.admin.getContextsForApplication(applicationId)\n : await mero.admin.getContexts();\n return mapApplicationContexts(response.contexts ?? []);\n }\n : null,\n [],\n [mero, applicationId],\n );\n return { contexts: data, loading, error, refetch };\n}\n\nexport function useApplicationContexts(applicationId?: string | null) {\n return useContexts(applicationId);\n}\n\nexport function useGroupMembers(groupId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<ListGroupMembersResponseData | null>(\n mero && groupId ? () => mero.admin.listGroupMembers(groupId) : null,\n null,\n [mero, groupId],\n );\n // `members` is a guaranteed array on the wire; `?? []` guards mocks / drift.\n return {\n members: data?.members ?? [],\n loading,\n error,\n refetch,\n };\n}\n\nexport function useGroupContexts(groupId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<GroupContextEntry[]>(\n mero && groupId ? () => mero.admin.listGroupContexts(groupId) : null,\n [],\n [mero, groupId],\n );\n return { contexts: data, loading, error, refetch };\n}\n\nexport function useGroupInvitations() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createInvitation = useCallback(\n async (groupId: string, request?: CreateGroupInvitationRequest) => {\n if (!mero) {\n return null;\n }\n return run(() => mero.admin.createGroupInvitation(groupId, request));\n },\n [mero, run],\n );\n\n return { createInvitation, loading, error };\n}\n\nexport function useJoinGroup() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const joinGroup = useCallback(\n async (request: JoinGroupRequest) => {\n if (!mero) {\n return null;\n }\n return run(() => mero.admin.joinGroup(request));\n },\n [mero, run],\n );\n\n return { joinGroup, loading, error };\n}\n\n/**\n * Takes the member's ACCOUNT (64 hex), as `useGroupMembers` rows are keyed by\n * and `useNodeIdentity().identity?.accountId` returns - NOT a signing key.\n * Both are 32-byte strings, so passing a key names nobody and raises nothing.\n */\nexport function useGroupCapabilities(groupId?: string | null, memberId?: string | null) {\n const { mero } = useMero();\n const [capabilities, setCapabilitiesState] = useState<number | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Read+write hybrid (setCapabilities shares this state), so it keeps the\n // inline latest-request-wins guard rather than useAsyncResource.\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n if (!mero || !groupId || !memberId) {\n if (mountedRef.current && seq === reqRef.current) {\n setCapabilitiesState(null);\n setError(null);\n setLoading(false);\n }\n return null;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const response = await mero.admin.getMemberCapabilities(groupId, memberId);\n if (mountedRef.current && seq === reqRef.current) {\n setCapabilitiesState(response.capabilities);\n }\n return response.capabilities;\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n return null;\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [groupId, memberId, mero, mountedRef]);\n\n useEffect(() => {\n reqRef.current += 1;\n setCapabilitiesState(null);\n setError(null);\n }, [groupId, memberId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n const setCapabilities = useCallback(\n async (nextCapabilities: number) => {\n if (!mero || !groupId || !memberId) {\n return null;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n await mero.admin.setMemberCapabilities(groupId, memberId, { capabilities: nextCapabilities });\n if (mountedRef.current) {\n setCapabilitiesState(nextCapabilities);\n }\n return nextCapabilities;\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current) {\n setError(errorValue);\n }\n return null;\n } finally {\n if (mountedRef.current) {\n setLoading(false);\n }\n }\n },\n [groupId, memberId, mero, mountedRef],\n );\n\n return { capabilities, loading, error, refetch, setCapabilities };\n}\n\nexport function useContextDiscovery(options: ContextDiscoveryOptions): ContextDiscoveryState {\n const { mero } = useMero();\n const [context, setContext] = useState<ApplicationContextRecord | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n\n const knownContextIdsKey = JSON.stringify(options.knownContextIds ?? []);\n\n const discover = useCallback(async () => {\n if (!mero) {\n const notConnectedError = new Error('Not connected');\n if (mountedRef.current) {\n setError(notConnectedError);\n }\n return null;\n }\n const knownContextIds = new Set(options.knownContextIds ?? []);\n const pollIntervalMs = options.pollIntervalMs ?? 1000;\n const timeoutMs = options.timeoutMs ?? 30000;\n const deadline = Date.now() + timeoutMs;\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n while (Date.now() <= deadline) {\n if (options.targetAlias) {\n const aliasMatch = extractAliasContextId(\n await mero.admin.lookupContextAlias(options.targetAlias),\n );\n\n if (aliasMatch && !knownContextIds.has(aliasMatch)) {\n const discoveredFromAlias = {\n contextId: aliasMatch,\n applicationId: options.applicationId,\n };\n\n if (mountedRef.current) {\n setContext(discoveredFromAlias);\n }\n\n return discoveredFromAlias;\n }\n }\n\n const response = await mero.admin.getContextsForApplication(options.applicationId);\n const contexts = mapApplicationContexts(response.contexts ?? []);\n const discovered = contexts.find(\n (applicationContext) => !knownContextIds.has(applicationContext.contextId),\n );\n\n if (discovered) {\n if (mountedRef.current) {\n setContext(discovered);\n }\n return discovered;\n }\n\n if (Date.now() + pollIntervalMs > deadline) {\n break;\n }\n\n await sleep(pollIntervalMs);\n }\n\n const timeoutError = new Error(\n `Timed out discovering a context for application ${options.applicationId}`,\n );\n\n if (mountedRef.current) {\n setContext(null);\n setError(timeoutError);\n }\n\n return null;\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current) {\n setContext(null);\n setError(errorValue);\n }\n return null;\n } finally {\n if (mountedRef.current) {\n setLoading(false);\n }\n }\n }, [\n knownContextIdsKey,\n mero,\n mountedRef,\n options.applicationId,\n options.knownContextIds,\n options.pollIntervalMs,\n options.targetAlias,\n options.timeoutMs,\n ]);\n\n const reset = useCallback(() => {\n if (mountedRef.current) {\n setContext(null);\n setError(null);\n setLoading(false);\n }\n }, [mountedRef]);\n\n return { context, loading, error, discover, reset };\n}\n\n// ---- Context CRUD Hooks ----\n\nexport function useCreateContext() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createContext = useCallback(\n async (request: CreateContextRequest) => {\n if (!mero) return null;\n return run(() => mero.admin.createContext(request));\n },\n [mero, run],\n );\n\n return { createContext, loading, error };\n}\n\nexport function useDeleteContext() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const deleteContext = useCallback(\n async (contextId: string) => {\n if (!mero) return null;\n return run(() => mero.admin.deleteContext(contextId));\n },\n [mero, run],\n );\n\n return { deleteContext, loading, error };\n}\n\nexport function useJoinContext() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const joinContext = useCallback(\n async (contextId: string) => {\n if (!mero) return null;\n return run(() => mero.admin.joinContext(contextId));\n },\n [mero, run],\n );\n\n return { joinContext, loading, error };\n}\n\nexport function useJoinSubgroupInheritance() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const joinSubgroupInheritance = useCallback(\n async (groupId: string) => {\n if (!mero) return null;\n return run(() => mero.admin.joinSubgroupInheritance(groupId));\n },\n [mero, run],\n );\n\n return { joinSubgroupInheritance, loading, error };\n}\n\nexport function useContextGroup(contextId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<string | null>(\n mero && contextId ? () => mero.admin.getContextGroup(contextId) : null,\n null,\n [mero, contextId],\n );\n return { groupId: data, loading, error, refetch };\n}\n\n// ---- Group Info / Management Hooks ----\n\nexport function useGroupInfo(groupId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<GroupInfo | null>(\n mero && groupId ? () => mero.admin.getGroupInfo(groupId) : null,\n null,\n [mero, groupId],\n );\n return { groupInfo: data, loading, error, refetch };\n}\n\nexport function useDeleteGroup() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const deleteGroup = useCallback(\n async (groupId: string) => {\n if (!mero) return null;\n return run(() => mero.admin.deleteGroup(groupId));\n },\n [mero, run],\n );\n\n return { deleteGroup, loading, error };\n}\n\nexport function useSyncGroup() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const syncGroup = useCallback(\n async (groupId: string) => {\n if (!mero) return null;\n return run(() => mero.admin.syncGroup(groupId));\n },\n [mero, run],\n );\n\n return { syncGroup, loading, error };\n}\n\n/**\n * Takes the invitee's signing KEY (bs58) - the one call on this resource that\n * does, because someone being added may have no account here yet. Every other\n * member call, including `useRemoveGroupMembers`, takes the ACCOUNT, so a value\n * round-tripped from an add is the wrong one to remove with.\n */\nexport function useAddGroupMembers() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const addGroupMembers = useCallback(\n async (groupId: string, request: AddGroupMembersRequest) => {\n if (!mero) return null;\n return run(() => mero.admin.addGroupMembers(groupId, request));\n },\n [mero, run],\n );\n\n return { addGroupMembers, loading, error };\n}\n\n/**\n * Takes the member's ACCOUNT (64 hex), as `useGroupMembers` rows are keyed by\n * and `useNodeIdentity().identity?.accountId` returns - NOT a signing key.\n * Both are 32-byte strings, so passing a key names nobody and raises nothing.\n */\nexport function useRemoveGroupMembers() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const removeGroupMembers = useCallback(\n async (groupId: string, request: RemoveGroupMembersRequest) => {\n if (!mero) return null;\n return run(() => mero.admin.removeGroupMembers(groupId, request));\n },\n [mero, run],\n );\n\n return { removeGroupMembers, loading, error };\n}\n\n// ---- Namespace Hooks ----\n\nexport function useNamespaces() {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<Namespace[]>(\n mero ? () => mero.admin.listNamespaces() : null,\n [],\n [mero],\n );\n return { namespaces: data, loading, error, refetch };\n}\n\nexport function useNamespace(namespaceId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<Namespace | null>(\n mero && namespaceId ? () => mero.admin.getNamespace(namespaceId) : null,\n null,\n [mero, namespaceId],\n );\n return { namespace: data, loading, error, refetch };\n}\n\n/**\n * Who this node is: `accountId` is what member-addressing takes and what\n * `useGroupMembers` rows are keyed by — `publicKey` is the signing key and\n * addresses nobody. Both are 32-byte strings, so a swap fails silently.\n */\nexport function useNodeIdentity() {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<NodeIdentity | null>(\n mero ? () => mero.admin.getNodeIdentity() : null,\n null,\n [mero],\n );\n return { identity: data, loading, error, refetch };\n}\n\n/**\n * @deprecated Use {@link useNodeIdentity}. Identity is per-node, not\n * per-namespace, and this no longer gates on participation: it answers for a\n * namespace this node never joined, so `identity != null` is not \"am I a\n * member?\" — ask `useNamespaces` for that. Its `publicKey` is the signing key,\n * NOT the account member-addressing wants.\n */\nexport function useNamespaceIdentity(namespaceId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<NamespaceIdentity | null>(\n mero && namespaceId ? () => mero.admin.getNamespaceIdentity(namespaceId) : null,\n null,\n [mero, namespaceId],\n );\n return { identity: data, loading, error, refetch };\n}\n\nexport function useNamespacesForApplication(applicationId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<Namespace[]>(\n mero && applicationId ? () => mero.admin.listNamespacesForApplication(applicationId) : null,\n [],\n [mero, applicationId],\n );\n return { namespaces: data, loading, error, refetch };\n}\n\nexport function useCreateNamespace() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createNamespace = useCallback(\n async (request: CreateNamespaceRequest) => {\n if (!mero) return null;\n return run(() => mero.admin.createNamespace(request));\n },\n [mero, run],\n );\n\n return { createNamespace, loading, error };\n}\n\nexport function useDeleteNamespace() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const deleteNamespace = useCallback(\n async (namespaceId: string) => {\n if (!mero) return null;\n return run(() => mero.admin.deleteNamespace(namespaceId));\n },\n [mero, run],\n );\n\n return { deleteNamespace, loading, error };\n}\n\nexport function useCreateNamespaceInvitation() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createNamespaceInvitation = useCallback(\n async (\n namespaceId: string,\n request?: CreateNamespaceInvitationRequest,\n ): Promise<CreateNamespaceInvitationResponseData | CreateRecursiveInvitationResponseData | null> => {\n if (!mero) return null;\n return run(() => mero.admin.createNamespaceInvitation(namespaceId, request));\n },\n [mero, run],\n );\n\n return { createNamespaceInvitation, loading, error };\n}\n\nexport function useJoinNamespace() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const joinNamespace = useCallback(\n async (namespaceId: string, request: JoinNamespaceRequest) => {\n if (!mero) return null;\n return run(() => mero.admin.joinNamespace(namespaceId, request));\n },\n [mero, run],\n );\n\n return { joinNamespace, loading, error };\n}\n\nexport function useCreateGroupInNamespace() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createGroupInNamespace = useCallback(\n async (namespaceId: string, request?: CreateGroupInNamespaceRequest) => {\n if (!mero) return null;\n return run(() => mero.admin.createGroupInNamespace(namespaceId, request));\n },\n [mero, run],\n );\n\n return { createGroupInNamespace, loading, error };\n}\n\nexport function useNamespaceGroups(namespaceId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<SubgroupEntry[]>(\n mero && namespaceId ? () => mero.admin.listNamespaceGroups(namespaceId) : null,\n [],\n [mero, namespaceId],\n );\n return { groups: data, loading, error, refetch };\n}\n\n// ---- Group Settings & Role Management ----\n\n/**\n * Takes the member's ACCOUNT (64 hex), as `useGroupMembers` rows are keyed by\n * and `useNodeIdentity().identity?.accountId` returns - NOT a signing key.\n * Both are 32-byte strings, so passing a key names nobody and raises nothing.\n */\nexport function useUpdateMemberRole() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const updateMemberRole = useCallback(\n async (groupId: string, identity: string, request: UpdateMemberRoleRequest) => {\n if (!mero) return null;\n return run(() => mero.admin.updateMemberRole(groupId, identity, request));\n },\n [mero, run],\n );\n\n return { updateMemberRole, loading, error };\n}\n\nexport function useSetDefaultCapabilities() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setDefaultCapabilities = useCallback(\n async (groupId: string, request: SetDefaultCapabilitiesRequest) => {\n if (!mero) return null;\n return run(() => mero.admin.setDefaultCapabilities(groupId, request));\n },\n [mero, run],\n );\n\n return { setDefaultCapabilities, loading, error };\n}\n\nexport function useSetSubgroupVisibility() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setSubgroupVisibility = useCallback(\n async (groupId: string, request: SetSubgroupVisibilityRequest) => {\n if (!mero) return null;\n return run(() => mero.admin.setSubgroupVisibility(groupId, request));\n },\n [mero, run],\n );\n\n return { setSubgroupVisibility, loading, error };\n}\n\nexport function useDefaultCapabilities(groupId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<number | null>(\n mero && groupId ? () => mero.admin.getDefaultCapabilities(groupId) : null,\n null,\n [mero, groupId],\n );\n return { defaultCapabilities: data, loading, error, refetch };\n}\n\nexport function useSubgroupVisibility(groupId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<string | null>(\n mero && groupId ? () => mero.admin.getSubgroupVisibility(groupId) : null,\n null,\n [mero, groupId],\n );\n return { subgroupVisibility: data, loading, error, refetch };\n}\n\nexport function useSetTeeAdmissionPolicy() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setTeeAdmissionPolicy = useCallback(\n async (groupId: string, request: SetTeeAdmissionPolicyRequest) => {\n if (!mero) return null;\n return run(() => mero.admin.setTeeAdmissionPolicy(groupId, request));\n },\n [mero, run],\n );\n\n return { setTeeAdmissionPolicy, loading, error };\n}\n\n// ---- Metadata Hooks ----\n\nexport function useSetGroupMetadata() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setGroupMetadata = useCallback(\n async (groupId: string, request: SetMetadataInput) => {\n if (!mero) return null;\n return run(() => mero.admin.setGroupMetadata(groupId, request));\n },\n [mero, run],\n );\n\n return { setGroupMetadata, loading, error };\n}\n\n/**\n * Takes the member's ACCOUNT (64 hex), as `useGroupMembers` rows are keyed by\n * and `useNodeIdentity().identity?.accountId` returns - NOT a signing key.\n * Both are 32-byte strings, so passing a key names nobody and raises nothing.\n */\nexport function useSetMemberMetadata() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setMemberMetadata = useCallback(\n async (groupId: string, identity: string, request: SetMetadataInput) => {\n if (!mero) return null;\n return run(() => mero.admin.setMemberMetadata(groupId, identity, request));\n },\n [mero, run],\n );\n\n return { setMemberMetadata, loading, error };\n}\n\nexport function useSetContextMetadata() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setContextMetadata = useCallback(\n async (groupId: string, contextId: string, request: SetMetadataInput) => {\n if (!mero) return null;\n return run(() => mero.admin.setContextMetadata(groupId, contextId, request));\n },\n [mero, run],\n );\n\n return { setContextMetadata, loading, error };\n}\n\nexport function useGroupMetadata(groupId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<MetadataRecord | null>(\n mero && groupId ? () => mero.admin.getGroupMetadata(groupId) : null,\n null,\n [mero, groupId],\n );\n return { metadata: data, loading, error, refetch };\n}\n\nexport function useMemberMetadata(groupId?: string | null, identity?: string | null) {\n const { mero } = useMero();\n const [metadata, setMetadata] = useState<MetadataRecord | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n // Drop the previous (group, member)'s record DURING RENDER. Clearing in an\n // effect leaves one render where `metadata` answers for the pair that was\n // asked about last, and a consumer that persists what it sees turns that\n // transient staleness into a permanent wrong answer.\n const prevKey = useRef<string | null>(null);\n const key = `${groupId ?? ''}:${identity ?? ''}`;\n if (prevKey.current !== null && prevKey.current !== key) {\n setMetadata(null);\n setError(null);\n }\n prevKey.current = key;\n\n // Shared fetch logic for the auto-mount effect and the explicit\n // refetch callable. The per-invocation `signal.aborted` flag covers\n // the response-during-unmount race cleanly without the global\n // mountedRef gate that — under StrictMode-like fast unmount/remount\n // cycles — could leave the hook stuck on `metadata = null` when an\n // in-flight response landed during cleanup and the followup mount's\n // useCallback referential identity hadn't changed enough to re-fire\n // the effect.\n const run = useCallback(\n async (signal: { aborted: boolean }) => {\n if (!mero || !groupId || !identity) {\n if (!signal.aborted) {\n setMetadata(null);\n setError(null);\n setLoading(false);\n }\n return;\n }\n if (!signal.aborted) {\n setLoading(true);\n setError(null);\n }\n try {\n const result = await mero.admin.getMemberMetadata(groupId, identity);\n if (!signal.aborted) setMetadata(result);\n } catch (err) {\n if (!signal.aborted) setError(toError(err));\n } finally {\n if (!signal.aborted) setLoading(false);\n }\n },\n [mero, groupId, identity],\n );\n\n useEffect(() => {\n const signal = { aborted: false };\n void run(signal);\n return () => {\n signal.aborted = true;\n };\n }, [run]);\n\n // Explicit refetch — the caller's `await refetch()` resolves only\n // after state has been written (preserves the prior API contract;\n // call sites like `useMemberDisplayName.setName` rely on the new\n // value being readable from state after the await).\n const refetch = useCallback(async () => {\n const signal = { aborted: false };\n await run(signal);\n }, [run]);\n\n return { metadata, loading, error, refetch };\n}\n\n// ---- Group Signing Key, Upgrades & Hierarchy ----\n\nexport function useUpgradeGroup() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const upgradeGroup = useCallback(\n async (groupId: string, request: UpgradeGroupRequest) => {\n if (!mero) return null;\n return run(() => mero.admin.upgradeGroup(groupId, request));\n },\n [mero, run],\n );\n\n return { upgradeGroup, loading, error };\n}\n\n/**\n * Install a registry package version onto the node — the discrete \"Download\"\n * step an Updates flow runs before an `upgradeGroup`. Resolves the installed\n * application id (`InstallApplicationResponseData`). Downloading does not by\n * itself change what any group runs; pair it with a subsequent upgrade.\n */\nexport function useInstallFromRegistry() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n /**\n * ⚠️ NO `registryUrl` ARGUMENT ANY MORE. Since core's registry-only\n * application distribution, a node installs by `package@version` and\n * resolves the artifact against the registry IT is configured with — a\n * client cannot name one. mero-js dropped `installFromRegistry` for\n * `installApplication({ package, version })` to match, so the old third\n * argument had nowhere to go.\n */\n const installFromRegistry = useCallback(\n async (packageName: string, version: string) => {\n if (!mero) return null;\n return run(() => mero.admin.installApplication({ package: packageName, version }));\n },\n [mero, run],\n );\n\n return { installFromRegistry, loading, error };\n}\n\n/**\n * Kick off a full state re-pull for a context — operator recovery for a\n * context stranded mid-sync. `force` re-pulls even when the node does not\n * flag the context as stranded.\n */\nexport function useResyncContext() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const resyncContext = useCallback(\n async (contextId: string, request: ResyncContextRequest = {}) => {\n if (!mero) return null;\n return run(() => mero.admin.resyncContext(contextId, request));\n },\n [mero, run],\n );\n\n return { resyncContext, loading, error };\n}\n\nexport function useGroupUpgradeStatus(groupId?: string | null) {\n const { mero } = useMero();\n const [upgradeStatus, setUpgradeStatus] = useState<GroupUpgradeStatusResponseData>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Latest-request-wins token (see useMigrationStatus) so overlapping refetches\n // can't land out of order and overwrite fresher data.\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n if (!mero || !groupId) {\n if (mountedRef.current) {\n setUpgradeStatus(null);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const result = await mero.admin.getGroupUpgradeStatus(groupId);\n if (mountedRef.current && seq === reqRef.current) {\n setUpgradeStatus(result);\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [groupId, mero, mountedRef]);\n\n // Clear stale status synchronously when the target group changes (and\n // invalidate any in-flight refetch), mirroring useMigrationStatus.\n useEffect(() => {\n reqRef.current += 1;\n setUpgradeStatus(null);\n setError(null);\n }, [groupId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { upgradeStatus, loading, error, refetch };\n}\n\nexport function useRetryGroupUpgrade() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const retryGroupUpgrade = useCallback(\n async (groupId: string) => {\n if (!mero) return null;\n return run(() => mero.admin.retryGroupUpgrade(groupId));\n },\n [mero, run],\n );\n\n return { retryGroupUpgrade, loading, error };\n}\n\n/** Move `childGroupId` under a new parent. */\nexport function useReparentGroup() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const reparentGroup = useCallback(\n async (childGroupId: string, request: ReparentGroupRequest) => {\n if (!mero) return null;\n return run(() => mero.admin.reparentGroup(childGroupId, request));\n },\n [mero, run],\n );\n\n return { reparentGroup, loading, error };\n}\n\nexport function useSubgroups(groupId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<SubgroupEntry[]>(\n mero && groupId ? () => mero.admin.listSubgroups(groupId) : null,\n [],\n [mero, groupId],\n );\n return { subgroups: data, loading, error, refetch };\n}\n\n// ---- Context-Group Relationship ----\n\nexport function useDetachContextFromGroup() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const detachContextFromGroup = useCallback(\n async (groupId: string, contextId: string) => {\n if (!mero) return null;\n return run(() => mero.admin.detachContextFromGroup(groupId, contextId));\n },\n [mero, run],\n );\n\n return { detachContextFromGroup, loading, error };\n}\n\n/**\n * Subscribe to a namespace's `GroupMigration` events, invoking `onEvent` per\n * frame and unsubscribing on unmount.\n *\n * A non-admin subscriber never sees `CascadeProgress`; core delivers that to\n * namespace admins only, so a UI must not wait on it to decide progress.\n */\n/**\n * Fallback poll cadence for `useMigrationStatus` when the SSE stream is\n * unavailable (no token, a proxy that buffers, an older node) and the caller\n * named no interval of its own. Chosen to match the heartbeat cadence that\n * migration facts actually arrive on; an explicit `pollIntervalMs` overrides it.\n */\nexport const DEFAULT_MIGRATION_POLL_INTERVAL_MS = 5000;\n\nexport function useMigrationEvents(\n namespaceId: string | null | undefined,\n onEvent: (event: GroupMigrationEventData) => void,\n): boolean {\n const { mero } = useMero();\n const mountedRef = useMountedRef();\n // Whether the stream is actually carrying frames. Callers use it to decide\n // whether they still need a fallback poll, so it must reflect the subscribe\n // ACTUALLY succeeding - not merely that we asked.\n const [live, setLive] = useState(false);\n // Held in a ref so a caller passing an inline arrow does not resubscribe on\n // every render - the subscription's lifetime is the namespace's, not the\n // callback identity's.\n const handlerRef = useRef(onEvent);\n handlerRef.current = onEvent;\n\n useEffect(() => {\n if (!mero || !namespaceId) return;\n const sse = mero.events;\n const unsubscribe = sse.onMigrationEvent((event) => handlerRef.current(event));\n // Sequential, and the result is recorded: connecting but failing to\n // subscribe is still a dead stream, and both used to be swallowed, which\n // left a caller unable to tell a live stream from a silent one.\n let cancelled = false;\n void (async () => {\n try {\n await sse.connect();\n await sse.subscribe({ groupIds: [namespaceId] });\n if (!cancelled && mountedRef.current) setLive(true);\n } catch {\n if (!cancelled && mountedRef.current) setLive(false);\n }\n })();\n return () => {\n cancelled = true;\n if (mountedRef.current) setLive(false);\n unsubscribe();\n };\n }, [mero, namespaceId, mountedRef]);\n\n return live;\n}\n\n/**\n * Migration-status rollup for a namespace (skew #3).\n *\n * Live: subscribes to the `GroupMigration` event family and re-reads on each\n * frame. It re-READS rather than folding the event's counters in, because the\n * rollup is recomputed from raw member rows and is the authoritative answer.\n * `pollIntervalMs` stays as the fallback when SSE is unavailable, and when the\n * caller names none it defaults to `DEFAULT_MIGRATION_POLL_INTERVAL_MS` for\n * exactly as long as the stream is down - so the panel can never sit silently\n * frozen with neither transport.\n * Derived counters are null-safe before the first load.\n */\nexport function useMigrationStatus(\n namespaceId?: string | null,\n options?: { pollIntervalMs?: number },\n) {\n const { mero } = useMero();\n const [status, setStatus] = useState<MigrationStatus | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Monotonic request token: only the latest in-flight request applies its\n // result, so an overlapping poll or a fast namespace change can't let a\n // stale response overwrite fresher data.\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n if (!mero || !namespaceId) {\n if (mountedRef.current) {\n setStatus(null);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n const seq = ++reqRef.current;\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const result = await mero.admin.getMigrationStatus(namespaceId);\n if (mountedRef.current && seq === reqRef.current) {\n setStatus(result);\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [namespaceId, mero, mountedRef]);\n\n // Clear stale state the instant the namespace changes, so the panel shows a\n // loading state rather than the previous namespace's data during the refetch.\n useEffect(() => {\n setStatus(null);\n setError(null);\n }, [namespaceId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n // Live updates. The frame is a signal, not the answer: it says something\n // moved, and the re-read is what stays authoritative. This runs BEFORE the\n // poll below because whether the stream is genuinely live is what decides\n // if a caller who named no interval needs a fallback poll at all.\n const sseLive = useMigrationEvents(namespaceId, () => void refetch());\n\n // An explicit interval always wins - a caller that asked to poll keeps\n // polling. When none was named, poll only while the stream is NOT live:\n // migration facts arrive by heartbeat gossip with no push transport of their\n // own, so with neither SSE nor an interval the panel loads once and then\n // silently never updates again, with no error to show for it.\n const pollIntervalMs =\n options?.pollIntervalMs ??\n (sseLive ? undefined : DEFAULT_MIGRATION_POLL_INTERVAL_MS);\n useEffect(() => {\n if (!pollIntervalMs || !mero || !namespaceId) return;\n const handle = setInterval(() => void refetch(), pollIntervalMs);\n return () => clearInterval(handle);\n }, [pollIntervalMs, mero, namespaceId, refetch]);\n\n const rollup: MigrationStatusRollup | null = status?.rollup ?? null;\n const members: MemberMigrationStatusEntry[] = status?.members ?? [];\n\n return {\n status,\n rollup,\n members,\n allMigrated: rollup?.allMigrated ?? false,\n /**\n * When this node watched the fleet converge, or `null`. Durable, unlike\n * `allMigrated`, which is recomputed from in-TTL heartbeats and lapses back\n * to false when a member simply goes quiet.\n */\n fleetCompletedAt: status?.fleetCompletedAt ?? null,\n membersPendingSignature: rollup?.membersPendingSignature ?? 0,\n /** Members whose migrate aborted (migration-check failed or apply errored). */\n failed: rollup?.failed ?? 0,\n loading,\n error,\n refetch,\n };\n}\n\n/**\n * Bundle-version skew (#2): reads the context's installed `applicationVersion`\n * (semver) and compares it to the app-declared `expected` build constant. Any\n * mismatch (either direction) is `isStale` → \"reload to update\". Subscribes to\n * `AppVersionChanged` so a live flip updates `appVersion` without a refetch.\n */\nexport function useAppVersion(contextId?: string | null, expected?: string) {\n const { mero } = useMero();\n const [appVersion, setAppVersion] = useState<string | undefined>(undefined);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Latest-request-wins token (see useMigrationStatus).\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n if (!mero || !contextId) {\n if (mountedRef.current) {\n setAppVersion(undefined);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n const seq = ++reqRef.current;\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const context = await mero.admin.getContext(contextId);\n if (mountedRef.current && seq === reqRef.current) {\n setAppVersion(context.applicationVersion);\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [contextId, mero, mountedRef]);\n\n // Reset on context change so a stale version isn't shown during the refetch.\n useEffect(() => {\n setAppVersion(undefined);\n setError(null);\n }, [contextId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n useEffect(() => {\n if (!mero?.events || !contextId) return;\n const off = mero.events.onAppVersionChanged((event: AppVersionChangedEvent) => {\n if (event.contextId !== contextId) return;\n if (mountedRef.current && event.toVersion) {\n // Invalidate any in-flight refetch so its (older) result can't clobber\n // this live update.\n reqRef.current += 1;\n setAppVersion(event.toVersion);\n }\n });\n return off;\n }, [mero, contextId, mountedRef]);\n\n const isStale = appVersion != null && expected != null && appVersion !== expected;\n\n return { appVersion, expected, isStale, loading, error, refetch };\n}\n\n/**\n * \"Is a newer version available?\" for an Updates view. Reads a package's\n * published versions from the registry and compares the newest to the running\n * `currentVersion` (e.g. a context's `applicationVersion`). `updateAvailable`\n * is true only when the registry's newest is strictly greater. This is the\n * registry-side check the admin acts on; gate rendering on admin status at the\n * call site. Pure read — fetching nothing until both `registryUrl` and\n * `packageName` are provided.\n */\nexport function useLatestVersion(\n registryUrl?: string | null,\n packageName?: string | null,\n currentVersion?: string | null,\n) {\n const { mero } = useMero();\n const [versions, setVersions] = useState<string[]>([]);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Latest-request-wins token (see useMigrationStatus).\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n if (!mero || !registryUrl || !packageName) {\n // Invalidate any in-flight request so a late response can't repopulate\n // stale versions for the previous package after the inputs were cleared.\n reqRef.current += 1;\n if (mountedRef.current) {\n setVersions([]);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n const seq = ++reqRef.current;\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const result = await mero.admin.getRegistryVersions(registryUrl, packageName);\n if (mountedRef.current && seq === reqRef.current) {\n setVersions(result);\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [mero, registryUrl, packageName, mountedRef]);\n\n // Clear stale versions the instant the package/registry changes.\n useEffect(() => {\n setVersions([]);\n setError(null);\n }, [registryUrl, packageName]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n // getRegistryVersions returns newest-first, so [0] is the latest published.\n const latestVersion = versions[0] ?? null;\n const updateAvailable =\n latestVersion != null &&\n currentVersion != null &&\n compareSemver(latestVersion, currentVersion) > 0;\n\n return { versions, latestVersion, currentVersion, updateAvailable, loading, error, refetch };\n}\n\ninterface GroupAppVersion {\n /** Semver of the application the group currently targets (`null` until loaded). */\n version: string | null;\n /** The group's `targetApplicationId`. */\n applicationId: string | null;\n /** The installed blob differs from the one the group targets (see hook doc). */\n pendingApply: boolean;\n /** Only populated via the group-info path; `null` in the namespace path. */\n activeUpgrade: GroupUpgradeStatusResponseData;\n}\n\nconst EMPTY_GROUP_APP_VERSION: GroupAppVersion = {\n version: null,\n applicationId: null,\n pendingApply: false,\n activeUpgrade: null,\n};\n\n/** An appKey carries no \"pending\" signal when it is absent or all-zero. */\nfunction isZeroAppKey(appKey?: string): boolean {\n return !appKey || /^0+$/.test(appKey);\n}\n\n/**\n * What app version does this group run, and is there a downloaded-but-not-yet-\n * applied update? Replaces the appKey-vs-installed-blob comparison apps\n * otherwise hand-roll: `pendingApply` is true when the group's `appKey` (the\n * blob it targets) is present, non-zero, and differs from the blob actually\n * installed for its `targetApplicationId`. Deciding whether to render or gate on\n * that status (admin-only actions, etc.) is the call site's job.\n *\n * Resolution stays cheap: the group's record comes from `listNamespaces()` when\n * the id is a namespace, else from `getGroupInfo()`; `getApplication()` then\n * reads the installed version and blob. `activeUpgrade` is returned only when it\n * arrives for free on the group-info path (it is not fetched separately).\n * Subscribes to `AppVersionChanged` and refetches, since any version flip in the\n * workspace can make the rollup stale.\n */\nexport function useGroupAppVersion(groupId?: string) {\n const { mero } = useMero();\n const [data, setData] = useState<GroupAppVersion>(EMPTY_GROUP_APP_VERSION);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Latest-request-wins token (see useMigrationStatus).\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n if (!mero || !groupId) {\n if (mountedRef.current) {\n setData(EMPTY_GROUP_APP_VERSION);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n // Namespace-first resolution: a top-level group is a namespace; only\n // subgroups need the getGroupInfo fallback (which also carries\n // activeUpgrade, so we surface it without a third call).\n const namespaces = await mero.admin.listNamespaces();\n const namespace = namespaces.find((entry) => entry.namespaceId === groupId);\n\n let appKey: string | undefined;\n let applicationId: string | null;\n let activeUpgrade: GroupUpgradeStatusResponseData = null;\n\n if (namespace) {\n appKey = namespace.appKey;\n applicationId = namespace.targetApplicationId;\n } else {\n const info = await mero.admin.getGroupInfo(groupId);\n appKey = info.appKey;\n applicationId = info.targetApplicationId;\n activeUpgrade = info.activeUpgrade ?? null;\n }\n\n let version: string | null = null;\n let pendingApply = false;\n if (applicationId) {\n const { application } = await mero.admin.getApplication(applicationId);\n version = application?.version ?? null;\n if (application && !isZeroAppKey(appKey)) {\n const installedHex = base58ToHex(application.blob.bytecode).toLowerCase();\n pendingApply = appKey!.toLowerCase() !== installedHex;\n }\n }\n\n if (mountedRef.current && seq === reqRef.current) {\n setData({ version, applicationId, pendingApply, activeUpgrade });\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [groupId, mero, mountedRef]);\n\n // Clear stale state synchronously when the target group changes (and\n // invalidate any in-flight refetch). Mirrors useGroupUpgradeStatus.\n useEffect(() => {\n reqRef.current += 1;\n setData(EMPTY_GROUP_APP_VERSION);\n setError(null);\n }, [groupId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n useEffect(() => {\n if (!mero?.events || !groupId) return;\n const off = mero.events.onAppVersionChanged(() => {\n if (mountedRef.current) void refetch();\n });\n return off;\n }, [mero, groupId, refetch, mountedRef]);\n\n return { ...data, loading, error, refetch };\n}\n\n/**\n * The caller's own identity-gated entries pending re-signature (skew #1).\n * `pending` is `pendingCount > 0` (from `count_my_pending`); `authorize()` runs\n * the one-tap `migrate_my_entries` convert and folds the resulting `remaining`\n * back into the count.\n */\nexport function useMyAuthoredMigration(contextId?: string | null) {\n const { mero } = useMero();\n const [summary, setSummary] = useState<MigrateMyEntriesSummary | null>(null);\n const [pendingCount, setPendingCount] = useState(0);\n const mountedRef = useMountedRef();\n const { loading, error, run } = useAsyncMutation();\n // Latest-request-wins token (see useMigrationStatus).\n const reqRef = useRef(0);\n\n const refresh = useCallback(async () => {\n if (!mero || !contextId) {\n if (mountedRef.current) setPendingCount(0);\n return;\n }\n const seq = ++reqRef.current;\n try {\n const count = await mero.rpc.countMyPending(contextId);\n if (mountedRef.current && seq === reqRef.current) setPendingCount(count);\n } catch {\n // best-effort count; leave the previous value on a transient failure\n }\n }, [mero, contextId, mountedRef]);\n\n // Clear stale per-context state synchronously when the target changes (and\n // invalidate any in-flight refresh), so the banner doesn't flash the previous\n // context's count until the new count resolves. Mirrors useMigrationStatus.\n useEffect(() => {\n reqRef.current += 1;\n setPendingCount(0);\n setSummary(null);\n }, [contextId]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const authorize = useCallback(async () => {\n if (!mero || !contextId) return null;\n const result = await run(() => mero.rpc.migrateMyEntries(contextId));\n if (result && mountedRef.current) {\n // Invalidate any in-flight refresh so a stale count can't overwrite the\n // authoritative post-convert remaining.\n reqRef.current += 1;\n setSummary(result);\n setPendingCount(result.remaining);\n }\n return result;\n }, [mero, contextId, run, mountedRef]);\n\n return {\n summary,\n pendingCount,\n pending: pendingCount > 0,\n authorize,\n loading,\n error,\n refresh,\n };\n}\n\n// ---- Blob Hooks ----\n\n/**\n * Options for the blob READ hooks.\n *\n * `contextId` is what picks the mode, and the two modes have wildly different\n * costs:\n *\n * - **omitted** — local-only read. The node answers from its own blob store\n * and returns immediately, or 404s.\n * - **supplied** — network discovery. The node probes that context's peers\n * (availability nodes first) for a holder. Core bounds the search by a ~30s\n * deadline, and for {@link useBlobUrl} the byte transfer is on top of that.\n *\n * So `loading` is load-bearing UI state on these hooks, not decoration: a\n * discovery read can plausibly spin for half a minute before it resolves\n * either way. Render a spinner (or a cancel affordance) accordingly.\n */\nexport interface BlobHookOptions {\n /** Context whose peers to probe. Omit for a local-only read. */\n contextId?: string;\n}\n\n/** Options for {@link useBlobUrl}. */\nexport interface UseBlobUrlOptions extends BlobHookOptions {\n /**\n * MIME type stamped on the `Blob` the object URL points at. The blob read\n * itself carries no type, and a peer-sourced answer has no `mimeType` at\n * all, so pass it when the consumer needs one (`<img>` sniffs; a download\n * `<a>` and an `<iframe>` do not).\n */\n type?: string;\n}\n\n/**\n * True when the failure is the node saying \"nobody has this blob\" (HTTP 404)\n * rather than a transport/auth failure.\n *\n * Duck-typed on `status` rather than `instanceof HTTPError`: a consumer app can\n * easily end up with two copies of mero-js (bundled + peer), and an\n * `instanceof` across that boundary silently reports false.\n */\nfunction isBlobNotFound(error: Error | null): boolean {\n return !!error && (error as { status?: unknown }).status === 404;\n}\n\n/**\n * A blob's presence and size, WITHOUT downloading it — the cheap half of the\n * blob surface, and the one to ask before pulling something large.\n *\n * `blobId` follows the same `string | null` convention as the other read\n * hooks: null/undefined means \"no read\", not \"read nothing\" — nothing is\n * fetched and `info` stays null.\n *\n * `hash` and `mimeType` on the result are genuinely optional: a peer probe\n * answers with presence and size only, so a discovery-sourced hit carries\n * neither. `info.source` (`'local' | 'peer'`, undefined on nodes that predate\n * the header) tells the two apart — do not treat a missing `mimeType` as a\n * malformed response.\n *\n * `notFound` distinguishes the legitimate \"no holder\" outcome (the node\n * answered 404) from a transport failure. `error` is set in BOTH cases — this\n * hook does not swallow the 404, it only labels it.\n *\n * Latency: immediate without `contextId`, up to core's ~30s discovery deadline\n * with one. See {@link BlobHookOptions}.\n */\nexport function useBlobInfo(blobId?: string | null, options?: BlobHookOptions) {\n const { mero } = useMero();\n const contextId = options?.contextId;\n const { data, loading, error, refetch } = useAsyncResource<GetBlobInfoResponseData | null>(\n mero && blobId\n ? () => mero.admin.getBlobInfo(blobId, contextId ? { contextId } : undefined)\n : null,\n null,\n [mero, blobId, contextId],\n );\n\n return { info: data, notFound: isBlobNotFound(error), loading, error, refetch };\n}\n\n/**\n * A blob's bytes as an object URL, ready for `<img src>`, an `<a href>`\n * download, or an `<iframe>`.\n *\n * Lifecycle is handled here so the consumer never has to revoke: the URL is\n * revoked on unmount, and whenever `blobId`/`contextId`/`type` change. `url`\n * goes back to null synchronously on such a change, so a revoked URL is never\n * handed out as the current one — render off `url` and it is always live.\n *\n * A response for a superseded `blobId` is dropped before an object URL is even\n * created, so an out-of-order arrival can neither overwrite the newer result\n * nor leak.\n *\n * Latency: this is the expensive hook. Without `contextId` it is a local read;\n * with one it is discovery (core's ~30s deadline) PLUS the transfer of the\n * bytes. Prefer {@link useBlobInfo} to decide whether the download is worth\n * starting, and always render `loading`.\n *\n * `notFound` marks the node's 404 (\"no peer holds this\") apart from a\n * transport failure; `error` is set for both.\n */\nexport function useBlobUrl(blobId?: string | null, options?: UseBlobUrlOptions) {\n const { mero } = useMero();\n const contextId = options?.contextId;\n const type = options?.type;\n const mountedRef = useMountedRef();\n const [url, setUrl] = useState<string | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n // Latest-request-wins token, same shape as useAsyncResource's.\n const reqRef = useRef(0);\n // The URL currently handed out, held in a ref so revocation never depends on\n // a render having happened.\n const urlRef = useRef<string | null>(null);\n\n const revoke = useCallback(() => {\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n urlRef.current = null;\n }\n }, []);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n if (!mero || !blobId) return;\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n try {\n const bytes = await mero.admin.getBlob(blobId, contextId ? { contextId } : undefined);\n // Check BEFORE creating the object URL: a loser allocates nothing, so\n // there is nothing to leak and nothing to overwrite the winner with.\n if (!mountedRef.current || seq !== reqRef.current) return;\n revoke();\n const objectUrl = URL.createObjectURL(new Blob([bytes], type ? { type } : undefined));\n urlRef.current = objectUrl;\n setUrl(objectUrl);\n } catch (err) {\n if (mountedRef.current && seq === reqRef.current) setError(toError(err));\n } finally {\n if (mountedRef.current && seq === reqRef.current) setLoading(false);\n }\n }, [mero, blobId, contextId, type, revoke, mountedRef]);\n\n // Invalidate the in-flight request and drop the current URL synchronously\n // when the inputs change, so the consumer never sees the previous blob's URL\n // (revoked or not) attributed to the new id.\n useEffect(() => {\n reqRef.current += 1;\n revoke();\n setUrl(null);\n setError(null);\n setLoading(false);\n }, [mero, blobId, contextId, type, revoke]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n // Final revoke on unmount. Separate from the input-change effect above so it\n // runs exactly once, on teardown, whatever the deps did.\n useEffect(() => revoke, [revoke]);\n\n return { url, notFound: isBlobNotFound(error), loading, error, refetch };\n}\n\n/**\n * Upload bytes to the node's blob store. Mutation-shaped, like the other\n * write hooks: `uploadBlob` resolves to `{ blobId, size }`, or null when the\n * client is absent or the call failed (read `error` for which).\n *\n * Pass `contextId` to announce the blob to that context, which is what lets\n * the context's other members later discover it with {@link useBlobUrl} /\n * {@link useBlobInfo}. Without it the blob is only readable on this node.\n */\nexport function useUploadBlob() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const uploadBlob = useCallback(\n async (request: UploadBlobRequest) => {\n if (!mero) return null;\n return run(() => mero.admin.uploadBlob(request));\n },\n [mero, run],\n );\n\n return { uploadBlob, loading, error };\n}\n","import type { ReactNode } from 'react';\nimport { useMyAuthoredMigration } from '../hooks';\n\nexport interface MigrationPendingBannerProps {\n /** Context whose authored entries to check / convert. */\n contextId: string;\n className?: string;\n /** Override the default prompt text. */\n children?: ReactNode;\n /** Fired once a convert leaves nothing pending (`remaining === 0`). */\n onMigrated?: () => void;\n}\n\n/**\n * Shows only when the current identity has entries below the target schema\n * (skew #1). A single button runs the one-tap `migrate_my_entries` convert and\n * the banner clears itself once nothing is pending.\n */\nexport function MigrationPendingBanner({\n contextId,\n className,\n children,\n onMigrated,\n}: MigrationPendingBannerProps) {\n const { pending, pendingCount, authorize, loading } = useMyAuthoredMigration(contextId);\n\n if (!pending) return null;\n\n const handleClick = async () => {\n const result = await authorize();\n if (result && result.remaining === 0) {\n onMigrated?.();\n }\n };\n\n const message =\n children ??\n `You have ${pendingCount} ${pendingCount === 1 ? 'entry' : 'entries'} to re-sign after a recent upgrade.`;\n\n return (\n <div className={className} data-testid=\"migration-pending-banner\" role=\"status\">\n <span>{message}</span>\n <button type=\"button\" onClick={handleClick} disabled={loading}>\n {loading ? 'Migrating…' : 'Migrate my data'}\n </button>\n </div>\n );\n}\n","import { useMigrationStatus } from '../hooks';\n\nexport interface MigrationAdminPanelProps {\n /** Namespace whose migration rollup to display. */\n namespaceId: string;\n /** Re-fetch interval; migration facts arrive via heartbeat gossip. */\n pollIntervalMs?: number;\n className?: string;\n}\n\n/**\n * Operator view of a namespace's migration rollup (skew #3): the cohort\n * counters, `membersPendingSignature`, and a per-member table. Read-only —\n * pair with the upgrade-trigger hooks to drive a migration.\n */\nexport function MigrationAdminPanel({ namespaceId, pollIntervalMs, className }: MigrationAdminPanelProps) {\n const { status, rollup, members, membersPendingSignature, failed, error } = useMigrationStatus(\n namespaceId,\n { pollIntervalMs },\n );\n\n // Surface a real failure rather than the misleading \"no status\" message.\n if (error && !status) {\n return (\n <div className={className} data-testid=\"migration-admin-panel\">\n Failed to load migration status: {error.message}\n </div>\n );\n }\n\n // Before the first successful fetch (initial paint or in-flight), show\n // loading — a successful read always yields a rollup, so a null status here\n // means \"not loaded yet\", never \"empty\".\n if (!status || !rollup) {\n return <div className={className} data-testid=\"migration-admin-panel\">Loading migration status…</div>;\n }\n\n return (\n <div className={className} data-testid=\"migration-admin-panel\">\n {error && (\n // A poll failed after data was already loaded — keep showing the last\n // good rollup but flag that it may be stale.\n <div data-testid=\"migration-status-error\" role=\"alert\">\n Could not refresh migration status: {error.message}\n </div>\n )}\n <dl>\n <div><dt>Target version</dt><dd>{status.targetVersion}</dd></div>\n <div><dt>Migrated</dt><dd>{rollup.migrated}</dd></div>\n <div><dt>In progress</dt><dd>{rollup.inProgress}</dd></div>\n <div><dt>Unknown</dt><dd>{rollup.unknown}</dd></div>\n <div><dt>Failed</dt><dd data-testid=\"migration-failed-count\">{failed}</dd></div>\n <div><dt>Total</dt><dd>{rollup.total}</dd></div>\n <div><dt>All migrated</dt><dd>{rollup.allMigrated ? 'yes' : 'no'}</dd></div>\n <div>\n <dt>Members pending signature</dt>\n <dd data-testid=\"members-pending-signature\">{membersPendingSignature}</dd>\n </div>\n </dl>\n <table>\n <thead>\n <tr><th>Peer</th><th>State</th><th>Schema</th><th>Pending</th><th>Reason</th></tr>\n </thead>\n <tbody>\n {members.map((m) => (\n <tr key={m.peer} data-testid=\"migration-member-row\">\n <td>{m.peer}</td>\n <td>{m.state}</td>\n <td>{m.report?.schemaVersion ?? '—'}</td>\n <td>{m.report?.authoredRemaining ?? '—'}</td>\n <td>{m.report?.migrationFailed ?? '—'}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n );\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["#style-inject:#style-inject","../src/components/styles.css","../src/types.ts","../src/auth/node-trust.ts","../src/auth/token-adoption.ts","../src/storage/index.ts","../src/delegated/session.ts","../src/context/MeroContext.tsx","../src/components/CalimeroLogo.tsx","../src/theme.ts","../src/components/LoginModal.tsx","../src/components/ConnectButton.tsx","../src/components/ConnectButtonAccount.tsx","../src/utils/base58.ts","../src/delegated/create-context.ts","../src/delegated/govern.ts","../src/hooks/index.ts","../src/components/MigrationPendingBanner.tsx","../src/components/MigrationAdminPanel.tsx","../src/delegated/relay-from-invitation.ts","../src/delegated/join-with-node.ts","../src/delegated/bootstrap-from-invitation.ts","../src/delegated/useDelegatedBootstrap.ts","../src/join/useJoinInvitation.ts"],"names":["AppMode","ConnectionType","refreshToken","createSignedReleaseVerifier","fetchNodeRelease","cloudNodeReleaseUrl","DEFAULT_RELEASE_MIRROR","fetchNodeReleaseVersion","attestRelayNodeKey","login","defaultAudience","createMeroClient","client","createContext","useMemo","LocalStorageTokenStore","useState","useRef","parseAuthCallback","useCallback","MeroJs","buildAuthLoginUrl","useEffect","AuthRevokedError","HTTPError","useContext","jsxs","jsx","DEFAULT_LOCAL_NODE_PORTS","discoverLocalNodes","nodeEndpoint","Fragment","createPortal","readEnrolmentCallback","completeDeviceEnrolment","CloudClient","deviceEnrolmentUrl","fetch","RelayClient","subgroupCreation","memberAddedOp","classifyError","memberJoinedOpenOp","signerFromSecret","groupDeletedOp","memberRemovedOp","memberRoleSetOp","defaultCapabilitiesSetOp","subgroupVisibilitySetOp","groupMetadataSetOp","memberMetadataSetOp","contextMetadataSetOp","groupReparentedOp","contextDetachedOp","compareSemver","createLocalStorageNonceSource","signMemberJoinOp"],"mappings":";;;;;;;;AACyB,SAAR,YAA6B,GAAA,EAAK,EAAE,QAAA,EAAS,GAAI,EAAC,EAAG;AAC1D,EAAA,IAAY,OAAO,QAAA,KAAa,WAAA,EAAa;AAE7C,EAAA,MAAM,OAAO,QAAA,CAAS,IAAA,IAAQ,SAAS,oBAAA,CAAqB,MAAM,EAAE,CAAC,CAAA;AACrE,EAAA,MAAM,KAAA,GAAQ,QAAA,CAAS,aAAA,CAAc,OAAO,CAAA;AAC5C,EAAA,KAAA,CAAM,IAAA,GAAO,UAAA;AAEb,EAAA,IAAI,aAAa,KAAA,EAAO;AACtB,IAAA,IAAI,KAAK,UAAA,EAAY;AACnB,MAAA,IAAA,CAAK,YAAA,CAAa,KAAA,EAAO,IAAA,CAAK,UAAU,CAAA;AAAA,IAC1C,CAAA,MAAO;AACL,MAAA,IAAA,CAAK,YAAY,KAAK,CAAA;AAAA,IACxB;AAAA,EACF,CAAA,MAAO;AACL,IAAA,IAAA,CAAK,YAAY,KAAK,CAAA;AAAA,EACxB;AAEA,EAAA,IAAI,MAAM,UAAA,EAAY;AACpB,IAAA,KAAA,CAAM,W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AC,QAAQ,EAAA,EAAI;AACf,UAAA,MAAM,OAAO,MAAA,CAAO,IAAI,KAAA,CAAM,OAAA,CAAQ,MAAM,CAAA,EAAG,OAAA,CAAQ,MAAA,KAAW,MAAA,GAAY,EAAE,MAAA,EAAQ,OAAA,CAAQ,MAAA,EAAO,GAAI,EAAE,CAAA;AAAA,QAC/G;AAAA,MACF,CAAA;AAAA,MACA;AAAA,KACF,CAAA;AAAA,IACA,CAAC,gBAAgB,WAAW;AAAA,GAC9B;AAEA,EAAA,OAAO,EAAE,cAAA,EAAgB,OAAA,EAAS,WAAA,EAAa,kBAAA,EAAmB;AACpE","file":"index.cjs","sourcesContent":["\n export default function styleInject(css, { insertAt } = {}) {\n if (!css || typeof document === 'undefined') return\n \n const head = document.head || document.getElementsByTagName('head')[0]\n const style = document.createElement('style')\n style.type = 'text/css'\n \n if (insertAt === 'top') {\n if (head.firstChild) {\n head.insertBefore(style, head.firstChild)\n } else {\n head.appendChild(style)\n }\n } else {\n head.appendChild(style)\n }\n \n if (style.styleSheet) {\n style.styleSheet.cssText = css\n } else {\n style.appendChild(document.createTextNode(css))\n }\n }\n ","import styleInject from '#style-inject';styleInject(\":root {\\n --mero-bg: #0d1117;\\n --mero-bg-secondary: #161b22;\\n --mero-bg-tertiary: #1c2128;\\n --mero-text: #e6edf3;\\n --mero-text-secondary: #8b949e;\\n --mero-accent: #a5ff11;\\n --mero-accent-hover: #8ed40d;\\n --mero-on-primary: #0d1117;\\n --mero-error: #ff6b6b;\\n --mero-border: #30363d;\\n --mero-disabled: #555555;\\n --mero-shadow: rgba(0, 0, 0, 0.5);\\n --mero-overlay: rgba(0, 0, 0, 0.75);\\n --mero-radius: 8px;\\n}\\n.mero-connect-button {\\n display: inline-flex;\\n align-items: center;\\n justify-content: center;\\n gap: 8px;\\n padding: 10px 20px;\\n background-color: var(--mero-accent);\\n border: 1px solid var(--mero-accent);\\n border-radius: var(--mero-radius);\\n cursor: pointer;\\n font-size: 14px;\\n font-weight: 600;\\n letter-spacing: 0.01em;\\n color: var(--mero-on-primary);\\n transition:\\n background-color 0.15s ease,\\n border-color 0.15s ease,\\n box-shadow 0.15s ease,\\n transform 0.1s ease;\\n min-width: 140px;\\n box-sizing: border-box;\\n font-family:\\n \\\"Inter\\\",\\n -apple-system,\\n BlinkMacSystemFont,\\n \\\"Segoe UI\\\",\\n Roboto,\\n Oxygen,\\n Ubuntu,\\n sans-serif;\\n -webkit-font-smoothing: antialiased;\\n -moz-osx-font-smoothing: grayscale;\\n line-height: 1;\\n}\\n.mero-connect-button:hover:not(.mero-connected):not(.mero-reconnecting) {\\n background-color: var(--mero-accent-hover);\\n border-color: var(--mero-accent-hover);\\n box-shadow: 0 0 0 4px rgba(165, 255, 17, 0.18);\\n box-shadow: 0 0 0 4px color-mix(in srgb, var(--mero-accent) 18%, transparent);\\n}\\n.mero-connect-button:active:not(.mero-connected):not(.mero-reconnecting) {\\n transform: translateY(1px);\\n}\\n.mero-connect-button:focus-visible {\\n outline: none;\\n box-shadow: 0 0 0 3px rgba(165, 255, 17, 0.45);\\n box-shadow: 0 0 0 3px color-mix(in srgb, var(--mero-accent) 45%, transparent);\\n}\\n.mero-connect-button.mero-logo-only {\\n min-width: 0;\\n width: 40px;\\n height: 40px;\\n padding: 0;\\n gap: 0;\\n}\\n.mero-connect-button.mero-connected {\\n background-color: var(--mero-accent);\\n color: var(--mero-on-primary);\\n border-color: var(--mero-accent);\\n}\\n.mero-connect-button.mero-connected:hover {\\n background-color: var(--mero-accent-hover);\\n border-color: var(--mero-accent-hover);\\n}\\n.mero-connect-button.mero-reconnecting {\\n background-color: var(--mero-bg-secondary);\\n color: var(--mero-text-secondary);\\n border-color: var(--mero-border);\\n cursor: not-allowed;\\n}\\n.mero-connect-container {\\n position: relative;\\n display: inline-block;\\n}\\n.mero-dropdown {\\n position: absolute;\\n top: 100%;\\n left: 0;\\n background-color: var(--mero-bg-secondary);\\n border: 1px solid var(--mero-border);\\n border-radius: var(--mero-radius);\\n margin-top: 6px;\\n padding: 0;\\n z-index: 1001;\\n width: 100%;\\n min-width: 180px;\\n overflow: hidden;\\n box-shadow: 0 8px 24px var(--mero-shadow);\\n}\\n.mero-dropdown-info {\\n padding: 10px 16px;\\n color: var(--mero-text-secondary);\\n font-size: 13px;\\n border-bottom: 1px solid var(--mero-border);\\n white-space: nowrap;\\n overflow: hidden;\\n text-overflow: ellipsis;\\n max-width: 220px;\\n}\\n.mero-dropdown-item {\\n display: block;\\n width: 100%;\\n padding: 10px 16px;\\n background: none;\\n border: none;\\n color: var(--mero-text);\\n text-align: left;\\n cursor: pointer;\\n font-size: 14px;\\n text-decoration: none;\\n font-family: inherit;\\n}\\n.mero-dropdown-item:hover {\\n background-color: var(--mero-accent);\\n color: var(--mero-on-primary);\\n}\\n.mero-logo {\\n width: 24px;\\n height: 24px;\\n color: currentColor;\\n}\\n@keyframes meroFadeIn {\\n from {\\n opacity: 0;\\n }\\n to {\\n opacity: 1;\\n }\\n}\\n@keyframes meroSlideIn {\\n from {\\n transform: translateY(-12px);\\n opacity: 0;\\n }\\n to {\\n transform: translateY(0);\\n opacity: 1;\\n }\\n}\\n@keyframes meroSpin {\\n to {\\n transform: rotate(360deg);\\n }\\n}\\n\")","/**\n * Types for mero-react\n */\n\nimport type { MeroClient, MeroJs, TokenStore } from '@calimero-network/mero-js';\nimport type { DelegatedSession } from './delegated/session';\n\n/**\n * Application mode determines the permission scope\n */\nexport enum AppMode {\n /**\n * @deprecated since 2.1.0 — SingleContext is no longer supported and will\n * be removed in 3.0.0. Auth-frontend no longer drives\n * context/namespace/group selection; the auth callback returns only\n * `access_token`, `refresh_token`, `application_id`, and `node_url`.\n * Switch to {@link AppMode.MultiContext} and have your app manage\n * context selection itself.\n *\n * Migration: see `example/app/src/pages/context/SelectContext.tsx` for a\n * reference implementation. It uses `useContexts` /\n * `useNamespacesForApplication` for listing, then calls\n * `mero.admin.createNamespace` / `createGroupInNamespace` /\n * `createContext` directly (rather than the `useCreate*` hooks) so the\n * underlying server error surfaces to the user instead of being\n * swallowed by `useAsyncMutation`.\n */\n SingleContext = 'single-context',\n /** Multi-context: user can manage multiple contexts */\n MultiContext = 'multi-context',\n /** Admin: full administrative access */\n Admin = 'admin',\n}\n\n/**\n * Connection type for the login modal\n */\nexport enum ConnectionType {\n /**\n * @deprecated The login modal no longer has Local/Remote tabs — it always\n * shows node discovery + manual URL entry. Behaves the same as `Remote`.\n */\n RemoteAndLocal = 'remote-and-local',\n /** Open the login modal (node discovery + manual URL entry) */\n Remote = 'remote',\n /**\n * @deprecated The hardcoded default-local-node view was removed. Behaves\n * the same as `Remote`.\n */\n Local = 'local',\n /** Custom URL (skip modal) */\n Custom = 'custom',\n}\n\n/**\n * Custom connection configuration\n */\nexport interface CustomConnectionConfig {\n type: ConnectionType.Custom;\n url: string;\n}\n\n/**\n * Context for an application\n */\nexport interface AppContext {\n contextId: string;\n executorId: string;\n applicationId: string;\n}\n\n/**\n * Result of an RPC execution\n */\nexport interface ExecutionResult<T = unknown> {\n success: boolean;\n result?: T;\n error?: string;\n}\n\nexport interface ApplicationContextRecord {\n contextId: string;\n applicationId: string;\n}\n\nexport interface ContextDiscoveryOptions {\n applicationId: string;\n knownContextIds?: string[];\n targetAlias?: string;\n pollIntervalMs?: number;\n timeoutMs?: number;\n}\n\nexport interface ContextDiscoveryState {\n context: ApplicationContextRecord | null;\n loading: boolean;\n error: Error | null;\n discover: () => Promise<ApplicationContextRecord | null>;\n reset: () => void;\n}\n\n/**\n * Mero context value exposed by useMero hook\n */\nexport interface MeroContextValue {\n /**\n * The connected client, or null.\n *\n * Two shapes, because there are two ways to connect: a node login yields a\n * `MeroJs`, an account + relay connection yields a relay-transport\n * `MeroClient`. Both expose `rpc` as an `ExecuteTransport`, which is what a\n * generated ABI client depends on — so application logic is identical across\n * the two and needs no branch.\n *\n * The union is deliberately not flattened behind a cast. A relay client has\n * no `admin`, so code reaching for one should not typecheck as though it\n * were there; narrow with {@link MeroContextValue.isDelegated} first.\n */\n mero: MeroJs | MeroClient | null;\n /** Whether the user is authenticated */\n isAuthenticated: boolean;\n /** Whether the connection is online */\n isOnline: boolean;\n /** The current node URL */\n nodeUrl: string | null;\n /** The application ID */\n applicationId: string | null;\n /** The context ID (from auth flow) */\n contextId: string | null;\n /** The context identity / executor public key (from auth flow) */\n contextIdentity: string | null;\n /** Connect to a node URL and start auth flow */\n connectToNode: (url: string) => void;\n /**\n * Adopt a delegated connection: an account, a device that account certified,\n * and a relay that writes on its behalf.\n *\n * Installs the relay client immediately — there is no redirect and no token to\n * wait for, because every request carries its own warrant.\n */\n connectWithAccount: (session: DelegatedSession) => void;\n /**\n * Whether the connection is delegated (account + relay) rather than a node\n * login. True means `mero` is a relay-transport client, authenticated by the\n * account's device certificate: `rpc` writes under warrants, and `admin` and\n * `events` answer caller-scoped — this account's own contexts and namespaces,\n * and events only for contexts it is a member of.\n */\n isDelegated: boolean;\n /**\n * What this connection may do, so an app asks WHAT IS ALLOWED instead of\n * which transport it runs on. A node login can do everything; an account on\n * a relay can create contexts (delegated creation) but not namespaces or\n * invitations — those are a node's own operations today. A capability that\n * later becomes available to accounts turns true here with no app change.\n */\n can: MeroCapabilities;\n /**\n * The app's registry identity, as the provider was given it. An account\n * founding a namespace names this application for it, since a namespace\n * founded through a relay starts with none.\n */\n app: { packageName?: string; packageVersion?: string; registryUrl?: string };\n /** Logout and clear tokens */\n logout: () => void;\n /** Loading state */\n isLoading: boolean;\n}\n\n/**\n * MeroProvider configuration\n */\nexport interface MeroProviderConfig {\n /** Application mode */\n mode: AppMode;\n /** Package name (for registry-based apps) */\n packageName?: string;\n /** Package version (optional, defaults to latest) */\n packageVersion?: string;\n /** Registry URL (optional) */\n registryUrl?: string;\n /** Request timeout in milliseconds */\n timeoutMs?: number;\n /**\n * Origins the OAuth callback is allowed to authenticate against. Defends\n * against a malicious `node_url` in the callback URL (token exfiltration):\n * the node login was initiated with is always trusted, and this allowlist\n * additionally permits direct-callback entry to known nodes. When neither is\n * available (no initiated node and no allowlist) a callback node_url is\n * rejected and a security error is logged.\n */\n allowedNodeUrls?: string[];\n /**\n * Token store for access/refresh tokens. Defaults to a localStorage-backed\n * store that persists across reloads.\n *\n * SECURITY: localStorage tokens — including the refresh token — are readable\n * by any script on the page, so an XSS bug can exfiltrate them. For sensitive\n * deployments pass a `MemoryTokenStore` (session-only) or a store backed by an\n * HttpOnly cookie set by your auth service.\n */\n tokenStore?: TokenStore;\n}\n\n/** See {@link MeroContextValue.can}. */\nexport interface MeroCapabilities {\n /** Found a namespace. */\n readonly createNamespace: boolean;\n /** Create a context inside a namespace this connection belongs to. */\n readonly createContext: boolean;\n /** Mint an invitation to a namespace. */\n readonly invite: boolean;\n}\n","/**\n * Trust decision for the node URL an OAuth callback wants us to authenticate\n * against.\n *\n * The auth flow redirects the browser to a node's auth UI and back to the app\n * with `access_token` / `refresh_token` / `node_url` in the callback URL. That\n * URL is attacker-influenceable, so a malicious `node_url` would otherwise make\n * the SDK send the freshly-minted tokens to an attacker's node (exfiltration).\n *\n * Defense: only authenticate against a node we can independently trust — the\n * node login was *initiated* with (saved before the redirect), or an\n * app-configured allowlist.\n */\n\n/** True iff both URLs parse and share the same origin (scheme + host + port). */\nexport function sameOrigin(a: string, b: string): boolean {\n try {\n return new URL(a).origin === new URL(b).origin;\n } catch {\n return false;\n }\n}\n\nexport interface ResolveTrustedNodeParams {\n /** `node_url` from the OAuth callback (untrusted, attacker-influenceable). */\n candidate: string | null | undefined;\n /** Node URL login was initiated with, saved before the redirect (trusted). */\n initiated: string | null;\n /** Additional trusted origins, for direct-callback entry without an initiated node. */\n allowedNodeUrls?: string[];\n}\n\nexport interface TrustedNodeResult {\n /** The node URL that is safe to authenticate against, or null. */\n url: string | null;\n /** A candidate node_url was present but could not be trusted (likely an attack). */\n rejected: boolean;\n}\n\n/**\n * Decide which node URL, if any, is safe to authenticate against.\n *\n * - No candidate → fall back to the initiated node.\n * - Candidate + initiated node → must share the initiated node's origin, else reject.\n * - Candidate + no initiated node + allowlist → must be in the allowlist, else reject.\n * - Candidate + no trust anchor (no initiated node and no allowlist) → reject. There is\n * nothing to validate the attacker-influenceable callback against, so refusing is the\n * safe default. The normal flow always records the initiated node (via `connectToNode`)\n * before redirecting; configure `allowedNodeUrls` to permit direct-callback entry.\n */\nexport function resolveTrustedNodeUrl(params: ResolveTrustedNodeParams): TrustedNodeResult {\n const { candidate, initiated, allowedNodeUrls } = params;\n\n if (!candidate) {\n return { url: initiated ?? null, rejected: false };\n }\n\n if (initiated) {\n return sameOrigin(candidate, initiated)\n ? { url: candidate, rejected: false }\n : { url: null, rejected: true };\n }\n\n if (allowedNodeUrls && allowedNodeUrls.length > 0) {\n return allowedNodeUrls.some((u) => sameOrigin(candidate, u))\n ? { url: candidate, rejected: false }\n : { url: null, rejected: true };\n }\n\n return { url: null, rejected: true };\n}\n","/**\n * Decide whether the token bundle carried in an SSO callback hash may replace\n * the bundle already in the token store.\n *\n * Since core 0.11.0 (calimero-network/core#3083) refresh tokens are SINGLE-USE:\n * every `POST /auth/refresh` consumes the presented refresh token and returns a\n * new one. Re-presenting a consumed refresh token is treated as theft — the node\n * answers 401 `x-auth-error: token_reuse` and revokes the whole token family, so\n * *every* holder is hard-logged-out.\n *\n * That makes an unconditional `tokenStore.setTokens(callbackBundle)` on the SSO\n * callback path actively dangerous. A desktop host (or any SSO initiator) hands\n * the app a token bundle in the URL hash; if mero-js has already rotated the\n * stored refresh token, writing the hash bundle over it resurrects a *consumed*\n * refresh token. The next refresh presents it → `token_reuse` → family revoked.\n *\n * So the hash bundle is adopted only when it is safe:\n * - there is no stored bundle (a genuinely fresh login), or\n * - the node changed (the stored bundle belongs to a different node), or\n * - the hash tokens are genuinely NEWER than what is stored, or\n * - the stored bundle is missing a refresh token that the hash can supply.\n *\n * Anything else — a stale hash, or a hash replaying the access token we already\n * hold — is ignored, leaving the live (possibly rotated) bundle untouched.\n */\n\nimport type { TokenData } from '@calimero-network/mero-js';\nimport { sameOrigin } from './node-trust';\n\nconst HOUR_MS = 3_600_000;\n\ninterface JwtClaims {\n /** Issued-at (seconds). The authoritative rotation-order signal when present. */\n iat?: number;\n /** Expiry (seconds). */\n exp?: number;\n}\n\n/**\n * Decode a JWT's payload claims without verifying the signature.\n *\n * Verification is the node's job — we only need the ordering claims to decide\n * which of two bundles is newer, and both bundles are already node-trusted by\n * the time we get here (see `resolveTrustedNodeUrl`).\n *\n * Returns null for anything that is not a decodable three-part JWT (opaque\n * tokens, test fixtures, garbage).\n */\nexport function decodeJwtClaims(token: string): JwtClaims | null {\n try {\n const parts = token.split('.');\n if (parts.length !== 3) return null;\n let b64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');\n while (b64.length % 4) b64 += '=';\n const payload: unknown = JSON.parse(atob(b64));\n if (!payload || typeof payload !== 'object') return null;\n const { iat, exp } = payload as JwtClaims;\n return {\n iat: typeof iat === 'number' && iat > 0 ? iat : undefined,\n exp: typeof exp === 'number' && exp > 0 ? exp : undefined,\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Absolute expiry (ms) of an access token, from its `exp` claim.\n *\n * Mirrors mero-js's internal `expiresAtFromJwt` (which it does not export —\n * checked against mero-js 6.1.0), including the \"assume one hour\" fallback for\n * tokens whose expiry we cannot read.\n */\nexport function expiresAtFromJwt(token: string, fallbackMs: number = Date.now() + HOUR_MS): number {\n const exp = decodeJwtClaims(token)?.exp;\n return exp ? exp * 1000 : fallbackMs;\n}\n\n/**\n * Is the callback's access token newer than the one we already hold?\n *\n * Prefers `iat` (issued-at) — the direct rotation-order signal — and falls back\n * to `exp`, then to the stored bundle's recorded `expires_at`. When the answer\n * cannot be established the token is NOT considered newer: refusing to adopt\n * costs a redundant login at worst, whereas adopting a stale bundle burns the\n * whole token family.\n */\nfunction isCallbackNewer(callbackAccessToken: string, stored: TokenData): boolean {\n const incoming = decodeJwtClaims(callbackAccessToken);\n if (!incoming) return false;\n\n const current = decodeJwtClaims(stored.access_token);\n if (current) {\n if (incoming.iat !== undefined && current.iat !== undefined && incoming.iat !== current.iat) {\n return incoming.iat > current.iat;\n }\n if (incoming.exp !== undefined && current.exp !== undefined && incoming.exp !== current.exp) {\n return incoming.exp > current.exp;\n }\n // Same claims (a replay of the token we already hold), or nothing to compare\n // on — either way the callback brings nothing new.\n return false;\n }\n\n // Stored access token is not a decodable JWT — compare against the expiry the\n // store recorded for it.\n return incoming.exp !== undefined && incoming.exp * 1000 > stored.expires_at;\n}\n\n/** Why the SSO hash bundle was (or was not) written to the token store. */\nexport type TokenAdoptionReason =\n /** No stored bundle — a genuinely fresh login. Seed from the hash. */\n | 'fresh-login'\n /** The stored bundle belongs to a different node. Re-seed from the hash. */\n | 'node-changed'\n /** The hash tokens are genuinely newer than the stored ones. */\n | 'newer'\n /** Same session, but the stored bundle has no refresh token and the hash does. */\n | 'fill-refresh'\n /** The hash tokens are stale, or replay the access token we already hold. */\n | 'stale';\n\nexport type TokenAdoptionDecision =\n | { adopt: true; tokens: TokenData; reason: Exclude<TokenAdoptionReason, 'stale'> }\n | { adopt: false; reason: 'stale' };\n\nexport interface ResolveTokenAdoptionParams {\n /** Access token from the callback hash. Always present (mero-js returns null otherwise). */\n callbackAccessToken: string;\n /**\n * Refresh token from the callback hash. `parseAuthCallback` yields `''` when the\n * hash carries no `refresh_token` — hosts are moving to access-only bundles\n * precisely so they cannot hand back a rotated-away refresh token.\n */\n callbackRefreshToken: string;\n /** Trusted node URL the callback resolved to (see `resolveTrustedNodeUrl`). */\n callbackNodeUrl: string;\n /** Bundle currently in the token store — mero-js may have rotated it already. */\n stored: TokenData | null;\n /** Node URL the stored bundle was issued by, i.e. the node URL before this callback. */\n storedNodeUrl: string | null;\n}\n\n/**\n * Decide what (if anything) to write to the token store for an SSO callback.\n *\n * Never returns a bundle with an empty `refresh_token` when a refresh token for\n * the same node is already stored: an access-only hash bundle is MERGED over the\n * stored one, so adopting a fresher access token cannot strip the session's\n * ability to refresh.\n */\nexport function resolveTokenAdoption(params: ResolveTokenAdoptionParams): TokenAdoptionDecision {\n const { callbackAccessToken, callbackRefreshToken, callbackNodeUrl, stored, storedNodeUrl } =\n params;\n\n const bundle = (refreshToken: string): TokenData => ({\n access_token: callbackAccessToken,\n refresh_token: refreshToken,\n expires_at: expiresAtFromJwt(callbackAccessToken),\n });\n\n // Fresh login — nothing to protect.\n if (!stored?.access_token) {\n return { adopt: true, tokens: bundle(callbackRefreshToken), reason: 'fresh-login' };\n }\n\n // Different node — the stored bundle is for someone else's token family, and\n // its refresh token is meaningless here, so it must NOT be carried over.\n const sameNode = !!storedNodeUrl && sameOrigin(callbackNodeUrl, storedNodeUrl);\n if (!sameNode) {\n return { adopt: true, tokens: bundle(callbackRefreshToken), reason: 'node-changed' };\n }\n\n // Same node, live bundle. Keep the stored refresh token unless the hash carries\n // one — the hash's refresh token may be a copy that mero-js has already rotated\n // away, but an *empty* one would strip refresh from the session entirely.\n const refreshToken = callbackRefreshToken || stored.refresh_token;\n\n if (isCallbackNewer(callbackAccessToken, stored)) {\n return { adopt: true, tokens: bundle(refreshToken), reason: 'newer' };\n }\n\n // The access token is not newer, but the stored bundle cannot refresh and the\n // hash can repair that. Keep the *stored* access token (it is at least as new).\n if (!stored.refresh_token && callbackRefreshToken) {\n return {\n adopt: true,\n tokens: { ...stored, refresh_token: callbackRefreshToken },\n reason: 'fill-refresh',\n };\n }\n\n // Stale (or a replay of the bundle we already hold). Writing it would resurrect\n // a consumed refresh token → `token_reuse` → the node revokes the whole family.\n return { adopt: false, reason: 'stale' };\n}\n","/**\n * Storage utilities for mero-react\n * \n * Provides localStorage-based token storage and other persistence utilities.\n */\n\nimport type { TokenData } from '@calimero-network/mero-js';\n\n// Storage keys\nconst STORAGE_KEYS = {\n ACCESS_TOKEN: 'mero:access_token',\n REFRESH_TOKEN: 'mero:refresh_token',\n EXPIRES_AT: 'mero:expires_at',\n NODE_URL: 'mero:node_url',\n // The node the token bundle currently in the TokenStore was issued by. Distinct\n // from NODE_URL, which `connectToNode` overwrites with the *target* node before\n // redirecting to login — so at callback time NODE_URL names where we are going,\n // not who minted the tokens we still hold. Telling those apart is what lets the\n // SSO callback re-seed on a node change without mistaking a different node's\n // bundle for a rotated one (see auth/token-adoption.ts).\n TOKEN_NODE_URL: 'mero:token_node_url',\n APPLICATION_ID: 'mero:application_id',\n CONTEXT_ID: 'mero:context_id',\n CONTEXT_IDENTITY: 'mero:context_identity',\n} as const;\n\nlet _storageAvailable: boolean | null = null;\n\nfunction isLocalStorageAvailable(): boolean {\n if (_storageAvailable !== null) return _storageAvailable;\n try {\n if (typeof window === 'undefined' || !window.localStorage) {\n _storageAvailable = false;\n return false;\n }\n const testKey = '__mero_test__';\n localStorage.setItem(testKey, 'test');\n localStorage.removeItem(testKey);\n _storageAvailable = true;\n } catch {\n _storageAvailable = false;\n }\n return _storageAvailable;\n}\n\nexport const localStorageTokenStorage = {\n async get(): Promise<TokenData | null> {\n if (!isLocalStorageAvailable()) {\n return null;\n }\n\n try {\n const accessToken = localStorage.getItem(STORAGE_KEYS.ACCESS_TOKEN);\n const refreshToken = localStorage.getItem(STORAGE_KEYS.REFRESH_TOKEN);\n const expiresAt = localStorage.getItem(STORAGE_KEYS.EXPIRES_AT);\n\n if (!accessToken || !refreshToken) {\n return null;\n }\n\n return {\n access_token: accessToken,\n refresh_token: refreshToken,\n expires_at: expiresAt ? parseInt(expiresAt, 10) : Date.now() + 3600000,\n };\n } catch (e) {\n console.error('[mero-react] Failed to get token from storage:', e);\n return null;\n }\n },\n\n async set(token: TokenData): Promise<void> {\n if (!isLocalStorageAvailable()) {\n return;\n }\n\n try {\n localStorage.setItem(STORAGE_KEYS.ACCESS_TOKEN, token.access_token);\n localStorage.setItem(STORAGE_KEYS.REFRESH_TOKEN, token.refresh_token);\n localStorage.setItem(STORAGE_KEYS.EXPIRES_AT, token.expires_at.toString());\n } catch (e) {\n console.error('[mero-react] Failed to save token to storage:', e);\n }\n },\n\n async clear(): Promise<void> {\n if (!isLocalStorageAvailable()) {\n return;\n }\n\n try {\n localStorage.removeItem(STORAGE_KEYS.ACCESS_TOKEN);\n localStorage.removeItem(STORAGE_KEYS.REFRESH_TOKEN);\n localStorage.removeItem(STORAGE_KEYS.EXPIRES_AT);\n } catch (e) {\n console.error('[mero-react] Failed to clear token from storage:', e);\n }\n },\n};\n\n/**\n * Get the stored node URL\n */\nexport function getNodeUrl(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.NODE_URL);\n}\n\n/**\n * Set the node URL\n */\nexport function setNodeUrl(url: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.NODE_URL, url);\n}\n\n/**\n * Clear the node URL\n */\nexport function clearNodeUrl(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.NODE_URL);\n}\n\n/**\n * Get the node URL that minted the token bundle currently in the TokenStore.\n */\nexport function getTokenNodeUrl(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.TOKEN_NODE_URL);\n}\n\n/**\n * Record the node URL that minted the token bundle now in the TokenStore.\n */\nexport function setTokenNodeUrl(url: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.TOKEN_NODE_URL, url);\n}\n\n/**\n * Clear the token bundle's node URL\n */\nexport function clearTokenNodeUrl(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.TOKEN_NODE_URL);\n}\n\n/**\n * Get the stored application ID\n */\nexport function getApplicationId(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.APPLICATION_ID);\n}\n\n/**\n * Set the application ID\n */\nexport function setApplicationId(id: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.APPLICATION_ID, id);\n}\n\n/**\n * Clear the application ID\n */\nexport function clearApplicationId(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.APPLICATION_ID);\n}\n\n/**\n * Get the stored context ID\n */\nexport function getContextId(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.CONTEXT_ID);\n}\n\n/**\n * Set the context ID\n */\nexport function setContextId(id: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.CONTEXT_ID, id);\n}\n\n/**\n * Clear the context ID\n */\nexport function clearContextId(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.CONTEXT_ID);\n}\n\n/**\n * Get the stored context identity\n */\nexport function getContextIdentity(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.CONTEXT_IDENTITY);\n}\n\n/**\n * Set the context identity\n */\nexport function setContextIdentity(id: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.CONTEXT_IDENTITY, id);\n}\n\n/**\n * Clear the context identity\n */\nexport function clearContextIdentity(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.CONTEXT_IDENTITY);\n}\n\n/**\n * Clear all mero-react storage\n */\nexport function clearAllStorage(): void {\n if (!isLocalStorageAvailable()) return;\n Object.values(STORAGE_KEYS).forEach((key) => {\n localStorage.removeItem(key);\n });\n}\n","/**\n * The delegated half of connecting: an account, a certified device, and a relay\n * that writes on their behalf.\n *\n * Kept deliberately apart from the node-login path in `MeroContext`. That path\n * is a redirect flow with token adoption, single-use refresh tokens and node-URL\n * trust validation — none of which applies here, because there is no session\n * token at all. A delegated client authenticates every request from a warrant it\n * signs itself. Weaving the two together would put a token-rotation decision in\n * front of a flow that has no tokens.\n *\n * Per-tab on purpose. The record lives in `sessionStorage`, so two tabs can hold\n * two different connections — one a node you run, one a relay you do not — with\n * the same application code in both.\n */\nimport {\n attestRelayNodeKey,\n cloudNodeReleaseUrl,\n createMeroClient,\n createSignedReleaseVerifier,\n DEFAULT_RELEASE_MIRROR,\n defaultAudience,\n fetchNodeRelease,\n fetchNodeReleaseVersion,\n login,\n type DcapVerify,\n type MeroClient,\n type VerifyTransportQuote,\n} from '@calimero-network/mero-js';\n\n/** Where the per-tab record lives. */\nconst KEY = 'calimero.delegated.connection';\n/**\n * Where the enrolled credential lives when there is no relay for it yet.\n *\n * Separate from {@link KEY}, and deliberately not \"a connection with a null\n * relay\": a record under that key means a usable client can be built from it,\n * and every reader relies on that. An account that has just enrolled is a\n * member of nothing, so the cloud names no relay for it and there is nothing to\n * build — but the certificate is real and must survive, or the only way to\n * bootstrap from an invitation would be to enrol again.\n */\nconst CREDENTIAL_KEY = 'calimero.delegated.credential';\n\n/**\n * What a delegated connection needs to be rebuilt after a reload.\n *\n * `deviceSecret` is here because the device key is what signs warrants, and a\n * reload that could not sign would be a dead session. It is a per-tab secret for\n * a certificate the account can revoke — not the account root, which never\n * leaves the wallet's origin.\n */\n/**\n * What the wallet certified: an account, a device it trusts, and the key that\n * device signs with. Everything except somewhere to send the result.\n *\n * Split out of {@link DelegatedSession} because it is reachable one step\n * earlier. An account that has just enrolled holds exactly this and no relay —\n * it is a member of nothing, so the cloud has no relay to name — and this is the\n * input that resolves one from an invitation instead.\n */\nexport interface DelegatedCredential {\n /** The author's account id, hex. */\n account: string;\n /** The author's `AccountProof<DeviceCert>`, hex borsh. */\n credential: string;\n /** The certified device's ed25519 signing secret, hex. */\n deviceSecret: string;\n}\n\nexport interface DelegatedSession extends DelegatedCredential {\n /**\n * The relay to write through — a node origin, or `null` for none yet.\n *\n * **`null` is a logged-in state, not a broken one.** A brand-new account is a\n * member of nothing, so the cloud names no relay for it — and that is the\n * normal condition of an account that has just been created, because being\n * signed in is how you come to be invited in the first place. Refusing to\n * connect without a relay locked a new account out of the only path that\n * would earn it one.\n *\n * What it does NOT mean is that writes quietly do nothing. There is no\n * client at all without a URL ({@link buildDelegatedClient} returns `null`),\n * so `mero` stays `null`, the session is authenticated, and anything reaching\n * for `rpc.execute` is told the relay is missing. A placeholder URL would be\n * the one unacceptable answer: it would look connected and refuse every\n * warrant.\n */\n relayUrl: string | null;\n /**\n * No `contextId`, deliberately.\n *\n * Which context to talk to is a CHOICE, made after connecting and changeable\n * without reconnecting — a node routinely holds several and comparing two of\n * them is ordinary use. It lives where the node-login path already keeps it\n * (`setContextId` / `getContextId`), and `admin.getContexts()` on this very\n * client answers what the choices are, caller-scoped by the request proof. A\n * copy here would be a second source of truth that a context switch would\n * immediately make stale, and it would make connecting depend on a value\n * nobody could type.\n */\n}\n\nexport function readDelegatedSession(): DelegatedSession | null {\n if (typeof sessionStorage === 'undefined') return null;\n try {\n const raw = sessionStorage.getItem(KEY);\n return raw ? (JSON.parse(raw) as DelegatedSession) : null;\n } catch {\n // Private mode, blocked site data, or a half-written record. Treat all\n // three as \"not connected\" rather than throwing during render.\n return null;\n }\n}\n\nexport function saveDelegatedSession(s: DelegatedSession): void {\n try {\n sessionStorage.setItem(KEY, JSON.stringify(s));\n } catch {\n // Non-fatal: the client still works for this page view, it just will not\n // survive a reload. Better than refusing to connect.\n }\n}\n\nexport function clearDelegatedSession(): void {\n try {\n sessionStorage.removeItem(KEY);\n } catch {\n /* nothing to clear if storage is unavailable */\n }\n}\n\n/**\n * The enrolled credential, whether or not a relay was ever found for it.\n *\n * A connected session is authoritative: it carries the same three fields and a\n * relay, so it is read first and the standalone record is the fallback. Without\n * that order a stale record from an earlier enrolment could out-rank the account\n * actually connected.\n */\nexport function readDelegatedCredential(): DelegatedCredential | null {\n const session = readDelegatedSession();\n if (session) {\n const { account, credential, deviceSecret } = session;\n return { account, credential, deviceSecret };\n }\n if (typeof sessionStorage === 'undefined') return null;\n try {\n const raw = sessionStorage.getItem(CREDENTIAL_KEY);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as Partial<DelegatedCredential>;\n // A half-written record is worse than none: it would be carried into a\n // signing call and fail as a malformed credential, somewhere that cannot say\n // where the bad value came from.\n if (!parsed.account || !parsed.credential || !parsed.deviceSecret) return null;\n return parsed as DelegatedCredential;\n } catch {\n return null;\n }\n}\n\nexport function saveDelegatedCredential(c: DelegatedCredential): void {\n try {\n sessionStorage.setItem(CREDENTIAL_KEY, JSON.stringify(c));\n } catch {\n /* this page view still holds it; it just will not survive a reload */\n }\n}\n\nexport function clearDelegatedCredential(): void {\n try {\n sessionStorage.removeItem(CREDENTIAL_KEY);\n } catch {\n /* nothing to clear if storage is unavailable */\n }\n}\n\n/**\n * A warrant nonce is spent on the node, so the counter must outlive the page.\n *\n * In `localStorage`, not session: a reload that restarted from zero would\n * replay a spent nonce and be refused. Keyed by relay and context because the\n * ledger the node keeps is per `(context, author device)`.\n *\n * This is the client-side half of core #4018. The node can answer \"where does\n * my sequence stand\" — `POST /contexts/{id}/warrant-nonce` with the caller's own\n * `authorProof` — but that route is mounted on the protected router, so a\n * delegated client on a relay cannot reach it. Until it moves, holding the\n * counter locally is the only option, and losing storage means burning refusals\n * until the counter catches up.\n */\nfunction persistedNonces(relayUrl: string, contextId: string | null) {\n // `null` only before a context is chosen, when no intent can be presented\n // either — `rpc.execute` takes a context id, so nothing draws from this\n // ledger yet. Spelled out rather than left as `undefined` in the key, so a\n // later context's counter can never inherit whatever this one reached.\n const key = `calimero.nonce.${relayUrl}.${contextId ?? 'no-context'}`;\n return {\n next: async (): Promise<bigint> => {\n let n = 0n;\n try {\n n = BigInt(localStorage.getItem(key) ?? '0');\n } catch {\n n = 0n;\n }\n try {\n localStorage.setItem(key, String(n + 1n));\n } catch {\n /* unpersisted: this page view still advances in memory */\n }\n return n;\n },\n };\n}\n\n/**\n * Record that `nonce` is spent in `contextId`'s ledger for this device, so the\n * context's intents start above it. A creation warrant's nonce is spent in the\n * NEW context's own per-device window — the one its later writes draw from.\n */\nexport function markContextNonceSpent(relayUrl: string, contextId: string, nonce: bigint): void {\n const key = `calimero.nonce.${relayUrl}.${contextId}`;\n try {\n const current = BigInt(localStorage.getItem(key) ?? '0');\n if (current <= nonce) localStorage.setItem(key, String(nonce + 1n));\n } catch {\n /* unpersisted: the first write meets a spent nonce once, and retries above it */\n }\n}\n\nconst RELAY_NODE_KEY_PREFIX = 'calimero.delegated.relay-node-key.';\n\nfunction relayOrigin(relayUrl: string): string {\n return relayUrl.replace(/\\/+$/, '');\n}\n\n/**\n * Pin a relay's device signing key, hex (32 bytes), learned out of band.\n *\n * `login()` binds the session to this key, and it must never be read from the\n * relay being logged in to — the answering party would choose what the device\n * signs about. Until the cloud publishes it (mdma#312), it comes from the\n * relay's operator.\n */\nexport function pinRelayNodeKey(relayUrl: string, nodeKey: string): void {\n localStorage.setItem(RELAY_NODE_KEY_PREFIX + relayOrigin(relayUrl), nodeKey.trim().toLowerCase());\n}\n\n/** The pinned key for a relay, or `null` if none was pinned. */\nexport function readPinnedRelayNodeKey(relayUrl: string): string | null {\n try {\n const v = localStorage.getItem(RELAY_NODE_KEY_PREFIX + relayOrigin(relayUrl));\n return v && /^[0-9a-f]{64}$/.test(v) ? v : null;\n } catch {\n return null;\n }\n}\n\nfunction isLoopback(relayUrl: string): boolean {\n try {\n const { hostname } = new URL(relayUrl);\n return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]';\n } catch {\n return false;\n }\n}\n\n/**\n * The relay's node key: the pinned one, or else learned from the relay's TEE\n * attestation (see mero-js `attestRelayNodeKey`) and pinned for next time.\n *\n * A mock quote proves nothing about hardware, so one is accepted only from a\n * loopback relay — a local rig. A real quote needs signature and measurement\n * verification this client does not do yet, so a real relay still needs its\n * key pinned; `null` then, and admin reads and events stay off.\n */\n/** The one relay image trusted: no shell, so nobody reads the TD. */\nconst TRUSTED_RELAY_PROFILE = 'locked-read-only';\n/**\n * The oldest relay release trusted: the first that serves delegated context\n * creation and governance at the namespace-op schema this client signs.\n */\nconst MIN_RELAY_RELEASE = '2.3.99';\n\nlet loadedDcap: Promise<DcapVerify> | undefined;\n\n/**\n * A verifier for a hosted relay's quote: the signed mero-tee release it says it\n * runs (fetched from the public mirror, trusted only for its signature), Intel's\n * chain, and all five registers of that release's image.\n *\n * `@phala/dcap-qvl` is loaded on the first quote it checks: it is most of the\n * weight, and an app that never meets a real relay never needs it. A failed\n * download is forgotten, so the next attempt tries again.\n */\nfunction relayQuoteVerifier(relayUrl: string): VerifyTransportQuote {\n const verify: VerifyTransportQuote = async (attestation) => {\n loadedDcap ??= import('@phala/dcap-qvl').then(\n ({ verify: dcapVerify }) => dcapVerify as DcapVerify,\n (error: unknown) => {\n loadedDcap = undefined;\n throw error;\n },\n );\n return createSignedReleaseVerifier({\n dcapVerify: await loadedDcap,\n release: async () =>\n fetchNodeRelease(cloudNodeReleaseUrl(DEFAULT_RELEASE_MIRROR, await fetchNodeReleaseVersion(relayUrl))),\n profile: TRUSTED_RELAY_PROFILE,\n minReleaseVersion: MIN_RELAY_RELEASE,\n })(attestation);\n };\n return Object.assign(verify, { includeCollateral: true as const });\n}\n\nexport async function resolveRelayNodeKey(relayUrl: string): Promise<string | null> {\n const pinned = readPinnedRelayNodeKey(relayUrl);\n if (pinned) return pinned;\n try {\n // A loopback relay is a dev rig answering with mock quotes; anything else\n // must prove its image.\n const local = isLoopback(relayUrl);\n const { nodeKey } = await attestRelayNodeKey({\n relayUrl,\n allowMock: local,\n ...(local ? {} : { verify: relayQuoteVerifier(relayUrl) }),\n });\n pinRelayNodeKey(relayUrl, nodeKey);\n return nodeKey;\n } catch (e) {\n console.warn('[mero-react] could not learn the relay node key from its attestation', e);\n return null;\n }\n}\n\n/** Milliseconds-since-epoch a JWT expires at, or `null` if unreadable. */\nfunction jwtExpiryMs(token: string): number | null {\n try {\n const payload = JSON.parse(atob(token.split('.')[1]!.replace(/-/g, '+').replace(/_/g, '/')));\n return typeof payload.exp === 'number' ? payload.exp * 1000 : null;\n } catch {\n return null;\n }\n}\n\n/**\n * A lazily minted `account_proof` session on the relay.\n *\n * A hosted relay's `/admin-api/` sits behind the node's forward-auth, which\n * knows no request proof — it answers a Bearer token or 401. Logging in with\n * the device certificate is how a keyholder gets that token. Minted on first\n * use and re-minted once it has expired. On failure it yields `undefined`, the\n * admin request then goes out unauthenticated and the node's 401 is what the\n * caller sees; the next call tries to log in again.\n */\nfunction relaySession(s: DelegatedSession & { relayUrl: string }, nodeKey: string) {\n let token: string | null = null;\n let inflight: Promise<string | undefined> | null = null;\n return async (): Promise<string | undefined> => {\n const exp = token ? jwtExpiryMs(token) : null;\n if (token && (exp === null || exp - Date.now() > 30_000)) return token;\n if (!inflight) {\n inflight = login({\n nodeUrl: s.relayUrl,\n node: nodeKey,\n deviceSecret: s.deviceSecret,\n accountProof: s.credential,\n audience: defaultAudience(),\n })\n .then((minted) => {\n token = minted.accessToken;\n return token;\n })\n .catch((e: unknown) => {\n console.warn('[mero-react] relay login failed', e);\n token = null;\n return undefined;\n })\n .finally(() => {\n inflight = null;\n });\n }\n return inflight;\n };\n}\n\n/**\n * Build the client a delegated session talks through.\n *\n * The result is a relay-transport `MeroClient`. Its `rpc.execute` takes the same\n * named arguments a node client's does, which is what lets a generated ABI\n * client — and every hook that only calls `execute` — work unchanged. What it\n * also has is `admin` and `events`, pointed at the relay and authenticated as\n * the account by the device certificate, so the caller-scoped reads answer this\n * account's own contexts and namespaces rather than the node's.\n */\nexport function buildDelegatedClient(\n s: DelegatedSession,\n contextId: string | null,\n): MeroClient | null {\n // No relay, no client — and deliberately no placeholder either.\n //\n // A relay-transport client IS a URL plus a credential; with no URL there is\n // nothing to post an intent to. `null` propagates as \"not connected for\n // writing\" while the session stays authenticated, which is the honest shape\n // for a brand-new account: it exists, it has a certificate, and it has not\n // been invited anywhere yet. A stand-in URL would make every write fail as a\n // refused warrant against a node that was never chosen.\n if (!s.relayUrl) return null;\n const nodeKey = readPinnedRelayNodeKey(s.relayUrl);\n return createMeroClient({\n transport: 'relay',\n relay: {\n relayUrl: s.relayUrl,\n authorAccount: s.account,\n authorProof: s.credential,\n deviceSecret: s.deviceSecret,\n // The active context, passed in rather than stored on the record: the\n // relay client holds ONE nonce source while `execute` takes a context per\n // call, so the ledger has to be re-keyed when the chosen context changes.\n nonces: persistedNonces(s.relayUrl, contextId),\n },\n // The certificate authenticates the requests too, not just the writes.\n //\n // This is the whole of what reads and events need: the device key signs each\n // request, and the node verifies it against the account's certificate with no\n // store read and no prior relationship. Measured against a node built from\n // core `aecba573b`: `listNamespaces` and `getContexts` answer `200` and are\n // caller-scoped, `/sse` answers `200`, and a real write arrives on the stream\n // as a `StateMutation` frame.\n //\n // What this replaces is a session minted by `login()` plus the relay node's\n // signing key learned out of band — two inputs, one of which the cloud does\n // not publish, for an answer the certificate already gives.\n proof: { credential: s.credential, deviceSecret: s.deviceSecret },\n // A session, when this relay's node key is pinned. A hosted relay's\n // forward-auth accepts a Bearer token and not the proof above, so without\n // one every admin read there is a 401. Given a session the client uses it\n // for every admin call; a relay with no pinned key keeps the proof path.\n session: nodeKey ? relaySession({ ...s, relayUrl: s.relayUrl }, nodeKey) : undefined,\n // Events too. `/sse` on a relay sits behind the same forward-auth, so the\n // proof above gets a 401 there; with the node key the client observes\n // through its own device-certificate login instead.\n observe: nodeKey ? { nodeKey } : undefined,\n });\n}\n\n// ------------------------------------------------------------------ relay map\n//\n// An account's namespaces may be served by different relays. A relay admits\n// the account to a namespace and then serves that namespace's contexts, so the\n// client keeps, per account, which relay serves which namespace and context:\n//\n// namespaces: { <namespace id>: <relay url> } — learned when a join succeeds\n// contexts: { <context id>: <relay url> } — learned from each relay's\n// caller-scoped listing\n//\n// In localStorage, beside the pinned node keys: URLs and ids only, nothing\n// secret, and it has to survive a reload for the open context to find its\n// relay. Losing it costs a re-listing, not access.\n\nconst RELAY_MAP_PREFIX = 'calimero.delegated.relays.';\n\nexport interface RelayMap {\n namespaces: Record<string, string>;\n contexts: Record<string, string>;\n}\n\nexport function readRelayMap(account: string): RelayMap {\n try {\n const raw = localStorage.getItem(RELAY_MAP_PREFIX + account);\n const parsed = raw ? (JSON.parse(raw) as Partial<RelayMap>) : {};\n return { namespaces: parsed.namespaces ?? {}, contexts: parsed.contexts ?? {} };\n } catch {\n return { namespaces: {}, contexts: {} };\n }\n}\n\nfunction writeRelayMap(account: string, map: RelayMap): void {\n try {\n localStorage.setItem(RELAY_MAP_PREFIX + account, JSON.stringify(map));\n } catch {\n /* unpersisted: this page view still routes from what it lists */\n }\n}\n\n/** Record the relay that admitted this account to a namespace (and, when known, the context it came for). */\nexport function rememberRelay(\n account: string,\n relayUrl: string,\n at: { namespaceId?: string; contextId?: string },\n): void {\n const map = readRelayMap(account);\n const url = relayOrigin(relayUrl);\n if (at.namespaceId) map.namespaces[at.namespaceId] = url;\n if (at.contextId) map.contexts[at.contextId] = url;\n writeRelayMap(account, map);\n}\n\n/** The relay that serves a context, if this account has learned it. */\nexport function relayForContext(account: string, contextId: string): string | null {\n return readRelayMap(account).contexts[contextId] ?? null;\n}\n\n/** Every relay this account is known to use: the session's, and each in the map. */\nexport function knownRelays(s: DelegatedSession): string[] {\n const map = readRelayMap(s.account);\n const all = [s.relayUrl, ...Object.values(map.namespaces), ...Object.values(map.contexts)]\n .filter((u): u is string => typeof u === 'string' && u.length > 0)\n .map(relayOrigin);\n return [...new Set(all)];\n}\n\ntype ListedContext = Awaited<ReturnType<MeroClient['admin']['getContexts']>>['contexts'][number];\n\n/**\n * This account's contexts on every relay it knows, each tagged with the relay\n * that listed it — and that relay recorded as the one serving it.\n *\n * Each relay answers only for itself and only for this caller, so the union is\n * exactly the account's contexts across relays. A relay that cannot be reached\n * or logged in to is skipped (its contexts simply do not appear), not fatal.\n */\nexport async function listDelegatedContexts(\n s: DelegatedSession,\n): Promise<Array<ListedContext & { relayUrl: string }>> {\n const out: Array<ListedContext & { relayUrl: string }> = [];\n const map = readRelayMap(s.account);\n for (const relayUrl of knownRelays(s)) {\n try {\n if (!(await resolveRelayNodeKey(relayUrl))) continue;\n const client = buildDelegatedClient({ ...s, relayUrl }, null);\n if (!client) continue;\n const { contexts } = await client.admin.getContexts();\n for (const c of contexts ?? []) {\n out.push({ ...c, relayUrl });\n map.contexts[c.id] = relayUrl;\n }\n } catch (e) {\n console.warn(`[mero-react] could not list contexts on ${relayUrl}`, e);\n }\n }\n writeRelayMap(s.account, map);\n return out;\n}\n\ntype ListedNamespace = Awaited<ReturnType<MeroClient['admin']['listNamespaces']>>[number];\n\n/**\n * This account's namespaces on every relay it knows, each tagged with the relay\n * that listed it and recorded as that namespace's relay. Same rules as\n * {@link listDelegatedContexts}: each relay answers for itself and this caller\n * only (`namespace:list-own`); an unreachable relay is skipped.\n */\nexport async function listDelegatedNamespaces(\n s: DelegatedSession,\n): Promise<Array<ListedNamespace & { relayUrl: string }>> {\n const out: Array<ListedNamespace & { relayUrl: string }> = [];\n const seen = new Set<string>();\n const map = readRelayMap(s.account);\n for (const relayUrl of knownRelays(s)) {\n try {\n if (!(await resolveRelayNodeKey(relayUrl))) continue;\n const client = buildDelegatedClient({ ...s, relayUrl }, null);\n if (!client) continue;\n for (const ns of await client.admin.listNamespaces()) {\n if (seen.has(ns.namespaceId)) continue;\n seen.add(ns.namespaceId);\n out.push({ ...ns, relayUrl });\n map.namespaces[ns.namespaceId] ??= relayUrl;\n }\n } catch (e) {\n console.warn(`[mero-react] could not list namespaces on ${relayUrl}`, e);\n }\n }\n writeRelayMap(s.account, map);\n return out;\n}\n","import React, {\n createContext,\n useContext,\n useState,\n useEffect,\n useCallback,\n useRef,\n useMemo,\n} from 'react';\nimport {\n MeroJs,\n LocalStorageTokenStore,\n parseAuthCallback,\n buildAuthLoginUrl,\n AuthRevokedError,\n HTTPError,\n} from '@calimero-network/mero-js';\nimport { AppMode } from '../types';\nimport type { AuthCallbackResult, MeroClient, TokenStore } from '@calimero-network/mero-js';\nimport { resolveTrustedNodeUrl } from '../auth/node-trust';\nimport { resolveTokenAdoption } from '../auth/token-adoption';\nimport {\n getNodeUrl,\n setNodeUrl,\n getTokenNodeUrl,\n setTokenNodeUrl,\n getApplicationId,\n setApplicationId,\n getContextId,\n setContextId,\n getContextIdentity,\n setContextIdentity,\n clearAllStorage,\n} from '../storage';\nimport type { MeroContextValue, MeroProviderConfig } from '../types';\n\nimport {\n buildDelegatedClient,\n clearDelegatedCredential,\n clearDelegatedSession,\n readDelegatedSession,\n listDelegatedContexts,\n readPinnedRelayNodeKey,\n relayForContext,\n resolveRelayNodeKey,\n saveDelegatedCredential,\n saveDelegatedSession,\n type DelegatedSession,\n} from '../delegated/session';\n\nconst MeroContext = createContext<MeroContextValue | null>(null);\n\nconst isBrowser = typeof window !== 'undefined';\n\n/**\n * Permission grants requested for the client token at login.\n *\n * Cores since 0.11.0-rc.9 default-deny admin-api routes the token holds no\n * scope for; cores >=0.11.0-rc.11 map the governance/blob/alias routes to the\n * client-grantable `namespace` / `group` / `blob` / `context:alias`\n * permissions, so app tokens must request them here or every workspace,\n * group, blob and context-alias call 403s.\n *\n * `context:list` is included even in single-context mode because every app\n * calls GET /admin-api/contexts/:id/identities-owned right after login, which\n * maps to a `context:list` requirement.\n *\n * `context:subscribe` is what `/sse`, `/sse/subscription` and `/ws` require\n * (core's `PermissionValidator`, `validator.rs`, maps all three to\n * `Context(Subscribe(Global))`). Without it every event stream an app opens is\n * refused `403` + `X-Auth-Error: permission_denied`, so the app renders, reads\n * and writes, and simply never receives a live update. Only `AppMode.Admin`\n * escaped, because `admin` covers every route.\n *\n * MEASURED against merod 0.11.0-rc.41 (build 88e323b): a client key minted with\n * the MultiContext list below minus `context:subscribe` gets `403` on\n * `GET /sse`; the same list with it gets `200`.\n *\n * Exported for tests.\n */\nexport function getPermissionsForMode(mode: AppMode): string[] {\n switch (mode) {\n case AppMode.SingleContext:\n return [\n 'context:execute',\n 'context:list',\n 'context:subscribe',\n 'application:list',\n 'blob',\n 'context:alias',\n ];\n case AppMode.MultiContext:\n return [\n 'context:create',\n 'context:list',\n 'context:execute',\n 'context:subscribe',\n 'application:list',\n 'namespace',\n 'group',\n 'blob',\n 'context:alias',\n ];\n case AppMode.Admin:\n return ['admin'];\n default:\n throw new Error(`Unsupported application mode: ${mode}`);\n }\n}\n\nexport interface MeroProviderProps extends MeroProviderConfig {\n children: React.ReactNode;\n}\n\nexport function MeroProvider({\n children,\n mode,\n packageName,\n packageVersion,\n registryUrl,\n timeoutMs = 30000,\n allowedNodeUrls,\n tokenStore: tokenStoreProp,\n}: MeroProviderProps) {\n const tokenStore = useMemo<TokenStore>(\n () => tokenStoreProp ?? new LocalStorageTokenStore(),\n [tokenStoreProp],\n );\n const [mero, setMero] = useState<MeroJs | MeroClient | null>(null);\n /**\n * The delegated record, or null for the node-login path.\n *\n * Read from storage in the initializer rather than an effect: a reload of a\n * delegated tab should render connected, not flash the connect button and\n * then replace it.\n */\n const [delegated, setDelegated] = useState<DelegatedSession | null>(() =>\n readDelegatedSession(),\n );\n const [isAuthenticated, setIsAuthenticated] = useState(false);\n const [isOnline, setIsOnline] = useState(true);\n const [isLoading, setIsLoading] = useState(true);\n const [nodeUrl, setNodeUrlState] = useState<string | null>(() => getNodeUrl());\n const [applicationId, setApplicationIdState] = useState<string | null>(\n () => getApplicationId() || null,\n );\n const [contextId, setContextIdState] = useState<string | null>(() => getContextId());\n const [contextIdentity, setContextIdentityState] = useState<string | null>(() => getContextIdentity());\n\n const meroRef = useRef<MeroJs | null>(null);\n // Guards the SSE 401 recovery below, so a burst of reconnect failures can't\n // stack concurrent validate/refresh attempts over one single-use refresh token.\n const recoveringRef = useRef(false);\n\n // Parse auth callback ONCE in a ref (StrictMode-safe: refs persist across unmount/remount)\n const callbackRef = useRef<AuthCallbackResult | null | undefined>(undefined);\n if (callbackRef.current === undefined && isBrowser) {\n callbackRef.current = parseAuthCallback(window.location.href);\n }\n\n const createMeroInstance = useCallback(\n (url: string): MeroJs => {\n if (meroRef.current) {\n meroRef.current.close();\n }\n const instance = new MeroJs({\n baseUrl: url,\n tokenStore,\n timeoutMs,\n });\n meroRef.current = instance;\n return instance;\n },\n [timeoutMs, tokenStore],\n );\n\n const checkAuth = useCallback(\n async (instance: MeroJs): Promise<boolean> => {\n // Validate the session via /auth/validate (signature, revocation, node\n // binding — no permission requirement) instead of probing\n // GET /admin-api/contexts. Since core 0.11.0-rc.9 the node enforces\n // token permission scopes, and /admin-api/contexts requires Global\n // `context:list` — which single-context tokens (execute-only) and\n // app-scoped tokens don't hold, so probing it 403'd valid sessions and\n // bounced every app straight back to the login page.\n const accessToken = tokenStore.getTokens()?.access_token;\n if (!accessToken) return false;\n\n const validate = async (token: string): Promise<boolean> => {\n try {\n const { valid } = await instance.auth.validateToken(token);\n return valid;\n } catch {\n return false;\n }\n };\n\n if (await validate(accessToken)) return true;\n\n // An expired access token does NOT mean the session is over: refresh\n // tokens last 30 days against core's 1-hour access TTL, so on any reload\n // more than an hour after login we land here holding a perfectly good\n // refresh token.\n //\n // `validateToken` has in fact already spent it. It pins the token under\n // test into an explicit `Authorization` header, and mero-js's init\n // headers override the transport's own token (mero-js\n // http-client/web-client.js `buildHeaders`). So the 401 + `x-auth-error:\n // token_expired` trips the transport's refresh hook — rotating the stored\n // bundle — and then the retry re-sends the SAME stale header, 401s again,\n // and reports `valid: false`. The session was silently renewed and thrown\n // away, and the app bounced to login; a second reload would then \"fix\"\n // itself, which is exactly how this reads as a random logout.\n //\n // So: re-read the store, and if the transport rotated it underneath us,\n // judge the session on the token we ACTUALLY hold now. We never call\n // /auth/refresh ourselves — doing so would race mero-js's single-flight\n // lock over a single-use refresh token and get the whole family revoked\n // (calimero-network/core#3083).\n const rotated = tokenStore.getTokens()?.access_token;\n if (!rotated || rotated === accessToken) return false;\n return validate(rotated);\n },\n [tokenStore],\n );\n\n const connectToNode = useCallback(\n (url: string) => {\n if (!isBrowser) return;\n setNodeUrl(url);\n setNodeUrlState(url);\n\n const callbackUrl = new URL(window.location.href);\n callbackUrl.hash = '';\n\n const loginUrl = buildAuthLoginUrl(url, {\n callbackUrl: callbackUrl.toString(),\n permissions: getPermissionsForMode(mode),\n mode,\n packageName,\n packageVersion,\n registryUrl,\n });\n\n window.location.href = loginUrl;\n },\n [mode, packageName, packageVersion, registryUrl],\n );\n\n /**\n * Adopt a delegated connection.\n *\n * No redirect and nothing to await: a delegated client carries its own\n * credential on every request, so it is usable the moment it is built. The\n * record is persisted first so a reload finds it.\n */\n const connectWithAccount = useCallback((session: DelegatedSession) => {\n saveDelegatedSession(session);\n // Kept as a credential too, so the identity outlives the connection. A relay\n // can be lost without the certificate being lost — the fleet row goes stale,\n // or the record is cleared — and re-enrolling to recover a key this tab still\n // holds would be a new device for no reason.\n const { account, credential, deviceSecret } = session;\n saveDelegatedCredential({ account, credential, deviceSecret });\n setDelegated(session);\n }, []);\n\n const logout = useCallback(() => {\n if (meroRef.current) {\n meroRef.current.clearToken();\n meroRef.current.close();\n }\n // Always clear the token store, even when not connected (meroRef is null) —\n // otherwise the access/refresh tokens persist in storage after logout.\n tokenStore.clear();\n clearAllStorage();\n clearDelegatedSession();\n // The certificate goes too. Logging out of an account and leaving its device\n // key in storage would leave the next visitor able to bootstrap as it from\n // any invitation they hold.\n clearDelegatedCredential();\n setDelegated(null);\n setMero(null);\n setIsAuthenticated(false);\n setNodeUrlState(null);\n setApplicationIdState(null);\n setContextIdState(null);\n setContextIdentityState(null);\n meroRef.current = null;\n }, [tokenStore]);\n\n /**\n * Install the relay client for a delegated record.\n *\n * Separate effect from the node-login initializer below, and the two are\n * mutually exclusive: a delegated connection has no token to adopt, no node\n * URL to validate and no callback to consume, so running that machinery for\n * it would only find nothing and log out.\n */\n useEffect(() => {\n if (!delegated) return;\n // Re-keys the warrant-nonce ledger when the chosen context changes, which is\n // why `contextId` is a dependency. The context itself is NOT set from here —\n // it comes from storage (the initializer above) or from whatever the app's\n // own picker selected, exactly as on the node-login path.\n // The open context's own relay: an account's namespaces may each be served\n // by a different one. Unknown (no context yet, or one not listed yet) →\n // the session's relay, which is the one that admitted it most recently.\n const relayUrl =\n (contextId ? relayForContext(delegated.account, contextId) : null) ?? delegated.relayUrl;\n const routed = { ...delegated, relayUrl };\n const client = buildDelegatedClient(routed, contextId);\n // A relay whose node key is not known yet: learn it before handing the app a\n // client. Published without it, the app's subscriptions open `/sse` on a\n // client with no session, which a hosted relay refuses with a 401 — the\n // client rebuilt a moment later reconnects, but the refusal is noise.\n const awaitingKey = Boolean(client && relayUrl && !readPinnedRelayNodeKey(relayUrl));\n // `null` when the account holds no relay yet, and the session is still\n // authenticated. Being signed in is how an account comes to be invited, so a\n // relay cannot be a precondition for it — and `mero: null` is what makes a\n // write say \"there is no relay\" instead of failing against a guessed node.\n if (!awaitingKey) setMero(client);\n setIsAuthenticated(true);\n setIsOnline(true);\n setNodeUrlState(relayUrl);\n setIsLoading(awaitingKey);\n\n /*\n * Which application this tab is for, asked rather than told.\n *\n * The node-login path is handed an `applicationId` by the auth callback. A\n * delegated tab has no callback, so it had none — and an app's context\n * picker that filters on it (correctly: \"I cannot tell which are mine\" and\n * \"all of them are mine\" are different answers) then had nothing to filter\n * with and stayed empty forever. That, not the relay, was the last reason\n * anyone had to type a context id in.\n *\n * `admin.getContexts()` on this client is caller-scoped through the request\n * proof — it answers this ACCOUNT's own contexts, each naming its\n * application — so the id is derivable from the credential already held.\n *\n * Not persisted with `setApplicationId`: it is derived from a cheap,\n * authoritative read, so caching it would only create a value to invalidate\n * when the account's contexts change.\n */\n let active = true;\n (async () => {\n // No relay, so no client and nothing to ask. A brand-new account is a\n // member of nothing — there are no contexts to derive an application from,\n // which is exactly the state an invitation changes.\n if (!client || !relayUrl) return;\n // Admin reads and events need a session the relay accepts, which needs\n // its node key. Pinned, or learned from the relay's attestation; learned\n // now, the client is rebuilt so its session and events use it too. With\n // neither, a hosted relay answers the proof-only path with 401: do not ask.\n if (awaitingKey) {\n const nodeKey = await resolveRelayNodeKey(relayUrl);\n if (!active) return;\n // Without a key the client still writes (intents carry their own\n // warrant); only admin reads and events need the session it enables.\n setMero(nodeKey ? (buildDelegatedClient(routed, contextId) ?? client) : client);\n setIsLoading(false);\n if (!nodeKey) return;\n }\n try {\n // Across every relay this account uses, each answering for itself.\n const contexts = await listDelegatedContexts(delegated);\n const apps = [\n ...new Set((contexts ?? []).map((c) => c.applicationId).filter(Boolean)),\n ];\n if (!active) return;\n if (apps.length === 1) {\n setApplicationIdState(apps[0]);\n }\n // More than one, and this stays null ON PURPOSE. A tab holds one\n // application's UI and nothing here says which — the account simply has\n // contexts for several. Picking the first would silently point the app at\n // another app's contract, which answers none of its methods; admitting\n // \"I don't know\" leaves the app's own \"waiting for this session to report\n // which application\" message honest, and a chooser is the follow-up.\n //\n // Zero contexts also stays null: there is no application to infer.\n } catch {\n // Left null, and deliberately not surfaced as a connection failure. The\n // writes work — every one carries its own warrant — and a read that did\n // not answer must not unwind a connection that did.\n }\n })();\n\n return () => {\n active = false;\n // `close` is a node-client concern; a relay client has nothing to tear\n // down, so do not reach for it.\n };\n }, [delegated, contextId]);\n\n // Initialization effect\n useEffect(() => {\n // A delegated tab is already connected by the effect above. This whole\n // path — callback parsing, token adoption, node-URL trust, /auth/validate —\n // describes a session the delegated client does not have.\n if (delegated) return;\n\n let active = true;\n\n const init = async () => {\n const callback = callbackRef.current;\n let nodeFromCallback: string | null = null;\n\n if (callback) {\n // Read BEFORE the callback overwrites either of them.\n // - initiatedNodeUrl: the node login was initiated with — the trust anchor.\n // - tokenNodeUrl: the node that minted the bundle currently in the store.\n // They differ exactly when the user is switching nodes: `connectToNode`\n // points NODE_URL at the *target* node before redirecting, while the store\n // still holds the *previous* node's bundle. Falling back to the initiated\n // node keeps sessions that predate TOKEN_NODE_URL working.\n const initiatedNodeUrl = getNodeUrl();\n const tokenNodeUrl = getTokenNodeUrl() ?? initiatedNodeUrl;\n\n // The callback URL is attacker-influenceable, so validate its node_url\n // BEFORE storing tokens or connecting — otherwise a malicious node_url\n // would receive the freshly-minted tokens (exfiltration).\n const { url, rejected } = resolveTrustedNodeUrl({\n candidate: callback.nodeUrl,\n initiated: initiatedNodeUrl,\n allowedNodeUrls,\n });\n\n // Always strip the callback params (tokens + node_url) from the address\n // bar and consume the parsed callback, whatever the trust outcome.\n if (isBrowser) {\n window.history.replaceState({}, '', window.location.pathname + window.location.search);\n }\n callbackRef.current = null;\n\n if (rejected) {\n // Untrusted node_url — likely a token-exfiltration attempt. Drop the\n // callback's tokens, but DON'T return: fall through to restore any\n // existing session from storage so a tampered callback can't log a\n // legitimately authenticated user out.\n console.error(\n '[MeroProvider] OAuth callback node_url is not trusted (it does not match the node ' +\n 'login was initiated with, nor `allowedNodeUrls`). Ignoring the callback; no tokens stored.',\n );\n } else if (url) {\n // Trusted node → the callback's tokens MAY be persisted. Whether they\n // SHOULD be is a separate question: refresh tokens are single-use since\n // core 0.11.0 (calimero-network/core#3083), so blindly writing the hash\n // bundle over a bundle mero-js has already rotated resurrects a consumed\n // refresh token — the node reads that as theft (`x-auth-error:\n // token_reuse`) and revokes the entire token family, hard-logging out\n // every holder. Adopt only a fresh, newer, or different-node bundle, and\n // merge rather than replace so an access-only hash (hosts are dropping\n // `refresh_token` from the hash) can never strip a live refresh token.\n const decision = resolveTokenAdoption({\n callbackAccessToken: callback.accessToken,\n callbackRefreshToken: callback.refreshToken,\n callbackNodeUrl: url,\n stored: tokenStore.getTokens(),\n storedNodeUrl: tokenNodeUrl,\n });\n\n if (decision.adopt) {\n tokenStore.setTokens(decision.tokens);\n setTokenNodeUrl(url);\n } else {\n console.warn(\n '[MeroProvider] Ignoring the SSO callback token bundle: it is stale (not newer than ' +\n 'the tokens already stored for this node). Adopting it would replay an already-rotated ' +\n 'refresh token, which the node revokes the whole token family for.',\n );\n }\n\n if (callback.applicationId) {\n setApplicationId(callback.applicationId);\n if (active) setApplicationIdState(callback.applicationId);\n }\n if (callback.contextId) {\n setContextId(callback.contextId);\n if (active) setContextIdState(callback.contextId);\n }\n if (callback.contextIdentity) {\n setContextIdentity(callback.contextIdentity);\n if (active) setContextIdentityState(callback.contextIdentity);\n }\n\n setNodeUrl(url);\n if (active) setNodeUrlState(url);\n nodeFromCallback = url;\n }\n // url === null && !rejected → callback had no node to bind to; ignore it.\n }\n\n const savedUrl = nodeFromCallback || getNodeUrl();\n if (!savedUrl) {\n if (active) setIsLoading(false);\n return;\n }\n\n const instance = createMeroInstance(savedUrl);\n const authed = await checkAuth(instance);\n\n if (!active) return;\n\n if (authed) {\n setMero(instance);\n setIsAuthenticated(true);\n setIsOnline(true);\n } else if (nodeFromCallback) {\n setMero(instance);\n }\n\n setIsLoading(false);\n };\n\n init().catch((err) => {\n console.error('[MeroProvider] Initialization failed:', err);\n if (active) setIsLoading(false);\n });\n\n return () => {\n active = false;\n };\n }, [createMeroInstance, checkAuth, allowedNodeUrls, tokenStore, delegated]);\n\n // SSE connection for online/offline detection — no polling.\n useEffect(() => {\n if (!isAuthenticated || !meroRef.current) return;\n\n let active = true;\n const sse = meroRef.current.events;\n\n const onConnect = () => { if (active) setIsOnline(true); };\n const onError = (err: Error) => {\n if (!active) return;\n setIsOnline(false);\n\n // A delegated stream has no token to renew. It is authenticated by a\n // request proof the device key signs for each connect, so a 401 here is\n // not an expiry the recovery below can fix — and that recovery ends in\n // `logout()`, which would tear down a connection whose credential is\n // still perfectly good. Report offline and let the client reconnect.\n if (delegated) return;\n\n // ── Which stream failures are worth acting on ──────────────────────────\n //\n // This used to be `if (!err.message.includes('401')) return;`, and the\n // comment under it explained that mero-js threw a bare\n // `SSE connection failed: <status>`, so nothing better was available.\n // That stopped being true in mero-js 19.14.1 (#166): the SSE path now\n // throws the same typed errors the request path does, carrying the\n // status and the `x-auth-error` header.\n //\n // Matching on '401' was not merely coarse, it was aimed at the wrong\n // number. Core answers a dead or under-scoped token on `/sse` with\n // **403**, not 401 — `token_expired` is the only 401 a stream sees. So\n // every failure that actually needed acting on was the one this gate\n // dropped, and the app sat at `isOnline = false` with no way back and no\n // prompt to log in again.\n //\n // Three cases now, because they need three different answers.\n\n // 1. The token family is gone (403 `token_revoked`, or a 401\n // `token_reuse`). mero-js has already STOPPED reconnecting — every\n // retry re-sends the same dead credential — so nothing will reopen\n // this stream, and there is no refresh token left to spend either.\n if (err instanceof AuthRevokedError) {\n logout();\n return;\n }\n\n if (err instanceof HTTPError && err.status === 403) {\n // 2. The token is live but was minted without `context:subscribe`.\n // Core requires that grant for `/sse`, `/sse/subscription` and\n // `/ws`, and the grant set is baked in at MINT time — so a refresh\n // re-issues the same unusable token and the stream 403s again,\n // forever. mero-react 9.1.2 (#73) fixed what we ASK for; a client\n // key minted before it can only be replaced by a fresh login.\n // `checkAuth` would return true here and reconnect us into that\n // loop, which is why this case must not go through it.\n if (err.headers?.get('x-auth-error') === 'permission_denied') {\n console.warn(\n '[MeroProvider] This session cannot open an event stream ' +\n '(403 permission_denied): its token predates the context:subscribe ' +\n 'grant. Logging out — a fresh login mints a key that can subscribe.',\n );\n logout();\n return;\n }\n // 3. Any other 403 is core refusing this caller for a reason a new\n // token would not change — \"Forbidden: not the session owner\". Not\n // an auth-token problem, so do not spend the session on it.\n return;\n }\n\n // A 401 is NOT proof the session is over, and it used to be treated as\n // such: `logout()` wipes the token store, so an expired access token cost\n // the user their still-valid 30-day refresh token and forced a real\n // re-login.\n //\n // The stream authenticates only at connect time (an open stream survives\n // expiry), so this fires on the first reconnect after the access token\n // ages out — a sleep/wake, a network blip, a PWA resume, a node restart.\n // Routine events, all of them. Ask `checkAuth`, which recovers a\n // merely-expired token via the transport's refresh and returns false only\n // when the session is genuinely dead.\n //\n // The string check stays as a fallback: not every caller is on 19.14.1,\n // and an older mero-js still reports this as `SSE connection failed: 401`.\n const status = err instanceof HTTPError ? err.status : null;\n if (status !== 401 && !err.message.includes('401')) return;\n\n if (recoveringRef.current) return;\n recoveringRef.current = true;\n void (async () => {\n try {\n const instance = meroRef.current;\n if (!instance) return;\n if (await checkAuth(instance)) {\n // Renewed. mero-js's `onTokenRefresh` hook has already updated the\n // instance's in-memory token, so the SseClient's `getAuthToken`\n // hands the reconnect the new one.\n if (active) await instance.events.connect().catch(() => {});\n return;\n }\n if (active) logout();\n } finally {\n recoveringRef.current = false;\n }\n })();\n };\n\n sse.on('connect', onConnect);\n sse.on('error', onError);\n sse.connect().catch(() => { if (active) setIsOnline(false); });\n\n return () => {\n active = false;\n sse.off('connect', onConnect);\n sse.off('error', onError);\n };\n // `checkAuth` and `logout` are both useCallback-stable (they close over the\n // memoized `tokenStore`), so listing them does not re-subscribe the stream.\n // Not for a delegated client: this stream is opened from the node client's\n // own `events`, and a relay client observes only when it was given the\n // relay's node key — which `buildDelegatedClient` wires up itself.\n }, [isAuthenticated, mero, checkAuth, logout, delegated]);\n\n const contextValue = useMemo<MeroContextValue>(\n () => ({\n mero,\n isAuthenticated,\n isOnline,\n nodeUrl,\n applicationId,\n contextId,\n contextIdentity,\n connectToNode,\n connectWithAccount,\n isDelegated: delegated !== null,\n can: delegated !== null\n // An account founds a namespace through its relay and gives it this\n // app's application (core#4269): possible only when the app names its\n // registry package. Invitations are still a node's to mint.\n ? { createNamespace: Boolean(packageName), createContext: true, invite: false }\n : { createNamespace: true, createContext: true, invite: true },\n app: { packageName, packageVersion, registryUrl },\n logout,\n isLoading,\n }),\n [mero, isAuthenticated, isOnline, nodeUrl, applicationId, contextId, contextIdentity, connectToNode, connectWithAccount, delegated, logout, isLoading, packageName, packageVersion, registryUrl],\n );\n\n return (\n <MeroContext.Provider value={contextValue}>\n {children}\n </MeroContext.Provider>\n );\n}\n\nexport function useMero(): MeroContextValue {\n const context = useContext(MeroContext);\n if (!context) {\n throw new Error('useMero must be used within a MeroProvider');\n }\n return context;\n}\n\nexport { MeroContext };\n","/**\n * CalimeroLogo - the official Calimero emblem.\n *\n * Uses `currentColor` for fills so the consumer can theme it with `color`,\n * a `style.color` override, or by passing `color` directly.\n */\n\nimport React from 'react';\n\nexport interface CalimeroLogoProps extends React.SVGAttributes<SVGSVGElement> {\n /** Width / height shorthand (applied to both). Default: 24. */\n size?: number | string;\n}\n\nexport function CalimeroLogo({\n size = 24,\n color,\n style,\n ...rest\n}: CalimeroLogoProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 193 193\"\n fill={color ?? 'currentColor'}\n style={style}\n xmlns=\"http://www.w3.org/2000/svg\"\n aria-hidden=\"true\"\n {...rest}\n >\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M13.5969 23.2235C63.4924 -4.81833 123.53 2.55678 148.374 10.0273C153.006 11.4201 155.606 16.2198 154.181 20.7478C152.757 25.2758 147.846 27.8173 143.214 26.4245C120.866 19.7045 66.3988 13.3369 22.3442 38.0961C21.3748 38.6409 20.8298 39.6384 20.8808 40.6778C22.5544 74.7376 40.6646 139.735 103.059 173.709C107.293 176.015 108.813 181.238 106.455 185.377C104.096 189.516 98.7523 191.002 94.5186 188.696C24.7767 150.721 5.18199 78.7606 3.35124 41.5008C2.98177 33.9812 6.96683 26.9496 13.5969 23.2235Z\"\n />\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M180.214 22.5271C185.054 22.2785 189.183 25.9121 189.437 30.6429C192.776 92.7591 159.782 138.316 138.517 157.587C133.185 162.419 125.221 164.303 117.934 161.241C102.817 154.887 88.1835 141.52 76.3001 128.189C64.2403 114.66 54.1712 100.2 48.3006 90.492C45.8345 86.4139 47.2173 81.1537 51.3891 78.743C55.561 76.3323 60.9421 77.684 63.4082 81.7621C68.803 90.6832 78.2588 104.272 89.5315 116.919C100.981 129.763 113.488 140.698 124.866 145.48C125.179 145.612 125.851 145.671 126.586 145.006C145.206 128.132 174.903 87.1988 171.912 31.5431C171.657 26.8122 175.374 22.7756 180.214 22.5271Z\"\n />\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M85.9137 55.4487C70.263 57.0264 57.2007 60.7039 50.4014 63.4262C45.9168 65.2218 40.7922 63.1236 38.9553 58.7397C37.1184 54.3559 39.2649 49.3464 43.7495 47.5508C52.2083 44.164 66.9167 40.1173 84.1135 38.3837C101.323 36.649 121.62 37.1693 140.947 43.4423C149.244 46.1351 155.088 53.9217 154.482 62.8728C153.225 81.429 144.514 100.403 127.158 122.145C124.177 125.88 118.663 126.546 114.842 123.631C111.021 120.717 110.341 115.327 113.322 111.592C129.481 91.3484 136.032 75.6017 136.971 61.7394C137.02 61.0029 136.547 60.0904 135.417 59.7238C119.18 54.4537 101.552 53.8722 85.9137 55.4487Z\"\n />\n </svg>\n );\n}\n\nexport default CalimeroLogo;\n","/**\n * Theme tokens for mero-react components.\n *\n * Defaults match the green palette used across Calimero apps (admin-dashboard,\n * tauri-app, app-registry). Pass a partial `MeroTheme` to `ConnectButton` or\n * `LoginModal` to override any token.\n */\n\nimport type { CSSProperties } from 'react';\n\nexport interface MeroTheme {\n /** Primary accent / CTA color */\n primary?: string;\n /** Primary accent on hover */\n primaryHover?: string;\n /** Text color rendered on top of `primary` (e.g. inside the Connect button when connected) */\n primaryText?: string;\n /** Main surface color (modal background, button background) */\n background?: string;\n /** Secondary surface color (input fields, info chips) */\n backgroundSecondary?: string;\n /** Tertiary surface color (subtle elevation) */\n backgroundTertiary?: string;\n /** Border color */\n border?: string;\n /** Primary text color */\n text?: string;\n /** Muted / secondary text color */\n textSecondary?: string;\n /** Error / danger color */\n error?: string;\n /** Modal backdrop color */\n overlay?: string;\n /** Border radius (any CSS length) */\n radius?: string;\n}\n\nexport type ResolvedMeroTheme = Required<MeroTheme>;\n\nexport const defaultMeroTheme: Readonly<ResolvedMeroTheme> = Object.freeze({\n primary: '#a5ff11',\n primaryHover: '#8ed40d',\n primaryText: '#0d1117',\n background: '#0d1117',\n backgroundSecondary: '#161b22',\n backgroundTertiary: '#1c2128',\n border: '#30363d',\n text: '#e6edf3',\n textSecondary: '#8b949e',\n error: '#ff6b6b',\n overlay: 'rgba(0, 0, 0, 0.75)',\n radius: '8px',\n});\n\n/**\n * Merge a partial theme with the defaults.\n *\n * Filtering rules — values that fall back to the default:\n * - `undefined` (the prop key wasn't set, or was set to `undefined`)\n * - empty string `''`\n * - whitespace-only strings (e.g. `' '`)\n *\n * These are dropped because they're invalid CSS and would produce\n * invisible elements (transparent backgrounds, missing borders, etc.).\n * If you genuinely want the browser default for a token, omit the key\n * from the theme prop rather than passing an empty string.\n *\n * Any other non-empty string is forwarded as-is — CSS syntax itself\n * is NOT validated.\n */\nexport function resolveMeroTheme(theme?: MeroTheme): ResolvedMeroTheme {\n if (!theme) return { ...defaultMeroTheme };\n const filtered = Object.fromEntries(\n Object.entries(theme).filter(\n ([, v]) => v !== undefined && typeof v === 'string' && v.trim() !== '',\n ),\n ) as Partial<MeroTheme>;\n return { ...defaultMeroTheme, ...filtered };\n}\n\n/**\n * Single source of truth mapping each `MeroTheme` token name to the CSS\n * custom-property name it surfaces as. Used by `themeToCssVars` to emit the\n * inline-style map and by component code (e.g. `LoginModal`) to read the\n * variable in inline styles via `var(--mero-*, fallback)`.\n *\n * Adding a new token? Add it here, in `MeroTheme`, and in `defaultMeroTheme`,\n * and the rest of the system picks it up automatically.\n */\nexport const MERO_CSS_VARS: Record<keyof MeroTheme, string> = {\n background: '--mero-bg',\n backgroundSecondary: '--mero-bg-secondary',\n backgroundTertiary: '--mero-bg-tertiary',\n text: '--mero-text',\n textSecondary: '--mero-text-secondary',\n primary: '--mero-accent',\n primaryHover: '--mero-accent-hover',\n primaryText: '--mero-on-primary',\n border: '--mero-border',\n error: '--mero-error',\n overlay: '--mero-overlay',\n radius: '--mero-radius',\n};\n\n/**\n * Build a `style` object that exposes a resolved theme as CSS variables, so\n * descendant CSS rules (e.g. those in `styles.css`) pick up the overrides.\n */\nexport function themeToCssVars(theme: ResolvedMeroTheme): CSSProperties {\n const vars: Record<string, string> = {};\n for (const key of Object.keys(MERO_CSS_VARS) as Array<keyof MeroTheme>) {\n vars[MERO_CSS_VARS[key]] = theme[key];\n }\n return vars as CSSProperties;\n}\n\n/**\n * Returns a `var(--mero-*, fallback)` reference for a theme token, suitable\n * for inline styles in portal-rendered components where descendant CSS\n * variables also need to support global `:root` overrides.\n */\nexport function cssVar(theme: ResolvedMeroTheme, key: keyof MeroTheme): string {\n return `var(${MERO_CSS_VARS[key]}, ${theme[key]})`;\n}\n","/**\n * LoginModal - Modal for connecting to a Calimero node\n *\n * A single section: the modal auto-discovers nodes on the well-known local\n * ports (see `nodeDiscovery`) and offers whatever is running as radio choices,\n * plus an always-available \"enter URL manually\" option. With nothing found it\n * falls straight through to manual URL entry.\n *\n * The old Local/Remote tabs are gone — the \"Local\" tab pointed at a hardcoded\n * default node (`node1.127.0.0.1.nip.io`) that doesn't resolve in most setups;\n * discovery + manual entry covers both cases properly.\n */\n\nimport { useMemo, useState, useEffect, useCallback, useRef } from 'react';\nimport { createPortal } from 'react-dom';\nimport { CalimeroLogo } from './CalimeroLogo';\nimport type { ConnectionType, CustomConnectionConfig } from '../types';\nimport {\n discoverLocalNodes,\n nodeEndpoint,\n DEFAULT_LOCAL_NODE_PORTS,\n} from '@calimero-network/mero-js';\nimport {\n cssVar,\n resolveMeroTheme,\n themeToCssVars,\n type MeroTheme,\n type ResolvedMeroTheme,\n} from '../theme';\n\n/** Sentinel selection value for the manual \"enter a URL\" option. */\nconst CUSTOM_SELECTION = '__custom__';\n\nexport interface LoginModalProps {\n /** Callback when user connects */\n onConnect: (url: string) => void;\n /** Callback when modal is closed */\n onClose: () => void;\n /**\n * @deprecated Ignored. The modal always shows node discovery + manual URL\n * entry; the old hardcoded-default \"Local\" view was removed. Kept so\n * existing call sites keep compiling.\n */\n connectionType?: ConnectionType | CustomConnectionConfig;\n /** Whether the modal is open */\n isOpen: boolean;\n /** Theme overrides — accepts any subset of `MeroTheme` tokens */\n theme?: MeroTheme;\n /**\n * Ports probed when discovering local nodes. Defaults to the well-known\n * Calimero dev ports (2428, 2429, 2528, 2529). Mostly an escape hatch for\n * non-standard setups and tests.\n */\n localNodePorts?: readonly number[];\n}\n\n/**\n * Validate URL format\n */\nfunction isValidUrl(urlString: string): boolean {\n if (!urlString || urlString.trim() === '') {\n return false;\n }\n\n try {\n const urlToTest =\n urlString.startsWith('http://') || urlString.startsWith('https://')\n ? urlString\n : `https://${urlString}`;\n\n const url = new URL(urlToTest);\n\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n return false;\n }\n\n if (!url.hostname) {\n return false;\n }\n\n const hostname = url.hostname;\n\n // Allow localhost\n if (hostname === 'localhost') {\n return true;\n }\n\n // Check for valid IP address\n const ipv4Regex = /^(\\d{1,3}\\.){3}\\d{1,3}$/;\n if (ipv4Regex.test(hostname)) {\n const octets = hostname.split('.').map(Number);\n return octets.every((octet) => octet >= 0 && octet <= 255);\n }\n\n // Check for valid domain name\n const domainRegex =\n /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n return domainRegex.test(hostname);\n } catch {\n return false;\n }\n}\n\n/** Strip the scheme for a compact node label (e.g. `localhost:2428`). */\nfunction displayNodeUrl(url: string): string {\n return url.replace(/^https?:\\/\\//, '').replace(/\\/+$/, '');\n}\n\n/**\n * Mix a color with transparent using CSS `color-mix`. Works for any valid CSS\n * color value (hex of any length, rgb(), hsl(), named colors, var(...)) — not\n * just 6-digit hex.\n */\nfunction tint(color: string, percent: number): string {\n return `color-mix(in srgb, ${color} ${percent}%, transparent)`;\n}\n\n/**\n * Build the inline-style map from a resolved theme. Each value is emitted as\n * `var(--mero-*, fallback)` so a global `:root { --mero-* }` rule reaches the\n * portal-rendered modal; the fallback ensures the modal still renders correctly\n * if the consumer hasn't imported `styles.css`.\n */\nfunction buildStyles(t: ResolvedMeroTheme) {\n const bg = cssVar(t, 'background');\n const bgSecondary = cssVar(t, 'backgroundSecondary');\n const text = cssVar(t, 'text');\n const textSecondary = cssVar(t, 'textSecondary');\n const accent = cssVar(t, 'primary');\n const onPrimary = cssVar(t, 'primaryText');\n const border = cssVar(t, 'border');\n const error = cssVar(t, 'error');\n const overlay = cssVar(t, 'overlay');\n const radius = cssVar(t, 'radius');\n\n const errorBg = tint(error, 10);\n const errorBorder = tint(error, 30);\n const accentGlow = tint(accent, 15);\n\n return {\n overlay: {\n position: 'fixed' as const,\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n backgroundColor: overlay,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n zIndex: 10000,\n padding: '1rem',\n animation: 'meroFadeIn 0.2s ease-out',\n },\n content: {\n backgroundColor: bg,\n borderRadius: radius,\n padding: '2rem',\n maxWidth: '420px',\n width: '100%',\n position: 'relative' as const,\n border: `1px solid ${border}`,\n boxShadow: `0 25px 50px -12px rgba(0, 0, 0, 0.6), 0 0 0 1px ${accentGlow}`,\n animation: 'meroSlideIn 0.25s ease-out',\n color: text,\n },\n closeButton: {\n position: 'absolute' as const,\n top: '0.75rem',\n right: '0.75rem',\n background: 'none',\n border: 'none',\n fontSize: '1.5rem',\n color: textSecondary,\n cursor: 'pointer',\n padding: '0.25rem',\n lineHeight: 1,\n },\n header: {\n display: 'flex',\n flexDirection: 'column' as const,\n alignItems: 'center',\n gap: '0.75rem',\n marginBottom: '1.5rem',\n },\n title: {\n fontSize: '1.25rem',\n fontWeight: 600,\n color: text,\n margin: 0,\n },\n info: {\n color: textSecondary,\n textAlign: 'center' as const,\n marginBottom: '1.5rem',\n fontSize: '0.875rem',\n },\n error: {\n color: error,\n backgroundColor: errorBg,\n border: `1px solid ${errorBorder}`,\n borderRadius: radius,\n padding: '0.75rem',\n marginBottom: '1rem',\n fontSize: '0.875rem',\n textAlign: 'center' as const,\n },\n radioList: {\n display: 'flex',\n flexDirection: 'column' as const,\n gap: '0.5rem',\n marginBottom: '1rem',\n },\n radioItem: {\n display: 'flex',\n alignItems: 'center',\n gap: '0.625rem',\n color: text,\n cursor: 'pointer',\n padding: '0.75rem 1rem',\n borderRadius: radius,\n border: `1px solid ${border}`,\n backgroundColor: bgSecondary,\n transition: 'all 0.15s ease',\n fontSize: '0.875rem',\n },\n radioItemActive: {\n // Override the full `border` shorthand (not just borderColor) so React\n // never has to mix shorthand + longhand on the same element.\n border: `1px solid ${accent}`,\n backgroundColor: accentGlow,\n color: text,\n },\n radioIndicator: {\n flexShrink: 0,\n width: '1rem',\n height: '1rem',\n borderRadius: '50%',\n border: `2px solid ${border}`,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n },\n radioIndicatorActive: {\n border: `2px solid ${accent}`,\n },\n radioDot: {\n width: '0.5rem',\n height: '0.5rem',\n borderRadius: '50%',\n backgroundColor: accent,\n },\n nodeMeta: {\n marginLeft: 'auto',\n fontSize: '0.75rem',\n color: textSecondary,\n },\n input: {\n width: '100%',\n padding: '0.75rem 1rem',\n borderRadius: radius,\n border: `1px solid ${border}`,\n backgroundColor: bgSecondary,\n color: text,\n fontSize: '0.875rem',\n outline: 'none',\n marginBottom: '1rem',\n boxSizing: 'border-box' as const,\n },\n toolbar: {\n display: 'flex',\n justifyContent: 'center',\n marginBottom: '1rem',\n },\n rescan: {\n background: 'none',\n border: 'none',\n color: accent,\n cursor: 'pointer',\n fontSize: '0.8125rem',\n padding: '0.25rem 0.5rem',\n },\n buttonGroup: {\n display: 'flex',\n justifyContent: 'center',\n },\n button: {\n padding: '0.75rem 2rem',\n borderRadius: radius,\n border: 'none',\n fontSize: '0.875rem',\n fontWeight: 600,\n cursor: 'pointer',\n backgroundColor: accent,\n color: onPrimary,\n transition: 'all 0.15s ease',\n },\n buttonDisabled: {\n opacity: 0.5,\n cursor: 'not-allowed',\n },\n loading: {\n display: 'flex',\n flexDirection: 'column' as const,\n alignItems: 'center',\n gap: '1rem',\n padding: '2rem',\n color: textSecondary,\n },\n discovering: {\n display: 'flex',\n flexDirection: 'column' as const,\n alignItems: 'center',\n gap: '0.75rem',\n padding: '1rem',\n color: textSecondary,\n fontSize: '0.875rem',\n },\n spinner: {\n width: '2rem',\n height: '2rem',\n border: `3px solid ${border}`,\n borderTopColor: accent,\n borderRadius: '50%',\n animation: 'meroSpin 1s linear infinite',\n },\n spinnerSmall: {\n width: '1.5rem',\n height: '1.5rem',\n border: `3px solid ${border}`,\n borderTopColor: accent,\n borderRadius: '50%',\n animation: 'meroSpin 1s linear infinite',\n },\n };\n}\n\n/**\n * LoginModal - Connection modal component\n */\nexport function LoginModal({\n onConnect,\n onClose,\n isOpen,\n theme,\n localNodePorts = DEFAULT_LOCAL_NODE_PORTS,\n}: LoginModalProps) {\n // `selected` is a discovered node URL or CUSTOM.\n const [selected, setSelected] = useState<string>(CUSTOM_SELECTION);\n const [discovered, setDiscovered] = useState<string[]>([]);\n const [discovering, setDiscovering] = useState<boolean>(false);\n const [customUrl, setCustomUrl] = useState<string>('');\n\n const [loading, setLoading] = useState<boolean>(false);\n const [error, setError] = useState<string | null>(null);\n\n const resolved = useMemo(() => resolveMeroTheme(theme), [theme]);\n const styles = useMemo(() => buildStyles(resolved), [resolved]);\n // Only emit inline `--mero-*` variables when a `theme` prop was actually\n // provided. Without a prop, we let global `:root { --mero-* }` rules cascade\n // through to the portal-rendered modal (with `var()` fallbacks in buildStyles\n // covering the case where no global rules are loaded).\n const themeVars = useMemo(\n () => (theme ? themeToCssVars(resolved) : undefined),\n [theme, resolved],\n );\n\n // Load saved URL into the manual field\n useEffect(() => {\n const savedUrl = localStorage.getItem('mero:node_url');\n if (savedUrl) {\n setCustomUrl(savedUrl);\n }\n }, []);\n\n // Probe local ports whenever the modal is open; a bumpable nonce lets the\n // user trigger a re-scan.\n const [scanNonce, setScanNonce] = useState(0);\n const portsKey = useMemo(() => localNodePorts.join(','), [localNodePorts]);\n\n useEffect(() => {\n if (!isOpen) {\n return;\n }\n\n const controller = new AbortController();\n let active = true;\n setDiscovering(true);\n // Clear any prior results so a re-scan never shows stale nodes.\n setDiscovered([]);\n setError(null);\n\n discoverLocalNodes({ ports: localNodePorts, signal: controller.signal })\n .then((nodes) => {\n if (!active) return;\n setDiscovered(nodes);\n // Default to the first discovered node, else fall through to manual.\n setSelected(nodes.length > 0 ? nodes[0] : CUSTOM_SELECTION);\n })\n // discoverLocalNodes is designed never to reject; the catch is purely\n // defensive so a future change can't surface an unhandled rejection.\n .catch(() => {\n if (active) setSelected(CUSTOM_SELECTION);\n })\n .finally(() => {\n if (active) setDiscovering(false);\n });\n\n return () => {\n active = false;\n controller.abort();\n };\n // portsKey captures localNodePorts content; scanNonce forces a re-scan.\n }, [isOpen, portsKey, scanNonce]);\n\n const isCustom = selected === CUSTOM_SELECTION;\n const hasDiscovered = discovered.length > 0;\n\n // Whether the connect button can fire in the current state.\n const canConnect =\n !loading && !discovering && (isCustom ? isValidUrl(customUrl) : true);\n\n // Keep a ref so the input's keydown handler always sees current validity.\n const canConnectRef = useRef(canConnect);\n canConnectRef.current = canConnect;\n\n const handleConnect = useCallback(async () => {\n const usingDiscovered = selected !== CUSTOM_SELECTION;\n const targetUrl = usingDiscovered ? selected : customUrl;\n\n // Manual URLs must look valid before we try them.\n if (!usingDiscovered && !isValidUrl(targetUrl)) {\n return;\n }\n\n const normalizedUrl = targetUrl.replace(/\\/+$/, '');\n\n // A discovered node already answered a health check — connect straight away.\n if (usingDiscovered) {\n onConnect(normalizedUrl);\n return;\n }\n\n // Manually entered URLs are verified via is-authed.\n setLoading(true);\n setError(null);\n\n try {\n const response = await fetch(\n nodeEndpoint(normalizedUrl, 'admin-api/is-authed'),\n );\n\n if (response.ok || response.status === 401) {\n setLoading(false);\n onConnect(normalizedUrl);\n } else {\n throw new Error(`Connection failed: ${response.statusText}`);\n }\n } catch (err) {\n console.error('Connection failed:', err);\n setError('Failed to connect. Please check the URL and try again.');\n setLoading(false);\n }\n }, [selected, customUrl, onConnect]);\n\n if (!isOpen) {\n return null;\n }\n\n const showManualInput = isCustom;\n const renderRadio = (value: string, label: string, meta?: string) => {\n const active = selected === value;\n return (\n // Selection is driven solely by the radio input's `onChange` — clicking\n // anywhere on the wrapping label forwards to the input, and keyboard\n // users can tab to / arrow through the (visually hidden but focusable)\n // input. A label `onClick` here would double-fire `setSelected`.\n <label\n key={value}\n data-testid={`node-option-${value === CUSTOM_SELECTION ? 'custom' : displayNodeUrl(value)}`}\n style={{\n ...styles.radioItem,\n ...(active ? styles.radioItemActive : {}),\n }}\n >\n <input\n type=\"radio\"\n name=\"mero-node\"\n value={value}\n checked={active}\n onChange={() => setSelected(value)}\n style={{ position: 'absolute', opacity: 0 }}\n />\n <span\n style={{\n ...styles.radioIndicator,\n ...(active ? styles.radioIndicatorActive : {}),\n }}\n >\n {active && <span style={styles.radioDot} />}\n </span>\n {label}\n {meta && <span style={styles.nodeMeta}>{meta}</span>}\n </label>\n );\n };\n\n const renderNodeSection = () => {\n if (discovering) {\n return (\n <div style={styles.discovering} data-testid=\"node-discovering\">\n <div style={styles.spinnerSmall} />\n <p>Searching for local nodes...</p>\n </div>\n );\n }\n\n return (\n <>\n <p style={styles.info}>\n {hasDiscovered\n ? 'Select your Calimero node to continue.'\n : 'No local node found. Enter a node URL to continue.'}\n </p>\n\n {hasDiscovered && (\n <div\n style={styles.radioList}\n role=\"radiogroup\"\n aria-label=\"Available nodes\"\n >\n {discovered.map((url) =>\n renderRadio(url, displayNodeUrl(url), 'local'),\n )}\n {/* Manual entry is always offered alongside discovered nodes. */}\n {renderRadio(CUSTOM_SELECTION, 'Enter node URL manually')}\n </div>\n )}\n\n {showManualInput && (\n <input\n type=\"text\"\n value={customUrl}\n onChange={(e) => setCustomUrl(e.target.value)}\n placeholder=\"https://your-node-url.calimero.network\"\n style={styles.input}\n data-testid=\"node-url-input\"\n autoFocus={!hasDiscovered}\n onKeyDown={(e) => {\n if (e.key === 'Enter' && canConnectRef.current) {\n handleConnect();\n }\n }}\n />\n )}\n\n <div style={styles.toolbar}>\n <button\n type=\"button\"\n style={styles.rescan}\n onClick={() => setScanNonce((n) => n + 1)}\n data-testid=\"rescan-button\"\n >\n ↻ Rescan local nodes\n </button>\n </div>\n </>\n );\n };\n\n const modalContent = (\n <>\n <style>{`\n @keyframes meroSpin { to { transform: rotate(360deg); } }\n @keyframes meroFadeIn { from { opacity: 0; } to { opacity: 1; } }\n @keyframes meroSlideIn { from { transform: translateY(-12px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }\n `}</style>\n <div style={{ ...themeVars, ...styles.overlay }} onClick={onClose}>\n <div style={styles.content} onClick={(e) => e.stopPropagation()}>\n <button style={styles.closeButton} onClick={onClose} aria-label=\"Close\">\n ×\n </button>\n\n <div style={styles.header}>\n <CalimeroLogo size={44} color={cssVar(resolved, 'primary')} />\n <h1 style={styles.title}>Connect to Calimero</h1>\n </div>\n\n {loading ? (\n <div style={styles.loading}>\n <p>Connecting to node...</p>\n <div style={styles.spinner} />\n </div>\n ) : (\n <>\n {error && <p style={styles.error}>{error}</p>}\n\n {renderNodeSection()}\n\n <div style={styles.buttonGroup}>\n <button\n onClick={handleConnect}\n disabled={!canConnect}\n style={{\n ...styles.button,\n ...(!canConnect ? styles.buttonDisabled : {}),\n }}\n data-testid=\"connect-button\"\n >\n Connect\n </button>\n </div>\n </>\n )}\n </div>\n </div>\n </>\n );\n\n return createPortal(modalContent, document.body);\n}\n\nexport default LoginModal;\n","/**\n * ConnectButton - A button component for connecting to Calimero\n *\n * Shows connection status and provides login/logout functionality.\n * Includes built-in LoginModal for node selection.\n */\n\nimport React, { useState, useEffect, useRef, useMemo } from 'react';\nimport { useMero } from '../context';\nimport { LoginModal } from './LoginModal';\nimport { CalimeroLogo } from './CalimeroLogo';\nimport type { ConnectionType, CustomConnectionConfig } from '../types';\nimport { ConnectionType as ConnectionTypeEnum } from '../types';\nimport { resolveMeroTheme, themeToCssVars, type MeroTheme } from '../theme';\n\nexport interface ConnectButtonProps {\n /**\n * Connection behaviour. `Custom` (object form) connects straight to the\n * given URL, skipping the modal; every other value opens the LoginModal,\n * which always shows node discovery + manual URL entry.\n */\n connectionType?: ConnectionType | CustomConnectionConfig;\n /** Custom class name */\n className?: string;\n /** Custom styles */\n style?: React.CSSProperties;\n /** Theme overrides — accepts any subset of `MeroTheme` tokens */\n theme?: MeroTheme;\n /**\n * Render only the Calimero logo, no text. Produces a square 40×40 icon\n * button. The label is still announced to screen readers via `aria-label`.\n * Default: false.\n */\n logoOnly?: boolean;\n /**\n * Override the default labels per state. A bare string is shorthand for\n * `{ connect: '<string>' }`. The connected and reconnecting states keep\n * their defaults unless explicitly overridden.\n */\n label?:\n | string\n | { connect?: string; connected?: string; reconnecting?: string };\n}\n\n/**\n * ConnectButton - Displays connection status and handles login/logout\n */\nexport function ConnectButton({\n connectionType = ConnectionTypeEnum.Remote,\n className,\n style,\n theme,\n logoOnly = false,\n label,\n}: ConnectButtonProps) {\n const { isAuthenticated, connectToNode, logout, nodeUrl, isOnline } = useMero();\n const [isDropdownOpen, setIsDropdownOpen] = useState(false);\n const [isModalOpen, setIsModalOpen] = useState(false);\n const dropdownRef = useRef<HTMLDivElement>(null);\n\n // Resolve once. Inline CSS variables are only emitted when a theme prop is\n // provided — otherwise we leave the cascade alone so global `:root { --mero-* }`\n // overrides take effect.\n const resolvedTheme = useMemo(\n () => (theme ? resolveMeroTheme(theme) : null),\n [theme],\n );\n const themeVars = useMemo(\n () => (resolvedTheme ? themeToCssVars(resolvedTheme) : undefined),\n [resolvedTheme],\n );\n\n // Close dropdown when clicking outside\n useEffect(() => {\n const handleClickOutside = (event: MouseEvent) => {\n if (\n dropdownRef.current &&\n !dropdownRef.current.contains(event.target as Node)\n ) {\n setIsDropdownOpen(false);\n }\n };\n document.addEventListener('mousedown', handleClickOutside);\n return () => document.removeEventListener('mousedown', handleClickOutside);\n }, []);\n\n const dashboardUrl = useMemo(() => {\n if (!isAuthenticated || !nodeUrl) return '#';\n return new URL('admin-dashboard/', nodeUrl).toString();\n }, [isAuthenticated, nodeUrl]);\n\n const labels = useMemo(() => {\n const overrides = typeof label === 'string' ? { connect: label } : label;\n return {\n connect: overrides?.connect ?? 'Connect',\n connected: overrides?.connected ?? 'Connected',\n reconnecting: overrides?.reconnecting ?? 'Reconnecting...',\n };\n }, [label]);\n\n const buttonClassName = logoOnly ? 'mero-logo-only' : '';\n\n const handleConnect = () => {\n // If Custom type with URL, connect directly\n if (\n typeof connectionType === 'object' &&\n connectionType.type === ConnectionTypeEnum.Custom\n ) {\n connectToNode(connectionType.url);\n return;\n }\n\n // Otherwise, open modal\n setIsModalOpen(true);\n };\n\n const handleModalConnect = (url: string) => {\n setIsModalOpen(false);\n connectToNode(url);\n };\n\n // Reconnecting state\n if (isAuthenticated && !isOnline) {\n return (\n <div\n className=\"mero-connect-container\"\n style={{ ...themeVars, display: 'inline-block' }}\n >\n <button\n className={['mero-connect-button', 'mero-reconnecting', buttonClassName, className].filter(Boolean).join(' ')}\n style={style}\n disabled\n aria-label={labels.reconnecting}\n title={logoOnly ? labels.reconnecting : undefined}\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n {!logoOnly && labels.reconnecting}\n </button>\n </div>\n );\n }\n\n // Connected state\n if (isAuthenticated) {\n return (\n <div\n ref={dropdownRef}\n className=\"mero-connect-container\"\n style={{ ...themeVars, position: 'relative', display: 'inline-block' }}\n >\n <button\n className={['mero-connect-button', 'mero-connected', buttonClassName, className].filter(Boolean).join(' ')}\n style={style}\n onClick={() => setIsDropdownOpen((prev) => !prev)}\n aria-label={labels.connected}\n title={logoOnly ? labels.connected : undefined}\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n {!logoOnly && labels.connected}\n </button>\n {isDropdownOpen && (\n <div className=\"mero-dropdown\">\n <div className=\"mero-dropdown-info\" title={nodeUrl || ''}>\n {nodeUrl}\n </div>\n <a\n href={dashboardUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"mero-dropdown-item\"\n >\n Dashboard\n </a>\n <button\n className=\"mero-dropdown-item\"\n onClick={() => {\n setIsDropdownOpen(false);\n logout();\n }}\n >\n Log out\n </button>\n </div>\n )}\n </div>\n );\n }\n\n // Disconnected state\n return (\n <div\n className=\"mero-connect-container\"\n style={{ ...themeVars, display: 'inline-block' }}\n >\n <button\n className={['mero-connect-button', buttonClassName, className].filter(Boolean).join(' ')}\n style={style}\n onClick={handleConnect}\n aria-label={labels.connect}\n title={logoOnly ? labels.connect : undefined}\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n {!logoOnly && labels.connect}\n </button>\n <LoginModal\n isOpen={isModalOpen}\n onConnect={handleModalConnect}\n onClose={() => setIsModalOpen(false)}\n theme={resolvedTheme ?? theme}\n />\n </div>\n );\n}\n\nexport default ConnectButton;\n","/**\n * ConnectButtonAccount — ConnectButton, plus a second way in.\n *\n * A copy of {@link ConnectButton} rather than a change to it, deliberately:\n * the node-login path is load-bearing for every shipped app, and this is an\n * experiment. `ConnectButton` and `LoginModal` are untouched.\n *\n * Two ways to connect, and the difference is who runs the node:\n *\n * - **I run a node** — exactly today's behaviour. `LoginModal` discovers nodes\n * or takes a URL, and `connectToNode` redirects into the node's auth flow.\n * - **I have an account** — no node. A wallet on another origin certifies this\n * tab's device key, and a relay writes on the account's behalf under warrants\n * signed here.\n *\n * ## One credential, two signatures over it\n *\n * The certificate the wallet mints is the whole of what this holds. The device\n * key it certifies signs two different things, and neither needs anything more:\n *\n * - a **warrant**, per intent, is what `rpc.execute` sends — an app's own logic,\n * including a generated ABI client, runs on this alone;\n * - a **request proof** (`X-Calimero-Proof`), per request, authenticates the\n * caller-scoped reads and the event stream. The node verifies the signature\n * against the certificate with no store read and no prior relationship, so\n * `getContexts` and `listNamespaces` answer this account's own and `/sse`\n * delivers this account's contexts.\n *\n * ## The pane asks for nothing\n *\n * It used to have three fields, and not one of them was a question an end user\n * could answer. All three are gone:\n *\n * - the **relay** is discovered. The same certificate proves the cloud's\n * account→relay lookup (`CloudClient.getAccountRelays`): the device signs an\n * account-bound nonce and the cloud names the relays. No cloud session, no\n * Google sign-in, no account root.\n * - the **wallet** is a platform constant, defaulted here, overridable only for\n * working on the wallet itself.\n * - the **context** is chosen after connecting, not before. `MeroContext` derives\n * this tab's `applicationId` from `admin.getContexts()` — caller-scoped by the\n * request proof — so an app's own context picker has what it needs and the\n * person picks from a list instead of pasting a 64-hex id.\n *\n * So the account path is one button.\n *\n * This pane used to ask for the relay node's signing key as well, to mint an\n * `account_proof` session with `login()`. Nothing needs it: the proof path was\n * measured serving the same reads and the same events without it, against a node\n * built from core `aecba573b`. A session remains the right shape where the device\n * key sits behind a boundary worth crossing once — a hardware key — which is not\n * this.\n */\n\nimport React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport {\n CloudClient,\n completeDeviceEnrolment,\n deviceEnrolmentUrl,\n readEnrolmentCallback,\n type CloudAccountRelay,\n type DeviceEnrolmentCallback,\n} from '@calimero-network/mero-js';\nimport { useMero } from '../context';\nimport { saveDelegatedCredential } from '../delegated/session';\nimport { LoginModal } from './LoginModal';\nimport { CalimeroLogo } from './CalimeroLogo';\nimport { resolveMeroTheme, themeToCssVars, type MeroTheme } from '../theme';\n\n/** Where this tab's device keypair lives. */\nconst DEVICE_KEY = 'calimero.device';\n/** The state parameter this tab sent to the wallet, to check what comes back. */\nconst STATE_KEY = 'calimero.enrol.state';\n\n/**\n * The hosted wallet, which is a property of the platform rather than of any app.\n *\n * A default here and not a required prop: every app that enrols an account\n * enrols it at the same wallet, so making each one name it would be asking a\n * question with one answer — and an app that got it wrong would send a device key\n * to the wrong origin.\n */\nconst HOSTED_WALLET = 'https://wallet.cloud.calimero.network/account-enroll';\n\nexport interface ConnectButtonAccountProps {\n className?: string;\n style?: React.CSSProperties;\n theme?: MeroTheme;\n /**\n * Overrides for local development. An app in production passes none of this,\n * and the pane asks the person for nothing at all.\n *\n * Nothing here is a value an end user could know, which is precisely why none\n * of it is a form field any more:\n *\n * - the **relay** is discovered — the certificate the enrolment returns proves\n * the cloud's account→relay lookup, so there is nothing to type and a prefill\n * would only be a staler second source of truth;\n * - the **context** is chosen after connecting, from the account's own contexts,\n * which `admin.getContexts()` answers caller-scoped through the request proof.\n */\n defaults?: {\n /**\n * Point enrolment at a wallet other than the hosted one.\n *\n * Exists for working ON the wallet: a wallet served from `localhost:8090`\n * cannot be reached through the hosted URL, and without this the only way to\n * test a wallet change would be to deploy it.\n */\n walletUrl?: string;\n };\n}\n\nconst hex = (b: ArrayBuffer | Uint8Array): string =>\n [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, '0')).join('');\n\n/**\n * Which of the account's relays to talk to, and what to say about it.\n *\n * Four outcomes, and the connection is made in ALL of them — what differs is\n * whether there is somewhere to write yet, and what the person is told:\n *\n * - a **fresh** relay with an address: use it, say nothing;\n * - only **stale** ones: use one anyway — the cloud reports `fresh` from a\n * heartbeat, and a heartbeat that lapsed a minute ago is not the same claim as\n * a node that is gone — but say so, because if the writes then fail this is\n * why;\n * - **rows with no address**: relays are assigned and the cloud has no URL for\n * any of them yet, which is the shape a node reports before its first\n * heartbeat lands. A wait.\n * - **no rows at all**: the normal state of a brand-new account. It is a member\n * of nothing, so nothing serves it.\n *\n * ## Why the last two connect instead of refusing\n *\n * This used to return \"not connected\" for both, and that was wrong in the case\n * it mattered most: you get invited *because* you are signed in, and accepting\n * an invitation is what earns a relay. Refusing to log the account in until it\n * had one locked a new account out of the only path that would give it one.\n *\n * Nothing is faked to achieve it. The session carries `relayUrl: null`, so no\n * client is built, `mero` stays `null`, and a write is told the relay is\n * missing rather than being sent to a guess.\n */\nfunction chooseRelay(relays: readonly CloudAccountRelay[]): {\n relayUrl: string | null;\n note: string | null;\n} {\n const reachable = relays.filter(\n (r): r is CloudAccountRelay & { relayUrl: string } => typeof r.relayUrl === 'string' && r.relayUrl.length > 0,\n );\n const fresh = reachable.find((r) => r.fresh);\n if (fresh) return { relayUrl: fresh.relayUrl, note: null };\n if (reachable.length > 0) {\n return {\n relayUrl: reachable[0].relayUrl,\n note:\n 'Connected through a relay whose last heartbeat has lapsed — it may not answer. It was ' +\n 'the only one with an address.',\n };\n }\n if (relays.length > 0) {\n return {\n relayUrl: null,\n note:\n `Signed in. Your account has ${relays.length} relay${relays.length === 1 ? '' : 's'} ` +\n 'assigned, but the cloud knows no address for any of them yet, so there is nowhere to ' +\n 'write through for the moment. Reads and writes resume as soon as one reports in.',\n };\n }\n return {\n relayUrl: null,\n note:\n 'Signed in, with nowhere to write yet: a new account is a member of nothing, so no node ' +\n 'serves it. Redeeming an invitation admits this account to a namespace and gives it a ' +\n 'relay — that is the normal first step, not an error.',\n };\n}\n\ninterface DeviceKeys {\n /** Ed25519 public key — what the certificate names, and what signs. */\n signPk: string;\n /** Ed25519 secret, hex seed. Signs warrants and the login statement. */\n signSk: string;\n /** X25519 public key — where wrapped scope keys are delivered. */\n kemPk: string;\n /** X25519 secret. Without it, anything delivered to `kemPk` is unreadable. */\n kemSk: string;\n}\n\n/**\n * This tab's device keys, generated once.\n *\n * TWO keypairs, for two jobs the `DeviceCert` names separately: an Ed25519 pair\n * that signs, and an X25519 pair that receives. Both halves of both are kept —\n * a public key certified without its private half is a key nothing can ever use.\n *\n * In `localStorage`, not session: they have to survive the redirect to the\n * wallet and back. A key regenerated on the way home would not match the\n * certificate the wallet just minted, and `completeDeviceEnrolment` would\n * rightly refuse it.\n */\nasync function deviceKeys(): Promise<DeviceKeys> {\n const had = localStorage.getItem(DEVICE_KEY);\n if (had) {\n const parsed = JSON.parse(had) as Partial<DeviceKeys>;\n // Keys minted before the agreement pair was real carry 32 random bytes as\n // `kemPk` and no `kemSk`. They cannot receive a wrapped scope key, ever, so\n // they are discarded rather than carried forward — the cost is re-enrolling\n // this device, which is cheap; the cost of keeping them is a delivery that\n // silently cannot be decrypted.\n if (parsed.kemSk && parsed.signSk && parsed.signPk && parsed.kemPk) {\n return parsed as DeviceKeys;\n }\n localStorage.removeItem(DEVICE_KEY);\n }\n\n const sign = (await crypto.subtle.generateKey({ name: 'Ed25519' }, true, [\n 'sign',\n 'verify',\n ])) as CryptoKeyPair;\n\n let agree: CryptoKeyPair;\n try {\n agree = (await crypto.subtle.generateKey({ name: 'X25519' }, true, [\n 'deriveBits',\n ])) as CryptoKeyPair;\n } catch {\n // Better to refuse than to certify a delivery key with no private half:\n // enrolment would appear to succeed and the failure would surface much\n // later, as an undecryptable scope key.\n throw new Error(\n 'this browser cannot generate an X25519 key, so it cannot receive wrapped ' +\n 'scope keys. Chrome 133+ and Safari 17+ support it; enrolling without one ' +\n 'would certify a delivery key nothing holds the secret for.',\n );\n }\n\n // pkcs8 wraps the 32-byte seed behind a 16-byte header, for both curves.\n const keys: DeviceKeys = {\n signPk: hex(await crypto.subtle.exportKey('raw', sign.publicKey)),\n signSk: hex((await crypto.subtle.exportKey('pkcs8', sign.privateKey)).slice(16)),\n kemPk: hex(await crypto.subtle.exportKey('raw', agree.publicKey)),\n kemSk: hex((await crypto.subtle.exportKey('pkcs8', agree.privateKey)).slice(16)),\n };\n localStorage.setItem(DEVICE_KEY, JSON.stringify(keys));\n return keys;\n}\n\nexport function ConnectButtonAccount({\n className,\n style,\n theme,\n defaults = {},\n}: ConnectButtonAccountProps) {\n const { isAuthenticated, isOnline, nodeUrl, isDelegated, connectToNode, connectWithAccount, logout } =\n useMero();\n\n const [isDropdownOpen, setIsDropdownOpen] = useState(false);\n const [isNodeModalOpen, setIsNodeModalOpen] = useState(false);\n const [isAccountOpen, setIsAccountOpen] = useState(false);\n const [note, setNote] = useState<string | null>(null);\n const dropdownRef = useRef<HTMLDivElement>(null);\n\n const walletUrl = defaults.walletUrl ?? HOSTED_WALLET;\n\n const resolvedTheme = useMemo(() => (theme ? resolveMeroTheme(theme) : null), [theme]);\n const themeVars = useMemo(\n () => (resolvedTheme ? themeToCssVars(resolvedTheme) : undefined),\n [resolvedTheme],\n );\n\n useEffect(() => {\n const onOutside = (e: MouseEvent) => {\n if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {\n setIsDropdownOpen(false);\n }\n };\n document.addEventListener('mousedown', onOutside);\n return () => document.removeEventListener('mousedown', onOutside);\n }, []);\n\n /**\n * Read the enrolment callback ONCE, during render.\n *\n * `readEnrolmentCallback` consumes the fragment — it strips it from the\n * address bar so a reload cannot replay the credential. That makes it unsafe\n * to call from an effect: React's StrictMode double-invokes effects in dev,\n * so the first run would swallow the credential and then abort through its\n * own cleanup, and the second would find nothing and silently show the\n * connect prompt again. `MeroContext` reads its auth callback this way for\n * the same reason.\n *\n * The throw case (`error=cancelled`) is captured rather than propagated: a\n * declined approval is an ordinary outcome to report, not a render failure.\n */\n const callbackRef = useRef<DeviceEnrolmentCallback | null | undefined>(undefined);\n const callbackErrorRef = useRef<string | null>(null);\n if (callbackRef.current === undefined && typeof window !== 'undefined') {\n try {\n callbackRef.current = readEnrolmentCallback();\n } catch (e) {\n callbackRef.current = null;\n callbackErrorRef.current = e instanceof Error ? e.message : String(e);\n }\n }\n /** One completion per callback, however many times the effect runs. */\n const completingRef = useRef(false);\n\n /**\n * Finish an enrolment we are returning from.\n *\n * Runs before the button paints anything, so a tab coming back from the\n * wallet lands connected rather than showing the connect prompt again.\n */\n useEffect(() => {\n if (callbackErrorRef.current) {\n setNote(callbackErrorRef.current);\n callbackErrorRef.current = null;\n return;\n }\n const back = callbackRef.current;\n if (!back || completingRef.current) return;\n completingRef.current = true;\n let cancelled = false;\n\n (async () => {\n try {\n const keys = await deviceKeys();\n\n // Nothing is carried across the redirect any more beyond the device keys\n // themselves. There used to be a `sessionStorage` record holding the\n // typed relay and context; both are now answered by the credential this\n // returns, so the record held nothing and the \"they were lost, try\n // again\" failure it guarded cannot happen.\n // The state we sent, not the one that came back. `expectState: back.state`\n // compared the returned value against itself and therefore always passed,\n // which left the parameter as decoration: any page able to drive this\n // origin's callback could have had a credential adopted here.\n const sent = (() => {\n try {\n return sessionStorage.getItem(STATE_KEY);\n } catch {\n return null;\n }\n })();\n try {\n sessionStorage.removeItem(STATE_KEY);\n } catch {\n /* single-use where storage allows it; the comparison below is the gate */\n }\n if (!sent) {\n // No record of having started this. Refused rather than adopted: this is\n // either a callback we did not initiate, or storage that lost the value\n // mid-flow, and neither justifies accepting a certificate.\n setNote(\n 'This enrolment could not be verified as one this tab started, so it was not ' +\n 'accepted. Start again from \"Enrol with your account\".',\n );\n return;\n }\n const enrolled = await completeDeviceEnrolment({\n ...back,\n devicePublicKey: keys.signPk,\n kemPublicKey: keys.kemPk,\n expectState: sent,\n });\n\n /*\n * Where to write: asked, not typed.\n *\n * The certificate that just came back is the only input this needs. The\n * cloud mints an account-bound nonce, the device key signs it, and the\n * relay list comes back attributed to this account — no cloud session,\n * no Google sign-in, no account root. Which is why this can run here, on\n * the way home from the wallet, for a person who has none of those.\n *\n * `CloudClient`'s default base URL is the prod manager\n * (`manager.cloud.calimero.network`), which is the right default for a\n * hosted account and the only deployment that answers this route today.\n */\n // Saved BEFORE the relay lookup, and kept whatever that lookup answers.\n //\n // A first-time account is a member of nothing, so `getAccountRelays`\n // correctly answers `[]` and no connection is made below. That is not a\n // failed enrolment: the certificate is real, and it is the input that\n // resolves a relay from an INVITATION instead\n // (`useDelegatedBootstrap`). Discarding it here would make \"no relay\n // yet\" mean \"enrol again\", which mints a second device for an account\n // whose first one was fine.\n saveDelegatedCredential({\n account: enrolled.account,\n credential: enrolled.credential,\n deviceSecret: keys.signSk,\n });\n\n const cloud = new CloudClient({\n routingCredential: {\n credential: enrolled.credential,\n deviceSecret: keys.signSk,\n },\n });\n const chosen = chooseRelay(await cloud.getAccountRelays(enrolled.account));\n // Connected either way — see `chooseRelay`. A null relay is an\n // authenticated account with nowhere to write yet, and the note says\n // what changes that.\n if (chosen.note) setNote(chosen.note);\n\n // Nothing else to obtain. The certificate this enrolment just returned\n // authenticates the reads and the event stream as well as the writes —\n // the device key signs each request and the node verifies it against the\n // certificate. There used to be a `login()` here, minting a session\n // against the relay node's signing key; that key had to be learned out of\n // band and the hosted case has never published one, so the picker was\n // dark on exactly the deployment it was written for.\n\n // Deliberately NOT gated on `cancelled`: the fragment has already been\n // consumed, so abandoning here would strand a credential that cannot be\n // read again. The context outlives this component, so installing the\n // connection after a StrictMode teardown is correct.\n connectWithAccount({\n relayUrl: chosen.relayUrl,\n account: enrolled.account,\n credential: enrolled.credential,\n deviceSecret: keys.signSk,\n });\n } catch (e) {\n if (!cancelled) setNote(e instanceof Error ? e.message : String(e));\n }\n })();\n\n return () => {\n cancelled = true;\n };\n }, [connectWithAccount]);\n\n const goToWallet = useCallback(async () => {\n // No inputs to validate: there is nothing left to ask for.\n const keys = await deviceKeys();\n // Remembered before leaving, so what comes back can be checked against what\n // we sent. Without this the state parameter is decoration: comparing the\n // returned value to itself always passes, which is what it did here.\n const state = hex(crypto.getRandomValues(new Uint8Array(16)));\n try {\n sessionStorage.setItem(STATE_KEY, state);\n } catch {\n // Storage unavailable (private mode, blocked site data). The redirect\n // still works and the check below reports it as unverifiable rather than\n // silently passing.\n }\n window.location.assign(\n deviceEnrolmentUrl({\n walletUrl,\n devicePublicKey: keys.signPk,\n kemPublicKey: keys.kemPk,\n returnTo: window.location.origin + window.location.pathname,\n state,\n }),\n );\n }, [walletUrl]);\n\n if (isAuthenticated && !isOnline) {\n return (\n <div className=\"mero-connect-container\" style={{ ...themeVars, display: 'inline-block' }}>\n <button\n className={['mero-connect-button', 'mero-reconnecting', className].filter(Boolean).join(' ')}\n style={style}\n disabled\n aria-label=\"Reconnecting...\"\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n Reconnecting...\n </button>\n </div>\n );\n }\n\n if (isAuthenticated) {\n return (\n <div\n ref={dropdownRef}\n className=\"mero-connect-container\"\n style={{ ...themeVars, position: 'relative', display: 'inline-block' }}\n >\n <button\n className={['mero-connect-button', 'mero-connected', className].filter(Boolean).join(' ')}\n style={style}\n onClick={() => setIsDropdownOpen((p) => !p)}\n aria-label=\"Connected\"\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n {isDelegated ? 'Connected (account)' : 'Connected'}\n </button>\n {isDropdownOpen && (\n <div className=\"mero-dropdown\">\n <div className=\"mero-dropdown-info\" title={nodeUrl || ''}>\n {/* A delegated account with no relay is signed in and has no node\n to name. Saying so beats an empty row that reads as a bug. */}\n {nodeUrl ?? (isDelegated ? 'no relay yet' : null)}\n </div>\n {/* No dashboard link on the delegated path: the admin dashboard is\n a node-operator surface, and a keyholder has no credential for\n it. Offering a link that 401s would be worse than omitting it. */}\n {!isDelegated && nodeUrl && (\n <a\n href={new URL('admin-dashboard/', nodeUrl).toString()}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"mero-dropdown-item\"\n >\n Dashboard\n </a>\n )}\n <button\n className=\"mero-dropdown-item\"\n onClick={() => {\n setIsDropdownOpen(false);\n logout();\n }}\n >\n Log out\n </button>\n </div>\n )}\n </div>\n );\n }\n\n return (\n <div className=\"mero-connect-container\" style={{ ...themeVars, display: 'inline-block' }}>\n <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>\n <button\n className={['mero-connect-button', className].filter(Boolean).join(' ')}\n style={style}\n onClick={() => setIsNodeModalOpen(true)}\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n I run a node\n </button>\n <button\n className={['mero-connect-button', className].filter(Boolean).join(' ')}\n style={style}\n onClick={() => setIsAccountOpen((p) => !p)}\n >\n I have an account\n </button>\n </div>\n\n {isAccountOpen && (\n <div\n style={{\n marginTop: 12,\n padding: 14,\n border: '1px solid rgba(127,127,127,.35)',\n borderRadius: 8,\n display: 'grid',\n gap: 8,\n maxWidth: 520,\n textAlign: 'left',\n font: '13px system-ui, sans-serif',\n }}\n >\n {/* No form fields. Every one this pane used to have asked for\n something only an operator could know, and all three are now\n answered by the certificate: the wallet is the platform's, the relay\n is looked up, and the context is chosen afterwards from the\n account's own. What is left is a button and an explanation of what\n pressing it does. */}\n <button className=\"mero-connect-button\" onClick={goToWallet}>\n Enrol with your account\n </button>\n <p style={{ margin: 0, opacity: 0.75 }}>\n You will approve a device key on the wallet's own page, then come\n back here. The relay never sees your account root — only the\n certificate it signed.\n </p>\n <p style={{ margin: 0, opacity: 0.75 }}>\n That one certificate is all of it: finding the relay that serves your\n account, writing through it, reading your own contexts and namespaces,\n and live events. Nothing to paste in.\n </p>\n {defaults.walletUrl && (\n /* Shown only when an app overrode it, so a local rig can see at a\n glance that it is not enrolling against the hosted wallet. */\n <p style={{ margin: 0, opacity: 0.6 }}>\n Enrolling at <code>{walletUrl}</code>, not the hosted wallet.\n </p>\n )}\n </div>\n )}\n\n {note && (\n <p style={{ font: '13px system-ui, sans-serif', color: '#b3261e' }}>{note}</p>\n )}\n\n <LoginModal\n isOpen={isNodeModalOpen}\n onConnect={(url) => {\n setIsNodeModalOpen(false);\n connectToNode(url);\n }}\n onClose={() => setIsNodeModalOpen(false)}\n theme={resolvedTheme ?? theme}\n />\n </div>\n );\n}\n\nexport default ConnectButtonAccount;\n","/**\n * Minimal Base58 (Bitcoin alphabet) decoder.\n *\n * Blob ids come back from the admin API Base58-encoded, while a namespace's\n * `appKey` is a hex string, so comparing \"what's installed\" to \"what the group\n * targets\" needs one side converted. Decoding Base58 to canonical lowercase hex\n * is the smaller, encoding-agnostic conversion.\n */\n\nconst ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Decode a Base58 string to a lowercase hex string (no `0x` prefix). Leading\n * `1` characters map to leading zero bytes, so the byte width is preserved.\n * Throws on any character outside the Base58 alphabet.\n */\nexport function base58ToHex(input: string): string {\n const bytes: number[] = [];\n for (const char of input) {\n let carry = ALPHABET.indexOf(char);\n if (carry === -1) throw new Error(`invalid base58 character: ${char}`);\n for (let i = 0; i < bytes.length; i++) {\n carry += bytes[i] * 58;\n bytes[i] = carry & 0xff;\n carry >>= 8;\n }\n while (carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n for (let k = 0; k < input.length && input[k] === '1'; k++) bytes.push(0);\n return bytes\n .reverse()\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n","/**\n * An account's governance through the relay that serves its namespace: create\n * a context, and the group ops a private context (a DM) needs.\n *\n * A thin layer over mero-js's `RelayClient.createContext` / `govern` (core's\n * `/admin-api/groups/{group}/context-intents` and `.../governance-intents`),\n * adding what only this package knows: which relay serves the namespace (the\n * relay map), and the nonce bookkeeping across page loads.\n *\n * Nodes check the AUTHOR's rights (CAN_CREATE_CONTEXT, CAN_CREATE_SUBGROUP,\n * MANAGE_MEMBERS…), never the relay's; the relay only needs standing to act.\n */\nimport {\n memberAddedOp,\n RelayClient,\n subgroupCreation,\n type GovernanceOp,\n type NonceSource,\n} from '@calimero-network/mero-js';\nimport { knownRelays, markContextNonceSpent, readRelayMap, rememberRelay, type DelegatedSession } from './session';\n\n/**\n * A governance warrant's nonce, for one (relay, group): spent in a sliding\n * per-(group, device) window 64 wide, so it must never go backwards. A stored\n * counter, floored at the clock so a cleared storage resumes above anything\n * spent before rather than replaying it.\n */\nfunction governanceNonce(relay: string, group: string): NonceSource {\n return { next: async () => nextGovernanceNonce(relay, group) };\n}\n\nfunction nextGovernanceNonce(relay: string, group: string): bigint {\n const key = `calimero.governance-nonce.${relay}.${group}`;\n let last = 0n;\n try {\n last = BigInt(localStorage.getItem(key) ?? '0');\n } catch {\n /* no storage: the clock floor alone */\n }\n const next = [last + 1n, BigInt(Date.now())].reduce((a, b) => (a > b ? a : b));\n try {\n localStorage.setItem(key, String(next));\n } catch {\n /* unpersisted */\n }\n return next;\n}\n\nfunction relayFor(s: DelegatedSession, namespaceId: string): string {\n // The relay that serves this namespace: learned when the account joined it.\n const url = readRelayMap(s.account).namespaces[namespaceId] ?? s.relayUrl;\n if (!url) throw new Error('no relay is known for this namespace, so there is nowhere to send this');\n return url.replace(/\\/+$/, '');\n}\n\n/** The `init` arguments as the JSON the route takes, from the bytes a caller may hold. */\nfunction initArgsOf(params: number[] | undefined): unknown {\n if (!params || params.length === 0) return {};\n return JSON.parse(new TextDecoder().decode(Uint8Array.from(params)));\n}\n\nexport interface CreateDelegatedContextRequest {\n readonly namespaceId: string;\n /** The group to create it in; the namespace itself when omitted. */\n readonly groupId?: string;\n readonly applicationId: string;\n readonly initializationParams?: number[];\n readonly name?: string;\n}\n\n/** A relay client for these calls: the author's credential, whatever nonces the call needs. */\nfunction client(s: DelegatedSession, relayUrl: string, nonces: NonceSource, fetch?: typeof globalThis.fetch) {\n return new RelayClient({\n relayUrl,\n authorAccount: s.account,\n authorProof: s.credential,\n deviceSecret: s.deviceSecret,\n nonces,\n fetch,\n });\n}\n\nexport async function createDelegatedContext(\n s: DelegatedSession,\n req: CreateDelegatedContextRequest,\n deps: { fetch?: typeof fetch } = {},\n): Promise<{ contextId: string }> {\n const relay = relayFor(s, req.namespaceId);\n // The creation warrant's nonce is spent in the NEW context's per-device\n // window — the one its writes draw from, empty until now — so the first\n // number is free, and the context's writes then start above it.\n const creationNonce = 0n;\n const created = await client(s, relay, { next: async () => creationNonce }, deps.fetch).createContext({\n groupId: req.groupId ?? req.namespaceId,\n applicationId: req.applicationId,\n initArgs: initArgsOf(req.initializationParams),\n name: req.name,\n });\n markContextNonceSpent(relay, created.contextId, creationNonce);\n rememberRelay(s.account, relay, { namespaceId: req.namespaceId, contextId: created.contextId });\n return { contextId: created.contextId };\n}\n\n/** Publish one delegable governance op through the namespace's relay. */\nexport async function delegatedGovernance(\n s: DelegatedSession,\n req: { namespaceId: string; group: string; op: GovernanceOp },\n deps: { fetch?: typeof fetch } = {},\n): Promise<{ groupId: string }> {\n const relay = relayFor(s, req.namespaceId);\n return client(s, relay, governanceNonce(relay, req.group), deps.fetch).govern({ groupId: req.group, op: req.op });\n}\n\n/**\n * A context only the author and `members` are in (a DM, a small room): a\n * restricted subgroup of the namespace (a root op, posted to the namespace),\n * each member added to it directly — they are in the namespace already, so\n * nobody is invited — and the context created inside it. The relay that\n * creates the subgroup is seated in it with CAN_AUTHOR_ON_BEHALF by core.\n */\nexport async function createDelegatedPrivateContext(\n s: DelegatedSession,\n req: CreateDelegatedContextRequest & { readonly members: readonly string[] },\n deps: { fetch?: typeof fetch } = {},\n): Promise<{ contextId: string; groupId: string }> {\n const { groupId } = await delegatedGovernance(\n s,\n {\n namespaceId: req.namespaceId,\n group: req.namespaceId,\n // The id is derived from a fresh salt (core#4244); a node refuses any other.\n op: (await subgroupCreation({ parentId: req.namespaceId, restricted: true, admin: s.account })).op,\n },\n deps,\n );\n for (const member of req.members) {\n await delegatedGovernance(s, { namespaceId: req.namespaceId, group: groupId, op: memberAddedOp(member, 'Member') }, deps);\n }\n const { contextId } = await createDelegatedContext(s, { ...req, groupId }, deps);\n return { contextId, groupId };\n}\n\n/**\n * Found a namespace as the account, through a relay it already uses. The\n * account becomes founder, owner and admin; the relay is seated in it (and a\n * TEE relay admits itself as its first TEE), so contexts can be created in it\n * through the same relay straight away.\n *\n * The relay's executor account cannot be asked about a namespace that does\n * not exist yet, so it is learned from one the account already has on that\n * relay. A brand-new account, in nothing yet, is told to join one first.\n */\nexport async function foundDelegatedNamespace(\n s: DelegatedSession,\n req: {\n readonly defaultCapabilities?: number;\n /** The application the namespace runs; without one no context can be created in it. */\n readonly application?: { applicationId: string; package: string; version: string };\n } = {},\n deps: { fetch?: typeof fetch } = {},\n): Promise<{ namespaceId: string; teeEnabled: boolean }> {\n const relays = knownRelays(s).map((u) => u.replace(/\\/+$/, ''));\n const relay = relays[0];\n if (!relay) throw new Error('no relay is known for this account, so there is nowhere to found a namespace');\n const known = Object.entries(readRelayMap(s.account).namespaces).find(\n ([, url]) => url.replace(/\\/+$/, '') === relay,\n )?.[0];\n if (!known) {\n throw new Error(\"join a namespace on this relay first: its executor account is learned from one you are in\");\n }\n const { executorAccount } = await client(s, relay, governanceNonce(relay, known), deps.fetch).describeGovernance(known);\n // The founding warrant and, with a default mask, a second one are both spent\n // in the NEW namespace's window, which is empty: any rising pair will do.\n let next = BigInt(Date.now());\n const founded = await client(s, relay, { next: async () => next++ }, deps.fetch).foundNamespace({\n executorAccount,\n ...(req.defaultCapabilities !== undefined ? { defaultCapabilities: req.defaultCapabilities } : {}),\n ...(req.application ? { application: req.application } : {}),\n });\n try {\n localStorage.setItem(`calimero.governance-nonce.${relay}.${founded.namespaceId}`, String(next));\n } catch {\n /* unpersisted: the clock floor still keeps later warrants above these */\n }\n rememberRelay(s.account, relay, { namespaceId: founded.namespaceId });\n if (req.application && founded.applicationSet !== true) {\n // Founded, but no context can be created in it until it has its\n // application; the same choice can be retried (it is still the first).\n throw new Error(\n `founded ${founded.namespaceId} but could not give it its application: ${founded.applicationError ?? 'unknown reason'}`,\n );\n }\n return { namespaceId: founded.namespaceId, teeEnabled: founded.teeEnabled };\n}\n\n/**\n * The latest version of `pkg` the registry publishes. Used when the app names\n * its package but not a version.\n */\nexport async function latestPublishedVersion(\n registryUrl: string,\n pkg: string,\n fetchFn: typeof fetch = globalThis.fetch,\n): Promise<string> {\n const url = `${registryUrl.replace(/\\/+$/, '')}/api/v2/bundles?package=${encodeURIComponent(pkg)}`;\n const response = await fetchFn(url, { headers: { Accept: 'application/json' } });\n if (!response.ok) throw new Error(`the registry has no ${pkg} (HTTP ${response.status})`);\n const bundles = (await response.json()) as Array<{ appVersion?: string }>;\n const newer = (a: string, b: string) => {\n const [x, y] = [a, b].map((v) => v.split(/[.-]/).map((n) => Number.parseInt(n, 10) || 0));\n for (let i = 0; i < Math.max(x.length, y.length); i++) {\n if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0);\n }\n return false;\n };\n const latest = bundles\n .map((b) => b.appVersion)\n .filter((v): v is string => typeof v === 'string' && v.length > 0)\n .reduce<string | undefined>((best, v) => (!best || newer(v, best) ? v : best), undefined);\n if (!latest) throw new Error(`the registry lists no version of ${pkg}`);\n return latest;\n}\n","/**\n * An account's group management through a relay: one delegated governance op\n * per call (`RelayClient.govern`), posted to the relay that serves the group's\n * namespace.\n *\n * A group op goes to the group it acts on; a root op (create, delete, move a\n * subgroup; join an open one) goes to the NAMESPACE. An account cannot read a\n * group's details, so the namespace of a subgroup is known only if this\n * account created it or was told it — remembered here per account.\n */\nimport { type GovernanceOp } from '@calimero-network/mero-js';\nimport { delegatedGovernance } from './create-context';\nimport { readRelayMap, type DelegatedSession } from './session';\n\nconst GROUP_NAMESPACE_PREFIX = 'calimero.delegated.group-namespace.';\n\nfunction readGroupNamespaces(account: string): Record<string, string> {\n try {\n return JSON.parse(localStorage.getItem(GROUP_NAMESPACE_PREFIX + account) ?? '{}') as Record<string, string>;\n } catch {\n return {};\n }\n}\n\n/** Record that `groupId` is a subgroup of `namespaceId`, for this account. */\nexport function rememberGroupNamespace(account: string, groupId: string, namespaceId: string): void {\n try {\n const all = readGroupNamespaces(account);\n all[groupId] = namespaceId;\n localStorage.setItem(GROUP_NAMESPACE_PREFIX + account, JSON.stringify(all));\n } catch {\n /* unpersisted: root ops on this subgroup will ask for its namespace */\n }\n}\n\n/** The namespace a group belongs to: itself if it is a namespace this account is in, else what was remembered. */\nexport function namespaceOfGroup(s: DelegatedSession, groupId: string): string | undefined {\n if (readRelayMap(s.account).namespaces[groupId]) return groupId;\n return readGroupNamespaces(s.account)[groupId];\n}\n\nfunction requireNamespace(s: DelegatedSession, groupId: string): string {\n const ns = namespaceOfGroup(s, groupId);\n if (!ns) {\n throw new Error(\n `the namespace of group ${groupId} is not known to this account: it can manage only groups in namespaces it joined or subgroups it created`,\n );\n }\n return ns;\n}\n\n/** A group op (member, role, capabilities, metadata, visibility, detach) on `groupId`. */\nexport async function governGroup(s: DelegatedSession, groupId: string, op: GovernanceOp): Promise<{ groupId: string }> {\n return delegatedGovernance(s, { namespaceId: requireNamespace(s, groupId), group: groupId, op });\n}\n\n/** A root op, posted to the namespace `groupId` belongs to. */\nexport async function governRoot(s: DelegatedSession, groupId: string, op: GovernanceOp): Promise<{ groupId: string }> {\n const namespaceId = requireNamespace(s, groupId);\n return delegatedGovernance(s, { namespaceId, group: namespaceId, op });\n}\n","import { useState, useCallback, useEffect, useMemo, useRef } from 'react';\nimport { classifyError, compareSemver } from '@calimero-network/mero-js';\nimport { useMero } from '../context';\nimport { base58ToHex } from '../utils/base58';\nimport { listDelegatedContexts, listDelegatedNamespaces, readDelegatedSession } from '../delegated/session';\nimport {\n contextDetachedOp,\n contextMetadataSetOp,\n defaultCapabilitiesSetOp,\n subgroupCreation,\n groupDeletedOp,\n groupMetadataSetOp,\n groupReparentedOp,\n memberAddedOp,\n memberJoinedOpenOp,\n memberMetadataSetOp,\n memberRemovedOp,\n memberRoleSetOp,\n signerFromSecret,\n subgroupVisibilitySetOp,\n type GovernanceMemberRole,\n} from '@calimero-network/mero-js';\nimport { governGroup, governRoot, rememberGroupNamespace } from '../delegated/govern';\nimport {\n createDelegatedContext,\n createDelegatedPrivateContext,\n foundDelegatedNamespace,\n latestPublishedVersion,\n} from '../delegated/create-context';\nimport type {\n Codec,\n EphemeralClient,\n Context,\n CreateContextRequest,\n CreateGroupInvitationRequest,\n CreateGroupInNamespaceRequest,\n CreateNamespaceInvitationRequest,\n CreateNamespaceInvitationResponseData,\n CreateNamespaceRequest,\n CreateRecursiveInvitationResponseData,\n GetBlobInfoResponseData,\n GroupContextEntry,\n GroupInfo,\n GroupUpgradeStatusResponseData,\n MetadataRecord,\n JoinGroupRequest,\n JoinNamespaceRequest,\n ListGroupMembersResponseData,\n Namespace,\n NamespaceIdentity,\n NodeIdentity,\n ReparentGroupRequest,\n AddGroupMembersRequest,\n RemoveGroupMembersRequest,\n SetDefaultCapabilitiesRequest,\n SetMetadataRequest,\n SetSubgroupVisibilityRequest,\n SetTeeAdmissionPolicyRequest,\n SubgroupEntry,\n SseEventData,\n UpdateMemberRoleRequest,\n UpgradeGroupRequest,\n UploadBlobRequest,\n ResyncContextRequest,\n MigrationStatus,\n MemberMigrationStatusEntry,\n MigrationStatusRollup,\n MigrateMyEntriesSummary,\n AppVersionChangedEvent,\n GroupMembershipEventData,\n GroupMigrationEventData,\n ClassifiedError,\n RedeemOutcome,\n} from '@calimero-network/mero-js';\nimport type {\n ApplicationContextRecord,\n ContextDiscoveryOptions,\n ContextDiscoveryState,\n} from '../types';\n\nexport { useMero } from '../context';\n\n/**\n * The presence types come straight from `mero-js` now — `Codec` and\n * `EphemeralEntry` are its own declarations, and `EphemeralClient` is the type\n * of the class behind `mero.ephemeral`, so a drift between what this hook\n * assumes and what the SDK does is a compile error rather than a runtime\n * surprise.\n *\n * Re-exported under the same names this package has always exported, so\n * consumers importing `Codec` / `EphemeralEntry` / `EphemeralClient` from\n * `@calimero-network/mero-react` keep compiling — they now simply get the\n * nominal `mero-js` types instead of structural copies of them.\n *\n * On `EphemeralEntry.ageMs`: it is ABSENT on a live delta and PRESENT on a\n * replayed seed entry, reporting how stale that entry already was (bounded by\n * the node's presence TTL). Absent and `0` are different — a `0` means \"the\n * node replayed this and it is brand new\", not \"no age information\". Read it\n * with `?? 0`, never with a truthiness check.\n */\nexport type { Codec, EphemeralEntry, EphemeralClient } from '@calimero-network/mero-js';\n\nexport interface UseEphemeralOptions<T> {\n /** Encoding for the presence slice. Defaults to JSON. */\n codec?: Codec<T>;\n /** Base value for the first `setPresence` merge. */\n initial?: T;\n /** Minimum ms between publishes. Trailing edge — the latest value wins. */\n throttleMs?: number;\n /** Include your own echoed presence in `peers`. Default false. */\n includeSelf?: boolean;\n}\n\n/** Shape returned by {@link useEphemeral}. */\nexport interface UseEphemeralResult<T> {\n peers: Map<string, T>;\n setPresence: (partial: Partial<T>) => void;\n ageOf: (author: string) => number | undefined;\n error: Error | null;\n}\n\n/**\n * Which asynchronous producer currently owns the latched error slot.\n *\n * Only genuinely ASYNCHRONOUS failures are latched — an event happened once,\n * in the past, and nothing about the current render can re-derive it. Anything\n * that is a standing property of the current props/client (notably \"this\n * client has no `mero.ephemeral` surface\") is NOT latched: it is recomputed\n * every render, so it can neither go stale nor be accidentally cleared.\n *\n * The slot is shared, so each producer only clears what it itself raised.\n */\ntype ErrorSource = 'identity' | 'publish';\n\n/**\n * The latched async error, tagged with its producer AND with the context it\n * belongs to.\n *\n * `contextKey` is what makes cross-context leaks structurally impossible\n * rather than a matter of remembering to clear: a write whose key is no longer\n * the current context is dropped on the way in (a publish that was in flight\n * across a context switch), and a latch whose key no longer matches is not\n * read on the way out. Neither path depends on some other effect having run a\n * clear first.\n */\ninterface LatchedEphemeralError {\n contextKey: string | null;\n source: ErrorSource;\n error: Error;\n}\n\nconst NO_EPHEMERAL_SURFACE_MESSAGE =\n 'useEphemeral: this client has no `mero.ephemeral` surface. Ephemeral ' +\n 'presence requires @calimero-network/mero-js >= 9.1.0; upgrade the ' +\n 'installed @calimero-network/mero-js (and any lockfile pin) to use it.';\n\nconst COULD_NOT_RESOLVE_IDENTITY_MESSAGE =\n 'useEphemeral: could not resolve a local context identity, so your own ' +\n 'presence cannot be filtered out. Pass includeSelf: true to accept this.';\n\n/**\n * How long after the last replayed entry (one carrying `ageMs`) the replay\n * window stays open before `peers` is reconciled down to what the replay\n * contained. Long enough to absorb a replay burst split across several SSE\n * frames/ticks, short enough that a swept peer does not linger.\n */\nconst REPLAY_RECONCILE_MS = 50;\n\n/**\n * Observe and publish ephemeral presence (cursors, typing, online) for a\n * context.\n *\n * ONE read path: the subscription. When a client subscribes, the node replays\n * that context's current presence to that connection as ordinary entries\n * before the live deltas start, so seeding and updating share a single shape\n * ({@link EphemeralEntry}) and a reconnect — `SseClient` auto-reconnects and\n * re-subscribes — re-seeds itself. There is no snapshot fetch and no\n * client-side reconciliation pass.\n *\n * Freshness is computed entirely from local clock deltas: a replayed entry is\n * current as of `Date.now() - ageMs`, a live delta as of `Date.now()`. No\n * cross-machine clock comparison is ever performed.\n *\n * No client-side TTL or heartbeat: the node sweeps at 7s and emits removals,\n * and re-publishes on your behalf every 2.5s. A replay is treated as\n * AUTHORITATIVE — see the replay-reconcile pass in the read effect — so a peer\n * swept while the SSE connection was down does not survive the reconnect.\n *\n * `error` is derived, not accumulated: standing conditions (no `ephemeral`\n * surface) are recomputed every render, one-shot async failures are latched\n * keyed by the context they happened in, and whether a latched failure is even\n * relevant (an unresolved identity when `includeSelf` is true) is decided at\n * read time. Nothing survives a context switch.\n */\nexport function useEphemeral<T>(\n contextId: string | null,\n options: UseEphemeralOptions<T> = {},\n): UseEphemeralResult<T> {\n const { includeSelf = false } = options;\n const { mero } = useMero();\n // Cast: the installed mero-js's `MeroJs` type predates `ephemeral` (see\n // `EphemeralClient` above), though it exists at runtime.\n const ephemeral = mero\n ? ((mero as unknown as { ephemeral?: EphemeralClient }).ephemeral ?? null)\n : null;\n\n const [peers, setPeers] = useState<Map<string, T>>(new Map());\n // The one latched async error (see `LatchedEphemeralError`). Not read\n // directly — `error` below derives what is actually reported from it.\n const [latchedError, setLatchedError] = useState<LatchedEphemeralError | null>(null);\n // The context the CURRENT render targets. Read by `setSourceError` so a\n // callback that resolves after a context switch can tell that its result is\n // no longer wanted without closing over anything but its own captured key.\n const contextKeyRef = useRef<string | null>(contextId);\n contextKeyRef.current = contextId;\n // `key` is the contextId captured when the failing operation was STARTED,\n // not when it settled. A late write from a context we have already left is\n // dropped here rather than being written and then hopefully cleared.\n const setSourceError = useCallback(\n (source: ErrorSource, err: Error, key: string | null) => {\n if (key !== contextKeyRef.current) return;\n setLatchedError({ contextKey: key, source, error: err });\n },\n [],\n );\n const clearSourceError = useCallback((source: ErrorSource, key: string | null) => {\n setLatchedError(prev =>\n prev && prev.source === source && prev.contextKey === key ? null : prev,\n );\n }, []);\n\n // DERIVED, never latched: \"this client has no `mero.ephemeral` surface\" is a\n // standing property of the current client, not an event. Recomputing it every\n // render is what makes it impossible to (a) leave it set after an upgraded\n // client arrives or (b) lose it to some other effect's clear — a context\n // switch, for instance, cannot hide a client that still has no surface.\n // Memoised only so the Error identity is stable while the condition holds.\n const surfaceError = useMemo(\n () => (mero && !ephemeral ? new Error(NO_EPHEMERAL_SURFACE_MESSAGE) : null),\n [mero, ephemeral],\n );\n\n // A latch is reported only if it belongs to the context being rendered, and\n // only if it is still MEANINGFUL: an unresolved local identity is an error\n // solely because self-filtering needs it, so opting into `includeSelf` makes\n // it a non-event — decided here, at read time, rather than by racing an\n // effect to clear it.\n const error =\n surfaceError ??\n (latchedError &&\n latchedError.contextKey === contextId &&\n !(latchedError.source === 'identity' && includeSelf)\n ? latchedError.error\n : null);\n // author -> local ms timestamp the entry is considered current as of.\n const receivedAtRef = useRef<Map<string, number>>(new Map());\n // `codec` and `initial` are held in refs, never in a dependency array:\n // `jsonCodec()` is a FACTORY, so `{ codec: jsonCodec() }` at the call site is\n // a fresh identity every render. As a dep it would tear down and re-create\n // the subscription on every render — and since every applied entry sets a\n // new Map (a new render), that is an unbounded resubscribe storm, each\n // resubscribe pulling a fresh presence replay. A codec swapped mid-flight is\n // not a real use case.\n const codecRef = useRef<Codec<T> | undefined>(options.codec);\n codecRef.current = options.codec;\n const initialRef = useRef<T | undefined>(options.initial);\n initialRef.current = options.initial;\n // This node's own context member key (device-level), resolved async. Never\n // compare this against an account id — that comparison silently never\n // matches, which is the classic self-echo bug.\n const selfRef = useRef<string | null>(null);\n const lastLocalRef = useRef<T | undefined>(options.initial);\n const pendingRef = useRef<T | undefined>(undefined);\n const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n // Seeded to the mount time (not 0) so an isolated call shortly after mount\n // is correctly treated as part of the initial \"burst\" and trailing-edge\n // throttled, rather than bypassing the throttle because it looks like it's\n // arriving long after a (nonexistent) previous publish.\n const lastSentAtRef = useRef<number>(Date.now());\n // Open replay window: the authors seen since a replayed entry (one carrying\n // `ageMs`) last arrived. Null when no replay is in progress.\n const replaySeenRef = useRef<Set<string> | null>(null);\n const replayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const ageOf = useCallback((author: string): number | undefined => {\n const at = receivedAtRef.current.get(author);\n return at === undefined ? undefined : Date.now() - at;\n }, []);\n\n // Clear ALL per-context state synchronously the instant the target context\n // changes. Read state, so a previous context's peers don't keep rendering\n // until the new context's replay arrives — and write state, because a\n // queued publish would otherwise fire into the PREVIOUS context (its\n // `setTimeout` closure captured the old `publish`), and `lastLocalRef` would\n // shallow-merge the old context's fields into the first slice published in\n // the new one. Presence is app-defined data (cursor position, typing target),\n // so both are genuine cross-context writes, not cosmetic leaks.\n //\n // The latched error is dropped here as well, but purely as housekeeping (it\n // is what makes A -> B -> A not resurrect A's old failure). Correctness does\n // not rest on it: the latch carries its own `contextKey`, so an error from a\n // context we have left is neither written nor read regardless of whether this\n // effect ran. The standing surface condition is untouched — it is derived, so\n // it re-reports itself on the very next render if it is still true.\n useEffect(() => {\n setPeers(new Map());\n receivedAtRef.current = new Map();\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n timerRef.current = null;\n }\n if (replayTimerRef.current) {\n clearTimeout(replayTimerRef.current);\n replayTimerRef.current = null;\n }\n replaySeenRef.current = null;\n pendingRef.current = undefined;\n lastLocalRef.current = initialRef.current;\n selfRef.current = null;\n setLatchedError(null);\n }, [contextId]);\n\n // Resolve THIS node's context member key — the same value the node stamps\n // as `author` on ephemeral entries.\n useEffect(() => {\n if (!mero || !contextId) return;\n // Captured at START. Everything this effect reports is tagged with it, so\n // a slow lookup that lands after a context switch cannot write into the\n // context we switched to.\n const key = contextId;\n let cancelled = false;\n mero.admin\n .getContextIdentitiesOwned(contextId)\n .then(res => {\n if (cancelled) return;\n const self = res.identities?.[0] ?? null;\n selfRef.current = self;\n if (!self) {\n // Latched unconditionally — `includeSelf` is NOT consulted here.\n // Whether an unresolved identity matters is a question about the\n // CURRENT props, so it is answered where `error` is derived; asking\n // it here is what previously left the error stranded when\n // `includeSelf` flipped to true while resolution still failed.\n setSourceError('identity', new Error(COULD_NOT_RESOLVE_IDENTITY_MESSAGE), key);\n return;\n }\n // A later run of this effect (contextId change, includeSelf toggle)\n // resolved a self identity where an earlier run didn't — clear the\n // \"could not resolve\" error this effect itself raised.\n clearSourceError('identity', key);\n // Ordering race: the identity lookup and the subscription's presence\n // replay land independently, so a self entry can already be seeded in\n // `peers`. Retroactively drop it now that we know who \"self\" is.\n if (!includeSelf) {\n receivedAtRef.current.delete(self);\n setPeers(prev => {\n if (!prev.has(self)) return prev;\n const next = new Map(prev);\n next.delete(self);\n return next;\n });\n }\n })\n .catch((err: unknown) => {\n if (!cancelled) {\n setSourceError('identity', toError(err), key);\n }\n });\n return () => { cancelled = true; };\n // `mero` itself is a dep on purpose: a real MeroProvider memoizes its\n // context value, so `mero` only changes identity when the underlying\n // client is actually replaced (e.g. `allowedNodeUrls` changes) — and\n // that replacement is exactly when this effect must re-resolve the\n // local identity against the new client. Keying on presence alone\n // (`Boolean(mero)`) would silently keep resolving against a closed,\n // stale client instance.\n }, [mero, contextId, includeSelf, setSourceError, clearSourceError]);\n\n // The single read path. Subscribing makes the node replay this context's\n // current presence to this connection as ordinary entries, then stream live\n // deltas — so this one handler both seeds and updates, and an SSE reconnect\n // (which re-subscribes) re-seeds without any extra machinery.\n //\n // A REPLAY IS AUTHORITATIVE. The node replays exactly who is present right\n // now; anything we still hold that the replay does not mention is gone.\n // Without reconciling against it, a peer swept while the connection was down\n // is a permanent ghost: its removal event was delivered to nobody, and the\n // replay — which lists only survivors — will never mention it again. That\n // sweep happens inside `SseClient`'s auto-reconnect, so it does NOT re-run\n // this effect; reconciliation has to be driven by the entries themselves,\n // which is why it keys off `ageMs` (present only on replayed entries) rather\n // than off subscribe/unsubscribe. Clearing `peers` eagerly on subscribe would\n // also miss the reconnect case entirely — and would blank the UI on every\n // `includeSelf` toggle.\n //\n // The window closes `REPLAY_RECONCILE_MS` after the last replayed entry, and\n // live entries arriving while it is open count as present too, so a peer that\n // publishes mid-replay is never swept. A replayed entry that somehow arrives\n // after the window closed re-adds its author immediately — the failure mode\n // is a flicker, never a resurrected ghost or a permanent loss.\n useEffect(() => {\n if (!ephemeral || !contextId) return;\n\n const closeReplayWindow = () => {\n replayTimerRef.current = null;\n const seen = replaySeenRef.current;\n replaySeenRef.current = null;\n if (!seen) return;\n setPeers(prev => {\n let next: Map<string, T> | null = null;\n for (const author of prev.keys()) {\n if (seen.has(author)) continue;\n if (!next) next = new Map(prev);\n next.delete(author);\n receivedAtRef.current.delete(author);\n }\n return next ?? prev;\n });\n };\n\n const unsubscribe = ephemeral.subscribe<T>(\n contextId,\n entry => {\n const { author, state } = entry;\n if (entry.ageMs !== undefined) {\n // A replayed entry: (re)open the reconcile window and debounce its\n // close, so a replay burst split across frames counts as one replay.\n if (!replaySeenRef.current) replaySeenRef.current = new Set();\n if (replayTimerRef.current) clearTimeout(replayTimerRef.current);\n replayTimerRef.current = setTimeout(closeReplayWindow, REPLAY_RECONCILE_MS);\n }\n if (entry.removed || state === undefined) {\n replaySeenRef.current?.delete(author);\n receivedAtRef.current.delete(author);\n setPeers(prev => {\n if (!prev.has(author)) return prev;\n const next = new Map(prev);\n next.delete(author);\n return next;\n });\n return;\n }\n if (!includeSelf && author === selfRef.current) return;\n replaySeenRef.current?.add(author);\n // `ageMs` is absent on a live delta (current as of now) and present on\n // a replayed entry (current as of `now - ageMs`). `?? 0` — never a\n // truthiness test: an `ageMs` of 0 is a real, meaningful value.\n receivedAtRef.current.set(author, Date.now() - (entry.ageMs ?? 0));\n setPeers(prev => new Map(prev).set(author, state));\n },\n codecRef.current,\n );\n\n return () => {\n if (replayTimerRef.current) {\n clearTimeout(replayTimerRef.current);\n replayTimerRef.current = null;\n }\n replaySeenRef.current = null;\n unsubscribe();\n };\n // `ephemeral` itself is a dep on purpose — see the identity-resolution\n // effect above. A replaced client must re-subscribe against the new\n // client, not keep reading/writing through the old (possibly closed)\n // one. `codec` is deliberately NOT a dep — see `codecRef`.\n }, [ephemeral, contextId, includeSelf]);\n\n const publish = useCallback((value: T) => {\n if (!ephemeral || !contextId) return;\n // Captured at START, like the identity lookup's `key`: `ephemeral.set` is\n // not cancellable, so a rejection can land long after a context switch.\n // Tagging the write with the context it was issued for is what keeps that\n // failure out of the new context's error slot.\n const key = contextId;\n lastSentAtRef.current = Date.now();\n void ephemeral.set<T>(key, value, codecRef.current).then(\n () => clearSourceError('publish', key),\n (err: unknown) => setSourceError('publish', toError(err), key),\n );\n }, [ephemeral, contextId, setSourceError, clearSourceError]);\n\n /**\n * Publish your own presence.\n *\n * SHALLOW merge over the last locally-set value (starting from `initial`):\n * presence is one slot per author, so fields are not independent channels\n * and a bare replace would silently drop whatever you did not mention.\n * Nested objects are replaced wholesale, not deep-merged —\n * `setPresence({ cursor: { x: 1 } })` DROPS `cursor.y` if it was set\n * separately.\n *\n * Throttled on the trailing edge: rapid calls collapse into one publish\n * carrying the newest value, never the oldest queued one.\n */\n const setPresence = useCallback((partial: Partial<T>) => {\n const next = { ...(lastLocalRef.current ?? ({} as T)), ...partial } as T;\n lastLocalRef.current = next;\n\n const throttleMs = options.throttleMs ?? 30;\n if (throttleMs <= 0) {\n publish(next);\n return;\n }\n\n pendingRef.current = next;\n if (timerRef.current) return;\n const elapsed = Date.now() - lastSentAtRef.current;\n const delay = Math.max(throttleMs - elapsed, 0);\n timerRef.current = setTimeout(() => {\n timerRef.current = null;\n const queued = pendingRef.current;\n pendingRef.current = undefined;\n if (queued !== undefined) publish(queued);\n }, delay);\n }, [publish, options.throttleMs]);\n\n // Cancel a queued publish on unmount.\n useEffect(() => () => {\n if (timerRef.current) clearTimeout(timerRef.current);\n }, []);\n\n return { peers, setPresence, ageOf, error };\n}\n\n/**\n * Shape accepted by the metadata-setter hooks — re-exported from mero-js so\n * callers have one canonical type. A `set*Metadata` call **replaces the whole\n * record**: `data` defaults to `{}` and wholly replaces the stored map; omit\n * `name` to keep the current name.\n */\nexport type SetMetadataInput = SetMetadataRequest;\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction mapApplicationContexts(contexts: Context[]): ApplicationContextRecord[] {\n return contexts.map((context) => ({\n contextId: context.id,\n applicationId: context.applicationId,\n }));\n}\n\nfunction useMountedRef() {\n const mountedRef = useRef(true);\n\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n return mountedRef;\n}\n\n/** Options a mutation hook that can fail meaningfully accepts. */\nexport interface MutationOptions {\n /**\n * Rethrow a failed request from the action, after recording it in `error`\n * and `failure`.\n *\n * By default an action resolves `null` on failure, which a caller awaiting it\n * cannot tell apart from \"not connected\" — and a `catch` around it never\n * runs, so a refused join reads as a successful one. Set this when the\n * caller branches on the outcome.\n */\n throwOnError?: boolean;\n}\n\nfunction useAsyncMutation({ throwOnError = false }: MutationOptions = {}) {\n const mountedRef = useMountedRef();\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [failure, setFailure] = useState<ClassifiedError | null>(null);\n\n const run = useCallback(\n async <T,>(action: () => Promise<T>): Promise<T | null> => {\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n setFailure(null);\n }\n\n try {\n return await action();\n } catch (err) {\n if (mountedRef.current) {\n setError(toError(err));\n setFailure(classifyError(err));\n }\n // The original error, not the wrapped one: it carries the status.\n if (throwOnError) throw err;\n return null;\n } finally {\n if (mountedRef.current) {\n setLoading(false);\n }\n }\n },\n [mountedRef, throwOnError],\n );\n\n return { loading, error, failure, run, setError };\n}\n\n/**\n * Generic read resource: fetch + loading/error/data with a latest-request-wins\n * guard. `fetcher` is null when the read is disabled (missing args) — the\n * resource resets to `initialValue` and nothing is fetched. `deps` drive both\n * the refetch and a synchronous reset when they change, so a slow earlier\n * request can never overwrite a newer one. This is the staleness guard the read\n * hooks used to hand-roll (and mostly lacked), now in one place.\n */\nfunction useAsyncResource<T>(\n fetcher: (() => Promise<T>) | null,\n initialValue: T,\n deps: readonly unknown[],\n): { data: T; loading: boolean; error: Error | null; refetch: () => Promise<void> } {\n const mountedRef = useMountedRef();\n const [data, setData] = useState<T>(initialValue);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const reqRef = useRef(0);\n\n // fetcherRef is refreshed every render so refetch() always calls the latest\n // closure; initialRef captures the (per-hook constant) initial value once.\n // Neither is a dependency — adding them would break latest-request-wins.\n const fetcherRef = useRef(fetcher);\n fetcherRef.current = fetcher;\n const initialRef = useRef(initialValue);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n const fn = fetcherRef.current;\n if (!fn) {\n if (mountedRef.current && seq === reqRef.current) {\n setData(initialRef.current);\n setError(null);\n setLoading(false);\n }\n return;\n }\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n try {\n const result = await fn();\n if (mountedRef.current && seq === reqRef.current) setData(result);\n } catch (err) {\n if (mountedRef.current && seq === reqRef.current) setError(toError(err));\n } finally {\n if (mountedRef.current && seq === reqRef.current) setLoading(false);\n }\n }, deps);\n\n // Invalidate any in-flight request and drop the previous key's data DURING\n // RENDER, not in an effect. An effect leaves one render where `data` still\n // answers for the old inputs, and a consumer that persists what it sees\n // (a \"this member already has a name\" marker, say) makes that transient\n // staleness permanent.\n const prevDeps = useRef(deps);\n if (\n deps.length !== prevDeps.current.length ||\n deps.some((d, i) => !Object.is(d, prevDeps.current[i]))\n ) {\n prevDeps.current = deps;\n reqRef.current += 1;\n setData(initialRef.current);\n setError(null);\n }\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nfunction extractAliasContextId(value: unknown): string | null {\n if (typeof value === 'string') {\n return value;\n }\n\n if (!value || typeof value !== 'object') {\n return null;\n }\n\n if ('value' in value && typeof value.value === 'string') {\n return value.value;\n }\n\n if ('contextId' in value && typeof value.contextId === 'string') {\n return value.contextId;\n }\n\n return null;\n}\n\n/**\n * Execute RPC methods against a context.\n * Tracks loading/error state. Unmount-safe.\n */\nexport function useExecute(contextId: string | null, executorId: string | null) {\n const { mero, isDelegated } = useMero();\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useRef(true);\n\n useEffect(() => {\n mountedRef.current = true;\n return () => { mountedRef.current = false; };\n }, []);\n\n const execute = useCallback(\n async <T = unknown>(method: string, params?: Record<string, unknown>): Promise<T | null> => {\n if (!mero || !contextId || !executorId) {\n // A delegated session with no client is one specific, ordinary state —\n // an account that has not been invited anywhere yet, so the cloud names\n // no relay for it — and it must not report as \"Not connected\", because\n // the account IS connected and re-authenticating cures nothing. The cure\n // is an invitation, so the message says so.\n if (mountedRef.current) {\n setError(\n new Error(\n !mero && isDelegated\n ? 'No relay for this account yet, so there is nowhere to send this write. ' +\n 'Redeeming an invitation admits the account to a namespace and gives it a ' +\n 'relay; reads and events resume with it.'\n : 'Not connected',\n ),\n );\n }\n return null;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n try {\n const result = await mero.rpc.execute<T>({\n contextId,\n method,\n argsJson: params,\n executorPublicKey: executorId,\n });\n return result;\n } catch (err) {\n const e = err instanceof Error ? err : new Error(String(err));\n if (mountedRef.current) setError(e);\n return null;\n } finally {\n if (mountedRef.current) setLoading(false);\n }\n },\n [mero, contextId, executorId, isDelegated],\n );\n\n return { execute, loading, error };\n}\n\n/** Event payload delivered to a `useSubscription` callback. */\nexport type SubscriptionEventData =\n | SseEventData\n | GroupMembershipEventData\n | GroupMigrationEventData;\n\n/** Ids to subscribe to. Either can be omitted, but not both. */\nexport interface SubscriptionInput {\n contextIds?: string[];\n groupIds?: string[];\n}\n\n/**\n * Subscribe to SSE events for context and/or group IDs.\n * StrictMode-safe: tracks the SseClient instance in a ref to avoid\n * double-connect on mount/unmount/remount cycles.\n */\nexport function useSubscription(\n contextIds: string[],\n callback: (event: SubscriptionEventData) => void,\n): void;\nexport function useSubscription(\n input: SubscriptionInput,\n callback: (event: SubscriptionEventData) => void,\n): void;\nexport function useSubscription(\n input: string[] | SubscriptionInput,\n callback: (event: SubscriptionEventData) => void,\n) {\n const { mero } = useMero();\n const callbackRef = useRef(callback);\n callbackRef.current = callback;\n\n const { contextIds = [], groupIds = [] } = Array.isArray(input)\n ? { contextIds: input, groupIds: [] as string[] }\n : input;\n\n const contextIdsKey = JSON.stringify(contextIds);\n const groupIdsKey = JSON.stringify(groupIds);\n\n useEffect(() => {\n if (!mero || (contextIds.length === 0 && groupIds.length === 0)) return;\n\n const sse = mero.events;\n\n const handler = (event: SubscriptionEventData) => {\n callbackRef.current(event);\n };\n\n sse.on('event', handler);\n sse.connect().catch(() => {});\n sse.subscribe({ contextIds, groupIds }).catch(() => {});\n\n return () => {\n sse.off('event', handler);\n };\n }, [mero, contextIdsKey, groupIdsKey]);\n}\n\n/**\n * Fetch contexts for the current node, optionally filtered by application ID.\n */\nexport function useContexts(applicationId?: string | null) {\n const { mero, isDelegated } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<ApplicationContextRecord[]>(\n mero\n ? async () => {\n // A delegated session may list only its own contexts: the\n // per-application listing is node-wide, so a relay refuses it (403).\n // The caller-scoped `getContexts` carries each context's application,\n // so filter here instead.\n if (isDelegated) {\n // Across every relay this account uses: its namespaces may each be\n // served by a different one, and each relay lists only its own.\n const session = readDelegatedSession();\n const listed = session ? await listDelegatedContexts(session) : [];\n const own = listed.filter(\n (c) => !applicationId || c.applicationId === applicationId,\n );\n return mapApplicationContexts(own);\n }\n const response = applicationId\n ? await mero.admin.getContextsForApplication(applicationId)\n : await mero.admin.getContexts();\n return mapApplicationContexts(response.contexts ?? []);\n }\n : null,\n [],\n [mero, applicationId, isDelegated],\n );\n return { contexts: data, loading, error, refetch };\n}\n\nexport function useApplicationContexts(applicationId?: string | null) {\n return useContexts(applicationId);\n}\n\nexport function useGroupMembers(groupId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<ListGroupMembersResponseData | null>(\n mero && groupId ? () => mero.admin.listGroupMembers(groupId) : null,\n null,\n [mero, groupId],\n );\n // `members` is a guaranteed array on the wire; `?? []` guards mocks / drift.\n return {\n members: data?.members ?? [],\n loading,\n error,\n refetch,\n };\n}\n\nexport function useGroupContexts(groupId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<GroupContextEntry[]>(\n mero && groupId ? () => mero.admin.listGroupContexts(groupId) : null,\n [],\n [mero, groupId],\n );\n return { contexts: data, loading, error, refetch };\n}\n\nexport function useGroupInvitations() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createInvitation = useCallback(\n async (groupId: string, request?: CreateGroupInvitationRequest) => {\n if (!mero) {\n return null;\n }\n return run(() => mero.admin.createGroupInvitation(groupId, request));\n },\n [mero, run],\n );\n\n return { createInvitation, loading, error };\n}\n\nexport function useJoinGroup() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const joinGroup = useCallback(\n async (request: JoinGroupRequest) => {\n if (!mero) {\n return null;\n }\n return run(() => mero.admin.joinGroup(request));\n },\n [mero, run],\n );\n\n return { joinGroup, loading, error };\n}\n\n/**\n * Takes the member's ACCOUNT (64 hex), as `useGroupMembers` rows are keyed by\n * and `useNodeIdentity().identity?.accountId` returns - NOT a signing key.\n * Both are 32-byte strings, so passing a key names nobody and raises nothing.\n */\nexport function useGroupCapabilities(groupId?: string | null, memberId?: string | null) {\n const { mero } = useMero();\n const [capabilities, setCapabilitiesState] = useState<number | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Read+write hybrid (setCapabilities shares this state), so it keeps the\n // inline latest-request-wins guard rather than useAsyncResource.\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n if (!mero || !groupId || !memberId) {\n if (mountedRef.current && seq === reqRef.current) {\n setCapabilitiesState(null);\n setError(null);\n setLoading(false);\n }\n return null;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const response = await mero.admin.getMemberCapabilities(groupId, memberId);\n if (mountedRef.current && seq === reqRef.current) {\n setCapabilitiesState(response.capabilities);\n }\n return response.capabilities;\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n return null;\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [groupId, memberId, mero, mountedRef]);\n\n useEffect(() => {\n reqRef.current += 1;\n setCapabilitiesState(null);\n setError(null);\n }, [groupId, memberId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n const setCapabilities = useCallback(\n async (nextCapabilities: number) => {\n if (!mero || !groupId || !memberId) {\n return null;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n await mero.admin.setMemberCapabilities(groupId, memberId, { capabilities: nextCapabilities });\n if (mountedRef.current) {\n setCapabilitiesState(nextCapabilities);\n }\n return nextCapabilities;\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current) {\n setError(errorValue);\n }\n return null;\n } finally {\n if (mountedRef.current) {\n setLoading(false);\n }\n }\n },\n [groupId, memberId, mero, mountedRef],\n );\n\n return { capabilities, loading, error, refetch, setCapabilities };\n}\n\nexport function useContextDiscovery(options: ContextDiscoveryOptions): ContextDiscoveryState {\n const { mero } = useMero();\n const [context, setContext] = useState<ApplicationContextRecord | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n\n const knownContextIdsKey = JSON.stringify(options.knownContextIds ?? []);\n\n const discover = useCallback(async () => {\n if (!mero) {\n const notConnectedError = new Error('Not connected');\n if (mountedRef.current) {\n setError(notConnectedError);\n }\n return null;\n }\n const knownContextIds = new Set(options.knownContextIds ?? []);\n const pollIntervalMs = options.pollIntervalMs ?? 1000;\n const timeoutMs = options.timeoutMs ?? 30000;\n const deadline = Date.now() + timeoutMs;\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n while (Date.now() <= deadline) {\n if (options.targetAlias) {\n const aliasMatch = extractAliasContextId(\n await mero.admin.lookupContextAlias(options.targetAlias),\n );\n\n if (aliasMatch && !knownContextIds.has(aliasMatch)) {\n const discoveredFromAlias = {\n contextId: aliasMatch,\n applicationId: options.applicationId,\n };\n\n if (mountedRef.current) {\n setContext(discoveredFromAlias);\n }\n\n return discoveredFromAlias;\n }\n }\n\n const response = await mero.admin.getContextsForApplication(options.applicationId);\n const contexts = mapApplicationContexts(response.contexts ?? []);\n const discovered = contexts.find(\n (applicationContext) => !knownContextIds.has(applicationContext.contextId),\n );\n\n if (discovered) {\n if (mountedRef.current) {\n setContext(discovered);\n }\n return discovered;\n }\n\n if (Date.now() + pollIntervalMs > deadline) {\n break;\n }\n\n await sleep(pollIntervalMs);\n }\n\n const timeoutError = new Error(\n `Timed out discovering a context for application ${options.applicationId}`,\n );\n\n if (mountedRef.current) {\n setContext(null);\n setError(timeoutError);\n }\n\n return null;\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current) {\n setContext(null);\n setError(errorValue);\n }\n return null;\n } finally {\n if (mountedRef.current) {\n setLoading(false);\n }\n }\n }, [\n knownContextIdsKey,\n mero,\n mountedRef,\n options.applicationId,\n options.knownContextIds,\n options.pollIntervalMs,\n options.targetAlias,\n options.timeoutMs,\n ]);\n\n const reset = useCallback(() => {\n if (mountedRef.current) {\n setContext(null);\n setError(null);\n setLoading(false);\n }\n }, [mountedRef]);\n\n return { context, loading, error, discover, reset };\n}\n\n// ---- Context CRUD Hooks ----\n\nexport function useCreateContext() {\n const { mero, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createContext = useCallback(\n async (request: CreateContextRequest) => {\n if (isDelegated) {\n // An account creates a context through the relay serving the namespace,\n // under a creation warrant (delegated/create-context.ts).\n const session = readDelegatedSession();\n if (!session || !request.groupId) return null;\n return run(() =>\n createDelegatedContext(session, {\n namespaceId: request.groupId!,\n applicationId: request.applicationId,\n initializationParams: request.initializationParams as number[] | undefined,\n }),\n );\n }\n if (!mero) return null;\n return run(() => mero.admin.createContext(request));\n },\n [mero, run, isDelegated],\n );\n\n return { createContext, loading, error };\n}\n\nexport interface CreatePrivateContextRequest {\n readonly namespaceId: string;\n readonly applicationId: string;\n /** The accounts that share it with you, and nobody else — e.g. the other person of a DM. */\n readonly members: readonly string[];\n readonly initializationParams?: number[];\n}\n\n/**\n * Create a context only you and `members` are in (a DM, a small room): its own\n * restricted group in the namespace, members added directly — they are in the\n * namespace already, so nobody is invited. Same call on either connection:\n *\n * - a node login makes the group, adds the members and creates the context\n * with its own admin calls (as mero-chat's DMs do);\n * - an account has the relay serving the namespace do the same three steps,\n * each under its own warrant (delegated/create-context.ts).\n */\nexport function useCreatePrivateContext() {\n const { mero, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createPrivateContext = useCallback(\n async (request: CreatePrivateContextRequest): Promise<{ contextId: string } | null> => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n return run(() => createDelegatedPrivateContext(session, request));\n }\n if (!mero) return null;\n return run(async () => {\n const { groupId } = await mero.admin.createGroupInNamespace(request.namespaceId, {\n visibility: 'restricted',\n });\n // The creator is the new group's admin already; the others join it here.\n await mero.admin.addGroupMembers(groupId, {\n members: request.members.map((identity) => ({ identity, role: 'Member' })),\n });\n const { contextId } = await mero.admin.createContext({\n applicationId: request.applicationId,\n groupId,\n initializationParams: request.initializationParams,\n });\n return { contextId };\n });\n },\n [mero, run, isDelegated],\n );\n\n return { createPrivateContext, loading, error };\n}\n\nexport function useDeleteContext() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const deleteContext = useCallback(\n async (contextId: string) => {\n if (!mero) return null;\n return run(() => mero.admin.deleteContext(contextId));\n },\n [mero, run],\n );\n\n return { deleteContext, loading, error };\n}\n\n/**\n * Join a context. `failure` says what kind of refusal a failed join was, and\n * whether trying again later could work; pass `{ throwOnError: true }` to have\n * `joinContext` reject instead of resolving `null`.\n */\nexport function useJoinContext(options: MutationOptions = {}) {\n const { mero } = useMero();\n const { loading, error, failure, run } = useAsyncMutation(options);\n\n const joinContext = useCallback(\n async (contextId: string) => {\n if (!mero) return null;\n return run(() => mero.admin.joinContext(contextId));\n },\n [mero, run],\n );\n\n return { joinContext, loading, error, failure };\n}\n\nexport function useJoinSubgroupInheritance() {\n const { mero, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const joinSubgroupInheritance = useCallback(\n async (groupId: string) => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n // Joining an open subgroup yourself: a root op carrying your own credential.\n return run(async () => {\n await governRoot(session, groupId, memberJoinedOpenOp({ member: session.account, groupId, credential: session.credential }));\n // An account's identity in the subgroup is its device key: what its ops are signed with.\n const { publicKey } = await signerFromSecret(session.deviceSecret);\n return { groupId, memberPublicKey: publicKey, wasInherited: false };\n });\n }\n if (!mero) return null;\n return run(() => mero.admin.joinSubgroupInheritance(groupId));\n },\n [mero, run, isDelegated],\n );\n\n return { joinSubgroupInheritance, loading, error };\n}\n\nexport function useContextGroup(contextId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<string | null>(\n mero && contextId ? () => mero.admin.getContextGroup(contextId) : null,\n null,\n [mero, contextId],\n );\n return { groupId: data, loading, error, refetch };\n}\n\n// ---- Group Info / Management Hooks ----\n\nexport function useGroupInfo(groupId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<GroupInfo | null>(\n mero && groupId ? () => mero.admin.getGroupInfo(groupId) : null,\n null,\n [mero, groupId],\n );\n return { groupInfo: data, loading, error, refetch };\n}\n\nexport function useDeleteGroup() {\n const { mero, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const deleteGroup = useCallback(\n async (groupId: string) => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n return run(() => governRoot(session, groupId, groupDeletedOp(groupId)));\n }\n if (!mero) return null;\n return run(() => mero.admin.deleteGroup(groupId));\n },\n [mero, run, isDelegated],\n );\n\n return { deleteGroup, loading, error };\n}\n\nexport function useSyncGroup() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const syncGroup = useCallback(\n async (groupId: string) => {\n if (!mero) return null;\n return run(() => mero.admin.syncGroup(groupId));\n },\n [mero, run],\n );\n\n return { syncGroup, loading, error };\n}\n\n/**\n * Takes the invitee's signing KEY (bs58) - the one call on this resource that\n * does, because someone being added may have no account here yet. Every other\n * member call, including `useRemoveGroupMembers`, takes the ACCOUNT, so a value\n * round-tripped from an add is the wrong one to remove with.\n */\nexport function useAddGroupMembers() {\n const { mero, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const addGroupMembers = useCallback(\n async (groupId: string, request: AddGroupMembersRequest) => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n return run(async () => {\n for (const m of request.members) {\n await governGroup(session, groupId, memberAddedOp(m.identity, m.role as GovernanceMemberRole));\n }\n });\n }\n if (!mero) return null;\n return run(() => mero.admin.addGroupMembers(groupId, request));\n },\n [mero, run, isDelegated],\n );\n\n return { addGroupMembers, loading, error };\n}\n\n/**\n * Takes the member's ACCOUNT (64 hex), as `useGroupMembers` rows are keyed by\n * and `useNodeIdentity().identity?.accountId` returns - NOT a signing key.\n * Both are 32-byte strings, so passing a key names nobody and raises nothing.\n */\nexport function useRemoveGroupMembers() {\n const { mero, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const removeGroupMembers = useCallback(\n async (groupId: string, request: RemoveGroupMembersRequest) => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n return run(async () => {\n for (const member of request.members) await governGroup(session, groupId, memberRemovedOp(member));\n });\n }\n if (!mero) return null;\n return run(() => mero.admin.removeGroupMembers(groupId, request));\n },\n [mero, run, isDelegated],\n );\n\n return { removeGroupMembers, loading, error };\n}\n\n// ---- Namespace Hooks ----\n\nexport function useNamespaces() {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<Namespace[]>(\n mero ? () => mero.admin.listNamespaces() : null,\n [],\n [mero],\n );\n return { namespaces: data, loading, error, refetch };\n}\n\nexport function useNamespace(namespaceId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<Namespace | null>(\n mero && namespaceId ? () => mero.admin.getNamespace(namespaceId) : null,\n null,\n [mero, namespaceId],\n );\n return { namespace: data, loading, error, refetch };\n}\n\n/**\n * Who this node is: `accountId` is what member-addressing takes and what\n * `useGroupMembers` rows are keyed by — `publicKey` is the signing key and\n * addresses nobody. Both are 32-byte strings, so a swap fails silently.\n */\nexport function useNodeIdentity() {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<NodeIdentity | null>(\n mero ? () => mero.admin.getNodeIdentity() : null,\n null,\n [mero],\n );\n return { identity: data, loading, error, refetch };\n}\n\n/**\n * @deprecated Use {@link useNodeIdentity}. Identity is per-node, not\n * per-namespace, and this no longer gates on participation: it answers for a\n * namespace this node never joined, so `identity != null` is not \"am I a\n * member?\" — ask `useNamespaces` for that. Its `publicKey` is the signing key,\n * NOT the account member-addressing wants.\n */\nexport function useNamespaceIdentity(namespaceId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<NamespaceIdentity | null>(\n mero && namespaceId ? () => mero.admin.getNamespaceIdentity(namespaceId) : null,\n null,\n [mero, namespaceId],\n );\n return { identity: data, loading, error, refetch };\n}\n\nexport function useNamespacesForApplication(applicationId?: string | null) {\n const { mero, isDelegated } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<Namespace[]>(\n mero && applicationId\n ? isDelegated\n ? async () => {\n // The per-application listing is node-wide, so a relay refuses it to\n // an account; list its own namespaces on every relay and filter.\n const session = readDelegatedSession();\n const listed = session ? await listDelegatedNamespaces(session) : [];\n return listed.filter((ns) => ns.targetApplicationId === applicationId);\n }\n : () => mero.admin.listNamespacesForApplication(applicationId)\n : null,\n [],\n [mero, applicationId, isDelegated],\n );\n return { namespaces: data, loading, error, refetch };\n}\n\n/** Where an app's package is looked up when the provider names no registry. */\nconst DEFAULT_REGISTRY_URL = 'https://apps.calimero.network';\n\nexport function useCreateNamespace() {\n const { mero, isDelegated, app } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createNamespace = useCallback(\n async (request: CreateNamespaceRequest) => {\n if (isDelegated) {\n // An account founds it through a relay it already uses (a signed\n // genesis under a governance warrant; delegated/create-context.ts).\n // Members it invites get mero-chat's default mask, so they can create\n // contexts in it without a separate grant.\n // It is given this app's application in the same call: a namespace\n // founded through a relay starts with none, and holds no context until\n // it has one.\n const session = readDelegatedSession();\n if (!session) return null;\n const pkg = app.packageName;\n return run(async () => {\n if (!pkg) {\n throw new Error('this app names no registry package, so a founded namespace could not be given its application');\n }\n const version = app.packageVersion ?? (await latestPublishedVersion(app.registryUrl ?? DEFAULT_REGISTRY_URL, pkg));\n return foundDelegatedNamespace(session, {\n defaultCapabilities: 231,\n application: { applicationId: request.applicationId, package: pkg, version },\n });\n });\n }\n if (!mero) return null;\n return run(() => mero.admin.createNamespace(request));\n },\n [mero, run, isDelegated, app],\n );\n\n return { createNamespace, loading, error };\n}\n\nexport function useDeleteNamespace() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const deleteNamespace = useCallback(\n async (namespaceId: string) => {\n if (!mero) return null;\n return run(() => mero.admin.deleteNamespace(namespaceId));\n },\n [mero, run],\n );\n\n return { deleteNamespace, loading, error };\n}\n\nexport function useCreateNamespaceInvitation() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createNamespaceInvitation = useCallback(\n async (\n namespaceId: string,\n request?: CreateNamespaceInvitationRequest,\n ): Promise<CreateNamespaceInvitationResponseData | CreateRecursiveInvitationResponseData | null> => {\n if (!mero) return null;\n return run(() => mero.admin.createNamespaceInvitation(namespaceId, request));\n },\n [mero, run],\n );\n\n return { createNamespaceInvitation, loading, error };\n}\n\n/**\n * Join a namespace by invitation. `failure` says what kind of refusal a failed\n * join was, and whether trying again later could work; pass\n * `{ throwOnError: true }` to have `joinNamespace` reject instead of resolving\n * `null`.\n *\n * To follow an invitation link, prefer {@link useRedeemInvitation}: it also\n * recognises a join that landed although its request failed.\n */\nexport function useJoinNamespace(options: MutationOptions = {}) {\n const { mero } = useMero();\n const { loading, error, failure, run } = useAsyncMutation(options);\n\n const joinNamespace = useCallback(\n async (namespaceId: string, request: JoinNamespaceRequest) => {\n if (!mero) return null;\n return run(() => mero.admin.joinNamespace(namespaceId, request));\n },\n [mero, run],\n );\n\n return { joinNamespace, loading, error, failure };\n}\n\n/**\n * Follow an invitation: join its namespace once, then check membership, and\n * report what happened as a {@link RedeemOutcome}.\n *\n * Unlike {@link useJoinNamespace}, a request that failed but whose join landed\n * anyway — the desktop proxy aborts at 30s, a join with no member online takes\n * longer — is `already-member`, not a failure. `shouldRetain(outcome)` from\n * mero-js says whether to keep the invitation for another attempt.\n *\n * `redeem` resolves `null` only when there is no client to send it through.\n */\nexport function useRedeemInvitation() {\n const { mero } = useMero();\n const mountedRef = useMountedRef();\n const [loading, setLoading] = useState(false);\n const [outcome, setOutcome] = useState<RedeemOutcome | null>(null);\n\n const redeem = useCallback(\n async (\n namespaceId: string,\n invitation: JoinNamespaceRequest['invitation'],\n options: { groupName?: string; teamName?: string } = {},\n ): Promise<RedeemOutcome | null> => {\n if (!mero) return null;\n if (mountedRef.current) {\n setLoading(true);\n setOutcome(null);\n }\n try {\n const result = await mero.admin.redeemInvitation(namespaceId, invitation, options);\n if (mountedRef.current) setOutcome(result);\n return result;\n } finally {\n if (mountedRef.current) setLoading(false);\n }\n },\n [mero, mountedRef],\n );\n\n return { redeem, outcome, loading };\n}\n\nexport function useCreateGroupInNamespace() {\n const { mero, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createGroupInNamespace = useCallback(\n async (namespaceId: string, request?: CreateGroupInNamespaceRequest) => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n // A subgroup's id is derived from its creator and a salt; remembered so later root\n // ops on it (delete, move, join) know which namespace to post to.\n return run(async () => {\n // The relay answers with the subgroup's id as core records it, which\n // is the one to keep (it need not be the one proposed).\n const { groupId } = await governRoot(\n session,\n namespaceId,\n // The id is derived from a fresh salt (core#4244); a node refuses any other.\n (\n await subgroupCreation({\n parentId: namespaceId,\n restricted: request?.visibility !== 'open',\n admin: session.account,\n })\n ).op,\n );\n rememberGroupNamespace(session.account, groupId, namespaceId);\n return { groupId };\n });\n }\n if (!mero) return null;\n return run(() => mero.admin.createGroupInNamespace(namespaceId, request));\n },\n [mero, run, isDelegated],\n );\n\n return { createGroupInNamespace, loading, error };\n}\n\nexport function useNamespaceGroups(namespaceId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<SubgroupEntry[]>(\n mero && namespaceId ? () => mero.admin.listNamespaceGroups(namespaceId) : null,\n [],\n [mero, namespaceId],\n );\n return { groups: data, loading, error, refetch };\n}\n\n// ---- Group Settings & Role Management ----\n\n/**\n * Takes the member's ACCOUNT (64 hex), as `useGroupMembers` rows are keyed by\n * and `useNodeIdentity().identity?.accountId` returns - NOT a signing key.\n * Both are 32-byte strings, so passing a key names nobody and raises nothing.\n */\nexport function useUpdateMemberRole() {\n const { mero, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const updateMemberRole = useCallback(\n async (groupId: string, identity: string, request: UpdateMemberRoleRequest) => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n return run(() => governGroup(session, groupId, memberRoleSetOp(identity, request.role as GovernanceMemberRole)));\n }\n if (!mero) return null;\n return run(() => mero.admin.updateMemberRole(groupId, identity, request));\n },\n [mero, run, isDelegated],\n );\n\n return { updateMemberRole, loading, error };\n}\n\nexport function useSetDefaultCapabilities() {\n const { mero, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setDefaultCapabilities = useCallback(\n async (groupId: string, request: SetDefaultCapabilitiesRequest) => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n return run(() => governGroup(session, groupId, defaultCapabilitiesSetOp(request.defaultCapabilities)));\n }\n if (!mero) return null;\n return run(() => mero.admin.setDefaultCapabilities(groupId, request));\n },\n [mero, run, isDelegated],\n );\n\n return { setDefaultCapabilities, loading, error };\n}\n\nexport function useSetSubgroupVisibility() {\n const { mero, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setSubgroupVisibility = useCallback(\n async (groupId: string, request: SetSubgroupVisibilityRequest) => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n return run(() =>\n governGroup(session, groupId, subgroupVisibilitySetOp(request.subgroupVisibility === 'open' ? 'open' : 'restricted')),\n );\n }\n if (!mero) return null;\n return run(() => mero.admin.setSubgroupVisibility(groupId, request));\n },\n [mero, run, isDelegated],\n );\n\n return { setSubgroupVisibility, loading, error };\n}\n\nexport function useDefaultCapabilities(groupId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<number | null>(\n mero && groupId ? () => mero.admin.getDefaultCapabilities(groupId) : null,\n null,\n [mero, groupId],\n );\n return { defaultCapabilities: data, loading, error, refetch };\n}\n\nexport function useSubgroupVisibility(groupId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<string | null>(\n mero && groupId ? () => mero.admin.getSubgroupVisibility(groupId) : null,\n null,\n [mero, groupId],\n );\n return { subgroupVisibility: data, loading, error, refetch };\n}\n\nexport function useSetTeeAdmissionPolicy() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setTeeAdmissionPolicy = useCallback(\n async (groupId: string, request: SetTeeAdmissionPolicyRequest) => {\n if (!mero) return null;\n return run(() => mero.admin.setTeeAdmissionPolicy(groupId, request));\n },\n [mero, run],\n );\n\n return { setTeeAdmissionPolicy, loading, error };\n}\n\n// ---- Metadata Hooks ----\n\nexport function useSetGroupMetadata() {\n const { mero, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setGroupMetadata = useCallback(\n async (groupId: string, request: SetMetadataInput) => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n return run(() => governGroup(session, groupId, groupMetadataSetOp(request)));\n }\n if (!mero) return null;\n return run(() => mero.admin.setGroupMetadata(groupId, request));\n },\n [mero, run, isDelegated],\n );\n\n return { setGroupMetadata, loading, error };\n}\n\n/**\n * Takes the member's ACCOUNT (64 hex), as `useGroupMembers` rows are keyed by\n * and `useNodeIdentity().identity?.accountId` returns - NOT a signing key.\n * Both are 32-byte strings, so passing a key names nobody and raises nothing.\n */\nexport function useSetMemberMetadata() {\n const { mero, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setMemberMetadata = useCallback(\n async (groupId: string, identity: string, request: SetMetadataInput) => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n return run(() => governGroup(session, groupId, memberMetadataSetOp(identity, request)));\n }\n if (!mero) return null;\n return run(() => mero.admin.setMemberMetadata(groupId, identity, request));\n },\n [mero, run, isDelegated],\n );\n\n return { setMemberMetadata, loading, error };\n}\n\nexport function useSetContextMetadata() {\n const { mero, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setContextMetadata = useCallback(\n async (groupId: string, contextId: string, request: SetMetadataInput) => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n return run(() => governGroup(session, groupId, contextMetadataSetOp(contextId, request)));\n }\n if (!mero) return null;\n return run(() => mero.admin.setContextMetadata(groupId, contextId, request));\n },\n [mero, run, isDelegated],\n );\n\n return { setContextMetadata, loading, error };\n}\n\nexport function useGroupMetadata(groupId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<MetadataRecord | null>(\n mero && groupId ? () => mero.admin.getGroupMetadata(groupId) : null,\n null,\n [mero, groupId],\n );\n return { metadata: data, loading, error, refetch };\n}\n\nexport function useMemberMetadata(groupId?: string | null, identity?: string | null) {\n const { mero } = useMero();\n const [metadata, setMetadata] = useState<MetadataRecord | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n // Drop the previous (group, member)'s record DURING RENDER. Clearing in an\n // effect leaves one render where `metadata` answers for the pair that was\n // asked about last, and a consumer that persists what it sees turns that\n // transient staleness into a permanent wrong answer.\n const prevKey = useRef<string | null>(null);\n const key = `${groupId ?? ''}:${identity ?? ''}`;\n if (prevKey.current !== null && prevKey.current !== key) {\n setMetadata(null);\n setError(null);\n }\n prevKey.current = key;\n\n // Shared fetch logic for the auto-mount effect and the explicit\n // refetch callable. The per-invocation `signal.aborted` flag covers\n // the response-during-unmount race cleanly without the global\n // mountedRef gate that — under StrictMode-like fast unmount/remount\n // cycles — could leave the hook stuck on `metadata = null` when an\n // in-flight response landed during cleanup and the followup mount's\n // useCallback referential identity hadn't changed enough to re-fire\n // the effect.\n const run = useCallback(\n async (signal: { aborted: boolean }) => {\n if (!mero || !groupId || !identity) {\n if (!signal.aborted) {\n setMetadata(null);\n setError(null);\n setLoading(false);\n }\n return;\n }\n if (!signal.aborted) {\n setLoading(true);\n setError(null);\n }\n try {\n const result = await mero.admin.getMemberMetadata(groupId, identity);\n if (!signal.aborted) setMetadata(result);\n } catch (err) {\n if (!signal.aborted) setError(toError(err));\n } finally {\n if (!signal.aborted) setLoading(false);\n }\n },\n [mero, groupId, identity],\n );\n\n useEffect(() => {\n const signal = { aborted: false };\n void run(signal);\n return () => {\n signal.aborted = true;\n };\n }, [run]);\n\n // Explicit refetch — the caller's `await refetch()` resolves only\n // after state has been written (preserves the prior API contract;\n // call sites like `useMemberDisplayName.setName` rely on the new\n // value being readable from state after the await).\n const refetch = useCallback(async () => {\n const signal = { aborted: false };\n await run(signal);\n }, [run]);\n\n return { metadata, loading, error, refetch };\n}\n\n// ---- Group Signing Key, Upgrades & Hierarchy ----\n\nexport function useUpgradeGroup() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const upgradeGroup = useCallback(\n async (groupId: string, request: UpgradeGroupRequest) => {\n if (!mero) return null;\n return run(() => mero.admin.upgradeGroup(groupId, request));\n },\n [mero, run],\n );\n\n return { upgradeGroup, loading, error };\n}\n\n/**\n * Install a registry package version onto the node — the discrete \"Download\"\n * step an Updates flow runs before an `upgradeGroup`. Resolves the installed\n * application id (`InstallApplicationResponseData`). Downloading does not by\n * itself change what any group runs; pair it with a subsequent upgrade.\n */\nexport function useInstallFromRegistry() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n /**\n * ⚠️ NO `registryUrl` ARGUMENT ANY MORE. Since core's registry-only\n * application distribution, a node installs by `package@version` and\n * resolves the artifact against the registry IT is configured with — a\n * client cannot name one. mero-js dropped `installFromRegistry` for\n * `installApplication({ package, version })` to match, so the old third\n * argument had nowhere to go.\n */\n const installFromRegistry = useCallback(\n async (packageName: string, version: string) => {\n if (!mero) return null;\n return run(() => mero.admin.installApplication({ package: packageName, version }));\n },\n [mero, run],\n );\n\n return { installFromRegistry, loading, error };\n}\n\n/**\n * Kick off a full state re-pull for a context — operator recovery for a\n * context stranded mid-sync. `force` re-pulls even when the node does not\n * flag the context as stranded.\n */\nexport function useResyncContext() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const resyncContext = useCallback(\n async (contextId: string, request: ResyncContextRequest = {}) => {\n if (!mero) return null;\n return run(() => mero.admin.resyncContext(contextId, request));\n },\n [mero, run],\n );\n\n return { resyncContext, loading, error };\n}\n\nexport function useGroupUpgradeStatus(groupId?: string | null) {\n const { mero } = useMero();\n const [upgradeStatus, setUpgradeStatus] = useState<GroupUpgradeStatusResponseData>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Latest-request-wins token (see useMigrationStatus) so overlapping refetches\n // can't land out of order and overwrite fresher data.\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n if (!mero || !groupId) {\n if (mountedRef.current) {\n setUpgradeStatus(null);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const result = await mero.admin.getGroupUpgradeStatus(groupId);\n if (mountedRef.current && seq === reqRef.current) {\n setUpgradeStatus(result);\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [groupId, mero, mountedRef]);\n\n // Clear stale status synchronously when the target group changes (and\n // invalidate any in-flight refetch), mirroring useMigrationStatus.\n useEffect(() => {\n reqRef.current += 1;\n setUpgradeStatus(null);\n setError(null);\n }, [groupId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { upgradeStatus, loading, error, refetch };\n}\n\nexport function useRetryGroupUpgrade() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const retryGroupUpgrade = useCallback(\n async (groupId: string) => {\n if (!mero) return null;\n return run(() => mero.admin.retryGroupUpgrade(groupId));\n },\n [mero, run],\n );\n\n return { retryGroupUpgrade, loading, error };\n}\n\n/** Move `childGroupId` under a new parent. */\nexport function useReparentGroup() {\n const { mero, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const reparentGroup = useCallback(\n async (childGroupId: string, request: ReparentGroupRequest) => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n return run(async () => {\n await governRoot(session, childGroupId, groupReparentedOp(childGroupId, request.newParentId));\n return { reparented: true };\n });\n }\n if (!mero) return null;\n return run(() => mero.admin.reparentGroup(childGroupId, request));\n },\n [mero, run, isDelegated],\n );\n\n return { reparentGroup, loading, error };\n}\n\nexport function useSubgroups(groupId?: string | null) {\n const { mero } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<SubgroupEntry[]>(\n mero && groupId ? () => mero.admin.listSubgroups(groupId) : null,\n [],\n [mero, groupId],\n );\n return { subgroups: data, loading, error, refetch };\n}\n\n// ---- Context-Group Relationship ----\n\nexport function useDetachContextFromGroup() {\n const { mero, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const detachContextFromGroup = useCallback(\n async (groupId: string, contextId: string) => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n return run(() => governGroup(session, groupId, contextDetachedOp(contextId)));\n }\n if (!mero) return null;\n return run(() => mero.admin.detachContextFromGroup(groupId, contextId));\n },\n [mero, run, isDelegated],\n );\n\n return { detachContextFromGroup, loading, error };\n}\n\n/**\n * Subscribe to a namespace's `GroupMigration` events, invoking `onEvent` per\n * frame and unsubscribing on unmount.\n *\n * A non-admin subscriber never sees `CascadeProgress`; core delivers that to\n * namespace admins only, so a UI must not wait on it to decide progress.\n */\n/**\n * Fallback poll cadence for `useMigrationStatus` when the SSE stream is\n * unavailable (no token, a proxy that buffers, an older node) and the caller\n * named no interval of its own. Chosen to match the heartbeat cadence that\n * migration facts actually arrive on; an explicit `pollIntervalMs` overrides it.\n */\nexport const DEFAULT_MIGRATION_POLL_INTERVAL_MS = 5000;\n\nexport function useMigrationEvents(\n namespaceId: string | null | undefined,\n onEvent: (event: GroupMigrationEventData) => void,\n): boolean {\n const { mero } = useMero();\n const mountedRef = useMountedRef();\n // Whether the stream is actually carrying frames. Callers use it to decide\n // whether they still need a fallback poll, so it must reflect the subscribe\n // ACTUALLY succeeding - not merely that we asked.\n const [live, setLive] = useState(false);\n // Held in a ref so a caller passing an inline arrow does not resubscribe on\n // every render - the subscription's lifetime is the namespace's, not the\n // callback identity's.\n const handlerRef = useRef(onEvent);\n handlerRef.current = onEvent;\n\n useEffect(() => {\n if (!mero || !namespaceId) return;\n const sse = mero.events;\n const unsubscribe = sse.onMigrationEvent((event) => handlerRef.current(event));\n // Sequential, and the result is recorded: connecting but failing to\n // subscribe is still a dead stream, and both used to be swallowed, which\n // left a caller unable to tell a live stream from a silent one.\n let cancelled = false;\n void (async () => {\n try {\n await sse.connect();\n await sse.subscribe({ groupIds: [namespaceId] });\n if (!cancelled && mountedRef.current) setLive(true);\n } catch {\n if (!cancelled && mountedRef.current) setLive(false);\n }\n })();\n return () => {\n cancelled = true;\n if (mountedRef.current) setLive(false);\n unsubscribe();\n };\n }, [mero, namespaceId, mountedRef]);\n\n return live;\n}\n\n/**\n * Migration-status rollup for a namespace (skew #3).\n *\n * Live: subscribes to the `GroupMigration` event family and re-reads on each\n * frame. It re-READS rather than folding the event's counters in, because the\n * rollup is recomputed from raw member rows and is the authoritative answer.\n * `pollIntervalMs` stays as the fallback when SSE is unavailable, and when the\n * caller names none it defaults to `DEFAULT_MIGRATION_POLL_INTERVAL_MS` for\n * exactly as long as the stream is down - so the panel can never sit silently\n * frozen with neither transport.\n * Derived counters are null-safe before the first load.\n */\nexport function useMigrationStatus(\n namespaceId?: string | null,\n options?: { pollIntervalMs?: number },\n) {\n const { mero } = useMero();\n const [status, setStatus] = useState<MigrationStatus | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Monotonic request token: only the latest in-flight request applies its\n // result, so an overlapping poll or a fast namespace change can't let a\n // stale response overwrite fresher data.\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n if (!mero || !namespaceId) {\n if (mountedRef.current) {\n setStatus(null);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n const seq = ++reqRef.current;\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const result = await mero.admin.getMigrationStatus(namespaceId);\n if (mountedRef.current && seq === reqRef.current) {\n setStatus(result);\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [namespaceId, mero, mountedRef]);\n\n // Clear stale state the instant the namespace changes, so the panel shows a\n // loading state rather than the previous namespace's data during the refetch.\n useEffect(() => {\n setStatus(null);\n setError(null);\n }, [namespaceId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n // Live updates. The frame is a signal, not the answer: it says something\n // moved, and the re-read is what stays authoritative. This runs BEFORE the\n // poll below because whether the stream is genuinely live is what decides\n // if a caller who named no interval needs a fallback poll at all.\n const sseLive = useMigrationEvents(namespaceId, () => void refetch());\n\n // An explicit interval always wins - a caller that asked to poll keeps\n // polling. When none was named, poll only while the stream is NOT live:\n // migration facts arrive by heartbeat gossip with no push transport of their\n // own, so with neither SSE nor an interval the panel loads once and then\n // silently never updates again, with no error to show for it.\n const pollIntervalMs =\n options?.pollIntervalMs ??\n (sseLive ? undefined : DEFAULT_MIGRATION_POLL_INTERVAL_MS);\n useEffect(() => {\n if (!pollIntervalMs || !mero || !namespaceId) return;\n const handle = setInterval(() => void refetch(), pollIntervalMs);\n return () => clearInterval(handle);\n }, [pollIntervalMs, mero, namespaceId, refetch]);\n\n const rollup: MigrationStatusRollup | null = status?.rollup ?? null;\n const members: MemberMigrationStatusEntry[] = status?.members ?? [];\n\n return {\n status,\n rollup,\n members,\n allMigrated: rollup?.allMigrated ?? false,\n /**\n * When this node watched the fleet converge, or `null`. Durable, unlike\n * `allMigrated`, which is recomputed from in-TTL heartbeats and lapses back\n * to false when a member simply goes quiet.\n */\n fleetCompletedAt: status?.fleetCompletedAt ?? null,\n membersPendingSignature: rollup?.membersPendingSignature ?? 0,\n /** Members whose migrate aborted (migration-check failed or apply errored). */\n failed: rollup?.failed ?? 0,\n loading,\n error,\n refetch,\n };\n}\n\n/**\n * Bundle-version skew (#2): reads the context's installed `applicationVersion`\n * (semver) and compares it to the app-declared `expected` build constant. Any\n * mismatch (either direction) is `isStale` → \"reload to update\". Subscribes to\n * `AppVersionChanged` so a live flip updates `appVersion` without a refetch.\n */\nexport function useAppVersion(contextId?: string | null, expected?: string) {\n const { mero } = useMero();\n const [appVersion, setAppVersion] = useState<string | undefined>(undefined);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Latest-request-wins token (see useMigrationStatus).\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n if (!mero || !contextId) {\n if (mountedRef.current) {\n setAppVersion(undefined);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n const seq = ++reqRef.current;\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const context = await mero.admin.getContext(contextId);\n if (mountedRef.current && seq === reqRef.current) {\n setAppVersion(context.applicationVersion);\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [contextId, mero, mountedRef]);\n\n // Reset on context change so a stale version isn't shown during the refetch.\n useEffect(() => {\n setAppVersion(undefined);\n setError(null);\n }, [contextId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n useEffect(() => {\n if (!mero?.events || !contextId) return;\n const off = mero.events.onAppVersionChanged((event: AppVersionChangedEvent) => {\n if (event.contextId !== contextId) return;\n if (mountedRef.current && event.toVersion) {\n // Invalidate any in-flight refetch so its (older) result can't clobber\n // this live update.\n reqRef.current += 1;\n setAppVersion(event.toVersion);\n }\n });\n return off;\n }, [mero, contextId, mountedRef]);\n\n const isStale = appVersion != null && expected != null && appVersion !== expected;\n\n return { appVersion, expected, isStale, loading, error, refetch };\n}\n\n/**\n * \"Is a newer version available?\" for an Updates view. Reads a package's\n * published versions from the registry and compares the newest to the running\n * `currentVersion` (e.g. a context's `applicationVersion`). `updateAvailable`\n * is true only when the registry's newest is strictly greater. This is the\n * registry-side check the admin acts on; gate rendering on admin status at the\n * call site. Pure read — fetching nothing until both `registryUrl` and\n * `packageName` are provided.\n */\nexport function useLatestVersion(\n registryUrl?: string | null,\n packageName?: string | null,\n currentVersion?: string | null,\n) {\n const { mero } = useMero();\n const [versions, setVersions] = useState<string[]>([]);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Latest-request-wins token (see useMigrationStatus).\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n if (!mero || !registryUrl || !packageName) {\n // Invalidate any in-flight request so a late response can't repopulate\n // stale versions for the previous package after the inputs were cleared.\n reqRef.current += 1;\n if (mountedRef.current) {\n setVersions([]);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n const seq = ++reqRef.current;\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const result = await mero.admin.getRegistryVersions(registryUrl, packageName);\n if (mountedRef.current && seq === reqRef.current) {\n setVersions(result);\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [mero, registryUrl, packageName, mountedRef]);\n\n // Clear stale versions the instant the package/registry changes.\n useEffect(() => {\n setVersions([]);\n setError(null);\n }, [registryUrl, packageName]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n // getRegistryVersions returns newest-first, so [0] is the latest published.\n const latestVersion = versions[0] ?? null;\n const updateAvailable =\n latestVersion != null &&\n currentVersion != null &&\n compareSemver(latestVersion, currentVersion) > 0;\n\n return { versions, latestVersion, currentVersion, updateAvailable, loading, error, refetch };\n}\n\ninterface GroupAppVersion {\n /** Semver of the application the group currently targets (`null` until loaded). */\n version: string | null;\n /** The group's `targetApplicationId`. */\n applicationId: string | null;\n /** The installed blob differs from the one the group targets (see hook doc). */\n pendingApply: boolean;\n /** Only populated via the group-info path; `null` in the namespace path. */\n activeUpgrade: GroupUpgradeStatusResponseData;\n}\n\nconst EMPTY_GROUP_APP_VERSION: GroupAppVersion = {\n version: null,\n applicationId: null,\n pendingApply: false,\n activeUpgrade: null,\n};\n\n/** An appKey carries no \"pending\" signal when it is absent or all-zero. */\nfunction isZeroAppKey(appKey?: string): boolean {\n return !appKey || /^0+$/.test(appKey);\n}\n\n/**\n * What app version does this group run, and is there a downloaded-but-not-yet-\n * applied update? Replaces the appKey-vs-installed-blob comparison apps\n * otherwise hand-roll: `pendingApply` is true when the group's `appKey` (the\n * blob it targets) is present, non-zero, and differs from the blob actually\n * installed for its `targetApplicationId`. Deciding whether to render or gate on\n * that status (admin-only actions, etc.) is the call site's job.\n *\n * Resolution stays cheap: the group's record comes from `listNamespaces()` when\n * the id is a namespace, else from `getGroupInfo()`; `getApplication()` then\n * reads the installed version and blob. `activeUpgrade` is returned only when it\n * arrives for free on the group-info path (it is not fetched separately).\n * Subscribes to `AppVersionChanged` and refetches, since any version flip in the\n * workspace can make the rollup stale.\n */\nexport function useGroupAppVersion(groupId?: string) {\n const { mero } = useMero();\n const [data, setData] = useState<GroupAppVersion>(EMPTY_GROUP_APP_VERSION);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Latest-request-wins token (see useMigrationStatus).\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n if (!mero || !groupId) {\n if (mountedRef.current) {\n setData(EMPTY_GROUP_APP_VERSION);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n // Namespace-first resolution: a top-level group is a namespace; only\n // subgroups need the getGroupInfo fallback (which also carries\n // activeUpgrade, so we surface it without a third call).\n const namespaces = await mero.admin.listNamespaces();\n const namespace = namespaces.find((entry) => entry.namespaceId === groupId);\n\n let appKey: string | undefined;\n let applicationId: string | null;\n let activeUpgrade: GroupUpgradeStatusResponseData = null;\n\n if (namespace) {\n appKey = namespace.appKey;\n applicationId = namespace.targetApplicationId;\n } else {\n const info = await mero.admin.getGroupInfo(groupId);\n appKey = info.appKey;\n applicationId = info.targetApplicationId;\n activeUpgrade = info.activeUpgrade ?? null;\n }\n\n let version: string | null = null;\n let pendingApply = false;\n if (applicationId) {\n const { application } = await mero.admin.getApplication(applicationId);\n version = application?.version ?? null;\n if (application && !isZeroAppKey(appKey)) {\n const installedHex = base58ToHex(application.blob.bytecode).toLowerCase();\n pendingApply = appKey!.toLowerCase() !== installedHex;\n }\n }\n\n if (mountedRef.current && seq === reqRef.current) {\n setData({ version, applicationId, pendingApply, activeUpgrade });\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [groupId, mero, mountedRef]);\n\n // Clear stale state synchronously when the target group changes (and\n // invalidate any in-flight refetch). Mirrors useGroupUpgradeStatus.\n useEffect(() => {\n reqRef.current += 1;\n setData(EMPTY_GROUP_APP_VERSION);\n setError(null);\n }, [groupId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n useEffect(() => {\n if (!mero?.events || !groupId) return;\n const off = mero.events.onAppVersionChanged(() => {\n if (mountedRef.current) void refetch();\n });\n return off;\n }, [mero, groupId, refetch, mountedRef]);\n\n return { ...data, loading, error, refetch };\n}\n\n/**\n * The caller's own identity-gated entries pending re-signature (skew #1).\n * `pending` is `pendingCount > 0` (from `count_my_pending`); `authorize()` runs\n * the one-tap `migrate_my_entries` convert and folds the resulting `remaining`\n * back into the count.\n */\nexport function useMyAuthoredMigration(contextId?: string | null) {\n const { mero } = useMero();\n const [summary, setSummary] = useState<MigrateMyEntriesSummary | null>(null);\n const [pendingCount, setPendingCount] = useState(0);\n const mountedRef = useMountedRef();\n const { loading, error, run } = useAsyncMutation();\n // Latest-request-wins token (see useMigrationStatus).\n const reqRef = useRef(0);\n\n const refresh = useCallback(async () => {\n if (!mero || !contextId) {\n if (mountedRef.current) setPendingCount(0);\n return;\n }\n const seq = ++reqRef.current;\n try {\n const count = await mero.rpc.countMyPending(contextId);\n if (mountedRef.current && seq === reqRef.current) setPendingCount(count);\n } catch {\n // best-effort count; leave the previous value on a transient failure\n }\n }, [mero, contextId, mountedRef]);\n\n // Clear stale per-context state synchronously when the target changes (and\n // invalidate any in-flight refresh), so the banner doesn't flash the previous\n // context's count until the new count resolves. Mirrors useMigrationStatus.\n useEffect(() => {\n reqRef.current += 1;\n setPendingCount(0);\n setSummary(null);\n }, [contextId]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const authorize = useCallback(async () => {\n if (!mero || !contextId) return null;\n const result = await run(() => mero.rpc.migrateMyEntries(contextId));\n if (result && mountedRef.current) {\n // Invalidate any in-flight refresh so a stale count can't overwrite the\n // authoritative post-convert remaining.\n reqRef.current += 1;\n setSummary(result);\n setPendingCount(result.remaining);\n }\n return result;\n }, [mero, contextId, run, mountedRef]);\n\n return {\n summary,\n pendingCount,\n pending: pendingCount > 0,\n authorize,\n loading,\n error,\n refresh,\n };\n}\n\n// ---- Blob Hooks ----\n\n/**\n * Options for the blob READ hooks.\n *\n * `contextId` is what picks the mode, and the two modes have wildly different\n * costs:\n *\n * - **omitted** — local-only read. The node answers from its own blob store\n * and returns immediately, or 404s.\n * - **supplied** — network discovery. The node probes that context's peers\n * (availability nodes first) for a holder. Core bounds the search by a ~30s\n * deadline, and for {@link useBlobUrl} the byte transfer is on top of that.\n *\n * So `loading` is load-bearing UI state on these hooks, not decoration: a\n * discovery read can plausibly spin for half a minute before it resolves\n * either way. Render a spinner (or a cancel affordance) accordingly.\n */\nexport interface BlobHookOptions {\n /** Context whose peers to probe. Omit for a local-only read. */\n contextId?: string;\n}\n\n/** Options for {@link useBlobUrl}. */\nexport interface UseBlobUrlOptions extends BlobHookOptions {\n /**\n * MIME type stamped on the `Blob` the object URL points at. The blob read\n * itself carries no type, and a peer-sourced answer has no `mimeType` at\n * all, so pass it when the consumer needs one (`<img>` sniffs; a download\n * `<a>` and an `<iframe>` do not).\n */\n type?: string;\n}\n\n/**\n * True when the failure is the node saying \"nobody has this blob\" (HTTP 404)\n * rather than a transport/auth failure.\n *\n * Duck-typed on `status` rather than `instanceof HTTPError`: a consumer app can\n * easily end up with two copies of mero-js (bundled + peer), and an\n * `instanceof` across that boundary silently reports false.\n */\nfunction isBlobNotFound(error: Error | null): boolean {\n return !!error && (error as { status?: unknown }).status === 404;\n}\n\n/**\n * A blob's presence and size, WITHOUT downloading it — the cheap half of the\n * blob surface, and the one to ask before pulling something large.\n *\n * `blobId` follows the same `string | null` convention as the other read\n * hooks: null/undefined means \"no read\", not \"read nothing\" — nothing is\n * fetched and `info` stays null.\n *\n * `hash` and `mimeType` on the result are genuinely optional: a peer probe\n * answers with presence and size only, so a discovery-sourced hit carries\n * neither. `info.source` (`'local' | 'peer'`, undefined on nodes that predate\n * the header) tells the two apart — do not treat a missing `mimeType` as a\n * malformed response.\n *\n * `notFound` distinguishes the legitimate \"no holder\" outcome (the node\n * answered 404) from a transport failure. `error` is set in BOTH cases — this\n * hook does not swallow the 404, it only labels it.\n *\n * Latency: immediate without `contextId`, up to core's ~30s discovery deadline\n * with one. See {@link BlobHookOptions}.\n */\nexport function useBlobInfo(blobId?: string | null, options?: BlobHookOptions) {\n const { mero } = useMero();\n const contextId = options?.contextId;\n const { data, loading, error, refetch } = useAsyncResource<GetBlobInfoResponseData | null>(\n mero && blobId\n ? () => mero.admin.getBlobInfo(blobId, contextId ? { contextId } : undefined)\n : null,\n null,\n [mero, blobId, contextId],\n );\n\n return { info: data, notFound: isBlobNotFound(error), loading, error, refetch };\n}\n\n/**\n * A blob's bytes as an object URL, ready for `<img src>`, an `<a href>`\n * download, or an `<iframe>`.\n *\n * Lifecycle is handled here so the consumer never has to revoke: the URL is\n * revoked on unmount, and whenever `blobId`/`contextId`/`type` change. `url`\n * goes back to null synchronously on such a change, so a revoked URL is never\n * handed out as the current one — render off `url` and it is always live.\n *\n * A response for a superseded `blobId` is dropped before an object URL is even\n * created, so an out-of-order arrival can neither overwrite the newer result\n * nor leak.\n *\n * Latency: this is the expensive hook. Without `contextId` it is a local read;\n * with one it is discovery (core's ~30s deadline) PLUS the transfer of the\n * bytes. Prefer {@link useBlobInfo} to decide whether the download is worth\n * starting, and always render `loading`.\n *\n * `notFound` marks the node's 404 (\"no peer holds this\") apart from a\n * transport failure; `error` is set for both.\n */\nexport function useBlobUrl(blobId?: string | null, options?: UseBlobUrlOptions) {\n const { mero } = useMero();\n const contextId = options?.contextId;\n const type = options?.type;\n const mountedRef = useMountedRef();\n const [url, setUrl] = useState<string | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n // Latest-request-wins token, same shape as useAsyncResource's.\n const reqRef = useRef(0);\n // The URL currently handed out, held in a ref so revocation never depends on\n // a render having happened.\n const urlRef = useRef<string | null>(null);\n\n const revoke = useCallback(() => {\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n urlRef.current = null;\n }\n }, []);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n if (!mero || !blobId) return;\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n try {\n const bytes = await mero.admin.getBlob(blobId, contextId ? { contextId } : undefined);\n // Check BEFORE creating the object URL: a loser allocates nothing, so\n // there is nothing to leak and nothing to overwrite the winner with.\n if (!mountedRef.current || seq !== reqRef.current) return;\n revoke();\n const objectUrl = URL.createObjectURL(new Blob([bytes], type ? { type } : undefined));\n urlRef.current = objectUrl;\n setUrl(objectUrl);\n } catch (err) {\n if (mountedRef.current && seq === reqRef.current) setError(toError(err));\n } finally {\n if (mountedRef.current && seq === reqRef.current) setLoading(false);\n }\n }, [mero, blobId, contextId, type, revoke, mountedRef]);\n\n // Invalidate the in-flight request and drop the current URL synchronously\n // when the inputs change, so the consumer never sees the previous blob's URL\n // (revoked or not) attributed to the new id.\n useEffect(() => {\n reqRef.current += 1;\n revoke();\n setUrl(null);\n setError(null);\n setLoading(false);\n }, [mero, blobId, contextId, type, revoke]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n // Final revoke on unmount. Separate from the input-change effect above so it\n // runs exactly once, on teardown, whatever the deps did.\n useEffect(() => revoke, [revoke]);\n\n return { url, notFound: isBlobNotFound(error), loading, error, refetch };\n}\n\n/**\n * Upload bytes to the node's blob store. Mutation-shaped, like the other\n * write hooks: `uploadBlob` resolves to `{ blobId, size }`, or null when the\n * client is absent or the call failed (read `error` for which).\n *\n * Pass `contextId` to announce the blob to that context, which is what lets\n * the context's other members later discover it with {@link useBlobUrl} /\n * {@link useBlobInfo}. Without it the blob is only readable on this node.\n */\nexport function useUploadBlob() {\n const { mero } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const uploadBlob = useCallback(\n async (request: UploadBlobRequest) => {\n if (!mero) return null;\n return run(() => mero.admin.uploadBlob(request));\n },\n [mero, run],\n );\n\n return { uploadBlob, loading, error };\n}\n","import type { ReactNode } from 'react';\nimport { useMyAuthoredMigration } from '../hooks';\n\nexport interface MigrationPendingBannerProps {\n /** Context whose authored entries to check / convert. */\n contextId: string;\n className?: string;\n /** Override the default prompt text. */\n children?: ReactNode;\n /** Fired once a convert leaves nothing pending (`remaining === 0`). */\n onMigrated?: () => void;\n}\n\n/**\n * Shows only when the current identity has entries below the target schema\n * (skew #1). A single button runs the one-tap `migrate_my_entries` convert and\n * the banner clears itself once nothing is pending.\n */\nexport function MigrationPendingBanner({\n contextId,\n className,\n children,\n onMigrated,\n}: MigrationPendingBannerProps) {\n const { pending, pendingCount, authorize, loading } = useMyAuthoredMigration(contextId);\n\n if (!pending) return null;\n\n const handleClick = async () => {\n const result = await authorize();\n if (result && result.remaining === 0) {\n onMigrated?.();\n }\n };\n\n const message =\n children ??\n `You have ${pendingCount} ${pendingCount === 1 ? 'entry' : 'entries'} to re-sign after a recent upgrade.`;\n\n return (\n <div className={className} data-testid=\"migration-pending-banner\" role=\"status\">\n <span>{message}</span>\n <button type=\"button\" onClick={handleClick} disabled={loading}>\n {loading ? 'Migrating…' : 'Migrate my data'}\n </button>\n </div>\n );\n}\n","import { useMigrationStatus } from '../hooks';\n\nexport interface MigrationAdminPanelProps {\n /** Namespace whose migration rollup to display. */\n namespaceId: string;\n /** Re-fetch interval; migration facts arrive via heartbeat gossip. */\n pollIntervalMs?: number;\n className?: string;\n}\n\n/**\n * Operator view of a namespace's migration rollup (skew #3): the cohort\n * counters, `membersPendingSignature`, and a per-member table. Read-only —\n * pair with the upgrade-trigger hooks to drive a migration.\n */\nexport function MigrationAdminPanel({ namespaceId, pollIntervalMs, className }: MigrationAdminPanelProps) {\n const { status, rollup, members, membersPendingSignature, failed, error } = useMigrationStatus(\n namespaceId,\n { pollIntervalMs },\n );\n\n // Surface a real failure rather than the misleading \"no status\" message.\n if (error && !status) {\n return (\n <div className={className} data-testid=\"migration-admin-panel\">\n Failed to load migration status: {error.message}\n </div>\n );\n }\n\n // Before the first successful fetch (initial paint or in-flight), show\n // loading — a successful read always yields a rollup, so a null status here\n // means \"not loaded yet\", never \"empty\".\n if (!status || !rollup) {\n return <div className={className} data-testid=\"migration-admin-panel\">Loading migration status…</div>;\n }\n\n return (\n <div className={className} data-testid=\"migration-admin-panel\">\n {error && (\n // A poll failed after data was already loaded — keep showing the last\n // good rollup but flag that it may be stale.\n <div data-testid=\"migration-status-error\" role=\"alert\">\n Could not refresh migration status: {error.message}\n </div>\n )}\n <dl>\n <div><dt>Target version</dt><dd>{status.targetVersion}</dd></div>\n <div><dt>Migrated</dt><dd>{rollup.migrated}</dd></div>\n <div><dt>In progress</dt><dd>{rollup.inProgress}</dd></div>\n <div><dt>Unknown</dt><dd>{rollup.unknown}</dd></div>\n <div><dt>Failed</dt><dd data-testid=\"migration-failed-count\">{failed}</dd></div>\n <div><dt>Total</dt><dd>{rollup.total}</dd></div>\n <div><dt>All migrated</dt><dd>{rollup.allMigrated ? 'yes' : 'no'}</dd></div>\n <div>\n <dt>Members pending signature</dt>\n <dd data-testid=\"members-pending-signature\">{membersPendingSignature}</dd>\n </div>\n </dl>\n <table>\n <thead>\n <tr><th>Peer</th><th>State</th><th>Schema</th><th>Pending</th><th>Reason</th></tr>\n </thead>\n <tbody>\n {members.map((m) => (\n <tr key={m.peer} data-testid=\"migration-member-row\">\n <td>{m.peer}</td>\n <td>{m.state}</td>\n <td>{m.report?.schemaVersion ?? '—'}</td>\n <td>{m.report?.authoredRemaining ?? '—'}</td>\n <td>{m.report?.migrationFailed ?? '—'}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n );\n}\n","/**\n * Resolving a relay from an INVITATION rather than from an account.\n *\n * # The gap this closes\n *\n * `ConnectButtonAccount` finds a relay by asking the cloud what serves the\n * *account* (`CloudClient.getAccountRelays`). A freshly enrolled account is a\n * member of nothing, so that read correctly answers `[]` and the button\n * correctly refuses to connect: there is nowhere to write, and a typed guess\n * would be a node that refuses every warrant.\n *\n * But a newcomer is not stuck — they are holding an invitation, and an\n * invitation names a namespace. `CloudClient.getNamespaceRouting` answers which\n * nodes serve *that namespace*, and it is deliberately anonymous: a joiner has\n * no cloud session, and needing one is exactly what this path exists to avoid.\n * So the bootstrap order is namespace first, account second — admission is what\n * makes `getAccountRelays` answer at all, not the other way round.\n *\n * # Two sources, one intersection, and why it must not be skipped\n *\n * The invitation's `admitters` list sits INSIDE the body the group admin\n * signed, so it is authorization: merod answers `403` to an `/admit` from a node\n * that list does not name, whatever else is true of it. The cloud's list is\n * every node currently assigned to the namespace — it cannot know which\n * invitation the caller holds, so it cannot filter by the signed list, and a\n * node assigned *after* the invitation was minted looks perfect in every field\n * the cloud reports and still refuses the claim.\n *\n * Intersecting here is therefore not belt-and-braces: it is the check that\n * turns an unexplainable `403` into \"your invitation names none of these nodes,\n * ask for a fresh one\". It is never relaxed to make a flow work.\n *\n * # `servable` and `canAdmit` are advisory; `writable` is information\n *\n * `servable` and `canAdmit` are derived from assignment heartbeats, and a lapsed\n * heartbeat is not the same fact as a node that will refuse. Measured against\n * prod: the cloud reported `servable: false, canAdmit: false, fresh: false` for a\n * node whose `/admin-api/health` answered `{\"status\":\"alive\"}` and which had just\n * minted the invitation being claimed. Gating on them meant refusing to knock on\n * an open door, so a node with an address is tried and the NODE decides —\n * `admit_join` re-verifies the invitation, the signature and the admitters list,\n * so asking loosens nothing and a refusal names its own cause. `stale` on the\n * result says the attempt rests on advisory data.\n *\n * `writable` — and its per-node form, `canExecute` — is about `CAN_AUTHOR_ON_BEHALF`,\n * which admission does **not** require: relaying a join the joiner signed is not\n * authoring on anyone's behalf. So a non-writable namespace is not a refusal\n * here; it is reported on the result, because it is precisely why the writes\n * would fail *after* connecting, and a caller that cannot tell the two apart\n * sends the user to the wrong place.\n */\n\nimport { CloudClient, type CloudNamespaceNode } from '@calimero-network/mero-js';\n\n/**\n * Which step could not be completed. Each one needs a different action from the\n * person, which is why this is an enum and not a message.\n *\n * - `admitters-lookup` — the cloud read itself failed (offline, 5xx, a refused\n * routing proof). Nothing has been learned about the namespace.\n * - `no-nodes` — the read succeeded and the cloud lists nothing. The namespace\n * has no fleet assignment, so there is no cloud node to admit through; the\n * invitation's admitters are somebody's self-hosted or desktop node, which the\n * cloud neither knows nor routes to.\n * - `not-invited` — nodes serve the namespace, and the invitation names none of\n * them. Terminal for this invitation: ask for a fresh one.\n * - `invited-unreachable` — a named node exists but cannot take a join now (no\n * fresh heartbeat, or the cloud reports the namespace as not servable). A\n * wait, not a wrong invitation.\n * - `no-relay-url` — a named node can admit but the cloud knows no address for\n * it, so there is nothing to connect through afterwards. Also a wait: it is\n * the shape a node reports before its first heartbeat lands.\n */\nexport type RelayResolutionStep =\n | 'admitters-lookup'\n | 'no-nodes'\n | 'not-invited'\n | 'invited-unreachable'\n | 'no-relay-url';\n\n/** A relay that can take this invitation's join, and connect afterwards. */\nexport interface ResolvedInvitationRelay {\n readonly ok: true;\n /** The node origin to connect through. */\n readonly relayUrl: string;\n /** Where to POST the signed join — the cloud's own, never rebuilt when given. */\n readonly admitUrl: string;\n /** The admitter's account, as the cloud reported it. */\n readonly admitterAccount: string | null;\n readonly peerId: string;\n /**\n * Whether this node can also run delegated writes (`CAN_AUTHOR_ON_BEHALF`).\n *\n * `false` is not a failure of admission — see the module note. It means the\n * connection that follows will read and receive events but have its intents\n * refused, which an admin grants away, so it is worth saying out loud.\n */\n readonly writable: boolean;\n /** Whether the chosen node's heartbeat for this namespace has lapsed. */\n readonly stale: boolean;\n}\n\nexport interface RelayResolutionFailure {\n readonly ok: false;\n readonly step: RelayResolutionStep;\n /** What to go and do about it, in one sentence. */\n readonly reason: string;\n}\n\nexport type ResolveRelayResult = ResolvedInvitationRelay | RelayResolutionFailure;\n\nexport interface ResolveRelayFromInvitationInput {\n /** The namespace the invitation admits you to, 64 hex. */\n readonly namespaceId: string;\n /**\n * The invitation's signed `admitters` — `invitation.invitation.admitters`.\n *\n * An EMPTY list is the legacy \"admission by broadcast\" shape, where any ready\n * peer may admit, and is treated as such. Omitting the field and passing an\n * empty array are therefore the same thing on purpose: there is no spelling\n * here that means \"nobody may admit\", because an invitation cannot say that.\n */\n readonly admitters?: readonly string[];\n /** The delegated credential — an `AccountProof<DeviceCert>`, hex. */\n readonly credential: string;\n /** The certified device's ed25519 signing secret, hex. */\n readonly deviceSecret: string;\n /** Point at a cloud other than the hosted manager. For local rigs. */\n readonly cloudBaseUrl?: string;\n /** Injected in tests. Anything with the one method this needs. */\n readonly cloud?: Pick<CloudClient, 'getNamespaceRouting'>;\n}\n\n/**\n * Normalise a hex account for comparison: lower-cased, `0x` stripped.\n *\n * Both sides are hex for the same 32 bytes, and a spelling mismatch would\n * present as \"your invitation does not name this node\" — a refusal that looks\n * like policy and is really formatting.\n */\nexport function normaliseAccount(account: string | null | undefined): string | null {\n if (!account) return null;\n const trimmed = account.trim().toLowerCase();\n const bare = trimmed.startsWith('0x') ? trimmed.slice(2) : trimmed;\n return bare.length > 0 ? bare : null;\n}\n\n/** Whether the invitation's signed list names this node. */\nfunction isInvited(node: CloudNamespaceNode, invited: ReadonlySet<string>): boolean {\n if (invited.size === 0) return true;\n const account = normaliseAccount(node.account);\n return account !== null && invited.has(account);\n}\n\n/**\n * Resolve a relay to bootstrap through, from an invitation and nothing else.\n *\n * Reads the cloud's routing for the namespace, intersects it with the\n * invitation's signed `admitters`, and returns the node to use — or which step\n * stopped it and what that means. It performs no admission and mints no keys:\n * the credential passed in is the one the wallet already certified.\n */\nexport async function resolveRelayFromInvitation(\n input: ResolveRelayFromInvitationInput,\n): Promise<ResolveRelayResult> {\n const cloud =\n input.cloud ??\n new CloudClient({\n cloudBaseUrl: input.cloudBaseUrl,\n routingCredential: { credential: input.credential, deviceSecret: input.deviceSecret },\n });\n\n let nodes: readonly CloudNamespaceNode[];\n let servable: boolean;\n try {\n const routing = await cloud.getNamespaceRouting(input.namespaceId);\n nodes = routing.nodes;\n servable = routing.servable;\n } catch (e) {\n // Named as its own step: nothing has been learned about the namespace, so\n // reporting this as \"no nodes serve it\" would be a claim the read never\n // made — and would send the user to ask for a new invitation over what is\n // usually a refused proof or a network blip.\n return {\n ok: false,\n step: 'admitters-lookup',\n reason:\n `The cloud could not be asked which nodes serve namespace ${input.namespaceId}: ` +\n `${e instanceof Error ? e.message : String(e)}. Nothing is known about the ` +\n 'invitation yet — this is the lookup failing, not the invitation.',\n };\n }\n\n if (nodes.length === 0) {\n return {\n ok: false,\n step: 'no-nodes',\n reason:\n 'The cloud lists no nodes serving this namespace, so there is no hosted node to be ' +\n 'admitted through. The namespace has no fleet assignment — whoever invited you is ' +\n 'running their own node, and admission has to go through a node the cloud routes to.',\n };\n }\n\n const invited = new Set(\n (input.admitters ?? [])\n .map(normaliseAccount)\n .filter((a): a is string => a !== null),\n );\n const named = nodes.filter((n) => isInvited(n, invited));\n\n if (named.length === 0) {\n return {\n ok: false,\n step: 'not-invited',\n reason:\n `${nodes.length} node${nodes.length === 1 ? '' : 's'} serve this namespace, but your ` +\n 'invitation names none of them. The signed admitter list is a snapshot from when the ' +\n 'invitation was minted, so a node assigned since is healthy and will still refuse the ' +\n 'claim. Ask for a fresh invitation.',\n };\n }\n\n // `canAdmit` and `servable` are ADVISORY here, not gates.\n //\n // They are derived from assignment heartbeats, and a lapsed heartbeat is not\n // the same fact as a node that will refuse: measured against prod, the cloud\n // reported `servable: false, canAdmit: false, fresh: false` for a node whose\n // `/admin-api/health` answered `{\"status\":\"alive\"}` and which had just minted\n // the invitation being claimed. Refusing on those flags meant refusing to\n // knock on a door that was open.\n //\n // So a node with an address is tried, and the node itself decides. Its answer\n // is the authoritative one: `admit_join` re-verifies the invitation, the\n // signature and the admitters list, so nothing is loosened by asking — the\n // worst case is a 403 that names its own cause, which is strictly better than\n // a client-side guess that names a heartbeat.\n const usable = named.filter((n) => n.canAdmit);\n const candidates = usable.length > 0 ? usable : named;\n const advisory = usable.length === 0 || !servable;\n\n const addressable = candidates.filter(\n (n): n is CloudNamespaceNode & { relayUrl: string } =>\n typeof n.relayUrl === 'string' && n.relayUrl.length > 0,\n );\n if (addressable.length === 0) {\n return {\n ok: false,\n step: 'no-relay-url',\n reason:\n 'A node your invitation names can admit you, but the cloud knows no address for it ' +\n 'yet, so there would be nothing to connect through afterwards. Try again shortly.',\n };\n }\n\n // Prefer a node that can do both legs — admit now and author later — so the\n // session lands on one node where possible. Preference only: admission is the\n // step that cannot proceed without a node, and authorship is not on the\n // invitation's list at all, so insisting would refuse a perfectly good\n // admitter for a permission admission never needed.\n const chosen =\n addressable.find((n) => n.canExecute) ?? addressable.find((n) => n.fresh) ?? addressable[0]!;\n\n return {\n ok: true,\n relayUrl: chosen.relayUrl,\n // The cloud's ready-made URL when it gave one, so the path is never rebuilt\n // from a guess; the fallback is the documented route on the same origin.\n admitUrl:\n chosen.admitUrl ??\n `${chosen.relayUrl.replace(/\\/+$/, '')}/admin-api/namespaces/${input.namespaceId}/admit`,\n admitterAccount: chosen.account,\n peerId: chosen.peerId,\n writable: chosen.canExecute,\n // Stale when the node's own heartbeat lapsed OR when the cloud's summary\n // disagrees with trying it at all. Both mean the same thing to a caller:\n // this was attempted on advisory data, so if the admit fails that is why.\n stale: !chosen.fresh || advisory,\n };\n}\n","/**\n * Present a signed join to ONE named node.\n *\n * This is the whole of admission for a caller with no node of its own: sign the\n * membership op with the device key the account certified, and POST it to a node\n * the invitation named as an admitter.\n *\n * POST /admin-api/namespaces/{namespaceId}/admit\n * { \"invitation\": SignedGroupOpenInvitation, \"signedOp\": \"<hex borsh SignedNamespaceOp>\" }\n *\n * Verified against core at rc.43 — `crates/server/src/admin/handlers/namespaces/\n * admit_join.rs`, request type `AdmitJoinApiRequest` in\n * `crates/server/primitives/src/admin/mod.rs`. The handler also refuses a\n * mismatch between the invitation's `group_id` and the namespace in the path, so\n * the two are never allowed to disagree here.\n *\n * ## Why it needs no token and no proof\n *\n * The joiner's signature IS the authorization. The op is signed by the device\n * key named in the credential it carries, and every peer checks\n * `signer == credential.statement.sign_pk` before applying a join — so an\n * admitter can carry this and can never author it: it cannot admit a different\n * account, change the group, or grant a role. It can refuse, and that is all.\n * This is also why the fleet ingress leaves the route unauthenticated, and why\n * this posts with `fetch` rather than through `AdminApiClient`, which is built\n * around a node credential this caller does not have.\n *\n * ## Why it lives here and not in mero-js\n *\n * Two reasons. `mero-js` is read-only for this change by instruction, and the\n * shape that is actually useful to a caller is the one that hands back a\n * {@link DelegatedSession} — the node that admitted you is the node to connect\n * through — which is `mero-react`'s concern. The pieces that are pure SDK, the\n * borsh op layout and the request type, are used from `mero-js` unchanged and\n * are not reimplemented here.\n *\n * ## Why the op has no parents\n *\n * A keyholder holds no node, so it has no view of the namespace DAG and cannot\n * name its heads. Empty parents is the only thing it *can* sign, and the direct\n * admission path exists precisely for callers in that position.\n */\n\nimport {\n createLocalStorageNonceSource,\n signMemberJoinOp,\n type AdmitJoinRequest,\n type SignedGroupOpenInvitation,\n} from '@calimero-network/mero-js';\nimport type { DelegatedCredential, DelegatedSession } from './session';\n\n/** Which step failed, when one did. */\nexport type JoinWithNodeStep =\n /** The op could not be signed. Local, deterministic, and nothing was sent. */\n | 'sign'\n /** The node refused it, or could not be reached. */\n | 'admit';\n\nexport interface JoinWithNodeSuccess {\n readonly ok: true;\n /**\n * Whether the admitter said it published the op.\n *\n * NOT \"you are a member\": membership lands when peers apply the op, which the\n * admitter neither performs nor waits for.\n */\n readonly published: boolean;\n /**\n * The session to connect with — the admitting node, used immediately.\n *\n * Deliberately not waiting for `getAccountRelays` to answer: the fleet writes\n * the account's recovery envelope asynchronously, so the cloud lookup lags the\n * admission by an unpredictable amount. The node that just carried the join is\n * known to serve this namespace right now, which is a better answer than a\n * lookup that will agree later.\n */\n readonly session: DelegatedSession;\n}\n\nexport interface JoinWithNodeFailure {\n readonly ok: false;\n readonly step: JoinWithNodeStep;\n readonly reason: string;\n /** The HTTP status, when the node answered with one. */\n readonly status?: number;\n}\n\nexport type JoinWithNodeResult = JoinWithNodeSuccess | JoinWithNodeFailure;\n\nexport interface JoinWithNodeInput {\n /**\n * The node to present the join to — its admin API origin.\n *\n * The primary parameter, so all three sources of a node URL feed one method:\n * one carried by the invitation (core emits only libp2p multiaddrs today —\n * see `resolve_admitter_addrs`, a node cannot know the URL its admin API is\n * proxied on — so this is the seam for when invitations carry a claim URL),\n * one resolved from the cloud's `/admitters` lookup, and one an operator\n * simply knows.\n */\n readonly nodeUrl: string;\n /**\n * The exact URL to POST to, when something already knows it.\n *\n * The cloud hands back a ready-made `admit_url` which need not be a path on\n * `nodeUrl`'s origin, and rebuilding it from a guess is how a working\n * admission becomes a 404. Omitted, the documented route on `nodeUrl` is used.\n */\n readonly admitUrl?: string;\n /** The namespace being joined, 64 hex. Must match the invitation's group. */\n readonly namespaceId: string;\n /**\n * The invitation, exactly as the inviter's node returned it.\n *\n * Passed through unchanged and never rebuilt field by field: the signature\n * covers the body, and re-modelling it through a local type drops the unsigned\n * bootstrap fields and invalidates the signature with them.\n */\n readonly invitation: SignedGroupOpenInvitation;\n /** The enrolled account, its certificate, and the device secret that signs. */\n readonly credential: DelegatedCredential;\n /** Injected in tests. */\n readonly deps?: {\n readonly fetch?: typeof fetch;\n readonly nonce?: () => Promise<bigint>;\n };\n}\n\n/**\n * Turn an admit refusal into the thing to go and do about it.\n *\n * Each status has one dominant cause and they have nothing to do with each\n * other, so a bare \"HTTP 403\" sends people to the wrong place — most often to\n * the invitation, when the real answer is which node it was presented to.\n */\nfunction explainAdmitFailure(status: number, body: string): string {\n const detail = body ? `: ${body}` : '';\n switch (status) {\n case 400:\n return (\n `The node refused the join as malformed (400)${detail}. The signature covers the ` +\n 'invitation exactly as sent, so an edited or re-serialised invitation fails here — as ' +\n \"does a namespace id that is not the invitation's own group.\"\n );\n case 403:\n return (\n `The node refused to carry this join (403)${detail}. Either it is not in the ` +\n \"invitation's signed admitters list — being live and listed by the cloud is not the \" +\n 'same thing — or the invitation itself was rejected as expired or not the inviter’s ' +\n 'to issue.'\n );\n case 409:\n return (\n `That node holds no device of its own, so it cannot endorse anyone (409)${detail}. ` +\n 'Another admitter from the same invitation would work.'\n );\n default:\n return `The join was not published (HTTP ${status})${detail}.`;\n }\n}\n\n/**\n * A join-nonce counter for this account, persisted so a reload does not replay.\n *\n * The device secret never appears in the key: storage keys are enumerable by\n * anything running on the origin. One counter per account is right here — a\n * bootstrap is once per account per device, and the node's receiving window\n * accepts gaps, so a shared counter can only ever skip, never reuse.\n */\nfunction joinNonce(account: string): () => Promise<bigint> {\n const source = createLocalStorageNonceSource(`calimero.delegated.joinnonce.${account}`);\n return () => source.next();\n}\n\n/** Strip a trailing slash so a pasted URL and a typed one address one node. */\nfunction origin(url: string): string {\n return url.replace(/\\/+$/, '');\n}\n\n/**\n * Sign the membership op and present it to `nodeUrl`.\n *\n * Resolves rather than throws for every expected refusal, because they are\n * different things for the person to do: a malformed op is final, an unreachable\n * node is a retry, and a 409 means pick another admitter.\n */\nexport async function joinWithNode(input: JoinWithNodeInput): Promise<JoinWithNodeResult> {\n const { account, credential, deviceSecret } = input.credential;\n\n let signedOp: string;\n try {\n signedOp = await signMemberJoinOp({\n namespaceId: input.namespaceId,\n member: account,\n invitation: input.invitation,\n credential,\n deviceSecret,\n nonce: await (input.deps?.nonce ?? joinNonce(account))(),\n });\n } catch (e) {\n return {\n ok: false,\n step: 'sign',\n reason:\n 'The join op could not be signed, so nothing was sent: ' +\n `${e instanceof Error ? e.message : String(e)}`,\n };\n }\n\n // `AdmitJoinRequest` names the shape, so a change to it in mero-js breaks this\n // at the typecheck rather than as a 400 from a node.\n const body: AdmitJoinRequest = { invitation: input.invitation, signedOp };\n const url =\n input.admitUrl ??\n `${origin(input.nodeUrl)}/admin-api/namespaces/${input.namespaceId}/admit`;\n\n const doFetch = input.deps?.fetch ?? fetch;\n let response: Response;\n try {\n response = await doFetch(url, {\n method: 'POST',\n // No Authorization header and no request proof, deliberately: the route is\n // unauthenticated because the joiner's signature is the authorization.\n headers: { 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify(body),\n });\n } catch (e) {\n return {\n ok: false,\n step: 'admit',\n reason:\n `The admitter at ${input.nodeUrl} could not be reached: ` +\n `${e instanceof Error ? e.message : String(e)}. The invitation is untouched — this is ` +\n 'the node being unreachable, not a refusal.',\n };\n }\n\n const text = await response.text();\n if (!response.ok) {\n return {\n ok: false,\n step: 'admit',\n status: response.status,\n reason: explainAdmitFailure(response.status, text),\n };\n }\n\n let published = false;\n try {\n const parsed = text ? (JSON.parse(text) as { data?: { published?: boolean } }) : {};\n published = parsed.data?.published === true;\n } catch {\n // A 2xx with a body this client cannot read is still a node that took the\n // call. Reported as \"not published\" rather than as an error, because that is\n // exactly what is not known.\n published = false;\n }\n\n return {\n ok: true,\n published,\n session: { relayUrl: origin(input.nodeUrl), account, credential, deviceSecret },\n };\n}\n","/**\n * Bootstrapping an account that is a member of nothing, from an invitation.\n *\n * # The one missing step\n *\n * A freshly enrolled account holds a certified device and belongs to no\n * namespace, so `CloudClient.getAccountRelays` answers `[]` — correctly, because\n * nothing serves an account that is a member of nothing. It is still signed in;\n * what it has no way to do is write. An invitation is what changes that, and the\n * chain is:\n *\n * invitation → namespaceId → a node URL\n * → POST the signed join to that node → the account is a member\n * → that same node is the relay, from this moment\n * → a fleet relay writes the recovery envelope asynchronously,\n * and getAccountRelays() agrees from then on\n *\n * The session does not wait for the cloud to catch up. The node that carried the\n * join is known to serve the namespace now; the lookup will agree later.\n *\n * # Where the node URL comes from, in preference order\n *\n * 1. one passed in — an operator's, or one a future invitation carries. Core\n * today emits only libp2p multiaddrs on an invitation (`resolve_admitter_addrs`)\n * because a node cannot know the URL its admin API is proxied on, so there is\n * nothing to read off the invitation yet and this is the seam for when there\n * is;\n * 2. the cloud's `/api/cloud/namespaces/{ns}/admitters`, intersected with the\n * invitation's signed `admitters` — see `resolveRelayFromInvitation`.\n *\n * # Nothing here is minted, weakened or worked around\n *\n * The credential and the device secret come from the enrolment the wallet\n * already performed. The op is signed by that device key, which is what stops an\n * admitter substituting a different member. The admitters intersection is done in\n * `resolveRelayFromInvitation` and is never relaxed.\n */\n\nimport type { SignedGroupOpenInvitation } from '@calimero-network/mero-js';\nimport type { DelegatedCredential, DelegatedSession } from './session';\nimport { joinWithNode, type JoinWithNodeStep } from './join-with-node';\nimport {\n resolveRelayFromInvitation,\n type RelayResolutionStep,\n type ResolvedInvitationRelay,\n} from './relay-from-invitation';\n\n/**\n * Which step failed. One exhaustive list to branch on: the relay-resolution\n * steps, the two `joinWithNode` reports, and the one only a hook can hit.\n *\n * - `no-credential` — this tab holds no enrolled account, so there is nothing to\n * admit. Only {@link useDelegatedBootstrap} can report it;\n * `bootstrapFromInvitation` is handed the credential as an argument.\n */\nexport type BootstrapStep = RelayResolutionStep | JoinWithNodeStep | 'no-credential';\n\nexport interface BootstrapSuccess {\n readonly ok: true;\n /** The session to connect with — hand it straight to `connectWithAccount`. */\n readonly session: DelegatedSession;\n /**\n * How the node was chosen, when the cloud chose it.\n *\n * `null` when the caller named the node itself, because then there was no\n * routing read to report — not because anything was skipped.\n */\n readonly relay: ResolvedInvitationRelay | null;\n /**\n * Whether the admitter said it published the op.\n *\n * NOT \"you are a member\": membership lands when peers apply the op, which the\n * admitter neither performs nor waits for. `false` with no error means the node\n * took the call and did not publish — worth surfacing rather than treating as\n * success.\n */\n readonly published: boolean;\n}\n\nexport interface BootstrapFailure {\n readonly ok: false;\n readonly step: BootstrapStep;\n readonly reason: string;\n /** The HTTP status, when the failing step was an HTTP call. */\n readonly status?: number;\n}\n\nexport type BootstrapResult = BootstrapSuccess | BootstrapFailure;\n\nexport interface BootstrapFromInvitationInput {\n /** The namespace the invitation admits you to, 64 hex. */\n readonly namespaceId: string;\n /** The invitation, exactly as the inviter's node returned it. */\n readonly invitation: SignedGroupOpenInvitation;\n /** The enrolled account, its certificate, and the device secret. */\n readonly credential: DelegatedCredential;\n /**\n * A node to present the join to, skipping the cloud lookup.\n *\n * Use it when something already knows the node — an operator, a local rig, or\n * an invitation that carries a claim URL once core emits one. Without it the\n * cloud's admitters lookup answers, and the invitation's signed list is what\n * narrows the answer.\n */\n readonly nodeUrl?: string;\n /** Point at a cloud other than the hosted manager. For local rigs. */\n readonly cloudBaseUrl?: string;\n /** Injected in tests. */\n readonly deps?: {\n readonly resolve?: typeof resolveRelayFromInvitation;\n readonly join?: typeof joinWithNode;\n readonly fetch?: typeof fetch;\n readonly nonce?: () => Promise<bigint>;\n };\n}\n\n/**\n * Resolve a node from the invitation, present the signed join to it, and return\n * the session to connect with.\n *\n * Never throws for an expected failure: every one of them is a different thing\n * for the person to do, so they come back as `{ ok: false, step, reason }`. A\n * generic \"could not join\" is exactly what this shape exists to prevent.\n */\nexport async function bootstrapFromInvitation(\n input: BootstrapFromInvitationInput,\n): Promise<BootstrapResult> {\n const resolve = input.deps?.resolve ?? resolveRelayFromInvitation;\n const join = input.deps?.join ?? joinWithNode;\n\n let relay: ResolvedInvitationRelay | null = null;\n let nodeUrl = input.nodeUrl;\n let admitUrl: string | undefined;\n\n if (!nodeUrl) {\n const resolved = await resolve({\n namespaceId: input.namespaceId,\n // The signed list, read off the invitation itself rather than passed\n // separately: two sources for one fact is how an intersection ends up\n // being performed against the wrong list.\n admitters: input.invitation.invitation.admitters,\n credential: input.credential.credential,\n deviceSecret: input.credential.deviceSecret,\n cloudBaseUrl: input.cloudBaseUrl,\n });\n if (!resolved.ok) return resolved;\n relay = resolved;\n nodeUrl = resolved.relayUrl;\n admitUrl = resolved.admitUrl;\n }\n\n const joined = await join({\n nodeUrl,\n admitUrl,\n namespaceId: input.namespaceId,\n invitation: input.invitation,\n credential: input.credential,\n deps: { fetch: input.deps?.fetch, nonce: input.deps?.nonce },\n });\n if (!joined.ok) return joined;\n\n return { ok: true, published: joined.published, relay, session: joined.session };\n}\n","/**\n * The delegated connect path, entered from an invitation instead of an account.\n *\n * `ConnectButtonAccount` enrols the device and then asks the cloud which relays\n * serve the ACCOUNT. For a first-time account that answer is `[]` and there is\n * nothing to connect to — correctly, since nothing yet serves an account that is\n * a member of nothing. This hook is the other door into the same connection: it\n * takes an invitation, resolves a relay from the NAMESPACE, presents the signed\n * join, and then connects through the node that carried it.\n *\n * It is `MeroContext`'s own `connectWithAccount` at the end, not a second\n * connection mechanism — the only difference is how the relay was found.\n */\n\nimport { useCallback, useState } from 'react';\nimport type { SignedGroupOpenInvitation } from '@calimero-network/mero-js';\nimport { useMero } from '../context';\nimport {\n bootstrapFromInvitation,\n type BootstrapResult,\n} from './bootstrap-from-invitation';\nimport {\n readDelegatedCredential,\n readDelegatedSession,\n rememberRelay,\n type DelegatedCredential,\n} from './session';\n\nexport interface UseDelegatedBootstrapOptions {\n /** Point at a cloud other than the hosted manager. For local rigs. */\n readonly cloudBaseUrl?: string;\n}\n\nexport interface UseDelegatedBootstrapResult {\n /** The enrolled account and its certificate, or `null` if none was ever held. */\n readonly credential: DelegatedCredential | null;\n /**\n * Whether this account is signed in with nowhere to write.\n *\n * True means: an enrolled credential is held and no relay is known for it, so\n * the account→relay lookup has nothing and an invitation is what changes that.\n * Being signed in is NOT the missing part — that is the whole point, since you\n * have to be signed in to be invited.\n *\n * False covers \"already has a relay\" and \"never enrolled\", which need the two\n * other entry points rather than this one.\n */\n readonly needsBootstrap: boolean;\n readonly running: boolean;\n /** The last attempt's outcome, kept so a UI can name the failing step. */\n readonly result: BootstrapResult | null;\n /**\n * Admit this account to the invitation's namespace and connect through the\n * admitting node.\n *\n * Resolves rather than throws for every expected refusal: the step names are\n * the point, because an empty intersection, an unreachable admitter and a\n * namespace with no fleet assignment need three different actions.\n */\n readonly bootstrap: (input: {\n readonly namespaceId: string;\n readonly invitation: SignedGroupOpenInvitation;\n /**\n * A node to present the join to, skipping the cloud lookup — an operator's,\n * a local rig's, or one a future invitation carries.\n */\n readonly nodeUrl?: string;\n /** The context the invitation is for, so its relay is known before any listing. */\n readonly contextId?: string;\n }) => Promise<BootstrapResult>;\n}\n\nexport function useDelegatedBootstrap(\n options: UseDelegatedBootstrapOptions = {},\n): UseDelegatedBootstrapResult {\n const { connectWithAccount } = useMero();\n const [running, setRunning] = useState(false);\n const [result, setResult] = useState<BootstrapResult | null>(null);\n\n // Read at render rather than held in state: the record is written by the\n // enrolment return in `ConnectButtonAccount`, in the same tab but outside\n // React's knowledge, so a cached copy would be stale exactly once — on the\n // load where it matters.\n const credential = readDelegatedCredential();\n // The stored record rather than the context's `nodeUrl`: that one is seeded\n // from `getNodeUrl()`, which can still hold a node URL from an earlier\n // node-login on this origin, and a stale value there would hide the very state\n // this reports.\n const relayUrl = readDelegatedSession()?.relayUrl ?? null;\n\n const { cloudBaseUrl } = options;\n const bootstrap = useCallback(\n async (input: {\n namespaceId: string;\n invitation: SignedGroupOpenInvitation;\n nodeUrl?: string;\n contextId?: string;\n }): Promise<BootstrapResult> => {\n const held = readDelegatedCredential();\n if (!held) {\n const failure: BootstrapResult = {\n ok: false,\n step: 'no-credential',\n reason:\n 'This tab holds no enrolled account, so there is no identity to admit. Enrol with ' +\n 'your account first — the invitation is then what gives it its first membership.',\n };\n setResult(failure);\n return failure;\n }\n setRunning(true);\n try {\n const outcome = await bootstrapFromInvitation({\n namespaceId: input.namespaceId,\n invitation: input.invitation,\n credential: held,\n nodeUrl: input.nodeUrl,\n cloudBaseUrl,\n });\n setResult(outcome);\n // Connected only on a node that actually took the join. A session\n // installed after a refusal would look connected and refuse every write,\n // which is the failure this whole path exists to avoid.\n if (outcome.ok) {\n // Added to the account's relay map, never replacing it: the relays\n // that serve its other namespaces stay reachable.\n if (outcome.session.relayUrl) {\n rememberRelay(held.account, outcome.session.relayUrl, {\n namespaceId: input.namespaceId,\n contextId: input.contextId,\n });\n }\n connectWithAccount(outcome.session);\n }\n return outcome;\n } finally {\n setRunning(false);\n }\n },\n [cloudBaseUrl, connectWithAccount],\n );\n\n return {\n credential,\n needsBootstrap: credential !== null && relayUrl === null,\n running,\n result,\n bootstrap,\n };\n}\n","/**\n * Join a namespace and one of its contexts from an invitation — the same call\n * whatever the connection is.\n *\n * - A node login publishes its own membership op (`joinNamespace`) and joins\n * the context (`joinContext`) on that node.\n * - An account (no node) signs the join with its device key and hands it to\n * an admitter the invitation names (`useDelegatedBootstrap`); from then on it\n * reaches the namespace through that relay.\n *\n * The app gets one result shape back either way, including whether the failure\n * is FINAL — worth discarding the invitation for — or worth retrying.\n */\nimport { useCallback, useState } from 'react';\nimport type { InviteRedeemer, SignedGroupOpenInvitation } from '@calimero-network/mero-js';\nimport { useMero } from '../context';\nimport { useDelegatedBootstrap } from '../delegated/useDelegatedBootstrap';\nimport type { BootstrapFailure } from '../delegated/bootstrap-from-invitation';\nimport { listDelegatedNamespaces, readDelegatedSession } from '../delegated/session';\n\n/** The HTTP status an error carries, read the way mero-js's classifier reads it. */\nfunction statusOf(err: unknown): number | undefined {\n if (!err || typeof err !== 'object') return undefined;\n const e = err as { status?: unknown; statusCode?: unknown; response?: { status?: unknown } };\n for (const c of [e.status, e.response?.status, e.statusCode]) {\n if (typeof c === 'number' && Number.isFinite(c)) return c;\n }\n return undefined;\n}\n\nexport interface JoinInvitationInput {\n readonly namespaceId: string;\n readonly contextId: string;\n readonly invitation: SignedGroupOpenInvitation;\n}\n\nexport type JoinInvitationStep = BootstrapFailure['step'] | 'node-join';\n\nexport type JoinInvitationResult =\n | { readonly ok: true }\n | {\n readonly ok: false;\n readonly step: JoinInvitationStep;\n /** What went wrong, in words a person can act on. */\n readonly reason: string;\n /** True when no retry can succeed: a fresh invitation is the only cure. */\n readonly final: boolean;\n /** The HTTP status of the refusal, when there was one. */\n readonly status?: number;\n };\n\n/** Which step failed, in the words a person can act on. */\nconst STEP_LABEL: Record<BootstrapFailure['step'], string> = {\n 'no-credential': 'No enrolled account',\n 'admitters-lookup': 'Admitters lookup failed',\n 'no-nodes': 'No hosted node serves this namespace',\n 'not-invited': 'This invitation names none of the serving nodes',\n 'invited-unreachable': 'The invited admitter cannot take a join right now',\n 'no-relay-url': 'The invited admitter has no address yet',\n sign: 'The join could not be signed',\n admit: 'The admitter refused the join',\n};\n\n/**\n * Whether an account's join failure is final. Per step: an admitter's 400/403\n * judged the op or the invitation; `not-invited` and `sign` fail identically\n * next time. Everything else (a lookup, an unreachable admitter, no fleet\n * assignment yet, a 409) is kept for a retry.\n */\nfunction accountJoinIsFinal(failure: BootstrapFailure): boolean {\n if (failure.step === 'admit') return failure.status === 400 || failure.status === 403;\n return failure.step === 'not-invited' || failure.step === 'sign';\n}\n\n/**\n * Whether a node's join failure means the invitation itself will never work.\n *\n * Errs toward false: a dropped invitation is unrecoverable for the user, a\n * retried one costs a round trip, so a timeout or anything unfamiliar keeps\n * it. Phrases, not bare words — `\"invalid\"` alone would also match an\n * \"invalid response\" from a proxy, a transient failure.\n */\nexport function isFinalInvitationError(message: string | undefined | null): boolean {\n if (!message) return false;\n const m = message.toLowerCase();\n return [\n 'invitation expired',\n 'expired invitation',\n 'invalid invitation',\n 'invitation is invalid',\n 'malformed invitation',\n 'malformed payload',\n 'invalid signature',\n 'signature verification failed',\n 'not admin',\n 'revoked',\n 'already a member',\n ].some((t) => m.includes(t));\n}\n\nexport function useJoinInvitation(): {\n joinInvitation: (input: JoinInvitationInput) => Promise<JoinInvitationResult>;\n joining: boolean;\n /** The namespaces this connection is a member of: a node's own, or an account's across its relays. */\n memberships: () => Promise<string[]>;\n /**\n * The `{ join, memberships }` pair mero-js's `redeemInvitation` drives, for\n * whichever connection this is, so an app redeems an invitation (join once,\n * then check membership) with no transport of its own. `join` throws on a\n * refusal, carrying its HTTP status for the outcome's reason.\n */\n invitationRedeemer: (input: JoinInvitationInput) => InviteRedeemer;\n} {\n const { mero, isDelegated } = useMero();\n const { credential, bootstrap } = useDelegatedBootstrap();\n const [joining, setJoining] = useState(false);\n\n const joinInvitation = useCallback(\n async (input: JoinInvitationInput): Promise<JoinInvitationResult> => {\n setJoining(true);\n try {\n // An account joins through an admitter: when the connection is one, or\n // when an account is enrolled and no node session exists. A node login\n // joins on its own node even if a credential lingers in this tab.\n const asAccount = isDelegated || (credential !== null && mero === null);\n if (asAccount) {\n const outcome = await bootstrap({\n namespaceId: input.namespaceId,\n invitation: input.invitation,\n contextId: input.contextId,\n });\n if (outcome.ok) return { ok: true };\n return {\n ok: false,\n step: outcome.step,\n reason: `${STEP_LABEL[outcome.step]}. ${outcome.reason}`,\n final: accountJoinIsFinal(outcome),\n ...(outcome.status !== undefined ? { status: outcome.status } : {}),\n };\n }\n\n if (!mero) {\n return { ok: false, step: 'node-join', reason: 'Not connected to a node.', final: false };\n }\n // The admin client directly, not the join hooks: those swallow errors\n // (they resolve to null), which would report a failed join as joined.\n await mero.admin.joinNamespace(input.namespaceId, { invitation: input.invitation });\n await mero.admin.joinContext(input.contextId);\n return { ok: true };\n } catch (e) {\n const reason = e instanceof Error ? e.message : String(e);\n const status = statusOf(e);\n return {\n ok: false,\n step: 'node-join',\n reason,\n final: isFinalInvitationError(reason),\n ...(status !== undefined ? { status } : {}),\n };\n } finally {\n setJoining(false);\n }\n },\n [mero, isDelegated, credential, bootstrap],\n );\n\n const memberships = useCallback(async (): Promise<string[]> => {\n const asAccount = isDelegated || (credential !== null && mero === null);\n const ids = (list: ReadonlyArray<{ namespaceId?: string; groupId?: string; id?: string }>) =>\n list.map((n) => n.namespaceId ?? n.groupId ?? n.id ?? '').filter(Boolean);\n if (asAccount) {\n const session = readDelegatedSession();\n return session ? ids(await listDelegatedNamespaces(session)) : [];\n }\n if (!mero) return [];\n return ids((await mero.admin.listNamespaces()) as Array<{ namespaceId?: string; groupId?: string; id?: string }>);\n }, [mero, isDelegated, credential]);\n\n const invitationRedeemer = useCallback(\n (input: JoinInvitationInput): InviteRedeemer => ({\n join: async () => {\n const outcome = await joinInvitation(input);\n if (!outcome.ok) {\n throw Object.assign(new Error(outcome.reason), outcome.status !== undefined ? { status: outcome.status } : {});\n }\n },\n memberships,\n }),\n [joinInvitation, memberships],\n );\n\n return { joinInvitation, joining, memberships, invitationRedeemer };\n}\n"]}
|