@openkey/sdk 0.10.1 → 0.11.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../core/src/pkce.ts","../../core/src/errors.ts","../../core/src/oauth.ts","../src/nostr.ts","../src/index.ts"],"sourcesContent":["/**\n * PKCE (Proof Key for Code Exchange) utilities.\n *\n * Uses a pure-JS base64url encoder (no `btoa()`) so it works across\n * Node.js, browsers, and React Native (including Hermes < 0.73).\n *\n * The default SHA-256 implementation uses `crypto.subtle.digest`.\n * For runtimes without Web Crypto, pass a custom `SHA256Fn`.\n */\n\n/**\n * A function that computes the SHA-256 hash of the input string.\n * Return the raw 32-byte digest as a Uint8Array.\n */\nexport type SHA256Fn = (input: string) => Promise<Uint8Array>;\n\n// Standard base64 alphabet lookup table\nconst BASE64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/**\n * Pure JS base64url encoding from a Uint8Array.\n * Does NOT use `btoa()` — safe for all runtimes.\n */\nexport function base64UrlEncode(buffer: Uint8Array): string {\n let base64 = '';\n const len = buffer.length;\n\n for (let i = 0; i < len; i += 3) {\n const b0 = buffer[i]!;\n const b1 = i + 1 < len ? buffer[i + 1]! : 0;\n const b2 = i + 2 < len ? buffer[i + 2]! : 0;\n\n const triplet = (b0 << 16) | (b1 << 8) | b2;\n\n base64 += BASE64_CHARS[(triplet >> 18) & 0x3f];\n base64 += BASE64_CHARS[(triplet >> 12) & 0x3f];\n base64 += i + 1 < len ? BASE64_CHARS[(triplet >> 6) & 0x3f] : '';\n base64 += i + 2 < len ? BASE64_CHARS[triplet & 0x3f] : '';\n }\n\n // Convert base64 to base64url: replace + with -, / with _, strip = padding\n return base64.replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n\n/**\n * Generate a cryptographically random code verifier for PKCE.\n * Returns a 43-character base64url string (32 random bytes).\n */\nexport function generateCodeVerifier(): string {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\n/**\n * Default SHA-256 implementation using Web Crypto API.\n * Available in Node.js 18+, modern browsers, and Hermes 0.73+.\n */\nasync function defaultSha256(input: string): Promise<Uint8Array> {\n const encoder = new TextEncoder();\n const data = encoder.encode(input);\n const digest = await crypto.subtle.digest('SHA-256', data);\n return new Uint8Array(digest);\n}\n\n/**\n * Generate the PKCE code challenge from a code verifier.\n *\n * @param verifier - The code verifier string\n * @param sha256 - Optional custom SHA-256 function (for expo-crypto, react-native-quick-crypto, etc.)\n * @returns Base64url-encoded SHA-256 hash of the verifier\n */\nexport async function generateCodeChallenge(\n verifier: string,\n sha256?: SHA256Fn,\n): Promise<string> {\n const hashFn = sha256 ?? defaultSha256;\n const digest = await hashFn(verifier);\n return base64UrlEncode(digest);\n}\n\n/**\n * Generate a cryptographically random state parameter.\n * Returns a 22-character base64url string (16 random bytes).\n */\nexport function generateState(): string {\n const array = new Uint8Array(16);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n","/**\n * Unified error codes across all OpenKey SDKs.\n */\nexport type OpenKeyErrorCode =\n | 'USER_CANCELLED'\n | 'POPUP_BLOCKED'\n | 'TIMEOUT'\n | 'NO_KEY'\n | 'UNAUTHORIZED'\n | 'STATE_MISMATCH'\n | 'NETWORK_ERROR'\n | 'UNKNOWN';\n\n/**\n * Error class for all OpenKey SDK errors.\n */\nexport class OpenKeyError extends Error {\n constructor(\n public code: OpenKeyErrorCode,\n message: string,\n ) {\n super(message);\n this.name = 'OpenKeyError';\n }\n}\n","import type { AuthTokens } from './types';\nimport { OpenKeyError } from './errors';\n\n// ======= Authorization URL =======\n\nexport interface BuildAuthorizationUrlOptions {\n /** OpenKey host URL (e.g. https://openkey.so) */\n host: string;\n /** OAuth client ID */\n clientId: string;\n /** Redirect URI for callback */\n redirectUri: string;\n /** PKCE code challenge (base64url-encoded) */\n codeChallenge: string;\n /** State parameter for CSRF protection */\n state: string;\n /** OAuth scopes to request */\n scopes: string[];\n /** Authorization endpoint path (default: /api/auth/oauth2/authorize) */\n authorizePath?: string;\n}\n\n/**\n * Build the OAuth 2.1 authorization URL with PKCE parameters.\n */\nexport function buildAuthorizationUrl(options: BuildAuthorizationUrlOptions): string {\n const {\n host,\n clientId,\n redirectUri,\n codeChallenge,\n state,\n scopes,\n authorizePath = '/api/auth/oauth2/authorize',\n } = options;\n\n const url = new URL(authorizePath, host);\n url.searchParams.set('client_id', clientId);\n url.searchParams.set('redirect_uri', redirectUri);\n url.searchParams.set('response_type', 'code');\n url.searchParams.set('scope', scopes.join(' '));\n url.searchParams.set('state', state);\n url.searchParams.set('code_challenge', codeChallenge);\n url.searchParams.set('code_challenge_method', 'S256');\n\n return url.toString();\n}\n\n// ======= Token Exchange =======\n\nexport interface ExchangeCodeOptions {\n /** OpenKey host URL */\n host: string;\n /** Authorization code from callback */\n code: string;\n /** Redirect URI (must match authorization request) */\n redirectUri: string;\n /** OAuth client ID */\n clientId: string;\n /** PKCE code verifier */\n codeVerifier: string;\n /** RFC 9700 resource indicator (optional) */\n resource?: string;\n /** Token endpoint path (default: /api/auth/oauth2/token) */\n tokenPath?: string;\n}\n\n/**\n * Exchange an authorization code for tokens.\n */\nexport async function exchangeAuthorizationCode(\n options: ExchangeCodeOptions,\n): Promise<AuthTokens> {\n const {\n host,\n code,\n redirectUri,\n clientId,\n codeVerifier,\n resource,\n tokenPath = '/api/auth/oauth2/token',\n } = options;\n\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n redirect_uri: redirectUri,\n client_id: clientId,\n code_verifier: codeVerifier,\n });\n\n if (resource) {\n body.set('resource', resource);\n }\n\n let response: Response;\n try {\n response = await fetch(`${host}${tokenPath}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n } catch (error) {\n throw new OpenKeyError(\n 'NETWORK_ERROR',\n error instanceof Error ? error.message : 'Network request failed',\n );\n }\n\n if (!response.ok) {\n let detail = '';\n try {\n detail = await response.text();\n } catch {\n // ignore\n }\n throw new OpenKeyError(\n 'UNKNOWN',\n `Token exchange failed: ${response.status} ${response.statusText}${detail ? ` - ${detail}` : ''}`,\n );\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n return mapTokenResponse(data);\n}\n\n// ======= Token Refresh =======\n\nexport interface RefreshTokenOptions {\n /** OpenKey host URL */\n host: string;\n /** Refresh token */\n refreshToken: string;\n /** OAuth client ID */\n clientId: string;\n /** RFC 9700 resource indicator (optional) */\n resource?: string;\n /** Token endpoint path (default: /api/auth/oauth2/token) */\n tokenPath?: string;\n}\n\n/**\n * Refresh an access token using a refresh token.\n */\nexport async function refreshAccessToken(\n options: RefreshTokenOptions,\n): Promise<AuthTokens> {\n const {\n host,\n refreshToken,\n clientId,\n resource,\n tokenPath = '/api/auth/oauth2/token',\n } = options;\n\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n client_id: clientId,\n });\n\n if (resource) {\n body.set('resource', resource);\n }\n\n let response: Response;\n try {\n response = await fetch(`${host}${tokenPath}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n } catch (error) {\n throw new OpenKeyError(\n 'NETWORK_ERROR',\n error instanceof Error ? error.message : 'Network request failed',\n );\n }\n\n if (!response.ok) {\n let detail = '';\n try {\n detail = await response.text();\n } catch {\n // ignore\n }\n throw new OpenKeyError(\n 'UNKNOWN',\n `Token refresh failed: ${response.status} ${response.statusText}${detail ? ` - ${detail}` : ''}`,\n );\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n return mapTokenResponse(data);\n}\n\n// ======= Helpers =======\n\n/**\n * Map a snake_case token response to the camelCase AuthTokens interface.\n */\nexport function mapTokenResponse(data: Record<string, unknown>): AuthTokens {\n return {\n accessToken: data.access_token as string,\n idToken: data.id_token as string,\n refreshToken: data.refresh_token as string | undefined,\n expiresIn: data.expires_in as number,\n };\n}\n\n/**\n * Parse an OAuth callback URL and extract the code and state parameters.\n * Returns null if the URL doesn't contain the expected parameters.\n */\nexport function parseOAuthCallback(url: string): { code: string; state: string } | null {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return null;\n }\n\n const code = parsed.searchParams.get('code');\n const state = parsed.searchParams.get('state');\n\n if (!code || !state) {\n return null;\n }\n\n return { code, state };\n}\n","// OpenKey Nostr signer - browser client for third-party apps.\n//\n// Structurally separate from the Ethereum/EIP-1193 flows in index.ts:\n// - Nostr identities are secp256k1 Schnorr (BIP-340/NIP-01), never routed\n// through the ECDSA sign/signTypedData paths above.\n// - The OpenKey session and any signing grants never leave the\n// OpenKey-origin iframe. Unlike `openkey:auth:response`, none of the\n// postMessage payloads below ever carry a sessionToken.\n// - Every iframe created here uses a canonical, non-wildcard `host` origin\n// for both `postMessage` targeting and incoming-message verification\n// (`event.origin === host && event.source === iframe.contentWindow`).\n\n/** NIP-01 unsigned event template. */\nexport interface UnsignedNostrEvent {\n pubkey: string;\n created_at: number;\n kind: number;\n tags: string[][];\n content: string;\n}\n\n/** A fully signed NIP-01 event, as returned by OpenKey custody signing. */\nexport interface SignedNostrEvent extends UnsignedNostrEvent {\n id: string;\n sig: string;\n}\n\n/** Public descriptor for the user's OpenKey-custodied Nostr identity. Never includes the secret key. */\nexport interface NostrIdentity {\n keyId: string;\n pubkey: string;\n npub: string;\n}\n\nexport interface NostrError {\n code: 'USER_CANCELLED' | 'TIMEOUT' | 'INTERACTION_REQUIRED' | 'UNAUTHORIZED' | 'UNKNOWN';\n message: string;\n}\n\ntype NostrFrameMessage =\n | { type: 'openkey:ready'; protocolVersion: number }\n | { type: 'openkey:close'; requestId: string; protocolVersion: number }\n | { type: 'openkey:resize'; requestId: string; protocolVersion: number; height: number }\n | { type: 'openkey:nostr:show'; requestId: string; protocolVersion: number }\n | { type: 'openkey:nostr:connect:response'; requestId: string; protocolVersion: number; success: true; keyId: string; pubkey: string; npub: string }\n | { type: 'openkey:nostr:connect:response'; requestId: string; protocolVersion: number; success: false; error: NostrError }\n | { type: 'openkey:nostr:sign:response'; requestId: string; protocolVersion: number; success: true; event: SignedNostrEvent }\n | { type: 'openkey:nostr:sign:response'; requestId: string; protocolVersion: number; success: false; error: NostrError };\n\nconst NOSTR_FRAME_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes, matches the Ethereum widget flow\nconst NOSTR_PROTOCOL_VERSION = 1;\n\nfunction newRequestId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n if (typeof crypto === 'undefined' || typeof crypto.getRandomValues !== 'function') {\n throw new Error('Secure request-id generation is unavailable.');\n }\n const bytes = new Uint32Array(4);\n crypto.getRandomValues(bytes);\n return `nostr-${Array.from(bytes, value => value.toString(16)).join('')}`;\n}\n\n/**\n * One ephemeral iframe per request. It is mounted off-screen at ~0 size and\n * only expanded into a visible, backdrop-covered modal when the OpenKey\n * widget page explicitly asks for it (`openkey:nostr:show`) - e.g. first-time\n * identity consent, a relay-scoped connect grant, or the first kind:9 message\n * to a new client origin. A silent signing request already covered by an\n * existing grant never sends `show`, so the user sees nothing at all.\n *\n * The hidden/visible states are pure CSS toggles on a container that always\n * holds the same `<iframe>` element - the iframe itself is never removed or\n * reparented, because doing so would reload it (and drop its in-flight\n * request state) in most browsers.\n */\nclass NostrFrame {\n private root: HTMLDivElement;\n private shadow: ShadowRoot;\n private iframe: HTMLIFrameElement;\n private outer: HTMLDivElement;\n private host: string;\n private messageHandler: (event: MessageEvent) => void = () => {};\n private revealed = false;\n private requestedHeight = 400;\n private viewportHandler = () => {\n this.syncViewport();\n this.applyFrameHeight();\n };\n\n constructor(host: string, url: string) {\n this.host = host;\n this.root = document.createElement('div');\n this.shadow = this.root.attachShadow({ mode: 'closed' });\n\n const style = document.createElement('style');\n style.textContent = `\n :host{all:initial}\n .nf-outer{position:fixed;top:-9999px;left:-9999px;width:1px;height:1px;overflow:hidden;opacity:0;pointer-events:none}\n .nf-outer.nf-visible{position:fixed;top:var(--nf-viewport-top,0px);left:var(--nf-viewport-left,0px);width:var(--nf-viewport-width,100vw);height:var(--nf-viewport-height,100dvh);box-sizing:border-box;padding:max(16px,env(safe-area-inset-top)) max(16px,env(safe-area-inset-right)) max(16px,env(safe-area-inset-bottom)) max(16px,env(safe-area-inset-left));overflow:auto;overscroll-behavior:contain;opacity:1;pointer-events:auto;background:rgba(0,0,0,0.42);z-index:999999;display:flex;align-items:center;justify-content:center}\n .nf-card{width:1px;height:1px;overflow:hidden}\n .nf-visible .nf-card{background:#fafafa;width:min(400px,100%);height:auto;max-height:100%;border-radius:16px;box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);overflow:auto;flex:0 1 auto}\n iframe{border:none;width:1px;height:1px;display:block;transition:height 200ms ease}\n .nf-visible iframe{width:100%;height:400px;max-height:100%}\n @media (prefers-reduced-motion:reduce){iframe{transition:none}}\n `;\n\n this.outer = document.createElement('div');\n this.outer.className = 'nf-outer';\n this.outer.setAttribute('role', 'dialog');\n this.outer.setAttribute('aria-modal', 'true');\n this.outer.setAttribute('aria-label', 'OpenKey approval');\n this.outer.setAttribute('aria-hidden', 'true');\n\n const card = document.createElement('div');\n card.className = 'nf-card';\n\n this.iframe = document.createElement('iframe');\n this.iframe.src = url;\n this.iframe.title = 'OpenKey approval';\n this.iframe.setAttribute('allow', 'clipboard-write *; publickey-credentials-get *; publickey-credentials-create *');\n this.iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox');\n\n card.appendChild(this.iframe);\n this.outer.appendChild(card);\n this.shadow.appendChild(style);\n this.shadow.appendChild(this.outer);\n document.body.appendChild(this.root);\n\n this.syncViewport();\n window.addEventListener('resize', this.viewportHandler);\n window.visualViewport?.addEventListener('resize', this.viewportHandler);\n window.visualViewport?.addEventListener('scroll', this.viewportHandler);\n }\n\n onMessage(handler: (data: NostrFrameMessage) => void) {\n this.messageHandler = (event: MessageEvent) => {\n // Canonical, non-wildcard origin only; exact window-identity match.\n if (event.origin !== this.host) return;\n if (event.source !== this.iframe.contentWindow) return;\n handler(event.data as NostrFrameMessage);\n };\n window.addEventListener('message', this.messageHandler);\n }\n\n reveal() {\n if (this.revealed) return;\n this.revealed = true;\n this.syncViewport();\n this.outer.classList.add('nf-visible');\n this.outer.setAttribute('aria-hidden', 'false');\n this.applyFrameHeight();\n }\n\n resize(height: number) {\n if (!Number.isFinite(height) || height <= 0) return;\n this.requestedHeight = height;\n if (this.revealed) this.applyFrameHeight();\n }\n\n private syncViewport() {\n const viewport = window.visualViewport;\n this.outer.style.setProperty('--nf-viewport-top', `${viewport?.offsetTop ?? 0}px`);\n this.outer.style.setProperty('--nf-viewport-left', `${viewport?.offsetLeft ?? 0}px`);\n this.outer.style.setProperty('--nf-viewport-width', `${viewport?.width ?? window.innerWidth}px`);\n this.outer.style.setProperty('--nf-viewport-height', `${viewport?.height ?? window.innerHeight}px`);\n }\n\n private applyFrameHeight() {\n if (!this.revealed) return;\n const viewportHeight = window.visualViewport?.height ?? window.innerHeight;\n const max = Math.max(1, Math.floor(viewportHeight - 32));\n this.iframe.style.height = `${Math.min(this.requestedHeight, max)}px`;\n }\n\n postMessage(message: object) {\n this.iframe.contentWindow?.postMessage(message, this.host);\n }\n\n destroy() {\n window.removeEventListener('message', this.messageHandler);\n window.removeEventListener('resize', this.viewportHandler);\n window.visualViewport?.removeEventListener('resize', this.viewportHandler);\n window.visualViewport?.removeEventListener('scroll', this.viewportHandler);\n this.root.remove();\n }\n}\n\n/**\n * Browser client for the OpenKey Nostr custody + signing flow. Get an\n * instance from `OpenKey#nostr` rather than constructing this directly.\n */\nexport class OpenKeyNostr {\n constructor(private host: string) {}\n\n /**\n * Get-or-create the user's OpenKey-custodied Nostr identity. Always shows\n * a visible consent card (identity creation, or - when `relayUrl` is\n * given - a relay-scoped kind:22242/NIP-42 grant for that exact relay).\n * Never resolves with the secret key; only `keyId`/`pubkey`/`npub`.\n */\n async connect(opts?: { relayUrl?: string }): Promise<NostrIdentity> {\n const url = this.widgetUrl();\n return this.run<NostrIdentity>(\n url,\n { type: 'openkey:nostr:connect:request', relayUrl: opts?.relayUrl },\n (data, resolve, reject) => {\n if (data.type !== 'openkey:nostr:connect:response') return false;\n if (data.success) resolve({ keyId: data.keyId, pubkey: data.pubkey, npub: data.npub });\n else reject(data.error);\n return true;\n },\n );\n }\n\n /**\n * Sign a NIP-01 event template with the user's OpenKey Nostr key. Silent\n * (no visible UI) when an active grant already covers this client origin\n * + key + kind (+ exact relay, for kind 22242). Otherwise shows a visible\n * consent card before signing - required for every first kind:9 message to\n * a new origin, per NIP-29 channel-message policy.\n */\n async signEvent(keyId: string, event: UnsignedNostrEvent): Promise<SignedNostrEvent> {\n const url = this.widgetUrl();\n return this.run<SignedNostrEvent>(\n url,\n { type: 'openkey:nostr:sign:request', keyId, event },\n (data, resolve, reject) => {\n if (data.type !== 'openkey:nostr:sign:response') return false;\n if (data.success) resolve(data.event);\n else reject(data.error);\n return true;\n },\n );\n }\n\n private widgetUrl(): string {\n const origin = encodeURIComponent(window.location.origin);\n return `${this.host}/widget/embed/nostr/approve?origin=${origin}`;\n }\n\n private run<T>(\n url: string,\n request: object,\n onData: (data: NostrFrameMessage, resolve: (v: T) => void, reject: (e: NostrError) => void) => boolean,\n ): Promise<T> {\n return new Promise((resolve, reject) => {\n let settled = false;\n const frame = new NostrFrame(this.host, url);\n const requestId = newRequestId();\n\n const settle = (fn: () => void) => {\n if (settled) return;\n settled = true;\n clearTimeout(timeout);\n fn();\n frame.destroy();\n };\n\n frame.onMessage((data) => {\n if (!data || typeof (data as { type?: unknown }).type !== 'string') return;\n\n if (data.type === 'openkey:ready') {\n if (data.protocolVersion !== NOSTR_PROTOCOL_VERSION) return;\n frame.postMessage({ ...request, requestId, protocolVersion: NOSTR_PROTOCOL_VERSION });\n return;\n }\n if (\n data.requestId !== requestId ||\n data.protocolVersion !== NOSTR_PROTOCOL_VERSION\n ) return;\n if (data.type === 'openkey:resize') {\n frame.resize(data.height);\n return;\n }\n if (data.type === 'openkey:nostr:show') {\n frame.reveal();\n return;\n }\n if (data.type === 'openkey:close') {\n settle(() => reject({ code: 'USER_CANCELLED', message: 'Request closed' }));\n return;\n }\n\n onData(data, (v) => settle(() => resolve(v)), (e) => settle(() => reject(e)));\n });\n\n const timeout = setTimeout(() => {\n settle(() => reject({ code: 'TIMEOUT', message: 'Nostr request timed out' }));\n }, NOSTR_FRAME_TIMEOUT_MS);\n });\n }\n}\n","// OpenKey SDK - Browser client for third-party apps\n// Provides \"Sign with OpenKey\" functionality via popup or iframe\n\nimport {\n generateCodeVerifier,\n generateCodeChallenge,\n generateState,\n buildAuthorizationUrl,\n} from '@openkey/core';\nimport { OpenKeyNostr } from './nostr';\n\nexport { OpenKeyNostr } from './nostr';\nexport type {\n UnsignedNostrEvent,\n SignedNostrEvent,\n NostrIdentity,\n NostrError,\n} from './nostr';\n\nexport interface EIP1193Provider {\n request(args: { method: string; params?: any[] }): Promise<any>;\n}\n\ninterface EIP6963ProviderInfo {\n uuid: string;\n name: string;\n icon: string;\n rdns: string;\n}\n\ninterface EIP6963ProviderDetail {\n info: EIP6963ProviderInfo;\n provider: EIP1193Provider;\n}\n\nexport type OpenKeyMode = 'iframe' | 'popup' | 'redirect';\n\nexport interface OpenKeyConfig {\n /** OpenKey host URL (default: https://openkey.so) */\n host?: string;\n /** OAuth API host URL (default: derived from host by prefixing 'api.') */\n oauthHost?: string;\n /** App identifier for display */\n appName?: string;\n /** UI mode: 'iframe' (default), 'popup', or 'redirect' */\n mode?: OpenKeyMode;\n /** App-provided wallet provider for external key signing */\n externalProvider?: EIP1193Provider;\n}\n\nexport interface SignMessageRequest {\n message: string;\n keyId?: string; // If not provided, user selects\n}\n\nexport interface SignTypedDataRequest {\n domain: {\n name?: string;\n version?: string;\n chainId?: number;\n verifyingContract?: string;\n };\n types: Record<string, Array<{ name: string; type: string }>>;\n primaryType: string;\n message: Record<string, unknown>;\n keyId?: string;\n}\n\nexport interface SignResult {\n signature: string;\n address: string;\n}\n\nexport interface AuthResult {\n address: string;\n keyId: string;\n keyType: 'MANAGED' | 'EXTERNAL';\n}\n\n/**\n * Confirmation returned by {@link OpenKey.signOut}. `requestId` is generated\n * by the SDK and echoed by the OpenKey-owned widget, so callers can associate\n * the acknowledgement with the sign-out they initiated.\n */\nexport interface SignOutAcknowledgement {\n requestId: string;\n /**\n * Whether the widget confirmed that the previous bearer no longer\n * authenticates. `false` means the SDK is locally signed out, but remote\n * revocation could not be verified.\n */\n revoked: boolean;\n}\n\nexport interface OpenKeyError {\n code: 'USER_CANCELLED' | 'POPUP_BLOCKED' | 'TIMEOUT' | 'NO_KEY' | 'UNAUTHORIZED' | 'UNKNOWN' | 'STATE_MISMATCH';\n message: string;\n}\n\n// ======= OAuth 2.1 Types =======\n\n/** OAuth configuration for third-party apps */\nexport interface OAuthConfig {\n /** OAuth client_id (registered with OpenKey) */\n clientId: string;\n /** Redirect URI (must match registered URI) */\n redirectUri: string;\n /** State parameter for CSRF protection (auto-generated if not provided) */\n state?: string;\n}\n\n/** Result from OAuth authorization */\nexport interface OAuthResult {\n /** Authorization code (exchange for tokens) */\n code: string;\n /** State parameter (verify matches request) */\n state: string;\n}\n\n/** Response from token exchange */\nexport interface OAuthTokenResponse {\n access_token: string;\n token_type: 'Bearer';\n expires_in: number;\n id_token: string;\n scope: string;\n refresh_token?: string;\n}\n\n// ======= Versioned TinyCloud authorization protocol =======\n//\n// This protocol replaces the legacy `signMessage()` path for TinyCloud\n// SIWE-ReCap requests. It preserves the legacy exact-byte behavior for\n// existing callers: `signMessage()` continues to sign the caller's exact\n// bytes and OpenKey NEVER rewrites them. Callers who want to let the user\n// narrow the requested capabilities call `authorizeTinyCloud()` instead.\n//\n// The response carries `signedMessage` — the exact bytes the signature\n// verifies against. TinyCloud completes the session with these bytes, not\n// the caller's original request. See `NodeUserAuthorization` in the\n// js-sdk for the consumer side of this contract.\n\nexport interface TinyCloudAuthorizationRequestV1 {\n protocolVersion: 1;\n /** Suggested SIWE (may be edited server-side before signing). */\n siwe: string;\n /** The keyId the user picked, if the caller has one in mind. */\n keyId?: string;\n /**\n * The session-key JWK bound to `siwe`. Required so the server can\n * regenerate a narrowed SIWE tied to the SAME session key when the\n * user removes capabilities. Passing a mismatched jwk (or omitting it\n * when the widget attempts to narrow) causes the /authorize-sign call\n * to fail — never a silent fallback to the caller's exact bytes.\n */\n jwk?: Record<string, unknown>;\n /**\n * The TinyCloud host the resulting session will activate against.\n * Bound into the /authorize-sign-prepare context so /authorize-sign\n * cannot swap hosts server-side. Optional for callers that do not\n * plan to activate a delegation (they should still forward it when\n * known; the empty string is treated as \"unknown\").\n */\n host?: string;\n /** Optional presentation envelope (name, reason, manifest). */\n presentation?: CapabilityPresentationEnvelopeV1;\n}\n\nexport interface TinyCloudAuthorizationResultV1 {\n protocolVersion: 1;\n /** EIP-55 signer address. */\n address: string;\n /** Signature over `signedMessage`. */\n signature: string;\n /** The EXACT bytes the signature verifies against. Never the caller's original. */\n signedMessage: string;\n /** The action IDs the user (or default consent) selected. */\n selectedActionKeys: string[];\n /** Effective grant set after any narrowing. */\n permissions: Array<{\n service: string;\n space: string;\n path: string;\n actions: string[];\n }>;\n}\n\nexport interface CapabilityPresentationEnvelopeV1 {\n protocolVersion: 1;\n /** Human-readable requester name shown in the review. */\n displayName?: string;\n /**\n * Reason string the requester supplied for the delegation. Rendered as\n * caller-supplied (never as verified) unless a signed manifest carries\n * the same reason string.\n */\n reason?: string;\n /** Manifest ID + digest, when the app publishes a signed manifest. */\n manifestId?: string;\n manifestDigest?: string;\n /**\n * Full manifest payload(s) the caller wants surfaced in the review. The\n * receiving route validates and size-bounds this before it is used. This\n * is display-only: no metadata may expand authority beyond what the\n * ReCap already grants. Bounded to a reasonable size at the transport\n * boundary — oversized envelopes are dropped.\n */\n manifests?: Array<{\n name?: string;\n appId?: string;\n payload?: Record<string, unknown>;\n }>;\n}\n\n// Sol MAJOR-3: transport messages must carry `requestId` and\n// `protocolVersion` for the SDK to correlate concurrent flows. Legacy\n// (unversioned) messages are allowed for backward compatibility with\n// the plain signMessage path, but versioned flows (authorizeTinyCloud)\n// always carry both fields and the SDK matches them on response.\ntype MessageType =\n | { type: 'openkey:auth:request'; appName: string }\n | { type: 'openkey:auth:response'; success: true; address: string; keyId: string; keyType?: 'MANAGED' | 'EXTERNAL'; sessionToken?: string; requestId?: string; protocolVersion?: number }\n | { type: 'openkey:auth:response'; success: false; error: OpenKeyError; requestId?: string; protocolVersion?: number }\n | { type: 'openkey:sign:request'; message: string; keyId?: string; sessionToken?: string; requestId?: string; protocolVersion?: number }\n | { type: 'openkey:sign:response'; success: true; signature: string; address: string; requestId?: string; protocolVersion?: number }\n | {\n type: 'openkey:sign:response';\n success: true;\n signature: string;\n address: string;\n /** Versioned: exact bytes the signature verifies against. */\n signedMessage?: string;\n /** Versioned: action IDs selected by the user. */\n selectedActionKeys?: string[];\n /** Versioned: effective grants after narrowing. */\n permissions?: Array<{\n service: string;\n space: string;\n path: string;\n actions: string[];\n }>;\n requestId?: string;\n protocolVersion?: number;\n }\n | { type: 'openkey:sign:response'; success: false; error: OpenKeyError; requestId?: string; protocolVersion?: number }\n // Sol MAJOR-3 (continuation): external-key review flow. The widget\n // renders the shared SigningApproval UI, calls /authorize-sign-prepare\n // and /authorize-sign-preview on the user's behalf, and — instead of\n // signing server-side with a managed key — hands the SDK back the\n // preview data so the SDK can invoke the user's wallet. The SDK then\n // completes /authorize-sign with the resulting `externalSignature`.\n | {\n type: 'openkey:externalSign:approve';\n success: true;\n requestId: string;\n protocolVersion: number;\n authorizationContextToken: string;\n previewApprovalToken: string;\n signedMessage: string;\n selectedActionIds: string[];\n address: string;\n }\n | {\n type: 'openkey:externalSign:approve';\n success: false;\n requestId: string;\n protocolVersion: number;\n error: OpenKeyError;\n }\n | { type: 'openkey:signTypedData:request'; data: SignTypedDataRequest; sessionToken?: string; requestId?: string; protocolVersion?: number }\n | { type: 'openkey:signTypedData:response'; success: true; signature: string; address: string; requestId?: string; protocolVersion?: number }\n | { type: 'openkey:signTypedData:response'; success: false; error: OpenKeyError; requestId?: string; protocolVersion?: number }\n | { type: 'openkey:link-wallet:request' }\n | { type: 'openkey:link-wallet:response'; success: true; address: string; keyId: string }\n | { type: 'openkey:link-wallet:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:link-wallet:delegate' }\n | { type: 'openkey:link-wallet:result'; success: true; address: string; keyId: string }\n | { type: 'openkey:link-wallet:result'; success: false; error: OpenKeyError }\n | { type: 'openkey:auth:use-external-wallet' }\n | { type: 'openkey:sign-out:request'; requestId: string; protocolVersion: 1; sessionToken?: string }\n | { type: 'openkey:sign-out:response'; success: true; requestId: string; protocolVersion: 1; revoked: boolean }\n | { type: 'openkey:sign-out:response'; success: false; requestId: string; protocolVersion: 1; error: OpenKeyError }\n | { type: 'openkey:resize'; height: number; protocolVersion?: number }\n | { type: 'openkey:ready'; protocolVersion?: number }\n | { type: 'openkey:close' };\n\ntype WidgetResponseMessage = Extract<MessageType, { success: boolean }>;\n\nconst DEFAULT_HOST = 'https://openkey.so';\nconst POPUP_WIDTH = 400;\nconst POPUP_HEIGHT = 600;\nconst DEFAULT_TIMEOUT = 5 * 60 * 1000; // 5 minutes\nconst IFRAME_READY_TIMEOUT = 3000; // 3 seconds\nconst OAUTH_STORAGE_KEY = 'openkey_oauth';\n\n/**\n * Sol final continuation contract requirement 5: pure validation of an\n * incoming iframe resize message envelope. Exported so unit tests can\n * exercise every rejection branch — wrong requestId, wrong version,\n * malformed height — without booting the browser runtime that\n * `IframeModal` requires.\n *\n * Two modes, chosen by the modal's bound correlation:\n * - Versioned request bound (`requestId` AND `protocolVersion` set): the\n * resize MUST carry that exact pair.\n * - No versioned request (both null — `connect`, `signMessage`, and the\n * other unversioned flows): the widget sends a plain\n * `{ type, height }`. It is accepted only when it carries no\n * `requestId`. The caller has already checked that the message came\n * from this modal's iframe (`event.source`) on the OpenKey origin\n * (TC-647).\n * A half-bound correlation (only one of the two set) drops everything.\n *\n * Returns the height clamped to 85% of the viewport when acceptable, or\n * `null` when the message must be dropped.\n */\nexport function validateIframeResize(\n incoming: unknown,\n expected: {\n requestId: string | null;\n protocolVersion: number | null;\n viewportHeight: number;\n },\n): number | null {\n if (!incoming || typeof incoming !== 'object') return null;\n const data = incoming as Record<string, unknown>;\n if (data.type !== 'openkey:resize') return null;\n if (expected.requestId === null && expected.protocolVersion === null) {\n // No versioned request on this modal: a correlated resize cannot\n // belong to it.\n if (data.requestId !== undefined) return null;\n } else {\n if (expected.requestId === null || expected.protocolVersion === null) return null;\n if (typeof data.protocolVersion !== 'number' || data.protocolVersion !== expected.protocolVersion) {\n return null;\n }\n if (typeof data.requestId !== 'string' || data.requestId !== expected.requestId) {\n return null;\n }\n }\n if (typeof data.height !== 'number' || !Number.isFinite(data.height) || data.height <= 0) {\n return null;\n }\n return Math.min(data.height, Math.floor(expected.viewportHeight * 0.85));\n}\n\n/**\n * Sol MAJOR-4 (final): pure routing helper — decides whether an\n * `authorizeTinyCloud` call should route through the external-wallet\n * preview→sign→finalize flow or the managed-key widget-signs-server-side\n * flow. Exported so unit tests can exercise every branch\n * (explicit-external + external-session, explicit-external + external-\n * session with different keyId, no-explicit + external-session,\n * explicit-managed + managed-session, no-session) without booting the\n * browser runtime.\n *\n * The decision is authoritative from the ACTIVE session's keyType when\n * no explicit `requestKeyId` was supplied.\n *\n * Kept as a thin wrapper for backwards compatibility. New callers should\n * prefer `resolveAuthorizeTinyCloudRouting` which also considers the\n * request's explicit `keyId`.\n */\nexport function shouldRouteAuthorizeTinyCloudExternal(state: {\n lastAuth: { keyType?: 'MANAGED' | 'EXTERNAL' | null } | null;\n}): boolean {\n return state.lastAuth?.keyType === 'EXTERNAL';\n}\n\n/**\n * Sol MAJOR-4 (final continuation): resolve the target key's identity and\n * route by that key's type — NOT by `lastAuth.keyType` alone.\n *\n * Sol's rejection: when the caller supplies an explicit `requestKeyId`\n * that identifies a DIFFERENT key than `lastAuth.keyId` (address vs\n * internal id, or a genuinely different key), the SDK must\n * - resolve THAT key's type,\n * - route by that resolved type (external ⇒ wallet path, managed ⇒\n * server-signing path), and\n * - reject an inconsistent explicit pin whose resolved type contradicts\n * the caller's other implicit assumptions (e.g. `lastAuth` is\n * external but the caller pinned a managed key).\n *\n * Inputs:\n * - `lastAuth`: the connected-session key metadata (may be null on\n * boot; the widget renders a connect flow first in that case).\n * - `requestKeyId`: the caller's explicit pin (may be absent).\n * - `knownKeys`: any keys we have metadata for; the SDK's higher-level\n * `authorizeTinyCloud` populates this from the server before calling\n * the resolver so the pure helper is fully synchronous and testable.\n *\n * Return shape:\n * { route: 'external' | 'managed', resolvedKeyId: string | null,\n * resolvedKeyType: 'EXTERNAL' | 'MANAGED' | null }\n *\n * `resolvedKeyId` is null only when neither `requestKeyId` nor\n * `lastAuth.keyId` exists. When both exist and identify the same key\n * (matching id OR matching known-key type), the resolver returns that\n * shared identity. When both exist and identify different keys AND we\n * know both types AND those types disagree, the resolver throws\n * `KEY_ID_TYPE_MISMATCH` so no silent route coercion occurs.\n */\nexport interface AuthorizeTinyCloudRouting {\n route: 'external' | 'managed';\n resolvedKeyId: string | null;\n resolvedKeyType: 'EXTERNAL' | 'MANAGED' | null;\n}\n\nexport class KeyIdTypeMismatchError extends Error {\n code: 'KEY_ID_TYPE_MISMATCH';\n requestKeyId: string;\n lastAuthKeyId: string | null;\n requestKeyType: 'EXTERNAL' | 'MANAGED' | null;\n lastAuthKeyType: 'EXTERNAL' | 'MANAGED' | null;\n constructor(fields: {\n message: string;\n requestKeyId: string;\n lastAuthKeyId: string | null;\n requestKeyType: 'EXTERNAL' | 'MANAGED' | null;\n lastAuthKeyType: 'EXTERNAL' | 'MANAGED' | null;\n }) {\n super(fields.message);\n this.name = 'KeyIdTypeMismatchError';\n this.code = 'KEY_ID_TYPE_MISMATCH';\n this.requestKeyId = fields.requestKeyId;\n this.lastAuthKeyId = fields.lastAuthKeyId;\n this.requestKeyType = fields.requestKeyType;\n this.lastAuthKeyType = fields.lastAuthKeyType;\n }\n}\n\nexport function resolveAuthorizeTinyCloudRouting(state: {\n lastAuth: { keyId?: string | null; keyType?: 'MANAGED' | 'EXTERNAL' | null } | null;\n requestKeyId?: string | null;\n knownKeys?: ReadonlyArray<{ id: string; address?: string; keyType: 'MANAGED' | 'EXTERNAL' }>;\n}): AuthorizeTinyCloudRouting {\n const lastAuthKeyId = state.lastAuth?.keyId ?? null;\n const lastAuthKeyType = (state.lastAuth?.keyType ?? null) as\n | 'EXTERNAL'\n | 'MANAGED'\n | null;\n\n const rawRequestKeyId = state.requestKeyId ?? null;\n const requestKeyId = rawRequestKeyId && rawRequestKeyId.length > 0 ? rawRequestKeyId : null;\n\n const knownKeys = state.knownKeys ?? [];\n\n // Helper: resolve a keyId string into its known type. Matches by id\n // first, then by address (address is a valid public identifier the\n // caller may pass in place of the internal record id).\n const lookupType = (id: string): 'EXTERNAL' | 'MANAGED' | null => {\n for (const k of knownKeys) {\n if (k.id === id) return k.keyType;\n if (k.address && k.address.toLowerCase() === id.toLowerCase()) return k.keyType;\n }\n // Convention: `external:<address>` is the SDK's synthetic id for a\n // wallet-only session that never enrolled with OpenKey. Callers\n // sometimes pass the bare address in requestKeyId; treat both\n // forms as EXTERNAL.\n if (id.startsWith('external:')) return 'EXTERNAL';\n return null;\n };\n\n // Case A: no request pin — fall back to lastAuth.keyType.\n if (!requestKeyId) {\n const route: 'external' | 'managed' =\n lastAuthKeyType === 'EXTERNAL' ? 'external' : 'managed';\n return {\n route,\n resolvedKeyId: lastAuthKeyId,\n resolvedKeyType: lastAuthKeyType,\n };\n }\n\n // Case B: request pin present. Resolve its type.\n let requestKeyType = lookupType(requestKeyId);\n // If the pin string-matches lastAuth.keyId AND we did not find it in\n // knownKeys, adopt lastAuth's type (they identify the same key).\n if (!requestKeyType && lastAuthKeyId && requestKeyId === lastAuthKeyId) {\n requestKeyType = lastAuthKeyType;\n }\n\n // If both sides tell us a type and they disagree, hard fail —\n // conflicting pins.\n if (requestKeyType && lastAuthKeyType && requestKeyType !== lastAuthKeyType) {\n throw new KeyIdTypeMismatchError({\n message: `authorizeTinyCloud: request.keyId ${requestKeyId} resolves to ${requestKeyType} but active session key ${lastAuthKeyId} is ${lastAuthKeyType}; refuse to route silently`,\n requestKeyId,\n lastAuthKeyId,\n requestKeyType,\n lastAuthKeyType,\n });\n }\n\n // If we still do not know the request's type, fall back to\n // lastAuth.keyType — the widget will surface a connect prompt if the\n // key is unknown.\n const effectiveType: 'EXTERNAL' | 'MANAGED' | null =\n requestKeyType ?? lastAuthKeyType;\n\n return {\n route: effectiveType === 'EXTERNAL' ? 'external' : 'managed',\n resolvedKeyId: requestKeyId,\n resolvedKeyType: effectiveType,\n };\n}\n\nclass IframeModal {\n private root: HTMLDivElement;\n private shadow: ShadowRoot;\n private iframe: HTMLIFrameElement;\n private onClose: () => void;\n private onMessage: (data: MessageType) => void;\n private messageHandler: (event: MessageEvent) => void;\n private host: string;\n // Sol final continuation contract requirement 5: when the modal carries a\n // versioned request, iframe resize traffic MUST correlate to its\n // requestId AND protocolVersion. Set by `setExpectedCorrelation` as soon\n // as the modal is created. When both are null the flow is unversioned and\n // only uncorrelated resizes from this iframe are accepted (TC-647).\n private expectedRequestId: string | null = null;\n private expectedProtocolVersion: number | null = null;\n\n constructor(opts: { url: string; host: string; onClose: () => void; onMessage: (data: MessageType) => void }) {\n this.host = opts.host;\n this.onClose = opts.onClose;\n this.onMessage = opts.onMessage;\n\n const isMobile = window.matchMedia('(max-width: 639px)').matches;\n\n this.root = document.createElement('div');\n this.shadow = this.root.attachShadow({ mode: 'closed' });\n\n const style = document.createElement('style');\n style.textContent = `\n :host{all:initial}\n .ok-backdrop{position:fixed;inset:0;background:rgba(0,0,0,0.42);z-index:999999;display:flex;align-items:${isMobile ? 'flex-end' : 'center'};justify-content:center;animation:ok-fade-in 150ms ease-out}\n .ok-card{position:relative;background:#fafafa;width:${isMobile ? '100%' : '400px'};border-radius:${isMobile ? '16px 16px 0 0' : '16px'};box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);overflow:hidden;overflow-y:auto;animation:${isMobile ? 'ok-slide-up 250ms ease-out' : 'ok-scale-in 200ms ease-out'};max-height:90vh}\n .ok-close{position:absolute;top:8px;right:8px;width:24px;height:24px;border:none;background:transparent;color:#6b7280;font-size:18px;cursor:pointer;z-index:1;display:flex;align-items:center;justify-content:center;border-radius:4px}\n .ok-close:hover{color:#111827}\n .ok-handle{width:40px;height:4px;background:#d4d4d4;border-radius:2px;margin:8px auto 0}\n iframe{border:none;width:100%;height:400px;display:block;transition:height 200ms ease}\n .ok-backdrop.ok-exit{animation:ok-fade-out 150ms ease-in}\n .ok-backdrop.ok-exit .ok-card{animation:${isMobile ? 'ok-slide-down 200ms ease-in' : 'ok-scale-out 150ms ease-in'}}\n @keyframes ok-fade-in{from{opacity:0}to{opacity:1}}\n @keyframes ok-fade-out{from{opacity:1}to{opacity:0}}\n @keyframes ok-scale-in{from{opacity:0;transform:scale(0.95)}to{opacity:1;transform:scale(1)}}\n @keyframes ok-scale-out{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(0.95)}}\n @keyframes ok-slide-up{from{transform:translateY(100%)}to{transform:translateY(0)}}\n @keyframes ok-slide-down{from{transform:translateY(0)}to{transform:translateY(100%)}}\n `;\n\n const backdrop = document.createElement('div');\n backdrop.className = 'ok-backdrop';\n backdrop.addEventListener('click', (e) => {\n if (e.target === backdrop) this.close();\n });\n\n const card = document.createElement('div');\n card.className = 'ok-card';\n\n if (isMobile) {\n const handle = document.createElement('div');\n handle.className = 'ok-handle';\n card.appendChild(handle);\n }\n\n const closeBtn = document.createElement('button');\n closeBtn.className = 'ok-close';\n closeBtn.textContent = '\\u00d7';\n closeBtn.addEventListener('click', () => this.close());\n card.appendChild(closeBtn);\n\n this.iframe = document.createElement('iframe');\n this.iframe.src = opts.url;\n this.iframe.setAttribute('allow', 'clipboard-write *; publickey-credentials-get *; publickey-credentials-create *');\n this.iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox');\n card.appendChild(this.iframe);\n\n backdrop.appendChild(card);\n this.shadow.appendChild(style);\n this.shadow.appendChild(backdrop);\n\n this.messageHandler = (event: MessageEvent) => {\n if (event.origin !== this.host) return;\n if (event.source !== this.iframe.contentWindow) return;\n const data = event.data as MessageType;\n if (data.type === 'openkey:resize') {\n // Sol final continuation contract requirement 5: a versioned\n // request's resize MUST carry its EXACT requestId AND\n // protocolVersion; an unversioned flow accepts only uncorrelated\n // resizes (TC-647). Origin and source were checked above. Every\n // branch is covered by unit tests over `validateIframeResize`.\n const h = validateIframeResize(event.data, {\n requestId: this.expectedRequestId,\n protocolVersion: this.expectedProtocolVersion,\n viewportHeight: window.innerHeight,\n });\n if (h === null) return;\n this.iframe.style.height = `${h}px`;\n return;\n }\n // Sol MAJOR-9: openkey:close MUST also carry versioning when the\n // request was versioned. The close message is the only other one\n // that a stray frame could try to inject to abort a legitimate\n // approval. For simplicity we drop unversioned close on messages\n // arriving from an authenticated iframe source and let the SDK's\n // timeout eventually fire.\n if (data.type === 'openkey:close') {\n // No protocol-version requirement enforced here because a\n // versionless close is a legitimate cancel from any widget\n // version; source+origin validation earlier is sufficient.\n }\n this.onMessage(data);\n };\n window.addEventListener('message', this.messageHandler);\n document.body.appendChild(this.root);\n }\n\n postMessage(message: object) {\n this.iframe.contentWindow?.postMessage(message, this.host);\n }\n\n /**\n * Sol final continuation contract requirement 5: bind the active\n * request correlation so subsequent resize (and future correlated)\n * messages can be verified against `requestId` + `protocolVersion`.\n *\n * The outer flow calls this right after creating the modal for a\n * versioned request, before the iframe can send anything, so no\n * uncorrelated resize is ever accepted for that request. Passing `null`\n * for both arguments means the flow is unversioned; passing `null` for\n * only one drops every resize.\n */\n setExpectedCorrelation(requestId: string | null, protocolVersion: number | null): void {\n this.expectedRequestId = requestId;\n this.expectedProtocolVersion = protocolVersion;\n }\n\n destroy() {\n window.removeEventListener('message', this.messageHandler);\n this.root.remove();\n }\n\n private close() {\n const backdrop = this.shadow.querySelector('.ok-backdrop');\n if (backdrop) {\n backdrop.classList.add('ok-exit');\n setTimeout(() => {\n this.destroy();\n this.onClose();\n }, 200);\n } else {\n this.destroy();\n this.onClose();\n }\n }\n}\n\nclass WalletPicker {\n private root: HTMLDivElement;\n private shadow: ShadowRoot;\n\n constructor(opts: { providers: EIP6963ProviderDetail[]; onSelect: (provider: EIP1193Provider) => void; onCancel: () => void }) {\n this.root = document.createElement('div');\n this.shadow = this.root.attachShadow({ mode: 'closed' });\n\n const style = document.createElement('style');\n style.textContent = `\n :host{all:initial}\n .wp-backdrop{position:fixed;inset:0;background:rgba(0,0,0,0.42);z-index:1000000;display:flex;align-items:center;justify-content:center;animation:wp-fade 150ms ease-out}\n .wp-card{background:#fff;width:340px;border-radius:16px;box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);padding:20px;animation:wp-scale 200ms ease-out}\n .wp-title{font:600 16px/1.3 system-ui,sans-serif;color:#111;margin:0 0 12px}\n .wp-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px}\n .wp-item{display:flex;align-items:center;gap:10px;padding:10px 12px;border:1px solid #e5e7eb;border-radius:10px;background:transparent;cursor:pointer;font:14px/1.3 system-ui,sans-serif;color:#111;width:100%;text-align:left;transition:border-color 150ms}\n .wp-item:hover{border-color:#6366f1}\n .wp-icon{width:28px;height:28px;border-radius:6px}\n .wp-empty{font:14px/1.4 system-ui,sans-serif;color:#6b7280;text-align:center;padding:16px 0}\n .wp-cancel{display:block;width:100%;margin-top:12px;padding:8px;border:none;background:transparent;color:#6b7280;font:14px/1.3 system-ui,sans-serif;cursor:pointer;border-radius:8px}\n .wp-cancel:hover{background:#f3f4f6;color:#111}\n @keyframes wp-fade{from{opacity:0}to{opacity:1}}\n @keyframes wp-scale{from{opacity:0;transform:scale(0.95)}to{opacity:1;transform:scale(1)}}\n @media(prefers-color-scheme:dark){\n .wp-card{background:#1a1a1a;box-shadow:0 25px 50px -12px rgba(0,0,0,0.5)}\n .wp-title{color:#f3f4f6}\n .wp-item{border-color:#374151;color:#f3f4f6}\n .wp-item:hover{border-color:#818cf8}\n .wp-empty{color:#9ca3af}\n .wp-cancel{color:#9ca3af}\n .wp-cancel:hover{background:#262626;color:#f3f4f6}\n }\n `;\n\n const backdrop = document.createElement('div');\n backdrop.className = 'wp-backdrop';\n backdrop.addEventListener('click', (e) => { if (e.target === backdrop) { this.destroy(); opts.onCancel(); } });\n\n const card = document.createElement('div');\n card.className = 'wp-card';\n\n const title = document.createElement('h2');\n title.className = 'wp-title';\n title.textContent = 'Select a wallet';\n card.appendChild(title);\n\n if (opts.providers.length === 0) {\n const empty = document.createElement('div');\n empty.className = 'wp-empty';\n empty.textContent = 'No wallets detected';\n card.appendChild(empty);\n } else {\n const list = document.createElement('ul');\n list.className = 'wp-list';\n for (const { info, provider } of opts.providers) {\n const item = document.createElement('button');\n item.className = 'wp-item';\n if (info.icon) {\n const icon = document.createElement('img');\n icon.className = 'wp-icon';\n icon.src = info.icon;\n icon.alt = info.name;\n item.appendChild(icon);\n }\n const name = document.createElement('span');\n name.textContent = info.name;\n item.appendChild(name);\n item.addEventListener('click', () => { this.destroy(); opts.onSelect(provider); });\n list.appendChild(item);\n }\n card.appendChild(list);\n }\n\n const cancel = document.createElement('button');\n cancel.className = 'wp-cancel';\n cancel.textContent = 'Cancel';\n cancel.addEventListener('click', () => { this.destroy(); opts.onCancel(); });\n card.appendChild(cancel);\n\n backdrop.appendChild(card);\n this.shadow.appendChild(style);\n this.shadow.appendChild(backdrop);\n document.body.appendChild(this.root);\n }\n\n destroy() {\n this.root.remove();\n }\n}\n\nfunction showToast(message = 'Opening in new window\\u2026', variant: 'info' | 'error' = 'info') {\n const bg = variant === 'error' ? '#dc2626' : '#1f2937';\n const root = document.createElement('div');\n const shadow = root.attachShadow({ mode: 'closed' });\n shadow.innerHTML = `<style>:host{all:initial}.ok-toast{position:fixed;top:16px;right:16px;z-index:1000000;background:${bg};color:#f9fafb;padding:10px 16px;border-radius:8px;font:14px/1.4 system-ui,sans-serif;box-shadow:0 4px 12px rgba(0,0,0,0.15);animation:ok-t-in 200ms ease-out;max-width:360px}@keyframes ok-t-in{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}</style><div class=\"ok-toast\">${message}</div>`;\n document.body.appendChild(root);\n setTimeout(() => root.remove(), 4000);\n}\n\nclass ExternalWalletError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ExternalWalletError';\n }\n}\n\nexport class OpenKey {\n private host: string;\n private oauthHost: string;\n private appName: string;\n private mode: OpenKeyMode;\n private config: OpenKeyConfig;\n private popup: Window | null = null;\n private lastAuth: AuthResult | null = null;\n private discoveredProviders: EIP6963ProviderDetail[] = [];\n private sessionToken: string | null = null;\n /** Cancels widget flows that could outlive a sign-out on this instance. */\n private activeFlowCancellations = new Set<() => void>();\n /**\n * Nostr identity custody + signing (secp256k1 Schnorr / BIP-340). Kept\n * fully separate from the Ethereum flows above: it never reuses\n * `lastAuth`/`sessionToken`, and its widget messages never carry a\n * sessionToken - the OpenKey session and any signing grants stay inside\n * the OpenKey-origin iframe for the whole lifetime of this client.\n */\n readonly nostr: OpenKeyNostr;\n\n constructor(config: OpenKeyConfig = {}) {\n this.config = config;\n this.host = config.host || DEFAULT_HOST;\n this.oauthHost = config.oauthHost || this.deriveOAuthHost(this.host);\n this.appName = config.appName || window.location.hostname;\n this.mode = config.mode ?? 'iframe';\n this.nostr = new OpenKeyNostr(this.host);\n\n // Listen for EIP-6963 wallet announcements\n if (typeof window !== 'undefined') {\n this.discoveredProviders = [];\n window.addEventListener('eip6963:announceProvider', (event: any) => {\n this.discoveredProviders.push(event.detail);\n });\n window.dispatchEvent(new Event('eip6963:requestProvider'));\n }\n }\n\n /**\n * Derive the OAuth API host from the main host by prefixing 'api.'\n * @param host - The main host URL\n * @returns The derived OAuth API host URL\n */\n private deriveOAuthHost(host: string): string {\n try {\n const url = new URL(host);\n if (url.hostname === 'localhost' || url.hostname === '127.0.0.1') {\n return host.replace(/\\/$/, '');\n }\n url.hostname = 'api.' + url.hostname;\n return url.toString().replace(/\\/$/, '');\n } catch {\n return 'https://api.openkey.so';\n }\n }\n\n /**\n * Sol MAJOR-4 (final continuation): fetch the caller's registered keys\n * so `resolveAuthorizeTinyCloudRouting` can resolve an explicit pin\n * whose keyId does not match the active session key. Called only when\n * the caller passes a `requestKeyId` we do not already recognise; the\n * common no-pin path skips the network round-trip.\n *\n * Failures do NOT block routing — we fall through with `knownKeys=[]`\n * so the resolver's lastAuth-based fallback still runs. If the caller\n * pinned a genuinely unknown key that turns out to be external, the\n * widget rejects the server-signing path and the SDK surfaces that\n * error from the finalize call rather than silently routing wrong.\n */\n private async fetchKnownKeysIfNeeded(\n requestKeyId: string | undefined,\n ): Promise<Array<{ id: string; address?: string; keyType: 'MANAGED' | 'EXTERNAL' }>> {\n if (!requestKeyId) return [];\n // If lastAuth already identifies this key (id or address), we do not\n // need a network round-trip — the resolver adopts lastAuth.keyType.\n const la = this.lastAuth;\n if (la?.keyId === requestKeyId) return [];\n if (la?.address && la.address.toLowerCase() === requestKeyId.toLowerCase()) return [];\n if (requestKeyId.startsWith('external:')) return [];\n try {\n const res = await fetch(`${this.oauthHost}/api/keys`, {\n method: 'GET',\n credentials: 'include',\n });\n if (!res.ok) return [];\n const body = (await res.json()) as {\n keys?: Array<{ id: string; address?: string; keyType: 'MANAGED' | 'EXTERNAL' }>;\n };\n return Array.isArray(body?.keys) ? body.keys : [];\n } catch {\n return [];\n }\n }\n\n /**\n * Connect to OpenKey and get user's wallet address\n * Opens auth flow for user to select/create a key\n */\n async connect(opts?: { mode?: OpenKeyMode }): Promise<AuthResult> {\n const result = await this.openFlow<AuthResult>('connect', {\n type: 'openkey:auth:request',\n appName: this.appName,\n }, opts?.mode);\n this.lastAuth = result;\n return result;\n }\n\n /**\n * Signs the active OpenKey account out through the OpenKey-owned widget.\n *\n * The SDK passes its Better Auth bearer through the OpenKey-owned widget\n * protocol so applications do not have to implement revocation themselves.\n * Local SDK session state is cleared before opening the widget, including\n * when remote revocation is unavailable.\n */\n async signOut(opts?: { mode?: OpenKeyMode }): Promise<SignOutAcknowledgement> {\n const requestId = `ok-signout-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n const sessionToken = this.sessionToken || undefined;\n // Redirect flows intentionally never resolve. Sign-out needs to return a\n // correlated acknowledgement, so use the OpenKey popup boundary instead.\n const mode = this.resolveMode(opts?.mode) === 'redirect' ? 'popup' : opts?.mode;\n\n // Stale connect/sign widgets must not later overwrite this signed-out\n // instance with their responses.\n this.cancelActiveFlows();\n // A failed/blocked widget must never leave this SDK instance authenticated.\n this.lastAuth = null;\n this.sessionToken = null;\n\n const acknowledgement = await this.openFlow<SignOutAcknowledgement>(\n 'sign-out',\n {\n type: 'openkey:sign-out:request',\n requestId,\n protocolVersion: 1,\n sessionToken,\n },\n mode,\n );\n\n if (acknowledgement.requestId !== requestId) {\n throw new Error('OpenKey signOut received an acknowledgement for a different request');\n }\n return acknowledgement;\n }\n\n /**\n * Better-auth session token relayed during connect(), or null if the\n * flow did not provide one. Use as a bearer token for API calls made\n * on the user's behalf (e.g. TinyCloud auto-sign bootstrap signing).\n */\n getSessionToken(): string | null {\n return this.sessionToken;\n }\n\n /**\n * Endpoint + bearer token for a TinyCloud auto-sign signing strategy.\n * The endpoint is on the OpenKey API host and only signs requests the\n * server-side bootstrap allowlist permits.\n */\n tinycloudSigningOptions(): { endpoint: string; token: string | null } {\n return {\n endpoint: `${this.oauthHost}/api/delegate/sign`,\n token: this.sessionToken,\n };\n }\n\n /**\n * Link an external wallet to the user's OpenKey account\n * Opens link-wallet widget flow\n */\n async linkWallet(opts?: { mode?: OpenKeyMode }): Promise<{ address: string; keyId: string }> {\n return this.openFlow<{ address: string; keyId: string }>('link-wallet', {\n type: 'openkey:link-wallet:request',\n }, opts?.mode);\n }\n\n /**\n * Sign a message with the user's OpenKey wallet\n * For external keys, routes directly to the user's wallet provider\n */\n async signMessage(request: SignMessageRequest, opts?: { mode?: OpenKeyMode }): Promise<SignResult> {\n if (this.lastAuth?.keyType === 'EXTERNAL') {\n return this.signWithExternalWallet(request);\n }\n return this.signWithOpenKey(request, opts?.mode);\n }\n\n /**\n * Versioned TinyCloud authorization protocol (v1).\n *\n * Unlike `signMessage()` (which is contractually byte-exact — the returned\n * signature always verifies against the caller's exact bytes), this method\n * permits the user to narrow the requested capabilities before signing.\n * OpenKey may therefore regenerate the SIWE. The response carries\n * `signedMessage` — the exact bytes the signature actually verifies against.\n *\n * TinyCloud completes the session with `signedMessage`, not the original\n * `siwe` passed in. Consumers MUST use the returned bytes and MUST NOT\n * assume the returned grants are a superset of what they requested — the\n * user is allowed to remove any grant that is not required.\n *\n * Legacy `signMessage()` callers are unaffected: their exact-byte contract\n * remains preserved and OpenKey never rewrites their bytes.\n */\n async authorizeTinyCloud(\n request: TinyCloudAuthorizationRequestV1,\n opts?: { mode?: OpenKeyMode },\n ): Promise<TinyCloudAuthorizationResultV1> {\n if (request.protocolVersion !== 1) {\n throw new Error(\n `authorizeTinyCloud only supports protocolVersion 1; got ${request.protocolVersion}`,\n );\n }\n if (typeof request.siwe !== 'string' || !request.siwe) {\n throw new Error('authorizeTinyCloud requires a non-empty SIWE');\n }\n // Sol MAJOR-3 (continuation) + Sol MAJOR-4 (final): route to the\n // external-wallet preview→sign→finalize flow whenever the ACTIVE\n // authentication session is against an EXTERNAL key. External keys\n // are held by the user's browser wallet — OpenKey does not have\n // the private material, so it cannot execute the managed-key\n // widget-signs-server-side path.\n //\n // Sol's final continuation rejection: the prior check\n // `this.lastAuth?.keyId === explicitKeyId && ... === 'EXTERNAL'`\n // let an explicitly-supplied external keyId enter the managed\n // widget path whenever the caller's `explicitKeyId` did not match\n // `lastAuth.keyId` string-for-string (for example: caller passes\n // the address; lastAuth carries the internal key record id — same\n // key, different identifier). A user cannot be authenticated with\n // two different active session keys at once — the ONE active\n // session's `keyType` is therefore authoritative for routing.\n //\n // Routing rules (revised):\n // 1. If `lastAuth?.keyType === 'EXTERNAL'`, route to external\n // (the wallet holds the material; the widget cannot sign\n // server-side either way).\n // 2. If `lastAuth?.keyType === 'MANAGED'`, route to managed.\n // 3. If `lastAuth` is missing (no active session), route to\n // managed — the widget renders a connect flow first, and\n // once the user connects the widget resolves keyType from\n // the fresh session; if that turns out to be EXTERNAL the\n // widget itself refuses to server-sign and asks the SDK to\n // re-enter via the external path.\n //\n // This resolves the key type authoritatively from the ONE active\n // session rather than relying on a fragile keyId string match.\n // See `shouldRouteAuthorizeTinyCloudExternal` for the full\n // routing-decision rationale and its unit tests for every branch.\n // Sol MAJOR-4 (final continuation): resolve the target key first\n // and route by ITS type, not by lastAuth.keyType alone. When the\n // caller pins a request.keyId that differs from the active session\n // key, we fetch the caller's key list from the server so the pure\n // `resolveAuthorizeTinyCloudRouting` helper can decide by resolved\n // type (or throw on conflicting pins).\n let routing: AuthorizeTinyCloudRouting;\n try {\n const knownKeys = await this.fetchKnownKeysIfNeeded(request.keyId);\n routing = resolveAuthorizeTinyCloudRouting({\n lastAuth: this.lastAuth,\n requestKeyId: request.keyId,\n knownKeys,\n });\n } catch (e) {\n if (e instanceof KeyIdTypeMismatchError) throw e;\n throw e instanceof Error\n ? e\n : new Error('authorizeTinyCloud: failed to resolve target key type');\n }\n if (routing.route === 'external') {\n return this.authorizeTinyCloudExternal(request, opts);\n }\n // Sol CRITICAL-1: Send a DISTINCT versioned sign request so the widget\n // knows to route through the server-authoritative /authorize-sign\n // endpoint. protocolVersion: 1 with the extended payload triggers the\n // server-authoritative narrowing path — the widget refuses to fall\n // back to legacy exact-byte signMessage() for a versioned request\n // whose origin is real.\n const requestId = `ok-auth-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n // Sol MAJOR-3: fall back to the connected key when the caller did not\n // pass an explicit keyId. Without this fallback the widget renders\n // 'Please connect first.' because it has no key context, and the\n // NodeUserAuthorization bridge never carries a keyId when the caller\n // only ran connect() — the widget path is otherwise unable to sign.\n const resolvedKeyId = routing.resolvedKeyId ?? request.keyId ?? this.lastAuth?.keyId;\n const raw = await this.openFlow<{\n signature: string;\n address: string;\n signedMessage?: string;\n selectedActionKeys?: string[];\n permissions?: TinyCloudAuthorizationResultV1['permissions'];\n }>(\n 'sign',\n {\n type: 'openkey:sign:request',\n requestId,\n protocolVersion: 1,\n message: request.siwe,\n keyId: resolvedKeyId,\n // Forward JWK so the widget can pass it to /authorize-sign for\n // narrowed-SIWE regeneration.\n jwk: request.jwk,\n // Forward the TinyCloud host so the widget can bind it into the\n // /authorize-sign-prepare context (Sol MAJOR-2).\n host: request.host,\n // Sol MAJOR-2 (envelope): forward the caller-supplied presentation\n // envelope so the widget can render honest provenance and the\n // /authorize-sign-prepare route can bind it into the authorization\n // context. The envelope is display-only; the widget transport\n // validates and size-bounds it before use and NEVER treats it as\n // verified unless the server actually origin-binds a manifest.\n presentation: request.presentation,\n sessionToken: this.sessionToken || undefined,\n },\n opts?.mode,\n );\n // Sol CRITICAL-1: NO silent fallback to `request.siwe`. If the widget\n // returned an authorization response without `signedMessage`, that is\n // a protocol violation and MUST fail — silently accepting the caller's\n // original bytes as `signedMessage` while selectedActionKeys/permissions\n // reflect a narrower set is exactly the bug this rewrite prevents.\n if (typeof raw.signedMessage !== 'string' || !raw.signedMessage) {\n throw new Error(\n 'authorizeTinyCloud: widget returned no signedMessage — signature would not correspond to the displayed authorization',\n );\n }\n if (!Array.isArray(raw.selectedActionKeys)) {\n throw new Error(\n 'authorizeTinyCloud: widget returned no selectedActionKeys — cannot verify displayed authorization matches the signed bytes',\n );\n }\n if (!Array.isArray(raw.permissions)) {\n throw new Error(\n 'authorizeTinyCloud: widget returned no permissions — cannot verify displayed authorization matches the signed bytes',\n );\n }\n return {\n protocolVersion: 1,\n address: raw.address,\n signature: raw.signature,\n signedMessage: raw.signedMessage,\n selectedActionKeys: raw.selectedActionKeys,\n permissions: raw.permissions,\n };\n }\n\n /**\n * Sol MAJOR-3 (continuation): authorizeTinyCloud path for external keys.\n * The wallet lives outside OpenKey, so the SDK opens the shared widget\n * for review + preview, then invokes the user's wallet to sign the\n * preview bytes, then finalizes server-side via /authorize-sign.\n *\n * Flow:\n * 1. Open the widget with `externalSign: true` — the widget renders\n * the shared SigningApproval UI, calls /authorize-sign-prepare,\n * calls /authorize-sign-preview after the user approves a\n * selection, and hands back `{ previewApprovalToken,\n * signedMessage, selectedActionIds, address, authorizationContextToken }`.\n * 2. SDK invokes the user's wallet on the returned signedMessage.\n * 3. SDK POSTs /authorize-sign with `externalSignature`.\n *\n * Legacy exact-byte signMessage callers are unaffected — this path is\n * only taken via authorizeTinyCloud (protocolVersion:1) when the target\n * key is EXTERNAL. Sol's rejection required this path to go through\n * the same review UI as managed keys.\n */\n private async authorizeTinyCloudExternal(\n request: TinyCloudAuthorizationRequestV1,\n opts?: { mode?: OpenKeyMode },\n ): Promise<TinyCloudAuthorizationResultV1> {\n const keyId = request.keyId ?? this.lastAuth?.keyId;\n if (!keyId) {\n throw new Error(\n 'authorizeTinyCloud (external) requires a keyId — call connect() first or pass request.keyId',\n );\n }\n const walletAddress = this.lastAuth?.address;\n if (!walletAddress) {\n throw new Error(\n 'authorizeTinyCloud (external) requires a connected wallet — call connect() first',\n );\n }\n // Sol MAJOR-3 (continuation): open the shared widget UI so the user\n // sees and can narrow the review, identical to the managed-key flow.\n const requestId = `ok-ext-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n const approval = await this.openFlow<{\n authorizationContextToken: string;\n previewApprovalToken: string;\n signedMessage: string;\n selectedActionIds: string[];\n address: string;\n }>(\n 'sign',\n {\n type: 'openkey:sign:request',\n requestId,\n protocolVersion: 1,\n message: request.siwe,\n keyId,\n jwk: request.jwk,\n host: request.host,\n // Sol MAJOR-2 (envelope): forward the caller-supplied presentation\n // envelope. Same rules as the managed path — display-only, size-\n // bounded at the transport, never treated as verified without\n // server-side origin-binding.\n presentation: request.presentation,\n sessionToken: this.sessionToken || undefined,\n // Sol MAJOR-3 (continuation): tell the widget to hand us back\n // the previewApproval instead of asking OpenKey to sign\n // server-side with a managed key. The widget will still render\n // the SAME SigningApproval component; it just diverges at the\n // \"sign\" step and emits `openkey:externalSign:approve` back\n // through the transport.\n externalSign: true,\n } as unknown as MessageType,\n opts?.mode,\n );\n if (!approval?.previewApprovalToken || !approval?.signedMessage) {\n throw new Error(\n 'authorizeTinyCloud (external): widget did not return a previewApprovalToken + signedMessage',\n );\n }\n if (\n approval.address &&\n approval.address.toLowerCase() !== walletAddress.toLowerCase()\n ) {\n throw new Error(\n `authorizeTinyCloud (external): widget preview address ${approval.address} does not match connected wallet ${walletAddress}`,\n );\n }\n // Wallet signs the exact bytes the widget previewed.\n const provider = await this.findWalletProvider(walletAddress);\n const hexMessage = this.toHex(approval.signedMessage);\n const walletSignature = (await provider.request({\n method: 'personal_sign',\n params: [hexMessage, walletAddress],\n })) as string;\n // Finalize — server verifies the wallet signature against the exact\n // same bytes it emitted for the preview.\n const finalizeRes = await fetch(\n `${this.oauthHost}/api/delegate/authorize-sign`,\n {\n method: 'POST',\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n authorizationContextToken: approval.authorizationContextToken,\n previewApprovalToken: approval.previewApprovalToken,\n selectedActionIds: approval.selectedActionIds,\n protocolVersion: 1,\n externalSignature: walletSignature,\n }),\n },\n );\n if (!finalizeRes.ok) {\n const body = await finalizeRes.json().catch(() => ({ error: `HTTP ${finalizeRes.status}` }));\n throw new Error(body.error || `authorize-sign failed (${finalizeRes.status})`);\n }\n const finalize = await finalizeRes.json();\n if (finalize.signedMessage !== approval.signedMessage) {\n throw new Error(\n 'authorizeTinyCloud (external): server signed different bytes than the preview showed',\n );\n }\n return {\n protocolVersion: 1,\n address: finalize.address,\n signature: finalize.signature,\n signedMessage: finalize.signedMessage,\n selectedActionKeys: finalize.selectedActionKeys ?? [],\n permissions: finalize.permissions ?? [],\n };\n }\n\n /**\n * Sign typed data (EIP-712) with the user's OpenKey wallet\n * For external keys, routes directly to the user's wallet provider\n */\n async signTypedData(request: SignTypedDataRequest, opts?: { mode?: OpenKeyMode }): Promise<SignResult> {\n if (this.lastAuth?.keyType === 'EXTERNAL') {\n return this.signTypedDataWithExternalWallet(request);\n }\n return this.signTypedDataWithOpenKey(request, opts?.mode);\n }\n\n private providerCandidates(): EIP1193Provider[] {\n const providers: EIP1193Provider[] = [];\n if (this.config.externalProvider) {\n providers.push(this.config.externalProvider);\n }\n providers.push(...this.discoveredProviders.map(({ provider }) => provider));\n if (typeof window !== 'undefined' && (window as any).ethereum) {\n providers.push((window as any).ethereum as EIP1193Provider);\n }\n return [...new Set(providers)];\n }\n\n private async providerHasAccount(\n provider: EIP1193Provider,\n method: 'eth_accounts' | 'eth_requestAccounts',\n targetAddress: string\n ): Promise<boolean> {\n try {\n const accounts = await provider.request({ method }) as string[];\n return accounts.some((account) => account.toLowerCase() === targetAddress.toLowerCase());\n } catch {\n return false;\n }\n }\n\n /**\n * Find a wallet provider that controls the given address.\n * Checks connected accounts first, then asks the wallet to authorize the\n * app origin if the external key was linked elsewhere.\n */\n async findWalletProvider(targetAddress: string): Promise<EIP1193Provider> {\n const providers = this.providerCandidates();\n\n for (const provider of providers) {\n if (await this.providerHasAccount(provider, 'eth_accounts', targetAddress)) {\n return provider;\n }\n }\n\n for (const provider of providers) {\n if (await this.providerHasAccount(provider, 'eth_requestAccounts', targetAddress)) {\n return provider;\n }\n }\n\n throw new ExternalWalletError('External wallet not found. Connect the wallet that owns this key and try again.');\n }\n\n private async signWithExternalWallet(request: SignMessageRequest): Promise<SignResult> {\n let provider: EIP1193Provider;\n try {\n provider = await this.findWalletProvider(this.lastAuth!.address);\n } catch (e) {\n showToast((e as Error).message, 'error');\n throw e;\n }\n try {\n const hexMessage = this.toHex(request.message);\n const signature = await provider.request({\n method: 'personal_sign',\n params: [hexMessage, this.lastAuth!.address],\n });\n return { signature: signature as string, address: this.lastAuth!.address };\n } catch (e: any) {\n const msg = e?.message?.includes('not been authorized')\n ? 'Wallet rejected the request. Approve the connection in your wallet and try again.'\n : e?.message || 'Signing failed';\n showToast(msg, 'error');\n throw new Error(msg);\n }\n }\n\n private async signTypedDataWithExternalWallet(request: SignTypedDataRequest): Promise<SignResult> {\n let provider: EIP1193Provider;\n try {\n provider = await this.findWalletProvider(this.lastAuth!.address);\n } catch (e) {\n showToast((e as Error).message, 'error');\n throw e;\n }\n try {\n const signature = await provider.request({\n method: 'eth_signTypedData_v4',\n params: [this.lastAuth!.address, JSON.stringify(request)],\n });\n return { signature: signature as string, address: this.lastAuth!.address };\n } catch (e: any) {\n const msg = e?.message?.includes('not been authorized')\n ? 'Wallet rejected the request. Approve the connection in your wallet and try again.'\n : e?.message || 'Signing failed';\n showToast(msg, 'error');\n throw new Error(msg);\n }\n }\n\n private signWithOpenKey(request: SignMessageRequest, mode?: OpenKeyMode): Promise<SignResult> {\n return this.openFlow<SignResult>('sign', {\n type: 'openkey:sign:request',\n message: request.message,\n keyId: request.keyId,\n sessionToken: this.sessionToken || undefined,\n }, mode);\n }\n\n private signTypedDataWithOpenKey(request: SignTypedDataRequest, mode?: OpenKeyMode): Promise<SignResult> {\n return this.openFlow<SignResult>('sign-typed-data', {\n type: 'openkey:signTypedData:request',\n data: request,\n sessionToken: this.sessionToken || undefined,\n }, mode);\n }\n\n private toHex(str: string): string {\n return '0x' + Array.from(new TextEncoder().encode(str)).map(b => b.toString(16).padStart(2, '0')).join('');\n }\n\n /**\n * Check if user is already authenticated\n */\n async isConnected(): Promise<boolean> {\n // Check for existing session via API\n try {\n const res = await fetch(`${this.host}/api/auth/session`, {\n credentials: 'include',\n });\n if (!res.ok) return false;\n const data = await res.json();\n return !!data.user;\n } catch {\n return false;\n }\n }\n\n // ======= OAuth 2.1 Provider Methods =======\n\n /**\n * OAuth 2.1 methods for third-party app authentication\n * Use this when your app has registered OAuth client credentials with OpenKey\n */\n oauth = {\n /**\n * Start OAuth authorization flow\n * Opens popup/redirect to OpenKey authorization endpoint\n * @returns Promise that resolves with authorization code after user consent\n */\n connect: async (config: OAuthConfig): Promise<OAuthResult> => {\n // Generate PKCE values\n const verifier = generateCodeVerifier();\n const challenge = await generateCodeChallenge(verifier);\n const state = config.state || generateState();\n\n // Store for later token exchange\n sessionStorage.setItem(\n OAUTH_STORAGE_KEY,\n JSON.stringify({ verifier, state })\n );\n\n // Build authorization URL\n const authUrl = buildAuthorizationUrl({\n host: this.oauthHost,\n clientId: config.clientId,\n redirectUri: config.redirectUri,\n codeChallenge: challenge,\n state,\n scopes: ['openid'],\n });\n\n return this.openOAuthFlow(authUrl, state, config.redirectUri);\n },\n\n /**\n * Exchange authorization code for tokens\n * Call this after receiving the callback with authorization code\n * @param code - Authorization code from callback URL\n * @param config - Same config used for connect()\n * @returns Promise that resolves with access_token, id_token, etc.\n */\n exchangeCode: async (\n code: string,\n config: OAuthConfig\n ): Promise<OAuthTokenResponse> => {\n const stored = sessionStorage.getItem(OAUTH_STORAGE_KEY);\n if (!stored) {\n throw new Error('No PKCE verifier found. Start a new OAuth flow.');\n }\n\n const { verifier } = JSON.parse(stored);\n\n const response = await fetch(`${this.oauthHost}/api/auth/oauth2/token`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n redirect_uri: config.redirectUri,\n client_id: config.clientId,\n code_verifier: verifier,\n }),\n });\n\n // Clear stored verifier\n sessionStorage.removeItem(OAUTH_STORAGE_KEY);\n\n if (!response.ok) {\n const error = await response.json();\n throw new Error(error.error_description || 'Token exchange failed');\n }\n\n return response.json();\n },\n\n /**\n * Verify state parameter from callback\n * Call this before exchangeCode to prevent CSRF attacks\n * @param receivedState - State parameter from callback URL\n * @returns true if state matches, false otherwise\n */\n verifyState: (receivedState: string): boolean => {\n const stored = sessionStorage.getItem(OAUTH_STORAGE_KEY);\n if (!stored) return false;\n const { state } = JSON.parse(stored);\n return state === receivedState;\n },\n\n /**\n * Parse authorization response from callback URL\n * @param url - Callback URL (defaults to current window.location.href)\n * @returns Parsed code and state, or error\n */\n parseCallback: (\n url?: string\n ): { code: string; state: string } | { error: string; errorDescription?: string } => {\n const urlObj = new URL(url || window.location.href);\n const error = urlObj.searchParams.get('error');\n\n if (error) {\n return {\n error,\n errorDescription: urlObj.searchParams.get('error_description') || undefined,\n };\n }\n\n const code = urlObj.searchParams.get('code');\n const state = urlObj.searchParams.get('state');\n\n if (!code || !state) {\n return { error: 'missing_params', errorDescription: 'Missing code or state parameter' };\n }\n\n return { code, state };\n },\n };\n\n private openOAuthFlow(\n url: string,\n state: string,\n redirectUri: string\n ): Promise<OAuthResult> {\n return new Promise((resolve, reject) => {\n if (this.mode !== 'redirect') {\n this.openOAuthPopup(url, state, redirectUri, resolve, reject);\n } else {\n // Full page redirect - won't resolve, page navigates away\n window.location.href = url;\n }\n });\n }\n\n private openOAuthPopup(\n url: string,\n state: string,\n redirectUri: string,\n resolve: (value: OAuthResult) => void,\n reject: (error: OpenKeyError) => void\n ) {\n const left = window.screenX + (window.outerWidth - POPUP_WIDTH) / 2;\n const top = window.screenY + (window.outerHeight - POPUP_HEIGHT) / 2;\n\n this.popup = window.open(\n url,\n 'openkey-oauth',\n `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},popup=true`\n );\n\n if (!this.popup) {\n showToast('Popup was blocked. Please allow popups for this site.', 'error');\n reject({\n code: 'POPUP_BLOCKED',\n message: 'Popup was blocked. Please allow popups or use redirect mode.',\n });\n return;\n }\n\n const redirectHost = new URL(redirectUri).origin;\n\n // Poll for redirect back with code\n const pollInterval = setInterval(() => {\n try {\n if (this.popup?.closed) {\n clearInterval(pollInterval);\n clearTimeout(timeout);\n reject({\n code: 'USER_CANCELLED',\n message: 'User closed the popup',\n });\n return;\n }\n\n // Check if redirected to callback URL\n const popupUrl = this.popup?.location?.href;\n if (popupUrl && popupUrl.startsWith(redirectHost)) {\n clearInterval(pollInterval);\n clearTimeout(timeout);\n\n const urlObj = new URL(popupUrl);\n const code = urlObj.searchParams.get('code');\n const returnedState = urlObj.searchParams.get('state');\n const error = urlObj.searchParams.get('error');\n\n this.popup?.close();\n\n if (error) {\n reject({\n code: 'UNAUTHORIZED',\n message: urlObj.searchParams.get('error_description') || error,\n });\n return;\n }\n\n if (returnedState !== state) {\n reject({\n code: 'STATE_MISMATCH',\n message: 'State mismatch - possible CSRF attack',\n });\n return;\n }\n\n if (code) {\n resolve({ code, state: returnedState });\n } else {\n reject({\n code: 'UNAUTHORIZED',\n message: 'Authorization failed - no code returned',\n });\n }\n }\n } catch {\n // Cross-origin - popup still on OpenKey domain, continue polling\n }\n }, 100);\n\n // Timeout\n const timeout = setTimeout(() => {\n clearInterval(pollInterval);\n this.popup?.close();\n reject({\n code: 'TIMEOUT',\n message: 'OAuth flow timed out',\n });\n }, DEFAULT_TIMEOUT);\n }\n\n private resolveMode(override?: OpenKeyMode): OpenKeyMode {\n return override ?? this.mode;\n }\n\n private hasDetectedEoa(): boolean {\n if (this.discoveredProviders.length > 0) return true;\n if (typeof window !== 'undefined' && (window as any).ethereum) return true;\n return false;\n }\n\n private async openFlow<T>(action: string, message: object, modeOverride?: OpenKeyMode): Promise<T> {\n const mode = this.resolveMode(modeOverride);\n const origin = encodeURIComponent(window.location.origin);\n const eoaFlag = action === 'connect' && this.hasDetectedEoa() ? '&hasEoa=true' : '';\n\n if (mode === 'popup') {\n const url = `${this.host}/widget/${action}?origin=${origin}${eoaFlag}`;\n return new Promise((resolve, reject) => this.openPopup(action, url, message, resolve, reject));\n }\n\n if (mode === 'redirect') {\n const url = `${this.host}/widget/${action}?origin=${origin}${eoaFlag}`;\n window.location.href = url;\n return new Promise(() => {}); // never resolves, page navigates\n }\n\n // iframe mode with auto-fallback\n const url = `${this.host}/widget/embed/${action}?origin=${origin}${eoaFlag}`;\n return this.openIframeModal<T>(url, action, message, origin);\n }\n\n private openIframeModal<T>(url: string, action: string, message: object, origin: string): Promise<T> {\n // Sol MAJOR-3: capture the outgoing request's correlation IDs so\n // response handlers can require them to match. Legacy unversioned\n // requests carry neither and skip correlation.\n const outgoingRequestId = (message as { requestId?: unknown }).requestId;\n const outgoingProtocolVersion = (message as { protocolVersion?: unknown }).protocolVersion;\n const isVersionedRequest =\n typeof outgoingRequestId === 'string' &&\n typeof outgoingProtocolVersion === 'number' &&\n outgoingProtocolVersion >= 1;\n return new Promise((resolve, reject) => {\n let readyReceived = false;\n let settled = false;\n let modal: IframeModal | null = null;\n let cancel: () => void;\n\n const settle = (fn: () => void) => {\n if (settled) return;\n settled = true;\n fn();\n };\n\n const cleanup = () => {\n clearTimeout(readyTimeout);\n clearTimeout(overallTimeout);\n modal?.destroy();\n modal = null;\n this.activeFlowCancellations.delete(cancel);\n };\n\n modal = new IframeModal({\n url,\n host: this.host,\n onClose: () => {\n settle(() => {\n cleanup();\n reject({ code: 'USER_CANCELLED', message: 'User cancelled the request' } as OpenKeyError);\n });\n },\n onMessage: (data: MessageType) => {\n if (data.type === 'openkey:ready') {\n readyReceived = true;\n modal?.postMessage(message);\n return;\n }\n // Sol MAJOR-3: correlate versioned responses. If the request\n // was versioned, drop any response that doesn't match the\n // outgoing requestId/protocolVersion. If the request was\n // unversioned (legacy), accept any response.\n if (isVersionedRequest) {\n const respRequestId = (data as { requestId?: unknown }).requestId;\n const respVersion = (data as { protocolVersion?: unknown }).protocolVersion;\n if (respRequestId !== outgoingRequestId) return;\n if (respVersion !== outgoingProtocolVersion) return;\n }\n\n if (data.type === 'openkey:close') {\n settle(() => {\n cleanup();\n reject({ code: 'USER_CANCELLED', message: 'User cancelled the request' } as OpenKeyError);\n });\n return;\n }\n\n if (data.type === 'openkey:link-wallet:delegate') {\n this.handleWalletLinkDelegation(modal!);\n return;\n }\n\n if (data.type === 'openkey:auth:use-external-wallet') {\n cleanup();\n this.handleExternalWalletConnect<T>(resolve, reject);\n return;\n }\n\n if (this.isResponseForAction(action, data)) {\n settle(() => {\n cleanup();\n if (data.success) {\n if (data.type === 'openkey:auth:response') {\n if (data.sessionToken) this.sessionToken = data.sessionToken;\n resolve({ address: data.address, keyId: data.keyId, keyType: data.keyType || 'MANAGED' } as T);\n } else if (data.type === 'openkey:link-wallet:response') {\n resolve({ address: data.address, keyId: data.keyId } as T);\n } else if (data.type === 'openkey:sign-out:response') {\n resolve({ requestId: data.requestId, revoked: data.revoked } as T);\n } else if (data.type === 'openkey:externalSign:approve') {\n resolve({\n authorizationContextToken: (data as any).authorizationContextToken,\n previewApprovalToken: (data as any).previewApprovalToken,\n signedMessage: (data as any).signedMessage,\n selectedActionIds: (data as any).selectedActionIds,\n address: (data as any).address,\n } as T);\n } else {\n resolve({\n signature: (data as any).signature,\n address: (data as any).address,\n signedMessage: (data as any).signedMessage,\n selectedActionKeys: (data as any).selectedActionKeys,\n permissions: (data as any).permissions,\n } as T);\n }\n } else {\n reject(data.error);\n }\n });\n }\n },\n });\n\n // Sol final continuation contract requirement 5: bind a versioned\n // request's correlation before the iframe can deliver any message,\n // so every resize for it must carry the exact (requestId,\n // protocolVersion) pair. Unversioned flows stay unbound and accept\n // only uncorrelated resizes from this iframe (TC-647).\n if (isVersionedRequest) {\n modal.setExpectedCorrelation(\n outgoingRequestId as string,\n outgoingProtocolVersion as number,\n );\n }\n\n // Auto-fallback: if no openkey:ready within 3s, fall back to popup\n const readyTimeout = setTimeout(() => {\n if (readyReceived || settled) return;\n cleanup();\n console.warn('OpenKey: iframe blocked by CSP, falling back to popup. Add frame-src https://openkey.so to your CSP.');\n showToast();\n const popupUrl = `${this.host}/widget/${action}?origin=${origin}`;\n this.openPopup(action, popupUrl, message, (val: any) => settle(() => resolve(val)), (err: any) => settle(() => reject(err)));\n }, IFRAME_READY_TIMEOUT);\n\n // Overall 5-minute timeout\n const overallTimeout = setTimeout(() => {\n settle(() => {\n cleanup();\n reject({ code: 'TIMEOUT', message: 'Request timed out' } as OpenKeyError);\n });\n }, DEFAULT_TIMEOUT);\n\n cancel = () => {\n settle(() => {\n cleanup();\n reject({ code: 'USER_CANCELLED', message: 'Superseded by sign-out' } as OpenKeyError);\n });\n };\n this.activeFlowCancellations.add(cancel);\n });\n }\n\n private isResponseForAction(action: string, data: MessageType): data is WidgetResponseMessage {\n const type = data.type;\n if (action === 'connect') return type === 'openkey:auth:response';\n if (action === 'sign') return type === 'openkey:sign:response' || type === 'openkey:externalSign:approve';\n if (action === 'sign-typed-data') return type === 'openkey:signTypedData:response';\n if (action === 'link-wallet') return type === 'openkey:link-wallet:response';\n if (action === 'sign-out') return type === 'openkey:sign-out:response';\n return false;\n }\n\n private handleWalletLinkDelegation(modal: IframeModal) {\n const sendResult = (result: MessageType) => modal.postMessage(result);\n\n new WalletPicker({\n providers: this.discoveredProviders,\n onCancel: () => {\n sendResult({ type: 'openkey:link-wallet:result', success: false, error: { code: 'USER_CANCELLED', message: 'Wallet linking cancelled' } });\n },\n onSelect: async (provider) => {\n try {\n const accounts = await provider.request({ method: 'eth_requestAccounts' }) as string[];\n const address = accounts[0];\n if (!address) throw new Error('No account returned');\n\n // Get challenge from API\n const challengeRes = await fetch(`${this.host}/api/keys/link/challenge`, {\n method: 'POST',\n credentials: 'include',\n });\n if (!challengeRes.ok) throw new Error('Failed to get challenge');\n const { message } = await challengeRes.json();\n\n // Sign challenge with wallet\n const hexMessage = this.toHex(message);\n const signature = await provider.request({\n method: 'personal_sign',\n params: [hexMessage, address],\n }) as string;\n\n // Submit to API\n const linkRes = await fetch(`${this.host}/api/keys/link`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify({ address, signature, message }),\n });\n if (!linkRes.ok) {\n const err = await linkRes.json();\n throw new Error(err.error || 'Failed to link wallet');\n }\n const { key } = await linkRes.json();\n\n sendResult({ type: 'openkey:link-wallet:result', success: true, address: key.address, keyId: key.id });\n } catch (e: any) {\n sendResult({ type: 'openkey:link-wallet:result', success: false, error: { code: 'UNKNOWN', message: e.message || 'Wallet linking failed' } });\n }\n },\n });\n }\n\n private handleExternalWalletConnect<T>(\n resolve: (value: T) => void,\n reject: (error: OpenKeyError) => void\n ) {\n new WalletPicker({\n providers: this.discoveredProviders,\n onCancel: () => {\n reject({ code: 'USER_CANCELLED', message: 'User cancelled wallet selection' });\n },\n onSelect: async (provider) => {\n try {\n const accounts = await provider.request({ method: 'eth_requestAccounts' }) as string[];\n const address = accounts[0];\n if (!address) throw new Error('No account returned');\n const result = { address, keyId: `external:${address}`, keyType: 'EXTERNAL' as const };\n this.lastAuth = result;\n resolve(result as T);\n } catch (e: any) {\n reject({ code: 'UNKNOWN', message: e.message || 'Failed to connect wallet' });\n }\n },\n });\n }\n\n private openPopup<T>(\n action: string,\n url: string,\n message: object,\n resolve: (value: T) => void,\n reject: (error: OpenKeyError) => void\n ) {\n // Calculate popup position\n const left = window.screenX + (window.outerWidth - POPUP_WIDTH) / 2;\n const top = window.screenY + (window.outerHeight - POPUP_HEIGHT) / 2;\n\n const popup = window.open(\n url,\n `openkey-${action}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,\n `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},popup=true`\n );\n this.popup = popup;\n\n if (!popup) {\n showToast('Popup was blocked. Please allow popups for this site.', 'error');\n reject({\n code: 'POPUP_BLOCKED',\n message: 'Popup was blocked. Please allow popups for this site.',\n });\n return;\n }\n\n let settled = false;\n let cancel: () => void;\n const cleanup = () => {\n window.removeEventListener('message', handleMessage);\n clearInterval(pollClosed);\n clearTimeout(timeout);\n this.activeFlowCancellations.delete(cancel);\n if (this.popup === popup) this.popup = null;\n };\n\n const settle = (fn: () => void) => {\n if (settled) return;\n settled = true;\n cleanup();\n fn();\n };\n\n // Poll to detect popup close\n const pollClosed = setInterval(() => {\n if (popup.closed) {\n settle(() => reject({\n code: 'USER_CANCELLED',\n message: 'User closed the popup',\n }));\n }\n }, 500);\n\n // Timeout\n const timeout = setTimeout(() => {\n settle(() => {\n popup.close();\n reject({\n code: 'TIMEOUT',\n message: 'Request timed out',\n });\n });\n }, DEFAULT_TIMEOUT);\n\n // Sol MAJOR-3: correlation IDs for versioned popups.\n const outgoingRequestId = (message as { requestId?: unknown }).requestId;\n const outgoingProtocolVersion = (message as { protocolVersion?: unknown }).protocolVersion;\n const isVersionedRequest =\n typeof outgoingRequestId === 'string' &&\n typeof outgoingProtocolVersion === 'number' &&\n outgoingProtocolVersion >= 1;\n // Listen for messages\n const handleMessage = (event: MessageEvent) => {\n if (event.origin !== this.host) return;\n if (event.source !== popup) return;\n\n const data = event.data as MessageType;\n\n if (data.type === 'openkey:ready') {\n // Widget is ready, send our request\n popup.postMessage(message, this.host);\n return;\n }\n\n if (data.type === 'openkey:close') {\n // Sol MAJOR-4: correlate close messages to the current versioned\n // request. A same-origin, same-source stale close from a\n // previous /widget/sign window MUST NOT tear down the active\n // request. Unversioned close messages are only accepted on\n // unversioned flows (legacy signMessage callers).\n if (isVersionedRequest) {\n const closeRequestId = (data as { requestId?: unknown }).requestId;\n const closeVersion = (data as { protocolVersion?: unknown }).protocolVersion;\n if (closeRequestId !== outgoingRequestId) return;\n if (closeVersion !== outgoingProtocolVersion) return;\n }\n settle(() => {\n popup.close();\n reject({\n code: 'USER_CANCELLED',\n message: 'User cancelled the request',\n });\n });\n return;\n }\n\n if (data.type === 'openkey:auth:use-external-wallet') {\n settle(() => {\n popup.close();\n this.handleExternalWalletConnect<T>(resolve, reject);\n });\n return;\n }\n\n // Handle responses\n if (this.isResponseForAction(action, data)) {\n // Sol MAJOR-3: drop cross-correlated responses on versioned flows.\n if (isVersionedRequest) {\n const respRequestId = (data as { requestId?: unknown }).requestId;\n const respVersion = (data as { protocolVersion?: unknown }).protocolVersion;\n if (respRequestId !== outgoingRequestId) return;\n if (respVersion !== outgoingProtocolVersion) return;\n }\n settle(() => {\n popup.close();\n if (data.success) {\n if (data.type === 'openkey:auth:response') {\n if (data.sessionToken) this.sessionToken = data.sessionToken;\n resolve({ address: data.address, keyId: data.keyId, keyType: data.keyType || 'MANAGED' } as T);\n } else if (data.type === 'openkey:link-wallet:response') {\n resolve({ address: data.address, keyId: data.keyId } as T);\n } else if (data.type === 'openkey:sign-out:response') {\n resolve({ requestId: data.requestId, revoked: data.revoked } as T);\n } else if (data.type === 'openkey:externalSign:approve') {\n // Sol MAJOR-3 (continuation): hand the preview payload back\n // to authorizeTinyCloudExternal so it can invoke the wallet.\n resolve({\n authorizationContextToken: (data as any).authorizationContextToken,\n previewApprovalToken: (data as any).previewApprovalToken,\n signedMessage: (data as any).signedMessage,\n selectedActionIds: (data as any).selectedActionIds,\n address: (data as any).address,\n } as T);\n } else {\n resolve({\n signature: (data as any).signature,\n address: (data as any).address,\n signedMessage: (data as any).signedMessage,\n selectedActionKeys: (data as any).selectedActionKeys,\n permissions: (data as any).permissions,\n } as T);\n }\n } else {\n reject(data.error);\n }\n });\n }\n };\n\n window.addEventListener('message', handleMessage);\n cancel = () => {\n settle(() => {\n popup.close();\n reject({ code: 'USER_CANCELLED', message: 'Superseded by sign-out' });\n });\n };\n this.activeFlowCancellations.add(cancel);\n }\n\n private cancelActiveFlows() {\n for (const cancel of [...this.activeFlowCancellations]) cancel();\n }\n\n /**\n * Disconnect and close any open flows\n */\n disconnect() {\n this.cancelActiveFlows();\n this.popup?.close();\n this.popup = null;\n }\n}\n\n/**\n * EIP-1193 compatible provider that wraps an OpenKey instance.\n * Transparently routes signing to either OpenKey (managed keys) or the user's\n * wallet (external keys).\n */\n\nexport class OpenKeyProvider implements EIP1193Provider {\n private openkey: OpenKey;\n private address: string;\n private keyId: string;\n private keyType: 'MANAGED' | 'EXTERNAL';\n\n constructor(openkey: OpenKey, authResult: AuthResult) {\n this.openkey = openkey;\n this.address = authResult.address;\n this.keyId = authResult.keyId;\n this.keyType = authResult.keyType;\n }\n\n async request({ method, params }: { method: string; params?: any[] }): Promise<any> {\n switch (method) {\n case 'eth_accounts':\n case 'eth_requestAccounts':\n return [this.address];\n\n case 'eth_chainId':\n return '0x1'; // mainnet\n\n case 'personal_sign': {\n if (this.keyType === 'EXTERNAL') {\n try {\n const provider = await this.openkey.findWalletProvider(this.address);\n return await provider.request({ method, params });\n } catch (e: any) {\n showToast(e?.message || 'External wallet signing failed', 'error');\n throw e;\n }\n }\n // Managed key: route through OpenKey\n const message = this.hexToString(params![0] as string);\n const result = await this.openkey.signMessage({ message, keyId: this.keyId });\n return result.signature;\n }\n\n case 'eth_signTypedData_v4': {\n if (this.keyType === 'EXTERNAL') {\n try {\n const provider = await this.openkey.findWalletProvider(this.address);\n return await provider.request({ method, params });\n } catch (e: any) {\n showToast(e?.message || 'External wallet signing failed', 'error');\n throw e;\n }\n }\n const data = JSON.parse(params![1] as string);\n const result = await this.openkey.signTypedData(data);\n return result.signature;\n }\n\n default:\n throw new Error(`Unsupported method: ${method}`);\n }\n }\n\n private hexToString(hex: string): string {\n const bytes = new Uint8Array(\n (hex.startsWith('0x') ? hex.slice(2) : hex).match(/.{1,2}/g)!.map(b => parseInt(b, 16))\n );\n return new TextDecoder().decode(bytes);\n }\n}\n\n// Default export for convenience\nexport default OpenKey;\n\n// Create singleton instance\nlet defaultInstance: OpenKey | null = null;\n\nexport function getOpenKey(config?: OpenKeyConfig): OpenKey {\n if (!defaultInstance || config) {\n defaultInstance = new OpenKey(config);\n }\n return defaultInstance;\n}\n"],"mappings":";AAiBA,IAAMA,IAAe;AAMd,SAASC,EAAgBC,GAA4B;AAC1D,MAAIC,IAAS,IACPC,IAAMF,EAAO;AAEnB,WAASG,IAAI,GAAGA,IAAID,GAAKC,KAAK,GAAG;AAC/B,QAAMC,IAAKJ,EAAOG,CAAC,GACbE,IAAKF,IAAI,IAAID,IAAMF,EAAOG,IAAI,CAAC,IAAK,GACpCG,IAAKH,IAAI,IAAID,IAAMF,EAAOG,IAAI,CAAC,IAAK,GAEpCI,IAAWH,KAAM,KAAOC,KAAM,IAAKC;AAEzCL,SAAUH,EAAcS,KAAW,KAAM,EAAI,GAC7CN,KAAUH,EAAcS,KAAW,KAAM,EAAI,GAC7CN,KAAUE,IAAI,IAAID,IAAMJ,EAAcS,KAAW,IAAK,EAAI,IAAI,IAC9DN,KAAUE,IA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;AAAA,MAEA,KAAK,wBAAwB;AAC3B,YAAI,KAAK,YAAY,YAAY;AAC/B,cAAI;AACF,kBAAM,WAAW,MAAM,KAAK,QAAQ,mBAAmB,KAAK,OAAO;AACnE,mBAAO,MAAM,SAAS,QAAQ,EAAE,QAAQ,OAAO,CAAC;AAAA,UAClD,SAAS,GAAQ;AACf,sBAAU,GAAG,WAAW,kCAAkC,OAAO;AACjE,kBAAM;AAAA,UACR;AAAA,QACF;AACA,cAAM,OAAO,KAAK,MAAM,OAAQ,CAAC,CAAW;AAC5C,cAAM,SAAS,MAAM,KAAK,QAAQ,cAAc,IAAI;AACpD,eAAO,OAAO;AAAA,MAChB;AAAA,MAEA;AACE,cAAM,IAAI,MAAM,uBAAuB,MAAM,EAAE;AAAA,IACnD;AAAA,EACF;AAAA,EAEQ,YAAY,KAAqB;AACvC,UAAM,QAAQ,IAAI;AAAA,OACf,IAAI,WAAW,IAAI,IAAI,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM,SAAS,EAAG,IAAI,OAAK,SAAS,GAAG,EAAE,CAAC;AAAA,IACxF;AACA,WAAO,IAAI,YAAY,EAAE,OAAO,KAAK;AAAA,EACvC;AACF;AAGA,IAAO,gBAAQ;AAGf,IAAI,kBAAkC;AAE/B,SAAS,WAAW,QAAiC;AAC1D,MAAI,CAAC,mBAAmB,QAAQ;AAC9B,sBAAkB,IAAI,QAAQ,MAAM;AAAA,EACtC;AACA,SAAO;AACT;","names":["BASE64_CHARS","base64UrlEncode","buffer","base64","len","i","b0","b1","b2","triplet","generateCodeVerifier","array","defaultSha256","input","data","digest","generateCodeChallenge","verifier","sha256","generateState","buildAuthorizationUrl","options","host","clientId","redirectUri","codeChallenge","state","scopes","authorizePath","url","k","url"]}
1
+ {"version":3,"sources":["../../core/src/pkce.ts","../../core/src/errors.ts","../../core/src/oauth.ts","../src/nostr.ts","../src/index.ts"],"sourcesContent":["/**\n * PKCE (Proof Key for Code Exchange) utilities.\n *\n * Uses a pure-JS base64url encoder (no `btoa()`) so it works across\n * Node.js, browsers, and React Native (including Hermes < 0.73).\n *\n * The default SHA-256 implementation uses `crypto.subtle.digest`.\n * For runtimes without Web Crypto, pass a custom `SHA256Fn`.\n */\n\n/**\n * A function that computes the SHA-256 hash of the input string.\n * Return the raw 32-byte digest as a Uint8Array.\n */\nexport type SHA256Fn = (input: string) => Promise<Uint8Array>;\n\n// Standard base64 alphabet lookup table\nconst BASE64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/**\n * Pure JS base64url encoding from a Uint8Array.\n * Does NOT use `btoa()` — safe for all runtimes.\n */\nexport function base64UrlEncode(buffer: Uint8Array): string {\n let base64 = '';\n const len = buffer.length;\n\n for (let i = 0; i < len; i += 3) {\n const b0 = buffer[i]!;\n const b1 = i + 1 < len ? buffer[i + 1]! : 0;\n const b2 = i + 2 < len ? buffer[i + 2]! : 0;\n\n const triplet = (b0 << 16) | (b1 << 8) | b2;\n\n base64 += BASE64_CHARS[(triplet >> 18) & 0x3f];\n base64 += BASE64_CHARS[(triplet >> 12) & 0x3f];\n base64 += i + 1 < len ? BASE64_CHARS[(triplet >> 6) & 0x3f] : '';\n base64 += i + 2 < len ? BASE64_CHARS[triplet & 0x3f] : '';\n }\n\n // Convert base64 to base64url: replace + with -, / with _, strip = padding\n return base64.replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n\n/**\n * Generate a cryptographically random code verifier for PKCE.\n * Returns a 43-character base64url string (32 random bytes).\n */\nexport function generateCodeVerifier(): string {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\n/**\n * Default SHA-256 implementation using Web Crypto API.\n * Available in Node.js 18+, modern browsers, and Hermes 0.73+.\n */\nasync function defaultSha256(input: string): Promise<Uint8Array> {\n const encoder = new TextEncoder();\n const data = encoder.encode(input);\n const digest = await crypto.subtle.digest('SHA-256', data);\n return new Uint8Array(digest);\n}\n\n/**\n * Generate the PKCE code challenge from a code verifier.\n *\n * @param verifier - The code verifier string\n * @param sha256 - Optional custom SHA-256 function (for expo-crypto, react-native-quick-crypto, etc.)\n * @returns Base64url-encoded SHA-256 hash of the verifier\n */\nexport async function generateCodeChallenge(\n verifier: string,\n sha256?: SHA256Fn,\n): Promise<string> {\n const hashFn = sha256 ?? defaultSha256;\n const digest = await hashFn(verifier);\n return base64UrlEncode(digest);\n}\n\n/**\n * Generate a cryptographically random state parameter.\n * Returns a 22-character base64url string (16 random bytes).\n */\nexport function generateState(): string {\n const array = new Uint8Array(16);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n","/**\n * Unified error codes across all OpenKey SDKs.\n */\nexport type OpenKeyErrorCode =\n | 'USER_CANCELLED'\n | 'POPUP_BLOCKED'\n | 'TIMEOUT'\n | 'NO_KEY'\n | 'UNAUTHORIZED'\n | 'STATE_MISMATCH'\n | 'NETWORK_ERROR'\n | 'UNKNOWN';\n\n/**\n * Error class for all OpenKey SDK errors.\n */\nexport class OpenKeyError extends Error {\n constructor(\n public code: OpenKeyErrorCode,\n message: string,\n ) {\n super(message);\n this.name = 'OpenKeyError';\n }\n}\n","import type { AuthTokens } from './types';\nimport { OpenKeyError } from './errors';\n\n// ======= Authorization URL =======\n\nexport interface BuildAuthorizationUrlOptions {\n /** OpenKey host URL (e.g. https://openkey.so) */\n host: string;\n /** OAuth client ID */\n clientId: string;\n /** Redirect URI for callback */\n redirectUri: string;\n /** PKCE code challenge (base64url-encoded) */\n codeChallenge: string;\n /** State parameter for CSRF protection */\n state: string;\n /** OAuth scopes to request */\n scopes: string[];\n /** Authorization endpoint path (default: /api/auth/oauth2/authorize) */\n authorizePath?: string;\n}\n\n/**\n * Build the OAuth 2.1 authorization URL with PKCE parameters.\n */\nexport function buildAuthorizationUrl(options: BuildAuthorizationUrlOptions): string {\n const {\n host,\n clientId,\n redirectUri,\n codeChallenge,\n state,\n scopes,\n authorizePath = '/api/auth/oauth2/authorize',\n } = options;\n\n const url = new URL(authorizePath, host);\n url.searchParams.set('client_id', clientId);\n url.searchParams.set('redirect_uri', redirectUri);\n url.searchParams.set('response_type', 'code');\n url.searchParams.set('scope', scopes.join(' '));\n url.searchParams.set('state', state);\n url.searchParams.set('code_challenge', codeChallenge);\n url.searchParams.set('code_challenge_method', 'S256');\n\n return url.toString();\n}\n\n// ======= Token Exchange =======\n\nexport interface ExchangeCodeOptions {\n /** OpenKey host URL */\n host: string;\n /** Authorization code from callback */\n code: string;\n /** Redirect URI (must match authorization request) */\n redirectUri: string;\n /** OAuth client ID */\n clientId: string;\n /** PKCE code verifier */\n codeVerifier: string;\n /** RFC 9700 resource indicator (optional) */\n resource?: string;\n /** Token endpoint path (default: /api/auth/oauth2/token) */\n tokenPath?: string;\n}\n\n/**\n * Exchange an authorization code for tokens.\n */\nexport async function exchangeAuthorizationCode(\n options: ExchangeCodeOptions,\n): Promise<AuthTokens> {\n const {\n host,\n code,\n redirectUri,\n clientId,\n codeVerifier,\n resource,\n tokenPath = '/api/auth/oauth2/token',\n } = options;\n\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n redirect_uri: redirectUri,\n client_id: clientId,\n code_verifier: codeVerifier,\n });\n\n if (resource) {\n body.set('resource', resource);\n }\n\n let response: Response;\n try {\n response = await fetch(`${host}${tokenPath}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n } catch (error) {\n throw new OpenKeyError(\n 'NETWORK_ERROR',\n error instanceof Error ? error.message : 'Network request failed',\n );\n }\n\n if (!response.ok) {\n let detail = '';\n try {\n detail = await response.text();\n } catch {\n // ignore\n }\n throw new OpenKeyError(\n 'UNKNOWN',\n `Token exchange failed: ${response.status} ${response.statusText}${detail ? ` - ${detail}` : ''}`,\n );\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n return mapTokenResponse(data);\n}\n\n// ======= Token Refresh =======\n\nexport interface RefreshTokenOptions {\n /** OpenKey host URL */\n host: string;\n /** Refresh token */\n refreshToken: string;\n /** OAuth client ID */\n clientId: string;\n /** RFC 9700 resource indicator (optional) */\n resource?: string;\n /** Token endpoint path (default: /api/auth/oauth2/token) */\n tokenPath?: string;\n}\n\n/**\n * Refresh an access token using a refresh token.\n */\nexport async function refreshAccessToken(\n options: RefreshTokenOptions,\n): Promise<AuthTokens> {\n const {\n host,\n refreshToken,\n clientId,\n resource,\n tokenPath = '/api/auth/oauth2/token',\n } = options;\n\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n client_id: clientId,\n });\n\n if (resource) {\n body.set('resource', resource);\n }\n\n let response: Response;\n try {\n response = await fetch(`${host}${tokenPath}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n } catch (error) {\n throw new OpenKeyError(\n 'NETWORK_ERROR',\n error instanceof Error ? error.message : 'Network request failed',\n );\n }\n\n if (!response.ok) {\n let detail = '';\n try {\n detail = await response.text();\n } catch {\n // ignore\n }\n throw new OpenKeyError(\n 'UNKNOWN',\n `Token refresh failed: ${response.status} ${response.statusText}${detail ? ` - ${detail}` : ''}`,\n );\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n return mapTokenResponse(data);\n}\n\n// ======= Helpers =======\n\n/**\n * Map a snake_case token response to the camelCase AuthTokens interface.\n */\nexport function mapTokenResponse(data: Record<string, unknown>): AuthTokens {\n return {\n accessToken: data.access_token as string,\n idToken: data.id_token as string,\n refreshToken: data.refresh_token as string | undefined,\n expiresIn: data.expires_in as number,\n };\n}\n\n/**\n * Parse an OAuth callback URL and extract the code and state parameters.\n * Returns null if the URL doesn't contain the expected parameters.\n */\nexport function parseOAuthCallback(url: string): { code: string; state: string } | null {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return null;\n }\n\n const code = parsed.searchParams.get('code');\n const state = parsed.searchParams.get('state');\n\n if (!code || !state) {\n return null;\n }\n\n return { code, state };\n}\n","// OpenKey Nostr signer - browser client for third-party apps.\n//\n// Structurally separate from the Ethereum/EIP-1193 flows in index.ts:\n// - Nostr identities are secp256k1 Schnorr (BIP-340/NIP-01), never routed\n// through the ECDSA sign/signTypedData paths above.\n// - The OpenKey session and any signing grants never leave the\n// OpenKey-origin iframe. Unlike `openkey:auth:response`, none of the\n// postMessage payloads below ever carry a sessionToken.\n// - Every iframe created here uses a canonical, non-wildcard `host` origin\n// for both `postMessage` targeting and incoming-message verification\n// (`event.origin === host && event.source === iframe.contentWindow`).\n\n/** NIP-01 unsigned event template. */\nexport interface UnsignedNostrEvent {\n pubkey: string;\n created_at: number;\n kind: number;\n tags: string[][];\n content: string;\n}\n\n/** A fully signed NIP-01 event, as returned by OpenKey custody signing. */\nexport interface SignedNostrEvent extends UnsignedNostrEvent {\n id: string;\n sig: string;\n}\n\n/** Public descriptor for the user's OpenKey-custodied Nostr identity. Never includes the secret key. */\nexport interface NostrIdentity {\n keyId: string;\n pubkey: string;\n npub: string;\n}\n\nexport interface NostrError {\n code: 'USER_CANCELLED' | 'TIMEOUT' | 'INTERACTION_REQUIRED' | 'UNAUTHORIZED' | 'UNKNOWN';\n message: string;\n}\n\ntype NostrFrameMessage =\n | { type: 'openkey:ready'; protocolVersion: number }\n | { type: 'openkey:close'; requestId: string; protocolVersion: number }\n | { type: 'openkey:resize'; requestId: string; protocolVersion: number; height: number }\n | { type: 'openkey:nostr:show'; requestId: string; protocolVersion: number }\n | { type: 'openkey:nostr:connect:response'; requestId: string; protocolVersion: number; success: true; keyId: string; pubkey: string; npub: string }\n | { type: 'openkey:nostr:connect:response'; requestId: string; protocolVersion: number; success: false; error: NostrError }\n | { type: 'openkey:nostr:sign:response'; requestId: string; protocolVersion: number; success: true; event: SignedNostrEvent }\n | { type: 'openkey:nostr:sign:response'; requestId: string; protocolVersion: number; success: false; error: NostrError };\n\nconst NOSTR_FRAME_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes, matches the Ethereum widget flow\nconst NOSTR_PROTOCOL_VERSION = 1;\n\nfunction newRequestId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n if (typeof crypto === 'undefined' || typeof crypto.getRandomValues !== 'function') {\n throw new Error('Secure request-id generation is unavailable.');\n }\n const bytes = new Uint32Array(4);\n crypto.getRandomValues(bytes);\n return `nostr-${Array.from(bytes, value => value.toString(16)).join('')}`;\n}\n\n/**\n * One ephemeral iframe per request. It is mounted off-screen at ~0 size and\n * only expanded into a visible, backdrop-covered modal when the OpenKey\n * widget page explicitly asks for it (`openkey:nostr:show`) - e.g. first-time\n * identity consent, a relay-scoped connect grant, or the first kind:9 message\n * to a new client origin. A silent signing request already covered by an\n * existing grant never sends `show`, so the user sees nothing at all.\n *\n * The hidden/visible states are pure CSS toggles on a container that always\n * holds the same `<iframe>` element - the iframe itself is never removed or\n * reparented, because doing so would reload it (and drop its in-flight\n * request state) in most browsers.\n */\nclass NostrFrame {\n private root: HTMLDivElement;\n private shadow: ShadowRoot;\n private iframe: HTMLIFrameElement;\n private outer: HTMLDivElement;\n private host: string;\n private messageHandler: (event: MessageEvent) => void = () => {};\n private revealed = false;\n private requestedHeight = 400;\n private viewportHandler = () => {\n this.syncViewport();\n this.applyFrameHeight();\n };\n\n constructor(host: string, url: string) {\n this.host = host;\n this.root = document.createElement('div');\n this.shadow = this.root.attachShadow({ mode: 'closed' });\n\n const style = document.createElement('style');\n style.textContent = `\n :host{all:initial}\n .nf-outer{position:fixed;top:-9999px;left:-9999px;width:1px;height:1px;overflow:hidden;opacity:0;pointer-events:none}\n .nf-outer.nf-visible{position:fixed;top:var(--nf-viewport-top,0px);left:var(--nf-viewport-left,0px);width:var(--nf-viewport-width,100vw);height:var(--nf-viewport-height,100dvh);box-sizing:border-box;padding:max(16px,env(safe-area-inset-top)) max(16px,env(safe-area-inset-right)) max(16px,env(safe-area-inset-bottom)) max(16px,env(safe-area-inset-left));overflow:auto;overscroll-behavior:contain;opacity:1;pointer-events:auto;background:rgba(0,0,0,0.42);z-index:999999;display:flex;align-items:center;justify-content:center}\n .nf-card{width:1px;height:1px;overflow:hidden}\n .nf-visible .nf-card{background:#fafafa;width:min(400px,100%);height:auto;max-height:100%;border-radius:16px;box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);overflow:auto;flex:0 1 auto}\n iframe{border:none;width:1px;height:1px;display:block;transition:height 200ms ease}\n .nf-visible iframe{width:100%;height:400px;max-height:100%}\n @media (prefers-reduced-motion:reduce){iframe{transition:none}}\n `;\n\n this.outer = document.createElement('div');\n this.outer.className = 'nf-outer';\n this.outer.setAttribute('role', 'dialog');\n this.outer.setAttribute('aria-modal', 'true');\n this.outer.setAttribute('aria-label', 'OpenKey approval');\n this.outer.setAttribute('aria-hidden', 'true');\n\n const card = document.createElement('div');\n card.className = 'nf-card';\n\n this.iframe = document.createElement('iframe');\n this.iframe.src = url;\n this.iframe.title = 'OpenKey approval';\n this.iframe.setAttribute('allow', 'clipboard-write *; publickey-credentials-get *; publickey-credentials-create *');\n this.iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox');\n\n card.appendChild(this.iframe);\n this.outer.appendChild(card);\n this.shadow.appendChild(style);\n this.shadow.appendChild(this.outer);\n document.body.appendChild(this.root);\n\n this.syncViewport();\n window.addEventListener('resize', this.viewportHandler);\n window.visualViewport?.addEventListener('resize', this.viewportHandler);\n window.visualViewport?.addEventListener('scroll', this.viewportHandler);\n }\n\n onMessage(handler: (data: NostrFrameMessage) => void) {\n this.messageHandler = (event: MessageEvent) => {\n // Canonical, non-wildcard origin only; exact window-identity match.\n if (event.origin !== this.host) return;\n if (event.source !== this.iframe.contentWindow) return;\n handler(event.data as NostrFrameMessage);\n };\n window.addEventListener('message', this.messageHandler);\n }\n\n reveal() {\n if (this.revealed) return;\n this.revealed = true;\n this.syncViewport();\n this.outer.classList.add('nf-visible');\n this.outer.setAttribute('aria-hidden', 'false');\n this.applyFrameHeight();\n }\n\n resize(height: number) {\n if (!Number.isFinite(height) || height <= 0) return;\n this.requestedHeight = height;\n if (this.revealed) this.applyFrameHeight();\n }\n\n private syncViewport() {\n const viewport = window.visualViewport;\n this.outer.style.setProperty('--nf-viewport-top', `${viewport?.offsetTop ?? 0}px`);\n this.outer.style.setProperty('--nf-viewport-left', `${viewport?.offsetLeft ?? 0}px`);\n this.outer.style.setProperty('--nf-viewport-width', `${viewport?.width ?? window.innerWidth}px`);\n this.outer.style.setProperty('--nf-viewport-height', `${viewport?.height ?? window.innerHeight}px`);\n }\n\n private applyFrameHeight() {\n if (!this.revealed) return;\n const viewportHeight = window.visualViewport?.height ?? window.innerHeight;\n const max = Math.max(1, Math.floor(viewportHeight - 32));\n this.iframe.style.height = `${Math.min(this.requestedHeight, max)}px`;\n }\n\n postMessage(message: object) {\n this.iframe.contentWindow?.postMessage(message, this.host);\n }\n\n destroy() {\n window.removeEventListener('message', this.messageHandler);\n window.removeEventListener('resize', this.viewportHandler);\n window.visualViewport?.removeEventListener('resize', this.viewportHandler);\n window.visualViewport?.removeEventListener('scroll', this.viewportHandler);\n this.root.remove();\n }\n}\n\n/**\n * Browser client for the OpenKey Nostr custody + signing flow. Get an\n * instance from `OpenKey#nostr` rather than constructing this directly.\n */\nexport class OpenKeyNostr {\n constructor(\n private host: string,\n private passkeysSupported: boolean = true,\n ) {}\n\n /**\n * Get-or-create the user's OpenKey-custodied Nostr identity. Always shows\n * a visible consent card (identity creation, or - when `relayUrl` is\n * given - a relay-scoped kind:22242/NIP-42 grant for that exact relay).\n * Never resolves with the secret key; only `keyId`/`pubkey`/`npub`.\n */\n async connect(opts?: { relayUrl?: string }): Promise<NostrIdentity> {\n const url = this.widgetUrl();\n return this.run<NostrIdentity>(\n url,\n { type: 'openkey:nostr:connect:request', relayUrl: opts?.relayUrl },\n (data, resolve, reject) => {\n if (data.type !== 'openkey:nostr:connect:response') return false;\n if (data.success) resolve({ keyId: data.keyId, pubkey: data.pubkey, npub: data.npub });\n else reject(data.error);\n return true;\n },\n );\n }\n\n /**\n * Sign a NIP-01 event template with the user's OpenKey Nostr key. Silent\n * (no visible UI) when an active grant already covers this client origin\n * + key + kind (+ exact relay, for kind 22242). Otherwise shows a visible\n * consent card before signing - required for every first kind:9 message to\n * a new origin, per NIP-29 channel-message policy.\n */\n async signEvent(keyId: string, event: UnsignedNostrEvent): Promise<SignedNostrEvent> {\n const url = this.widgetUrl();\n return this.run<SignedNostrEvent>(\n url,\n { type: 'openkey:nostr:sign:request', keyId, event },\n (data, resolve, reject) => {\n if (data.type !== 'openkey:nostr:sign:response') return false;\n if (data.success) resolve(data.event);\n else reject(data.error);\n return true;\n },\n );\n }\n\n private widgetUrl(): string {\n const origin = encodeURIComponent(window.location.origin);\n const passkeysFlag = this.passkeysSupported ? '' : '&passkeys=false';\n return `${this.host}/widget/embed/nostr/approve?origin=${origin}${passkeysFlag}`;\n }\n\n private run<T>(\n url: string,\n request: object,\n onData: (data: NostrFrameMessage, resolve: (v: T) => void, reject: (e: NostrError) => void) => boolean,\n ): Promise<T> {\n return new Promise((resolve, reject) => {\n let settled = false;\n const frame = new NostrFrame(this.host, url);\n const requestId = newRequestId();\n\n const settle = (fn: () => void) => {\n if (settled) return;\n settled = true;\n clearTimeout(timeout);\n fn();\n frame.destroy();\n };\n\n frame.onMessage((data) => {\n if (!data || typeof (data as { type?: unknown }).type !== 'string') return;\n\n if (data.type === 'openkey:ready') {\n if (data.protocolVersion !== NOSTR_PROTOCOL_VERSION) return;\n frame.postMessage({ ...request, requestId, protocolVersion: NOSTR_PROTOCOL_VERSION });\n return;\n }\n if (\n data.requestId !== requestId ||\n data.protocolVersion !== NOSTR_PROTOCOL_VERSION\n ) return;\n if (data.type === 'openkey:resize') {\n frame.resize(data.height);\n return;\n }\n if (data.type === 'openkey:nostr:show') {\n frame.reveal();\n return;\n }\n if (data.type === 'openkey:close') {\n settle(() => reject({ code: 'USER_CANCELLED', message: 'Request closed' }));\n return;\n }\n\n onData(data, (v) => settle(() => resolve(v)), (e) => settle(() => reject(e)));\n });\n\n const timeout = setTimeout(() => {\n settle(() => reject({ code: 'TIMEOUT', message: 'Nostr request timed out' }));\n }, NOSTR_FRAME_TIMEOUT_MS);\n });\n }\n}\n","// OpenKey SDK - Browser client for third-party apps\n// Provides \"Sign with OpenKey\" functionality via popup or iframe\n\nimport {\n generateCodeVerifier,\n generateCodeChallenge,\n generateState,\n buildAuthorizationUrl,\n} from '@openkey/core';\nimport { OpenKeyNostr } from './nostr';\n\nexport { OpenKeyNostr } from './nostr';\nexport type {\n UnsignedNostrEvent,\n SignedNostrEvent,\n NostrIdentity,\n NostrError,\n} from './nostr';\n\nexport interface EIP1193Provider {\n request(args: { method: string; params?: any[] }): Promise<any>;\n}\n\ninterface EIP6963ProviderInfo {\n uuid: string;\n name: string;\n icon: string;\n rdns: string;\n}\n\ninterface EIP6963ProviderDetail {\n info: EIP6963ProviderInfo;\n provider: EIP1193Provider;\n}\n\nexport type OpenKeyMode = 'iframe' | 'popup' | 'redirect';\n\nexport interface OpenKeyConfig {\n /** OpenKey host URL (default: https://openkey.so) */\n host?: string;\n /** OAuth API host URL (default: derived from host by prefixing 'api.') */\n oauthHost?: string;\n /** App identifier for display */\n appName?: string;\n /** UI mode: 'iframe' (default), 'popup', or 'redirect' */\n mode?: OpenKeyMode;\n /** App-provided wallet provider for external key signing */\n externalProvider?: EIP1193Provider;\n /**\n * Whether the client can use passkeys (WebAuthn). Default: true. Pass\n * false from clients where WebAuthn does not work (for example an\n * ad-hoc-signed desktop webview); the OpenKey UI then offers only email\n * and social sign-in.\n */\n passkeysSupported?: boolean;\n}\n\n/**\n * Query suffix telling the OpenKey widget that passkeys are unavailable.\n * Empty when passkeys are supported, so default URLs are unchanged.\n */\nexport function passkeysQueryFlag(passkeysSupported: boolean): string {\n return passkeysSupported ? '' : '&passkeys=false';\n}\n\nexport interface SignMessageRequest {\n message: string;\n keyId?: string; // If not provided, user selects\n}\n\nexport interface SignTypedDataRequest {\n domain: {\n name?: string;\n version?: string;\n chainId?: number;\n verifyingContract?: string;\n };\n types: Record<string, Array<{ name: string; type: string }>>;\n primaryType: string;\n message: Record<string, unknown>;\n keyId?: string;\n}\n\nexport interface SignResult {\n signature: string;\n address: string;\n}\n\nexport interface AuthResult {\n address: string;\n keyId: string;\n keyType: 'MANAGED' | 'EXTERNAL';\n}\n\n/**\n * Confirmation returned by {@link OpenKey.signOut}. `requestId` is generated\n * by the SDK and echoed by the OpenKey-owned widget, so callers can associate\n * the acknowledgement with the sign-out they initiated.\n */\nexport interface SignOutAcknowledgement {\n requestId: string;\n /**\n * Whether the widget confirmed that the previous bearer no longer\n * authenticates. `false` means the SDK is locally signed out, but remote\n * revocation could not be verified.\n */\n revoked: boolean;\n}\n\nexport interface OpenKeyError {\n code: 'USER_CANCELLED' | 'POPUP_BLOCKED' | 'TIMEOUT' | 'NO_KEY' | 'UNAUTHORIZED' | 'UNKNOWN' | 'STATE_MISMATCH';\n message: string;\n}\n\n// ======= OAuth 2.1 Types =======\n\n/** OAuth configuration for third-party apps */\nexport interface OAuthConfig {\n /** OAuth client_id (registered with OpenKey) */\n clientId: string;\n /** Redirect URI (must match registered URI) */\n redirectUri: string;\n /** State parameter for CSRF protection (auto-generated if not provided) */\n state?: string;\n}\n\n/** Result from OAuth authorization */\nexport interface OAuthResult {\n /** Authorization code (exchange for tokens) */\n code: string;\n /** State parameter (verify matches request) */\n state: string;\n}\n\n/** Response from token exchange */\nexport interface OAuthTokenResponse {\n access_token: string;\n token_type: 'Bearer';\n expires_in: number;\n id_token: string;\n scope: string;\n refresh_token?: string;\n}\n\n// ======= Versioned TinyCloud authorization protocol =======\n//\n// This protocol replaces the legacy `signMessage()` path for TinyCloud\n// SIWE-ReCap requests. It preserves the legacy exact-byte behavior for\n// existing callers: `signMessage()` continues to sign the caller's exact\n// bytes and OpenKey NEVER rewrites them. Callers who want to let the user\n// narrow the requested capabilities call `authorizeTinyCloud()` instead.\n//\n// The response carries `signedMessage` — the exact bytes the signature\n// verifies against. TinyCloud completes the session with these bytes, not\n// the caller's original request. See `NodeUserAuthorization` in the\n// js-sdk for the consumer side of this contract.\n\nexport interface TinyCloudAuthorizationRequestV1 {\n protocolVersion: 1;\n /** Suggested SIWE (may be edited server-side before signing). */\n siwe: string;\n /** The keyId the user picked, if the caller has one in mind. */\n keyId?: string;\n /**\n * The session-key JWK bound to `siwe`. Required so the server can\n * regenerate a narrowed SIWE tied to the SAME session key when the\n * user removes capabilities. Passing a mismatched jwk (or omitting it\n * when the widget attempts to narrow) causes the /authorize-sign call\n * to fail — never a silent fallback to the caller's exact bytes.\n */\n jwk?: Record<string, unknown>;\n /**\n * The TinyCloud host the resulting session will activate against.\n * Bound into the /authorize-sign-prepare context so /authorize-sign\n * cannot swap hosts server-side. Optional for callers that do not\n * plan to activate a delegation (they should still forward it when\n * known; the empty string is treated as \"unknown\").\n */\n host?: string;\n /** Optional presentation envelope (name, reason, manifest). */\n presentation?: CapabilityPresentationEnvelopeV1;\n}\n\nexport interface TinyCloudAuthorizationResultV1 {\n protocolVersion: 1;\n /** EIP-55 signer address. */\n address: string;\n /** Signature over `signedMessage`. */\n signature: string;\n /** The EXACT bytes the signature verifies against. Never the caller's original. */\n signedMessage: string;\n /** The action IDs the user (or default consent) selected. */\n selectedActionKeys: string[];\n /** Effective grant set after any narrowing. */\n permissions: Array<{\n service: string;\n space: string;\n path: string;\n actions: string[];\n }>;\n}\n\nexport interface CapabilityPresentationEnvelopeV1 {\n protocolVersion: 1;\n /** Human-readable requester name shown in the review. */\n displayName?: string;\n /**\n * Reason string the requester supplied for the delegation. Rendered as\n * caller-supplied (never as verified) unless a signed manifest carries\n * the same reason string.\n */\n reason?: string;\n /** Manifest ID + digest, when the app publishes a signed manifest. */\n manifestId?: string;\n manifestDigest?: string;\n /**\n * Full manifest payload(s) the caller wants surfaced in the review. The\n * receiving route validates and size-bounds this before it is used. This\n * is display-only: no metadata may expand authority beyond what the\n * ReCap already grants. Bounded to a reasonable size at the transport\n * boundary — oversized envelopes are dropped.\n */\n manifests?: Array<{\n name?: string;\n appId?: string;\n payload?: Record<string, unknown>;\n }>;\n}\n\n// Sol MAJOR-3: transport messages must carry `requestId` and\n// `protocolVersion` for the SDK to correlate concurrent flows. Legacy\n// (unversioned) messages are allowed for backward compatibility with\n// the plain signMessage path, but versioned flows (authorizeTinyCloud)\n// always carry both fields and the SDK matches them on response.\ntype MessageType =\n | { type: 'openkey:auth:request'; appName: string }\n | { type: 'openkey:auth:response'; success: true; address: string; keyId: string; keyType?: 'MANAGED' | 'EXTERNAL'; requestId?: string; protocolVersion?: number }\n | { type: 'openkey:auth:response'; success: false; error: OpenKeyError; requestId?: string; protocolVersion?: number }\n | { type: 'openkey:sign:request'; message: string; keyId?: string; requestId?: string; protocolVersion?: number }\n | { type: 'openkey:sign:response'; success: true; signature: string; address: string; requestId?: string; protocolVersion?: number }\n | {\n type: 'openkey:sign:response';\n success: true;\n signature: string;\n address: string;\n /** Versioned: exact bytes the signature verifies against. */\n signedMessage?: string;\n /** Versioned: action IDs selected by the user. */\n selectedActionKeys?: string[];\n /** Versioned: effective grants after narrowing. */\n permissions?: Array<{\n service: string;\n space: string;\n path: string;\n actions: string[];\n }>;\n requestId?: string;\n protocolVersion?: number;\n }\n | { type: 'openkey:sign:response'; success: false; error: OpenKeyError; requestId?: string; protocolVersion?: number }\n // Sol MAJOR-3 (continuation): external-key review flow. The widget\n // renders the shared SigningApproval UI, calls /authorize-sign-prepare\n // and /authorize-sign-preview on the user's behalf, and — instead of\n // signing server-side with a managed key — hands the SDK back the\n // preview data so the SDK can invoke the user's wallet. The SDK then\n // completes /authorize-sign with the resulting `externalSignature`.\n | {\n type: 'openkey:externalSign:approve';\n success: true;\n requestId: string;\n protocolVersion: number;\n authorizationContextToken: string;\n previewApprovalToken: string;\n signedMessage: string;\n selectedActionIds: string[];\n address: string;\n }\n | {\n type: 'openkey:externalSign:approve';\n success: false;\n requestId: string;\n protocolVersion: number;\n error: OpenKeyError;\n }\n | { type: 'openkey:signTypedData:request'; data: SignTypedDataRequest; requestId?: string; protocolVersion?: number }\n | { type: 'openkey:signTypedData:response'; success: true; signature: string; address: string; requestId?: string; protocolVersion?: number }\n | { type: 'openkey:signTypedData:response'; success: false; error: OpenKeyError; requestId?: string; protocolVersion?: number }\n | { type: 'openkey:link-wallet:request' }\n | { type: 'openkey:link-wallet:response'; success: true; address: string; keyId: string }\n | { type: 'openkey:link-wallet:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:link-wallet:delegate' }\n | { type: 'openkey:link-wallet:result'; success: true; address: string; keyId: string }\n | { type: 'openkey:link-wallet:result'; success: false; error: OpenKeyError }\n | { type: 'openkey:auth:use-external-wallet' }\n | { type: 'openkey:sign-out:request'; requestId: string; protocolVersion: 1 }\n | { type: 'openkey:sign-out:response'; success: true; requestId: string; protocolVersion: 1; revoked: boolean }\n | { type: 'openkey:sign-out:response'; success: false; requestId: string; protocolVersion: 1; error: OpenKeyError }\n | { type: 'openkey:resize'; height: number; protocolVersion?: number }\n | { type: 'openkey:ready'; protocolVersion?: number }\n | { type: 'openkey:close' };\n\ntype WidgetResponseMessage = Extract<MessageType, { success: boolean }>;\n\nconst DEFAULT_HOST = 'https://openkey.so';\nconst POPUP_WIDTH = 400;\nconst POPUP_HEIGHT = 600;\nconst DEFAULT_TIMEOUT = 5 * 60 * 1000; // 5 minutes\nconst IFRAME_READY_TIMEOUT = 3000; // 3 seconds\nconst OAUTH_STORAGE_KEY = 'openkey_oauth';\n\n/**\n * Sol final continuation contract requirement 5: pure validation of an\n * incoming iframe resize message envelope. Exported so unit tests can\n * exercise every rejection branch — wrong requestId, wrong version,\n * malformed height — without booting the browser runtime that\n * `IframeModal` requires.\n *\n * Two modes, chosen by the modal's bound correlation:\n * - Versioned request bound (`requestId` AND `protocolVersion` set): the\n * resize MUST carry that exact pair.\n * - No versioned request (both null — `connect`, `signMessage`, and the\n * other unversioned flows): the widget sends a plain\n * `{ type, height }`. It is accepted only when it carries no\n * `requestId`. The caller has already checked that the message came\n * from this modal's iframe (`event.source`) on the OpenKey origin\n * (TC-647).\n * A half-bound correlation (only one of the two set) drops everything.\n *\n * Returns the height clamped to 85% of the viewport when acceptable, or\n * `null` when the message must be dropped.\n */\nexport function validateIframeResize(\n incoming: unknown,\n expected: {\n requestId: string | null;\n protocolVersion: number | null;\n viewportHeight: number;\n },\n): number | null {\n if (!incoming || typeof incoming !== 'object') return null;\n const data = incoming as Record<string, unknown>;\n if (data.type !== 'openkey:resize') return null;\n if (expected.requestId === null && expected.protocolVersion === null) {\n // No versioned request on this modal: a correlated resize cannot\n // belong to it.\n if (data.requestId !== undefined) return null;\n } else {\n if (expected.requestId === null || expected.protocolVersion === null) return null;\n if (typeof data.protocolVersion !== 'number' || data.protocolVersion !== expected.protocolVersion) {\n return null;\n }\n if (typeof data.requestId !== 'string' || data.requestId !== expected.requestId) {\n return null;\n }\n }\n if (typeof data.height !== 'number' || !Number.isFinite(data.height) || data.height <= 0) {\n return null;\n }\n return Math.min(data.height, Math.floor(expected.viewportHeight * 0.85));\n}\n\n/**\n * Sol MAJOR-4 (final): pure routing helper — decides whether an\n * `authorizeTinyCloud` call should route through the external-wallet\n * preview→sign→finalize flow or the managed-key widget-signs-server-side\n * flow. Exported so unit tests can exercise every branch\n * (explicit-external + external-session, explicit-external + external-\n * session with different keyId, no-explicit + external-session,\n * explicit-managed + managed-session, no-session) without booting the\n * browser runtime.\n *\n * The decision is authoritative from the ACTIVE session's keyType when\n * no explicit `requestKeyId` was supplied.\n *\n * Kept as a thin wrapper for backwards compatibility. New callers should\n * prefer `resolveAuthorizeTinyCloudRouting` which also considers the\n * request's explicit `keyId`.\n */\nexport function shouldRouteAuthorizeTinyCloudExternal(state: {\n lastAuth: { keyType?: 'MANAGED' | 'EXTERNAL' | null } | null;\n}): boolean {\n return state.lastAuth?.keyType === 'EXTERNAL';\n}\n\n/**\n * Sol MAJOR-4 (final continuation): resolve the target key's identity and\n * route by that key's type — NOT by `lastAuth.keyType` alone.\n *\n * Sol's rejection: when the caller supplies an explicit `requestKeyId`\n * that identifies a DIFFERENT key than `lastAuth.keyId` (address vs\n * internal id, or a genuinely different key), the SDK must\n * - resolve THAT key's type,\n * - route by that resolved type (external ⇒ wallet path, managed ⇒\n * server-signing path), and\n * - reject an inconsistent explicit pin whose resolved type contradicts\n * the caller's other implicit assumptions (e.g. `lastAuth` is\n * external but the caller pinned a managed key).\n *\n * Inputs:\n * - `lastAuth`: the connected-session key metadata (may be null on\n * boot; the widget renders a connect flow first in that case).\n * - `requestKeyId`: the caller's explicit pin (may be absent).\n * - `knownKeys`: any keys we have metadata for; the SDK's higher-level\n * `authorizeTinyCloud` populates this from the server before calling\n * the resolver so the pure helper is fully synchronous and testable.\n *\n * Return shape:\n * { route: 'external' | 'managed', resolvedKeyId: string | null,\n * resolvedKeyType: 'EXTERNAL' | 'MANAGED' | null }\n *\n * `resolvedKeyId` is null only when neither `requestKeyId` nor\n * `lastAuth.keyId` exists. When both exist and identify the same key\n * (matching id OR matching known-key type), the resolver returns that\n * shared identity. When both exist and identify different keys AND we\n * know both types AND those types disagree, the resolver throws\n * `KEY_ID_TYPE_MISMATCH` so no silent route coercion occurs.\n */\nexport interface AuthorizeTinyCloudRouting {\n route: 'external' | 'managed';\n resolvedKeyId: string | null;\n resolvedKeyType: 'EXTERNAL' | 'MANAGED' | null;\n}\n\nexport class KeyIdTypeMismatchError extends Error {\n code: 'KEY_ID_TYPE_MISMATCH';\n requestKeyId: string;\n lastAuthKeyId: string | null;\n requestKeyType: 'EXTERNAL' | 'MANAGED' | null;\n lastAuthKeyType: 'EXTERNAL' | 'MANAGED' | null;\n constructor(fields: {\n message: string;\n requestKeyId: string;\n lastAuthKeyId: string | null;\n requestKeyType: 'EXTERNAL' | 'MANAGED' | null;\n lastAuthKeyType: 'EXTERNAL' | 'MANAGED' | null;\n }) {\n super(fields.message);\n this.name = 'KeyIdTypeMismatchError';\n this.code = 'KEY_ID_TYPE_MISMATCH';\n this.requestKeyId = fields.requestKeyId;\n this.lastAuthKeyId = fields.lastAuthKeyId;\n this.requestKeyType = fields.requestKeyType;\n this.lastAuthKeyType = fields.lastAuthKeyType;\n }\n}\n\nexport function resolveAuthorizeTinyCloudRouting(state: {\n lastAuth: { keyId?: string | null; keyType?: 'MANAGED' | 'EXTERNAL' | null } | null;\n requestKeyId?: string | null;\n knownKeys?: ReadonlyArray<{ id: string; address?: string; keyType: 'MANAGED' | 'EXTERNAL' }>;\n}): AuthorizeTinyCloudRouting {\n const lastAuthKeyId = state.lastAuth?.keyId ?? null;\n const lastAuthKeyType = (state.lastAuth?.keyType ?? null) as\n | 'EXTERNAL'\n | 'MANAGED'\n | null;\n\n const rawRequestKeyId = state.requestKeyId ?? null;\n const requestKeyId = rawRequestKeyId && rawRequestKeyId.length > 0 ? rawRequestKeyId : null;\n\n const knownKeys = state.knownKeys ?? [];\n\n // Helper: resolve a keyId string into its known type. Matches by id\n // first, then by address (address is a valid public identifier the\n // caller may pass in place of the internal record id).\n const lookupType = (id: string): 'EXTERNAL' | 'MANAGED' | null => {\n for (const k of knownKeys) {\n if (k.id === id) return k.keyType;\n if (k.address && k.address.toLowerCase() === id.toLowerCase()) return k.keyType;\n }\n // Convention: `external:<address>` is the SDK's synthetic id for a\n // wallet-only session that never enrolled with OpenKey. Callers\n // sometimes pass the bare address in requestKeyId; treat both\n // forms as EXTERNAL.\n if (id.startsWith('external:')) return 'EXTERNAL';\n return null;\n };\n\n // Case A: no request pin — fall back to lastAuth.keyType.\n if (!requestKeyId) {\n const route: 'external' | 'managed' =\n lastAuthKeyType === 'EXTERNAL' ? 'external' : 'managed';\n return {\n route,\n resolvedKeyId: lastAuthKeyId,\n resolvedKeyType: lastAuthKeyType,\n };\n }\n\n // Case B: request pin present. Resolve its type.\n let requestKeyType = lookupType(requestKeyId);\n // If the pin string-matches lastAuth.keyId AND we did not find it in\n // knownKeys, adopt lastAuth's type (they identify the same key).\n if (!requestKeyType && lastAuthKeyId && requestKeyId === lastAuthKeyId) {\n requestKeyType = lastAuthKeyType;\n }\n\n // If both sides tell us a type and they disagree, hard fail —\n // conflicting pins.\n if (requestKeyType && lastAuthKeyType && requestKeyType !== lastAuthKeyType) {\n throw new KeyIdTypeMismatchError({\n message: `authorizeTinyCloud: request.keyId ${requestKeyId} resolves to ${requestKeyType} but active session key ${lastAuthKeyId} is ${lastAuthKeyType}; refuse to route silently`,\n requestKeyId,\n lastAuthKeyId,\n requestKeyType,\n lastAuthKeyType,\n });\n }\n\n // If we still do not know the request's type, fall back to\n // lastAuth.keyType — the widget will surface a connect prompt if the\n // key is unknown.\n const effectiveType: 'EXTERNAL' | 'MANAGED' | null =\n requestKeyType ?? lastAuthKeyType;\n\n return {\n route: effectiveType === 'EXTERNAL' ? 'external' : 'managed',\n resolvedKeyId: requestKeyId,\n resolvedKeyType: effectiveType,\n };\n}\n\nclass IframeModal {\n private root: HTMLDivElement;\n private shadow: ShadowRoot;\n private iframe: HTMLIFrameElement;\n private onClose: () => void;\n private onMessage: (data: MessageType) => void;\n private messageHandler: (event: MessageEvent) => void;\n private host: string;\n // Sol final continuation contract requirement 5: when the modal carries a\n // versioned request, iframe resize traffic MUST correlate to its\n // requestId AND protocolVersion. Set by `setExpectedCorrelation` as soon\n // as the modal is created. When both are null the flow is unversioned and\n // only uncorrelated resizes from this iframe are accepted (TC-647).\n private expectedRequestId: string | null = null;\n private expectedProtocolVersion: number | null = null;\n\n constructor(opts: { url: string; host: string; onClose: () => void; onMessage: (data: MessageType) => void }) {\n this.host = opts.host;\n this.onClose = opts.onClose;\n this.onMessage = opts.onMessage;\n\n const isMobile = window.matchMedia('(max-width: 639px)').matches;\n\n this.root = document.createElement('div');\n this.shadow = this.root.attachShadow({ mode: 'closed' });\n\n const style = document.createElement('style');\n style.textContent = `\n :host{all:initial}\n .ok-backdrop{position:fixed;inset:0;background:rgba(0,0,0,0.42);z-index:999999;display:flex;align-items:${isMobile ? 'flex-end' : 'center'};justify-content:center;animation:ok-fade-in 150ms ease-out}\n .ok-card{position:relative;background:#fafafa;width:${isMobile ? '100%' : '400px'};border-radius:${isMobile ? '16px 16px 0 0' : '16px'};box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);overflow:hidden;overflow-y:auto;animation:${isMobile ? 'ok-slide-up 250ms ease-out' : 'ok-scale-in 200ms ease-out'};max-height:90vh}\n .ok-close{position:absolute;top:8px;right:8px;width:24px;height:24px;border:none;background:transparent;color:#6b7280;font-size:18px;cursor:pointer;z-index:1;display:flex;align-items:center;justify-content:center;border-radius:4px}\n .ok-close:hover{color:#111827}\n .ok-handle{width:40px;height:4px;background:#d4d4d4;border-radius:2px;margin:8px auto 0}\n iframe{border:none;width:100%;height:400px;display:block;transition:height 200ms ease}\n .ok-backdrop.ok-exit{animation:ok-fade-out 150ms ease-in}\n .ok-backdrop.ok-exit .ok-card{animation:${isMobile ? 'ok-slide-down 200ms ease-in' : 'ok-scale-out 150ms ease-in'}}\n @keyframes ok-fade-in{from{opacity:0}to{opacity:1}}\n @keyframes ok-fade-out{from{opacity:1}to{opacity:0}}\n @keyframes ok-scale-in{from{opacity:0;transform:scale(0.95)}to{opacity:1;transform:scale(1)}}\n @keyframes ok-scale-out{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(0.95)}}\n @keyframes ok-slide-up{from{transform:translateY(100%)}to{transform:translateY(0)}}\n @keyframes ok-slide-down{from{transform:translateY(0)}to{transform:translateY(100%)}}\n `;\n\n const backdrop = document.createElement('div');\n backdrop.className = 'ok-backdrop';\n backdrop.addEventListener('click', (e) => {\n if (e.target === backdrop) this.close();\n });\n\n const card = document.createElement('div');\n card.className = 'ok-card';\n\n if (isMobile) {\n const handle = document.createElement('div');\n handle.className = 'ok-handle';\n card.appendChild(handle);\n }\n\n const closeBtn = document.createElement('button');\n closeBtn.className = 'ok-close';\n closeBtn.textContent = '\\u00d7';\n closeBtn.addEventListener('click', () => this.close());\n card.appendChild(closeBtn);\n\n this.iframe = document.createElement('iframe');\n this.iframe.src = opts.url;\n this.iframe.setAttribute('allow', 'clipboard-write *; publickey-credentials-get *; publickey-credentials-create *');\n this.iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox');\n card.appendChild(this.iframe);\n\n backdrop.appendChild(card);\n this.shadow.appendChild(style);\n this.shadow.appendChild(backdrop);\n\n this.messageHandler = (event: MessageEvent) => {\n if (event.origin !== this.host) return;\n if (event.source !== this.iframe.contentWindow) return;\n const data = event.data as MessageType;\n if (data.type === 'openkey:resize') {\n // Sol final continuation contract requirement 5: a versioned\n // request's resize MUST carry its EXACT requestId AND\n // protocolVersion; an unversioned flow accepts only uncorrelated\n // resizes (TC-647). Origin and source were checked above. Every\n // branch is covered by unit tests over `validateIframeResize`.\n const h = validateIframeResize(event.data, {\n requestId: this.expectedRequestId,\n protocolVersion: this.expectedProtocolVersion,\n viewportHeight: window.innerHeight,\n });\n if (h === null) return;\n this.iframe.style.height = `${h}px`;\n return;\n }\n // Sol MAJOR-9: openkey:close MUST also carry versioning when the\n // request was versioned. The close message is the only other one\n // that a stray frame could try to inject to abort a legitimate\n // approval. For simplicity we drop unversioned close on messages\n // arriving from an authenticated iframe source and let the SDK's\n // timeout eventually fire.\n if (data.type === 'openkey:close') {\n // No protocol-version requirement enforced here because a\n // versionless close is a legitimate cancel from any widget\n // version; source+origin validation earlier is sufficient.\n }\n this.onMessage(data);\n };\n window.addEventListener('message', this.messageHandler);\n document.body.appendChild(this.root);\n }\n\n postMessage(message: object) {\n this.iframe.contentWindow?.postMessage(message, this.host);\n }\n\n /**\n * Sol final continuation contract requirement 5: bind the active\n * request correlation so subsequent resize (and future correlated)\n * messages can be verified against `requestId` + `protocolVersion`.\n *\n * The outer flow calls this right after creating the modal for a\n * versioned request, before the iframe can send anything, so no\n * uncorrelated resize is ever accepted for that request. Passing `null`\n * for both arguments means the flow is unversioned; passing `null` for\n * only one drops every resize.\n */\n setExpectedCorrelation(requestId: string | null, protocolVersion: number | null): void {\n this.expectedRequestId = requestId;\n this.expectedProtocolVersion = protocolVersion;\n }\n\n destroy() {\n window.removeEventListener('message', this.messageHandler);\n this.root.remove();\n }\n\n private close() {\n const backdrop = this.shadow.querySelector('.ok-backdrop');\n if (backdrop) {\n backdrop.classList.add('ok-exit');\n setTimeout(() => {\n this.destroy();\n this.onClose();\n }, 200);\n } else {\n this.destroy();\n this.onClose();\n }\n }\n}\n\nclass WalletPicker {\n private root: HTMLDivElement;\n private shadow: ShadowRoot;\n\n constructor(opts: { providers: EIP6963ProviderDetail[]; onSelect: (provider: EIP1193Provider) => void; onCancel: () => void }) {\n this.root = document.createElement('div');\n this.shadow = this.root.attachShadow({ mode: 'closed' });\n\n const style = document.createElement('style');\n style.textContent = `\n :host{all:initial}\n .wp-backdrop{position:fixed;inset:0;background:rgba(0,0,0,0.42);z-index:1000000;display:flex;align-items:center;justify-content:center;animation:wp-fade 150ms ease-out}\n .wp-card{background:#fff;width:340px;border-radius:16px;box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);padding:20px;animation:wp-scale 200ms ease-out}\n .wp-title{font:600 16px/1.3 system-ui,sans-serif;color:#111;margin:0 0 12px}\n .wp-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px}\n .wp-item{display:flex;align-items:center;gap:10px;padding:10px 12px;border:1px solid #e5e7eb;border-radius:10px;background:transparent;cursor:pointer;font:14px/1.3 system-ui,sans-serif;color:#111;width:100%;text-align:left;transition:border-color 150ms}\n .wp-item:hover{border-color:#6366f1}\n .wp-icon{width:28px;height:28px;border-radius:6px}\n .wp-empty{font:14px/1.4 system-ui,sans-serif;color:#6b7280;text-align:center;padding:16px 0}\n .wp-cancel{display:block;width:100%;margin-top:12px;padding:8px;border:none;background:transparent;color:#6b7280;font:14px/1.3 system-ui,sans-serif;cursor:pointer;border-radius:8px}\n .wp-cancel:hover{background:#f3f4f6;color:#111}\n @keyframes wp-fade{from{opacity:0}to{opacity:1}}\n @keyframes wp-scale{from{opacity:0;transform:scale(0.95)}to{opacity:1;transform:scale(1)}}\n @media(prefers-color-scheme:dark){\n .wp-card{background:#1a1a1a;box-shadow:0 25px 50px -12px rgba(0,0,0,0.5)}\n .wp-title{color:#f3f4f6}\n .wp-item{border-color:#374151;color:#f3f4f6}\n .wp-item:hover{border-color:#818cf8}\n .wp-empty{color:#9ca3af}\n .wp-cancel{color:#9ca3af}\n .wp-cancel:hover{background:#262626;color:#f3f4f6}\n }\n `;\n\n const backdrop = document.createElement('div');\n backdrop.className = 'wp-backdrop';\n backdrop.addEventListener('click', (e) => { if (e.target === backdrop) { this.destroy(); opts.onCancel(); } });\n\n const card = document.createElement('div');\n card.className = 'wp-card';\n\n const title = document.createElement('h2');\n title.className = 'wp-title';\n title.textContent = 'Select a wallet';\n card.appendChild(title);\n\n if (opts.providers.length === 0) {\n const empty = document.createElement('div');\n empty.className = 'wp-empty';\n empty.textContent = 'No wallets detected';\n card.appendChild(empty);\n } else {\n const list = document.createElement('ul');\n list.className = 'wp-list';\n for (const { info, provider } of opts.providers) {\n const item = document.createElement('button');\n item.className = 'wp-item';\n if (info.icon) {\n const icon = document.createElement('img');\n icon.className = 'wp-icon';\n icon.src = info.icon;\n icon.alt = info.name;\n item.appendChild(icon);\n }\n const name = document.createElement('span');\n name.textContent = info.name;\n item.appendChild(name);\n item.addEventListener('click', () => { this.destroy(); opts.onSelect(provider); });\n list.appendChild(item);\n }\n card.appendChild(list);\n }\n\n const cancel = document.createElement('button');\n cancel.className = 'wp-cancel';\n cancel.textContent = 'Cancel';\n cancel.addEventListener('click', () => { this.destroy(); opts.onCancel(); });\n card.appendChild(cancel);\n\n backdrop.appendChild(card);\n this.shadow.appendChild(style);\n this.shadow.appendChild(backdrop);\n document.body.appendChild(this.root);\n }\n\n destroy() {\n this.root.remove();\n }\n}\n\nfunction showToast(message = 'Opening in new window\\u2026', variant: 'info' | 'error' = 'info') {\n const bg = variant === 'error' ? '#dc2626' : '#1f2937';\n const root = document.createElement('div');\n const shadow = root.attachShadow({ mode: 'closed' });\n shadow.innerHTML = `<style>:host{all:initial}.ok-toast{position:fixed;top:16px;right:16px;z-index:1000000;background:${bg};color:#f9fafb;padding:10px 16px;border-radius:8px;font:14px/1.4 system-ui,sans-serif;box-shadow:0 4px 12px rgba(0,0,0,0.15);animation:ok-t-in 200ms ease-out;max-width:360px}@keyframes ok-t-in{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}</style><div class=\"ok-toast\">${message}</div>`;\n document.body.appendChild(root);\n setTimeout(() => root.remove(), 4000);\n}\n\nclass ExternalWalletError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ExternalWalletError';\n }\n}\n\nexport class OpenKey {\n private host: string;\n private oauthHost: string;\n private appName: string;\n private mode: OpenKeyMode;\n private passkeysSupported: boolean;\n private config: OpenKeyConfig;\n private popup: Window | null = null;\n private lastAuth: AuthResult | null = null;\n private discoveredProviders: EIP6963ProviderDetail[] = [];\n /** Cancels widget flows that could outlive a sign-out on this instance. */\n private activeFlowCancellations = new Set<() => void>();\n /**\n * Nostr identity custody + signing (secp256k1 Schnorr / BIP-340). Kept\n * fully separate from the Ethereum flows above: it never reuses\n * `lastAuth`, and its widget messages never carry a session token -\n * the OpenKey session and any signing grants stay inside\n * the OpenKey-origin iframe for the whole lifetime of this client.\n */\n readonly nostr: OpenKeyNostr;\n\n constructor(config: OpenKeyConfig = {}) {\n this.config = config;\n this.host = config.host || DEFAULT_HOST;\n this.oauthHost = config.oauthHost || this.deriveOAuthHost(this.host);\n this.appName = config.appName || window.location.hostname;\n this.mode = config.mode ?? 'iframe';\n this.passkeysSupported = config.passkeysSupported ?? true;\n this.nostr = new OpenKeyNostr(this.host, this.passkeysSupported);\n\n // Listen for EIP-6963 wallet announcements\n if (typeof window !== 'undefined') {\n this.discoveredProviders = [];\n window.addEventListener('eip6963:announceProvider', (event: any) => {\n this.discoveredProviders.push(event.detail);\n });\n window.dispatchEvent(new Event('eip6963:requestProvider'));\n }\n }\n\n /**\n * Derive the OAuth API host from the main host by prefixing 'api.'\n * @param host - The main host URL\n * @returns The derived OAuth API host URL\n */\n private deriveOAuthHost(host: string): string {\n try {\n const url = new URL(host);\n if (url.hostname === 'localhost' || url.hostname === '127.0.0.1') {\n return host.replace(/\\/$/, '');\n }\n url.hostname = 'api.' + url.hostname;\n return url.toString().replace(/\\/$/, '');\n } catch {\n return 'https://api.openkey.so';\n }\n }\n\n /**\n * Sol MAJOR-4 (final continuation): fetch the caller's registered keys\n * so `resolveAuthorizeTinyCloudRouting` can resolve an explicit pin\n * whose keyId does not match the active session key. Called only when\n * the caller passes a `requestKeyId` we do not already recognise; the\n * common no-pin path skips the network round-trip.\n *\n * Failures do NOT block routing — we fall through with `knownKeys=[]`\n * so the resolver's lastAuth-based fallback still runs. If the caller\n * pinned a genuinely unknown key that turns out to be external, the\n * widget rejects the server-signing path and the SDK surfaces that\n * error from the finalize call rather than silently routing wrong.\n */\n private async fetchKnownKeysIfNeeded(\n requestKeyId: string | undefined,\n ): Promise<Array<{ id: string; address?: string; keyType: 'MANAGED' | 'EXTERNAL' }>> {\n if (!requestKeyId) return [];\n // If lastAuth already identifies this key (id or address), we do not\n // need a network round-trip — the resolver adopts lastAuth.keyType.\n const la = this.lastAuth;\n if (la?.keyId === requestKeyId) return [];\n if (la?.address && la.address.toLowerCase() === requestKeyId.toLowerCase()) return [];\n if (requestKeyId.startsWith('external:')) return [];\n try {\n const res = await fetch(`${this.oauthHost}/api/keys`, {\n method: 'GET',\n credentials: 'include',\n });\n if (!res.ok) return [];\n const body = (await res.json()) as {\n keys?: Array<{ id: string; address?: string; keyType: 'MANAGED' | 'EXTERNAL' }>;\n };\n return Array.isArray(body?.keys) ? body.keys : [];\n } catch {\n return [];\n }\n }\n\n /**\n * Connect to OpenKey and get user's wallet address\n * Opens auth flow for user to select/create a key\n */\n async connect(opts?: { mode?: OpenKeyMode }): Promise<AuthResult> {\n const result = await this.openFlow<AuthResult>('connect', {\n type: 'openkey:auth:request',\n appName: this.appName,\n }, opts?.mode);\n this.lastAuth = result;\n return result;\n }\n\n /**\n * Signs the active OpenKey account out through the OpenKey-owned widget.\n *\n * The OpenKey-owned widget revokes the OpenKey session it holds itself;\n * the SDK never holds an OpenKey session token. Local SDK state is cleared\n * before opening the widget, including when remote revocation is\n * unavailable.\n */\n async signOut(opts?: { mode?: OpenKeyMode }): Promise<SignOutAcknowledgement> {\n const requestId = `ok-signout-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n // Redirect flows intentionally never resolve. Sign-out needs to return a\n // correlated acknowledgement, so use the OpenKey popup boundary instead.\n const mode = this.resolveMode(opts?.mode) === 'redirect' ? 'popup' : opts?.mode;\n\n // Stale connect/sign widgets must not later overwrite this signed-out\n // instance with their responses.\n this.cancelActiveFlows();\n // A failed/blocked widget must never leave this SDK instance authenticated.\n this.lastAuth = null;\n\n const acknowledgement = await this.openFlow<SignOutAcknowledgement>(\n 'sign-out',\n {\n type: 'openkey:sign-out:request',\n requestId,\n protocolVersion: 1,\n },\n mode,\n );\n\n if (acknowledgement.requestId !== requestId) {\n throw new Error('OpenKey signOut received an acknowledgement for a different request');\n }\n return acknowledgement;\n }\n\n /**\n * Always null. OpenKey no longer gives its session token to the embedding\n * page (TC-688): the token unlocked OpenKey's key and account APIs, not\n * just the requesting app's flows.\n *\n * @deprecated Kept so existing callers compile. Third-party server-side\n * signing uses an OAuth access token from the OpenKey OAuth flow.\n */\n getSessionToken(): string | null {\n return null;\n }\n\n /**\n * Endpoint for a TinyCloud auto-sign signing strategy. `token` is always\n * null; see {@link OpenKey.getSessionToken}.\n *\n * @deprecated The endpoint accepts an OAuth access token as its bearer.\n */\n tinycloudSigningOptions(): { endpoint: string; token: string | null } {\n return {\n endpoint: `${this.oauthHost}/api/delegate/sign`,\n token: null,\n };\n }\n\n /**\n * Link an external wallet to the user's OpenKey account\n * Opens link-wallet widget flow\n */\n async linkWallet(opts?: { mode?: OpenKeyMode }): Promise<{ address: string; keyId: string }> {\n return this.openFlow<{ address: string; keyId: string }>('link-wallet', {\n type: 'openkey:link-wallet:request',\n }, opts?.mode);\n }\n\n /**\n * Sign a message with the user's OpenKey wallet\n * For external keys, routes directly to the user's wallet provider\n */\n async signMessage(request: SignMessageRequest, opts?: { mode?: OpenKeyMode }): Promise<SignResult> {\n if (this.lastAuth?.keyType === 'EXTERNAL') {\n return this.signWithExternalWallet(request);\n }\n return this.signWithOpenKey(request, opts?.mode);\n }\n\n /**\n * Versioned TinyCloud authorization protocol (v1).\n *\n * Unlike `signMessage()` (which is contractually byte-exact — the returned\n * signature always verifies against the caller's exact bytes), this method\n * permits the user to narrow the requested capabilities before signing.\n * OpenKey may therefore regenerate the SIWE. The response carries\n * `signedMessage` — the exact bytes the signature actually verifies against.\n *\n * TinyCloud completes the session with `signedMessage`, not the original\n * `siwe` passed in. Consumers MUST use the returned bytes and MUST NOT\n * assume the returned grants are a superset of what they requested — the\n * user is allowed to remove any grant that is not required.\n *\n * Legacy `signMessage()` callers are unaffected: their exact-byte contract\n * remains preserved and OpenKey never rewrites their bytes.\n */\n async authorizeTinyCloud(\n request: TinyCloudAuthorizationRequestV1,\n opts?: { mode?: OpenKeyMode },\n ): Promise<TinyCloudAuthorizationResultV1> {\n if (request.protocolVersion !== 1) {\n throw new Error(\n `authorizeTinyCloud only supports protocolVersion 1; got ${request.protocolVersion}`,\n );\n }\n if (typeof request.siwe !== 'string' || !request.siwe) {\n throw new Error('authorizeTinyCloud requires a non-empty SIWE');\n }\n // Sol MAJOR-3 (continuation) + Sol MAJOR-4 (final): route to the\n // external-wallet preview→sign→finalize flow whenever the ACTIVE\n // authentication session is against an EXTERNAL key. External keys\n // are held by the user's browser wallet — OpenKey does not have\n // the private material, so it cannot execute the managed-key\n // widget-signs-server-side path.\n //\n // Sol's final continuation rejection: the prior check\n // `this.lastAuth?.keyId === explicitKeyId && ... === 'EXTERNAL'`\n // let an explicitly-supplied external keyId enter the managed\n // widget path whenever the caller's `explicitKeyId` did not match\n // `lastAuth.keyId` string-for-string (for example: caller passes\n // the address; lastAuth carries the internal key record id — same\n // key, different identifier). A user cannot be authenticated with\n // two different active session keys at once — the ONE active\n // session's `keyType` is therefore authoritative for routing.\n //\n // Routing rules (revised):\n // 1. If `lastAuth?.keyType === 'EXTERNAL'`, route to external\n // (the wallet holds the material; the widget cannot sign\n // server-side either way).\n // 2. If `lastAuth?.keyType === 'MANAGED'`, route to managed.\n // 3. If `lastAuth` is missing (no active session), route to\n // managed — the widget renders a connect flow first, and\n // once the user connects the widget resolves keyType from\n // the fresh session; if that turns out to be EXTERNAL the\n // widget itself refuses to server-sign and asks the SDK to\n // re-enter via the external path.\n //\n // This resolves the key type authoritatively from the ONE active\n // session rather than relying on a fragile keyId string match.\n // See `shouldRouteAuthorizeTinyCloudExternal` for the full\n // routing-decision rationale and its unit tests for every branch.\n // Sol MAJOR-4 (final continuation): resolve the target key first\n // and route by ITS type, not by lastAuth.keyType alone. When the\n // caller pins a request.keyId that differs from the active session\n // key, we fetch the caller's key list from the server so the pure\n // `resolveAuthorizeTinyCloudRouting` helper can decide by resolved\n // type (or throw on conflicting pins).\n let routing: AuthorizeTinyCloudRouting;\n try {\n const knownKeys = await this.fetchKnownKeysIfNeeded(request.keyId);\n routing = resolveAuthorizeTinyCloudRouting({\n lastAuth: this.lastAuth,\n requestKeyId: request.keyId,\n knownKeys,\n });\n } catch (e) {\n if (e instanceof KeyIdTypeMismatchError) throw e;\n throw e instanceof Error\n ? e\n : new Error('authorizeTinyCloud: failed to resolve target key type');\n }\n if (routing.route === 'external') {\n return this.authorizeTinyCloudExternal(request, opts);\n }\n // Sol CRITICAL-1: Send a DISTINCT versioned sign request so the widget\n // knows to route through the server-authoritative /authorize-sign\n // endpoint. protocolVersion: 1 with the extended payload triggers the\n // server-authoritative narrowing path — the widget refuses to fall\n // back to legacy exact-byte signMessage() for a versioned request\n // whose origin is real.\n const requestId = `ok-auth-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n // Sol MAJOR-3: fall back to the connected key when the caller did not\n // pass an explicit keyId. Without this fallback the widget renders\n // 'Please connect first.' because it has no key context, and the\n // NodeUserAuthorization bridge never carries a keyId when the caller\n // only ran connect() — the widget path is otherwise unable to sign.\n const resolvedKeyId = routing.resolvedKeyId ?? request.keyId ?? this.lastAuth?.keyId;\n const raw = await this.openFlow<{\n signature: string;\n address: string;\n signedMessage?: string;\n selectedActionKeys?: string[];\n permissions?: TinyCloudAuthorizationResultV1['permissions'];\n }>(\n 'sign',\n {\n type: 'openkey:sign:request',\n requestId,\n protocolVersion: 1,\n message: request.siwe,\n keyId: resolvedKeyId,\n // Forward JWK so the widget can pass it to /authorize-sign for\n // narrowed-SIWE regeneration.\n jwk: request.jwk,\n // Forward the TinyCloud host so the widget can bind it into the\n // /authorize-sign-prepare context (Sol MAJOR-2).\n host: request.host,\n // Sol MAJOR-2 (envelope): forward the caller-supplied presentation\n // envelope so the widget can render honest provenance and the\n // /authorize-sign-prepare route can bind it into the authorization\n // context. The envelope is display-only; the widget transport\n // validates and size-bounds it before use and NEVER treats it as\n // verified unless the server actually origin-binds a manifest.\n presentation: request.presentation,\n },\n opts?.mode,\n );\n // Sol CRITICAL-1: NO silent fallback to `request.siwe`. If the widget\n // returned an authorization response without `signedMessage`, that is\n // a protocol violation and MUST fail — silently accepting the caller's\n // original bytes as `signedMessage` while selectedActionKeys/permissions\n // reflect a narrower set is exactly the bug this rewrite prevents.\n if (typeof raw.signedMessage !== 'string' || !raw.signedMessage) {\n throw new Error(\n 'authorizeTinyCloud: widget returned no signedMessage — signature would not correspond to the displayed authorization',\n );\n }\n if (!Array.isArray(raw.selectedActionKeys)) {\n throw new Error(\n 'authorizeTinyCloud: widget returned no selectedActionKeys — cannot verify displayed authorization matches the signed bytes',\n );\n }\n if (!Array.isArray(raw.permissions)) {\n throw new Error(\n 'authorizeTinyCloud: widget returned no permissions — cannot verify displayed authorization matches the signed bytes',\n );\n }\n return {\n protocolVersion: 1,\n address: raw.address,\n signature: raw.signature,\n signedMessage: raw.signedMessage,\n selectedActionKeys: raw.selectedActionKeys,\n permissions: raw.permissions,\n };\n }\n\n /**\n * Sol MAJOR-3 (continuation): authorizeTinyCloud path for external keys.\n * The wallet lives outside OpenKey, so the SDK opens the shared widget\n * for review + preview, then invokes the user's wallet to sign the\n * preview bytes, then finalizes server-side via /authorize-sign.\n *\n * Flow:\n * 1. Open the widget with `externalSign: true` — the widget renders\n * the shared SigningApproval UI, calls /authorize-sign-prepare,\n * calls /authorize-sign-preview after the user approves a\n * selection, and hands back `{ previewApprovalToken,\n * signedMessage, selectedActionIds, address, authorizationContextToken }`.\n * 2. SDK invokes the user's wallet on the returned signedMessage.\n * 3. SDK POSTs /authorize-sign with `externalSignature`.\n *\n * Legacy exact-byte signMessage callers are unaffected — this path is\n * only taken via authorizeTinyCloud (protocolVersion:1) when the target\n * key is EXTERNAL. Sol's rejection required this path to go through\n * the same review UI as managed keys.\n */\n private async authorizeTinyCloudExternal(\n request: TinyCloudAuthorizationRequestV1,\n opts?: { mode?: OpenKeyMode },\n ): Promise<TinyCloudAuthorizationResultV1> {\n const keyId = request.keyId ?? this.lastAuth?.keyId;\n if (!keyId) {\n throw new Error(\n 'authorizeTinyCloud (external) requires a keyId — call connect() first or pass request.keyId',\n );\n }\n const walletAddress = this.lastAuth?.address;\n if (!walletAddress) {\n throw new Error(\n 'authorizeTinyCloud (external) requires a connected wallet — call connect() first',\n );\n }\n // Sol MAJOR-3 (continuation): open the shared widget UI so the user\n // sees and can narrow the review, identical to the managed-key flow.\n const requestId = `ok-ext-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n const approval = await this.openFlow<{\n authorizationContextToken: string;\n previewApprovalToken: string;\n signedMessage: string;\n selectedActionIds: string[];\n address: string;\n }>(\n 'sign',\n {\n type: 'openkey:sign:request',\n requestId,\n protocolVersion: 1,\n message: request.siwe,\n keyId,\n jwk: request.jwk,\n host: request.host,\n // Sol MAJOR-2 (envelope): forward the caller-supplied presentation\n // envelope. Same rules as the managed path — display-only, size-\n // bounded at the transport, never treated as verified without\n // server-side origin-binding.\n presentation: request.presentation,\n // Sol MAJOR-3 (continuation): tell the widget to hand us back\n // the previewApproval instead of asking OpenKey to sign\n // server-side with a managed key. The widget will still render\n // the SAME SigningApproval component; it just diverges at the\n // \"sign\" step and emits `openkey:externalSign:approve` back\n // through the transport.\n externalSign: true,\n } as unknown as MessageType,\n opts?.mode,\n );\n if (!approval?.previewApprovalToken || !approval?.signedMessage) {\n throw new Error(\n 'authorizeTinyCloud (external): widget did not return a previewApprovalToken + signedMessage',\n );\n }\n if (\n approval.address &&\n approval.address.toLowerCase() !== walletAddress.toLowerCase()\n ) {\n throw new Error(\n `authorizeTinyCloud (external): widget preview address ${approval.address} does not match connected wallet ${walletAddress}`,\n );\n }\n // Wallet signs the exact bytes the widget previewed.\n const provider = await this.findWalletProvider(walletAddress);\n const hexMessage = this.toHex(approval.signedMessage);\n const walletSignature = (await provider.request({\n method: 'personal_sign',\n params: [hexMessage, walletAddress],\n })) as string;\n // Finalize — server verifies the wallet signature against the exact\n // same bytes it emitted for the preview.\n const finalizeRes = await fetch(\n `${this.oauthHost}/api/delegate/authorize-sign`,\n {\n method: 'POST',\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n authorizationContextToken: approval.authorizationContextToken,\n previewApprovalToken: approval.previewApprovalToken,\n selectedActionIds: approval.selectedActionIds,\n protocolVersion: 1,\n externalSignature: walletSignature,\n }),\n },\n );\n if (!finalizeRes.ok) {\n const body = await finalizeRes.json().catch(() => ({ error: `HTTP ${finalizeRes.status}` }));\n throw new Error(body.error || `authorize-sign failed (${finalizeRes.status})`);\n }\n const finalize = await finalizeRes.json();\n if (finalize.signedMessage !== approval.signedMessage) {\n throw new Error(\n 'authorizeTinyCloud (external): server signed different bytes than the preview showed',\n );\n }\n return {\n protocolVersion: 1,\n address: finalize.address,\n signature: finalize.signature,\n signedMessage: finalize.signedMessage,\n selectedActionKeys: finalize.selectedActionKeys ?? [],\n permissions: finalize.permissions ?? [],\n };\n }\n\n /**\n * Sign typed data (EIP-712) with the user's OpenKey wallet\n * For external keys, routes directly to the user's wallet provider\n */\n async signTypedData(request: SignTypedDataRequest, opts?: { mode?: OpenKeyMode }): Promise<SignResult> {\n if (this.lastAuth?.keyType === 'EXTERNAL') {\n return this.signTypedDataWithExternalWallet(request);\n }\n return this.signTypedDataWithOpenKey(request, opts?.mode);\n }\n\n private providerCandidates(): EIP1193Provider[] {\n const providers: EIP1193Provider[] = [];\n if (this.config.externalProvider) {\n providers.push(this.config.externalProvider);\n }\n providers.push(...this.discoveredProviders.map(({ provider }) => provider));\n if (typeof window !== 'undefined' && (window as any).ethereum) {\n providers.push((window as any).ethereum as EIP1193Provider);\n }\n return [...new Set(providers)];\n }\n\n private async providerHasAccount(\n provider: EIP1193Provider,\n method: 'eth_accounts' | 'eth_requestAccounts',\n targetAddress: string\n ): Promise<boolean> {\n try {\n const accounts = await provider.request({ method }) as string[];\n return accounts.some((account) => account.toLowerCase() === targetAddress.toLowerCase());\n } catch {\n return false;\n }\n }\n\n /**\n * Find a wallet provider that controls the given address.\n * Checks connected accounts first, then asks the wallet to authorize the\n * app origin if the external key was linked elsewhere.\n */\n async findWalletProvider(targetAddress: string): Promise<EIP1193Provider> {\n const providers = this.providerCandidates();\n\n for (const provider of providers) {\n if (await this.providerHasAccount(provider, 'eth_accounts', targetAddress)) {\n return provider;\n }\n }\n\n for (const provider of providers) {\n if (await this.providerHasAccount(provider, 'eth_requestAccounts', targetAddress)) {\n return provider;\n }\n }\n\n throw new ExternalWalletError('External wallet not found. Connect the wallet that owns this key and try again.');\n }\n\n private async signWithExternalWallet(request: SignMessageRequest): Promise<SignResult> {\n let provider: EIP1193Provider;\n try {\n provider = await this.findWalletProvider(this.lastAuth!.address);\n } catch (e) {\n showToast((e as Error).message, 'error');\n throw e;\n }\n try {\n const hexMessage = this.toHex(request.message);\n const signature = await provider.request({\n method: 'personal_sign',\n params: [hexMessage, this.lastAuth!.address],\n });\n return { signature: signature as string, address: this.lastAuth!.address };\n } catch (e: any) {\n const msg = e?.message?.includes('not been authorized')\n ? 'Wallet rejected the request. Approve the connection in your wallet and try again.'\n : e?.message || 'Signing failed';\n showToast(msg, 'error');\n throw new Error(msg);\n }\n }\n\n private async signTypedDataWithExternalWallet(request: SignTypedDataRequest): Promise<SignResult> {\n let provider: EIP1193Provider;\n try {\n provider = await this.findWalletProvider(this.lastAuth!.address);\n } catch (e) {\n showToast((e as Error).message, 'error');\n throw e;\n }\n try {\n const signature = await provider.request({\n method: 'eth_signTypedData_v4',\n params: [this.lastAuth!.address, JSON.stringify(request)],\n });\n return { signature: signature as string, address: this.lastAuth!.address };\n } catch (e: any) {\n const msg = e?.message?.includes('not been authorized')\n ? 'Wallet rejected the request. Approve the connection in your wallet and try again.'\n : e?.message || 'Signing failed';\n showToast(msg, 'error');\n throw new Error(msg);\n }\n }\n\n private signWithOpenKey(request: SignMessageRequest, mode?: OpenKeyMode): Promise<SignResult> {\n return this.openFlow<SignResult>('sign', {\n type: 'openkey:sign:request',\n message: request.message,\n keyId: request.keyId,\n }, mode);\n }\n\n private signTypedDataWithOpenKey(request: SignTypedDataRequest, mode?: OpenKeyMode): Promise<SignResult> {\n return this.openFlow<SignResult>('sign-typed-data', {\n type: 'openkey:signTypedData:request',\n data: request,\n }, mode);\n }\n\n private toHex(str: string): string {\n return '0x' + Array.from(new TextEncoder().encode(str)).map(b => b.toString(16).padStart(2, '0')).join('');\n }\n\n /**\n * Check if user is already authenticated\n */\n async isConnected(): Promise<boolean> {\n // Check for existing session via API\n try {\n const res = await fetch(`${this.host}/api/auth/session`, {\n credentials: 'include',\n });\n if (!res.ok) return false;\n const data = await res.json();\n return !!data.user;\n } catch {\n return false;\n }\n }\n\n // ======= OAuth 2.1 Provider Methods =======\n\n /**\n * OAuth 2.1 methods for third-party app authentication\n * Use this when your app has registered OAuth client credentials with OpenKey\n */\n oauth = {\n /**\n * Start OAuth authorization flow\n * Opens popup/redirect to OpenKey authorization endpoint\n * @returns Promise that resolves with authorization code after user consent\n */\n connect: async (config: OAuthConfig): Promise<OAuthResult> => {\n // Generate PKCE values\n const verifier = generateCodeVerifier();\n const challenge = await generateCodeChallenge(verifier);\n const state = config.state || generateState();\n\n // Store for later token exchange\n sessionStorage.setItem(\n OAUTH_STORAGE_KEY,\n JSON.stringify({ verifier, state })\n );\n\n // Build authorization URL\n const authUrl = buildAuthorizationUrl({\n host: this.oauthHost,\n clientId: config.clientId,\n redirectUri: config.redirectUri,\n codeChallenge: challenge,\n state,\n scopes: ['openid'],\n });\n\n return this.openOAuthFlow(authUrl, state, config.redirectUri);\n },\n\n /**\n * Exchange authorization code for tokens\n * Call this after receiving the callback with authorization code\n * @param code - Authorization code from callback URL\n * @param config - Same config used for connect()\n * @returns Promise that resolves with access_token, id_token, etc.\n */\n exchangeCode: async (\n code: string,\n config: OAuthConfig\n ): Promise<OAuthTokenResponse> => {\n const stored = sessionStorage.getItem(OAUTH_STORAGE_KEY);\n if (!stored) {\n throw new Error('No PKCE verifier found. Start a new OAuth flow.');\n }\n\n const { verifier } = JSON.parse(stored);\n\n const response = await fetch(`${this.oauthHost}/api/auth/oauth2/token`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n redirect_uri: config.redirectUri,\n client_id: config.clientId,\n code_verifier: verifier,\n }),\n });\n\n // Clear stored verifier\n sessionStorage.removeItem(OAUTH_STORAGE_KEY);\n\n if (!response.ok) {\n const error = await response.json();\n throw new Error(error.error_description || 'Token exchange failed');\n }\n\n return response.json();\n },\n\n /**\n * Verify state parameter from callback\n * Call this before exchangeCode to prevent CSRF attacks\n * @param receivedState - State parameter from callback URL\n * @returns true if state matches, false otherwise\n */\n verifyState: (receivedState: string): boolean => {\n const stored = sessionStorage.getItem(OAUTH_STORAGE_KEY);\n if (!stored) return false;\n const { state } = JSON.parse(stored);\n return state === receivedState;\n },\n\n /**\n * Parse authorization response from callback URL\n * @param url - Callback URL (defaults to current window.location.href)\n * @returns Parsed code and state, or error\n */\n parseCallback: (\n url?: string\n ): { code: string; state: string } | { error: string; errorDescription?: string } => {\n const urlObj = new URL(url || window.location.href);\n const error = urlObj.searchParams.get('error');\n\n if (error) {\n return {\n error,\n errorDescription: urlObj.searchParams.get('error_description') || undefined,\n };\n }\n\n const code = urlObj.searchParams.get('code');\n const state = urlObj.searchParams.get('state');\n\n if (!code || !state) {\n return { error: 'missing_params', errorDescription: 'Missing code or state parameter' };\n }\n\n return { code, state };\n },\n };\n\n private openOAuthFlow(\n url: string,\n state: string,\n redirectUri: string\n ): Promise<OAuthResult> {\n return new Promise((resolve, reject) => {\n if (this.mode !== 'redirect') {\n this.openOAuthPopup(url, state, redirectUri, resolve, reject);\n } else {\n // Full page redirect - won't resolve, page navigates away\n window.location.href = url;\n }\n });\n }\n\n private openOAuthPopup(\n url: string,\n state: string,\n redirectUri: string,\n resolve: (value: OAuthResult) => void,\n reject: (error: OpenKeyError) => void\n ) {\n const left = window.screenX + (window.outerWidth - POPUP_WIDTH) / 2;\n const top = window.screenY + (window.outerHeight - POPUP_HEIGHT) / 2;\n\n this.popup = window.open(\n url,\n 'openkey-oauth',\n `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},popup=true`\n );\n\n if (!this.popup) {\n showToast('Popup was blocked. Please allow popups for this site.', 'error');\n reject({\n code: 'POPUP_BLOCKED',\n message: 'Popup was blocked. Please allow popups or use redirect mode.',\n });\n return;\n }\n\n const redirectHost = new URL(redirectUri).origin;\n\n // Poll for redirect back with code\n const pollInterval = setInterval(() => {\n try {\n if (this.popup?.closed) {\n clearInterval(pollInterval);\n clearTimeout(timeout);\n reject({\n code: 'USER_CANCELLED',\n message: 'User closed the popup',\n });\n return;\n }\n\n // Check if redirected to callback URL\n const popupUrl = this.popup?.location?.href;\n if (popupUrl && popupUrl.startsWith(redirectHost)) {\n clearInterval(pollInterval);\n clearTimeout(timeout);\n\n const urlObj = new URL(popupUrl);\n const code = urlObj.searchParams.get('code');\n const returnedState = urlObj.searchParams.get('state');\n const error = urlObj.searchParams.get('error');\n\n this.popup?.close();\n\n if (error) {\n reject({\n code: 'UNAUTHORIZED',\n message: urlObj.searchParams.get('error_description') || error,\n });\n return;\n }\n\n if (returnedState !== state) {\n reject({\n code: 'STATE_MISMATCH',\n message: 'State mismatch - possible CSRF attack',\n });\n return;\n }\n\n if (code) {\n resolve({ code, state: returnedState });\n } else {\n reject({\n code: 'UNAUTHORIZED',\n message: 'Authorization failed - no code returned',\n });\n }\n }\n } catch {\n // Cross-origin - popup still on OpenKey domain, continue polling\n }\n }, 100);\n\n // Timeout\n const timeout = setTimeout(() => {\n clearInterval(pollInterval);\n this.popup?.close();\n reject({\n code: 'TIMEOUT',\n message: 'OAuth flow timed out',\n });\n }, DEFAULT_TIMEOUT);\n }\n\n private resolveMode(override?: OpenKeyMode): OpenKeyMode {\n return override ?? this.mode;\n }\n\n private hasDetectedEoa(): boolean {\n if (this.discoveredProviders.length > 0) return true;\n if (typeof window !== 'undefined' && (window as any).ethereum) return true;\n return false;\n }\n\n private async openFlow<T>(action: string, message: object, modeOverride?: OpenKeyMode): Promise<T> {\n const mode = this.resolveMode(modeOverride);\n const origin = encodeURIComponent(window.location.origin);\n const eoaFlag = action === 'connect' && this.hasDetectedEoa() ? '&hasEoa=true' : '';\n const passkeysFlag = passkeysQueryFlag(this.passkeysSupported);\n\n if (mode === 'popup') {\n const url = `${this.host}/widget/${action}?origin=${origin}${eoaFlag}${passkeysFlag}`;\n return new Promise((resolve, reject) => this.openPopup(action, url, message, resolve, reject));\n }\n\n if (mode === 'redirect') {\n const url = `${this.host}/widget/${action}?origin=${origin}${eoaFlag}${passkeysFlag}`;\n window.location.href = url;\n return new Promise(() => {}); // never resolves, page navigates\n }\n\n // iframe mode with auto-fallback\n const url = `${this.host}/widget/embed/${action}?origin=${origin}${eoaFlag}${passkeysFlag}`;\n return this.openIframeModal<T>(url, action, message, origin);\n }\n\n private openIframeModal<T>(url: string, action: string, message: object, origin: string): Promise<T> {\n // Sol MAJOR-3: capture the outgoing request's correlation IDs so\n // response handlers can require them to match. Legacy unversioned\n // requests carry neither and skip correlation.\n const outgoingRequestId = (message as { requestId?: unknown }).requestId;\n const outgoingProtocolVersion = (message as { protocolVersion?: unknown }).protocolVersion;\n const isVersionedRequest =\n typeof outgoingRequestId === 'string' &&\n typeof outgoingProtocolVersion === 'number' &&\n outgoingProtocolVersion >= 1;\n return new Promise((resolve, reject) => {\n let readyReceived = false;\n let settled = false;\n let modal: IframeModal | null = null;\n let cancel: () => void;\n\n const settle = (fn: () => void) => {\n if (settled) return;\n settled = true;\n fn();\n };\n\n const cleanup = () => {\n clearTimeout(readyTimeout);\n clearTimeout(overallTimeout);\n modal?.destroy();\n modal = null;\n this.activeFlowCancellations.delete(cancel);\n };\n\n modal = new IframeModal({\n url,\n host: this.host,\n onClose: () => {\n settle(() => {\n cleanup();\n reject({ code: 'USER_CANCELLED', message: 'User cancelled the request' } as OpenKeyError);\n });\n },\n onMessage: (data: MessageType) => {\n if (data.type === 'openkey:ready') {\n readyReceived = true;\n modal?.postMessage(message);\n return;\n }\n // Sol MAJOR-3: correlate versioned responses. If the request\n // was versioned, drop any response that doesn't match the\n // outgoing requestId/protocolVersion. If the request was\n // unversioned (legacy), accept any response.\n if (isVersionedRequest) {\n const respRequestId = (data as { requestId?: unknown }).requestId;\n const respVersion = (data as { protocolVersion?: unknown }).protocolVersion;\n if (respRequestId !== outgoingRequestId) return;\n if (respVersion !== outgoingProtocolVersion) return;\n }\n\n if (data.type === 'openkey:close') {\n settle(() => {\n cleanup();\n reject({ code: 'USER_CANCELLED', message: 'User cancelled the request' } as OpenKeyError);\n });\n return;\n }\n\n if (data.type === 'openkey:link-wallet:delegate') {\n this.handleWalletLinkDelegation(modal!);\n return;\n }\n\n if (data.type === 'openkey:auth:use-external-wallet') {\n cleanup();\n this.handleExternalWalletConnect<T>(resolve, reject);\n return;\n }\n\n if (this.isResponseForAction(action, data)) {\n settle(() => {\n cleanup();\n if (data.success) {\n if (data.type === 'openkey:auth:response') {\n resolve({ address: data.address, keyId: data.keyId, keyType: data.keyType || 'MANAGED' } as T);\n } else if (data.type === 'openkey:link-wallet:response') {\n resolve({ address: data.address, keyId: data.keyId } as T);\n } else if (data.type === 'openkey:sign-out:response') {\n resolve({ requestId: data.requestId, revoked: data.revoked } as T);\n } else if (data.type === 'openkey:externalSign:approve') {\n resolve({\n authorizationContextToken: (data as any).authorizationContextToken,\n previewApprovalToken: (data as any).previewApprovalToken,\n signedMessage: (data as any).signedMessage,\n selectedActionIds: (data as any).selectedActionIds,\n address: (data as any).address,\n } as T);\n } else {\n resolve({\n signature: (data as any).signature,\n address: (data as any).address,\n signedMessage: (data as any).signedMessage,\n selectedActionKeys: (data as any).selectedActionKeys,\n permissions: (data as any).permissions,\n } as T);\n }\n } else {\n reject(data.error);\n }\n });\n }\n },\n });\n\n // Sol final continuation contract requirement 5: bind a versioned\n // request's correlation before the iframe can deliver any message,\n // so every resize for it must carry the exact (requestId,\n // protocolVersion) pair. Unversioned flows stay unbound and accept\n // only uncorrelated resizes from this iframe (TC-647).\n if (isVersionedRequest) {\n modal.setExpectedCorrelation(\n outgoingRequestId as string,\n outgoingProtocolVersion as number,\n );\n }\n\n // Auto-fallback: if no openkey:ready within 3s, fall back to popup\n const readyTimeout = setTimeout(() => {\n if (readyReceived || settled) return;\n cleanup();\n console.warn('OpenKey: iframe blocked by CSP, falling back to popup. Add frame-src https://openkey.so to your CSP.');\n showToast();\n const popupUrl = `${this.host}/widget/${action}?origin=${origin}${passkeysQueryFlag(this.passkeysSupported)}`;\n this.openPopup(action, popupUrl, message, (val: any) => settle(() => resolve(val)), (err: any) => settle(() => reject(err)));\n }, IFRAME_READY_TIMEOUT);\n\n // Overall 5-minute timeout\n const overallTimeout = setTimeout(() => {\n settle(() => {\n cleanup();\n reject({ code: 'TIMEOUT', message: 'Request timed out' } as OpenKeyError);\n });\n }, DEFAULT_TIMEOUT);\n\n cancel = () => {\n settle(() => {\n cleanup();\n reject({ code: 'USER_CANCELLED', message: 'Superseded by sign-out' } as OpenKeyError);\n });\n };\n this.activeFlowCancellations.add(cancel);\n });\n }\n\n private isResponseForAction(action: string, data: MessageType): data is WidgetResponseMessage {\n const type = data.type;\n if (action === 'connect') return type === 'openkey:auth:response';\n if (action === 'sign') return type === 'openkey:sign:response' || type === 'openkey:externalSign:approve';\n if (action === 'sign-typed-data') return type === 'openkey:signTypedData:response';\n if (action === 'link-wallet') return type === 'openkey:link-wallet:response';\n if (action === 'sign-out') return type === 'openkey:sign-out:response';\n return false;\n }\n\n private handleWalletLinkDelegation(modal: IframeModal) {\n const sendResult = (result: MessageType) => modal.postMessage(result);\n\n new WalletPicker({\n providers: this.discoveredProviders,\n onCancel: () => {\n sendResult({ type: 'openkey:link-wallet:result', success: false, error: { code: 'USER_CANCELLED', message: 'Wallet linking cancelled' } });\n },\n onSelect: async (provider) => {\n try {\n const accounts = await provider.request({ method: 'eth_requestAccounts' }) as string[];\n const address = accounts[0];\n if (!address) throw new Error('No account returned');\n\n // Get challenge from API\n const challengeRes = await fetch(`${this.host}/api/keys/link/challenge`, {\n method: 'POST',\n credentials: 'include',\n });\n if (!challengeRes.ok) throw new Error('Failed to get challenge');\n const { message } = await challengeRes.json();\n\n // Sign challenge with wallet\n const hexMessage = this.toHex(message);\n const signature = await provider.request({\n method: 'personal_sign',\n params: [hexMessage, address],\n }) as string;\n\n // Submit to API\n const linkRes = await fetch(`${this.host}/api/keys/link`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify({ address, signature, message }),\n });\n if (!linkRes.ok) {\n const err = await linkRes.json();\n throw new Error(err.error || 'Failed to link wallet');\n }\n const { key } = await linkRes.json();\n\n sendResult({ type: 'openkey:link-wallet:result', success: true, address: key.address, keyId: key.id });\n } catch (e: any) {\n sendResult({ type: 'openkey:link-wallet:result', success: false, error: { code: 'UNKNOWN', message: e.message || 'Wallet linking failed' } });\n }\n },\n });\n }\n\n private handleExternalWalletConnect<T>(\n resolve: (value: T) => void,\n reject: (error: OpenKeyError) => void\n ) {\n new WalletPicker({\n providers: this.discoveredProviders,\n onCancel: () => {\n reject({ code: 'USER_CANCELLED', message: 'User cancelled wallet selection' });\n },\n onSelect: async (provider) => {\n try {\n const accounts = await provider.request({ method: 'eth_requestAccounts' }) as string[];\n const address = accounts[0];\n if (!address) throw new Error('No account returned');\n const result = { address, keyId: `external:${address}`, keyType: 'EXTERNAL' as const };\n this.lastAuth = result;\n resolve(result as T);\n } catch (e: any) {\n reject({ code: 'UNKNOWN', message: e.message || 'Failed to connect wallet' });\n }\n },\n });\n }\n\n private openPopup<T>(\n action: string,\n url: string,\n message: object,\n resolve: (value: T) => void,\n reject: (error: OpenKeyError) => void\n ) {\n // Calculate popup position\n const left = window.screenX + (window.outerWidth - POPUP_WIDTH) / 2;\n const top = window.screenY + (window.outerHeight - POPUP_HEIGHT) / 2;\n\n const popup = window.open(\n url,\n `openkey-${action}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,\n `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},popup=true`\n );\n this.popup = popup;\n\n if (!popup) {\n showToast('Popup was blocked. Please allow popups for this site.', 'error');\n reject({\n code: 'POPUP_BLOCKED',\n message: 'Popup was blocked. Please allow popups for this site.',\n });\n return;\n }\n\n let settled = false;\n let cancel: () => void;\n const cleanup = () => {\n window.removeEventListener('message', handleMessage);\n clearInterval(pollClosed);\n clearTimeout(timeout);\n this.activeFlowCancellations.delete(cancel);\n if (this.popup === popup) this.popup = null;\n };\n\n const settle = (fn: () => void) => {\n if (settled) return;\n settled = true;\n cleanup();\n fn();\n };\n\n // Poll to detect popup close\n const pollClosed = setInterval(() => {\n if (popup.closed) {\n settle(() => reject({\n code: 'USER_CANCELLED',\n message: 'User closed the popup',\n }));\n }\n }, 500);\n\n // Timeout\n const timeout = setTimeout(() => {\n settle(() => {\n popup.close();\n reject({\n code: 'TIMEOUT',\n message: 'Request timed out',\n });\n });\n }, DEFAULT_TIMEOUT);\n\n // Sol MAJOR-3: correlation IDs for versioned popups.\n const outgoingRequestId = (message as { requestId?: unknown }).requestId;\n const outgoingProtocolVersion = (message as { protocolVersion?: unknown }).protocolVersion;\n const isVersionedRequest =\n typeof outgoingRequestId === 'string' &&\n typeof outgoingProtocolVersion === 'number' &&\n outgoingProtocolVersion >= 1;\n // Listen for messages\n const handleMessage = (event: MessageEvent) => {\n if (event.origin !== this.host) return;\n if (event.source !== popup) return;\n\n const data = event.data as MessageType;\n\n if (data.type === 'openkey:ready') {\n // Widget is ready, send our request\n popup.postMessage(message, this.host);\n return;\n }\n\n if (data.type === 'openkey:close') {\n // Sol MAJOR-4: correlate close messages to the current versioned\n // request. A same-origin, same-source stale close from a\n // previous /widget/sign window MUST NOT tear down the active\n // request. Unversioned close messages are only accepted on\n // unversioned flows (legacy signMessage callers).\n if (isVersionedRequest) {\n const closeRequestId = (data as { requestId?: unknown }).requestId;\n const closeVersion = (data as { protocolVersion?: unknown }).protocolVersion;\n if (closeRequestId !== outgoingRequestId) return;\n if (closeVersion !== outgoingProtocolVersion) return;\n }\n settle(() => {\n popup.close();\n reject({\n code: 'USER_CANCELLED',\n message: 'User cancelled the request',\n });\n });\n return;\n }\n\n if (data.type === 'openkey:auth:use-external-wallet') {\n settle(() => {\n popup.close();\n this.handleExternalWalletConnect<T>(resolve, reject);\n });\n return;\n }\n\n // Handle responses\n if (this.isResponseForAction(action, data)) {\n // Sol MAJOR-3: drop cross-correlated responses on versioned flows.\n if (isVersionedRequest) {\n const respRequestId = (data as { requestId?: unknown }).requestId;\n const respVersion = (data as { protocolVersion?: unknown }).protocolVersion;\n if (respRequestId !== outgoingRequestId) return;\n if (respVersion !== outgoingProtocolVersion) return;\n }\n settle(() => {\n popup.close();\n if (data.success) {\n if (data.type === 'openkey:auth:response') {\n resolve({ address: data.address, keyId: data.keyId, keyType: data.keyType || 'MANAGED' } as T);\n } else if (data.type === 'openkey:link-wallet:response') {\n resolve({ address: data.address, keyId: data.keyId } as T);\n } else if (data.type === 'openkey:sign-out:response') {\n resolve({ requestId: data.requestId, revoked: data.revoked } as T);\n } else if (data.type === 'openkey:externalSign:approve') {\n // Sol MAJOR-3 (continuation): hand the preview payload back\n // to authorizeTinyCloudExternal so it can invoke the wallet.\n resolve({\n authorizationContextToken: (data as any).authorizationContextToken,\n previewApprovalToken: (data as any).previewApprovalToken,\n signedMessage: (data as any).signedMessage,\n selectedActionIds: (data as any).selectedActionIds,\n address: (data as any).address,\n } as T);\n } else {\n resolve({\n signature: (data as any).signature,\n address: (data as any).address,\n signedMessage: (data as any).signedMessage,\n selectedActionKeys: (data as any).selectedActionKeys,\n permissions: (data as any).permissions,\n } as T);\n }\n } else {\n reject(data.error);\n }\n });\n }\n };\n\n window.addEventListener('message', handleMessage);\n cancel = () => {\n settle(() => {\n popup.close();\n reject({ code: 'USER_CANCELLED', message: 'Superseded by sign-out' });\n });\n };\n this.activeFlowCancellations.add(cancel);\n }\n\n private cancelActiveFlows() {\n for (const cancel of [...this.activeFlowCancellations]) cancel();\n }\n\n /**\n * Disconnect and close any open flows\n */\n disconnect() {\n this.cancelActiveFlows();\n this.popup?.close();\n this.popup = null;\n }\n}\n\n/**\n * EIP-1193 compatible provider that wraps an OpenKey instance.\n * Transparently routes signing to either OpenKey (managed keys) or the user's\n * wallet (external keys).\n */\n\nexport class OpenKeyProvider implements EIP1193Provider {\n private openkey: OpenKey;\n private address: string;\n private keyId: string;\n private keyType: 'MANAGED' | 'EXTERNAL';\n\n constructor(openkey: OpenKey, authResult: AuthResult) {\n this.openkey = openkey;\n this.address = authResult.address;\n this.keyId = authResult.keyId;\n this.keyType = authResult.keyType;\n }\n\n async request({ method, params }: { method: string; params?: any[] }): Promise<any> {\n switch (method) {\n case 'eth_accounts':\n case 'eth_requestAccounts':\n return [this.address];\n\n case 'eth_chainId':\n return '0x1'; // mainnet\n\n case 'personal_sign': {\n if (this.keyType === 'EXTERNAL') {\n try {\n const provider = await this.openkey.findWalletProvider(this.address);\n return await provider.request({ method, params });\n } catch (e: any) {\n showToast(e?.message || 'External wallet signing failed', 'error');\n throw e;\n }\n }\n // Managed key: route through OpenKey\n const message = this.hexToString(params![0] as string);\n const result = await this.openkey.signMessage({ message, keyId: this.keyId });\n return result.signature;\n }\n\n case 'eth_signTypedData_v4': {\n if (this.keyType === 'EXTERNAL') {\n try {\n const provider = await this.openkey.findWalletProvider(this.address);\n return await provider.request({ method, params });\n } catch (e: any) {\n showToast(e?.message || 'External wallet signing failed', 'error');\n throw e;\n }\n }\n const data = JSON.parse(params![1] as string);\n const result = await this.openkey.signTypedData(data);\n return result.signature;\n }\n\n default:\n throw new Error(`Unsupported method: ${method}`);\n }\n }\n\n private hexToString(hex: string): string {\n const bytes = new Uint8Array(\n (hex.startsWith('0x') ? hex.slice(2) : hex).match(/.{1,2}/g)!.map(b => parseInt(b, 16))\n );\n return new TextDecoder().decode(bytes);\n }\n}\n\n// Default export for convenience\nexport default OpenKey;\n\n// Create singleton instance\nlet defaultInstance: OpenKey | null = null;\n\nexport function getOpenKey(config?: OpenKeyConfig): OpenKey {\n if (!defaultInstance || config) {\n defaultInstance = new OpenKey(config);\n }\n return defaultInstance;\n}\n"],"mappings":";AAiBA,IAAMA,IAAe;AAMd,SAASC,EAAgBC,GAA4B;AAC1D,MAAIC,IAAS,IACPC,IAAMF,EAAO;AAEnB,WAASG,IAAI,GAAGA,IAAID,GAAKC,KAAK,GAAG;AAC/B,QAAMC,IAAKJ,EAAOG,CAAC,GACbE,IAAKF,IAAI,IAAID,IAAMF,EAAOG,IAAI,CAAC,IAAK,GACpCG,IAAKH,IAAI,IAAID,IAAMF,EAAOG,IAAI,CAAC,IAAK,GAEpCI,IAAWH,KAAM,KAAOC,KAAM,IAAKC;AAEzCL,SAAUH,EAAcS,KAAW,KAAM,EAAI,GAC7CN,KAAUH,EAAcS,KAAW,KAAM,EAAI,GAC7CN,KAAUE,IAAI,IAAID,IAAMJ,EAAcS,KAAW,IAAK,EAAI,IAAI,IAC9DN,KA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eAAO,OAAO;AAAA,MAChB;AAAA,MAEA,KAAK,wBAAwB;AAC3B,YAAI,KAAK,YAAY,YAAY;AAC/B,cAAI;AACF,kBAAM,WAAW,MAAM,KAAK,QAAQ,mBAAmB,KAAK,OAAO;AACnE,mBAAO,MAAM,SAAS,QAAQ,EAAE,QAAQ,OAAO,CAAC;AAAA,UAClD,SAAS,GAAQ;AACf,sBAAU,GAAG,WAAW,kCAAkC,OAAO;AACjE,kBAAM;AAAA,UACR;AAAA,QACF;AACA,cAAM,OAAO,KAAK,MAAM,OAAQ,CAAC,CAAW;AAC5C,cAAM,SAAS,MAAM,KAAK,QAAQ,cAAc,IAAI;AACpD,eAAO,OAAO;AAAA,MAChB;AAAA,MAEA;AACE,cAAM,IAAI,MAAM,uBAAuB,MAAM,EAAE;AAAA,IACnD;AAAA,EACF;AAAA,EAEQ,YAAY,KAAqB;AACvC,UAAM,QAAQ,IAAI;AAAA,OACf,IAAI,WAAW,IAAI,IAAI,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM,SAAS,EAAG,IAAI,OAAK,SAAS,GAAG,EAAE,CAAC;AAAA,IACxF;AACA,WAAO,IAAI,YAAY,EAAE,OAAO,KAAK;AAAA,EACvC;AACF;AAGA,IAAO,gBAAQ;AAGf,IAAI,kBAAkC;AAE/B,SAAS,WAAW,QAAiC;AAC1D,MAAI,CAAC,mBAAmB,QAAQ;AAC9B,sBAAkB,IAAI,QAAQ,MAAM;AAAA,EACtC;AACA,SAAO;AACT;","names":["BASE64_CHARS","base64UrlEncode","buffer","base64","len","i","b0","b1","b2","triplet","generateCodeVerifier","array","defaultSha256","input","data","digest","generateCodeChallenge","verifier","sha256","generateState","buildAuthorizationUrl","options","host","clientId","redirectUri","codeChallenge","state","scopes","authorizePath","url","k","url"]}