@entros/verify 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/EntrosVerify.tsx","../src/messaging.ts","../src/url.ts","../src/popup-manager.ts"],"sourcesContent":["/**\n * `@entros/verify` — public surface.\n *\n * Drop-in React component for Entros verification. See\n * https://entros.io and https://docs.entros.io/integrate/verify.\n */\n\nexport { EntrosVerify } from \"./EntrosVerify\";\nexport type { EntrosVerifyProps } from \"./EntrosVerify\";\nexport type {\n Cluster,\n EntrosVerifyError,\n EntrosVerifyErrorReason,\n EntrosVerifyProgress,\n EntrosVerifyProgressStatus,\n EntrosVerifyResult,\n} from \"./types\";\n","/**\n * <EntrosVerify> — drop-in trigger for the Entros verification popup.\n *\n * Renders a button. On click, opens a popup window to entros.io. User\n * completes wallet-connected verification inside the popup; the popup\n * posts the result back via postMessage; this component fires the\n * integrator's onVerified callback.\n *\n * See README and `EntrosVerifyProps` for usage.\n */\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { CSSProperties, ReactElement, ReactNode } from \"react\";\n\nimport { openVerifyPopup, type PopupHandle } from \"./popup-manager\";\nimport type {\n Cluster,\n EntrosVerifyError,\n EntrosVerifyErrorReason,\n EntrosVerifyProgress,\n EntrosVerifyResult,\n} from \"./types\";\n\nconst DEFAULT_BASE_ORIGIN = \"https://entros.io\";\nconst DEFAULT_POPUP_WIDTH = 480;\nconst DEFAULT_POPUP_HEIGHT = 720;\n/**\n * After a verification settles (done or error), state returns to idle so\n * the component is ready for re-use without consumer intervention. Long\n * enough to render the brief \"done\" / \"error\" UX without blocking re-clicks.\n */\nconst SETTLE_RESET_MS = 1500;\n\nexport interface EntrosVerifyProps {\n /** Integrator key registered with Entros. Required. */\n integratorKey: string;\n /** Solana cluster. Defaults to \"devnet\". v1 supports devnet only. */\n cluster?: Cluster;\n /**\n * Optional Trust Score floor. The popup runs the verification regardless\n * and reports the result; if `minTrustScore` is set and the resulting\n * score is below it, the popup posts `entros/error` with reason\n * `validation_failed` instead of `entros/verified`.\n */\n minTrustScore?: number;\n /** Called on successful verification. Required. */\n onVerified: (result: EntrosVerifyResult) => void;\n /** Called on any failure or cancellation. Optional. */\n onError?: (error: EntrosVerifyError) => void;\n /** Called on progress heartbeats from the popup. Optional. */\n onProgress?: (progress: EntrosVerifyProgress) => void;\n /** Popup width in CSS pixels. Defaults to 480. */\n popupWidth?: number;\n /** Popup height in CSS pixels. Defaults to 720. */\n popupHeight?: number;\n /** See README.md#full-api for timeout behavior and the default. */\n timeoutMs?: number;\n /** Custom button content. Defaults to \"Verify with Entros\". */\n children?: ReactNode;\n /** className applied to the trigger button. */\n className?: string;\n /** Inline style applied to the trigger button. */\n style?: CSSProperties;\n /**\n * If true, when the popup is blocked the component renders an inline\n * retry button. Clicking it triggers a fresh window.open from a confirmed\n * user gesture, which most browsers allow. Defaults to true.\n */\n popupBlockedFallback?: boolean;\n /**\n * INTERNAL: Override the entros.io base origin. Intended for end-to-end\n * testing against a localhost popup host. Production consumers should\n * not set this.\n */\n baseOrigin?: string;\n}\n\ntype State =\n | { kind: \"idle\" }\n | { kind: \"opening\" }\n | { kind: \"blocked\" }\n | { kind: \"waiting\" }\n | { kind: \"done\" }\n | { kind: \"error\"; reason: EntrosVerifyErrorReason };\n\nexport function EntrosVerify(props: EntrosVerifyProps): ReactElement {\n const [state, setState] = useState<State>({ kind: \"idle\" });\n const handleRef = useRef<PopupHandle | null>(null);\n const resetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n // Refs hold the latest callbacks so trigger stays stable across re-renders\n // even when consumers pass inline arrow functions. Avoids unnecessary\n // re-creation of the click handler on every parent render.\n const onVerifiedRef = useRef(props.onVerified);\n const onErrorRef = useRef(props.onError);\n const onProgressRef = useRef(props.onProgress);\n useEffect(() => {\n onVerifiedRef.current = props.onVerified;\n onErrorRef.current = props.onError;\n onProgressRef.current = props.onProgress;\n });\n\n // Tear down any in-flight popup + reset timer on unmount.\n useEffect(() => {\n return () => {\n if (handleRef.current) {\n handleRef.current.cancel();\n handleRef.current = null;\n }\n if (resetTimerRef.current !== null) {\n clearTimeout(resetTimerRef.current);\n resetTimerRef.current = null;\n }\n };\n }, []);\n\n const scheduleReset = useCallback(() => {\n if (resetTimerRef.current !== null) {\n clearTimeout(resetTimerRef.current);\n }\n resetTimerRef.current = setTimeout(() => {\n resetTimerRef.current = null;\n setState({ kind: \"idle\" });\n }, SETTLE_RESET_MS);\n }, []);\n\n const trigger = useCallback(() => {\n if (resetTimerRef.current !== null) {\n clearTimeout(resetTimerRef.current);\n resetTimerRef.current = null;\n }\n setState({ kind: \"opening\" });\n\n const handle = openVerifyPopup({\n baseOrigin: props.baseOrigin ?? DEFAULT_BASE_ORIGIN,\n integratorKey: props.integratorKey,\n cluster: props.cluster ?? \"devnet\",\n minTrustScore: props.minTrustScore,\n popupWidth: props.popupWidth ?? DEFAULT_POPUP_WIDTH,\n popupHeight: props.popupHeight ?? DEFAULT_POPUP_HEIGHT,\n timeoutMs: props.timeoutMs,\n onVerified: (result) => {\n handleRef.current = null;\n setState({ kind: \"done\" });\n onVerifiedRef.current(result);\n scheduleReset();\n },\n onError: (error) => {\n handleRef.current = null;\n setState({ kind: \"error\", reason: error.reason });\n onErrorRef.current?.(error);\n scheduleReset();\n },\n onProgress: (progress) => {\n onProgressRef.current?.(progress);\n },\n });\n\n if (handle === null) {\n setState({ kind: \"blocked\" });\n onErrorRef.current?.({ reason: \"popup_blocked\" });\n return;\n }\n\n handleRef.current = handle;\n setState({ kind: \"waiting\" });\n }, [\n props.baseOrigin,\n props.cluster,\n props.integratorKey,\n props.minTrustScore,\n props.popupHeight,\n props.popupWidth,\n props.timeoutMs,\n scheduleReset,\n ]);\n\n const isWaiting = state.kind === \"opening\" || state.kind === \"waiting\";\n const showFallback =\n state.kind === \"blocked\" && (props.popupBlockedFallback ?? true);\n\n return (\n <div className=\"entros-verify-container\" data-state={state.kind}>\n <button\n type=\"button\"\n onClick={trigger}\n disabled={isWaiting}\n className={props.className}\n style={props.style}\n >\n {isWaiting\n ? \"Verifying…\"\n : (props.children ?? \"Verify with Entros\")}\n </button>\n {showFallback && (\n <div role=\"alert\" className=\"entros-verify-blocked\">\n <span>Popup blocked. </span>\n <button type=\"button\" onClick={trigger} className={props.className}>\n Click here to open verification\n </button>\n </div>\n )}\n </div>\n );\n}\n","/**\n * Type guards and validation for postMessage envelopes received from the\n * Entros verify popup. The component is the trust boundary — every message\n * arriving on `window` is hostile until proven otherwise.\n *\n * Validation order in popup-manager.ts:\n * 1. event.origin matches expected popup origin (caller's responsibility)\n * 2. isEntrosMessage(event.data)\n * 3. event.data.request_id matches the parent's expected ID\n * 4. isFreshMessage(event.data)\n * 5. payload-specific guard for the message type\n *\n * Skipping any step is a security regression.\n */\n\nimport type {\n EntrosMessage,\n ErrorPayload,\n HeartbeatPayload,\n VerifiedPayload,\n} from \"./types\";\n\n/**\n * Maximum allowed clock drift between popup and parent. 90 seconds.\n *\n * The popup timestamps each message when it posts it. This window checks\n * delivery freshness and does not limit total verification duration.\n */\nconst MAX_TIMESTAMP_DRIFT_MS = 90 * 1000;\n\n/** Allowed error reason values on the wire. */\nconst ERROR_REASONS = new Set<string>([\n \"wallet_rejected\",\n \"validation_failed\",\n \"network_error\",\n \"user_canceled\",\n \"origin_invalid\",\n \"popup_blocked\",\n \"timeout\",\n \"unknown\",\n]);\n\nconst HEARTBEAT_STATUSES = new Set<string>([\n \"wallet_connecting\",\n \"capturing\",\n \"proving\",\n \"submitting\",\n \"attesting\",\n]);\n\nconst ENTROS_MESSAGE_TYPES = new Set<string>([\n \"entros/verified\",\n \"entros/error\",\n \"entros/heartbeat\",\n]);\n\nconst CLUSTERS = new Set<string>([\"devnet\"]);\n\nexport function isEntrosMessage(data: unknown): data is EntrosMessage {\n if (typeof data !== \"object\" || data === null) return false;\n const msg = data as Record<string, unknown>;\n return (\n msg.source === \"entros\" &&\n msg.version === 1 &&\n typeof msg.type === \"string\" &&\n ENTROS_MESSAGE_TYPES.has(msg.type) &&\n typeof msg.request_id === \"string\" &&\n msg.request_id.length > 0 &&\n typeof msg.timestamp === \"number\" &&\n Number.isFinite(msg.timestamp) &&\n \"payload\" in msg\n );\n}\n\nexport function isFreshMessage(msg: EntrosMessage, now: number = Date.now()): boolean {\n return Math.abs(now - msg.timestamp) < MAX_TIMESTAMP_DRIFT_MS;\n}\n\nexport function isVerifiedPayload(payload: unknown): payload is VerifiedPayload {\n if (typeof payload !== \"object\" || payload === null) return false;\n const p = payload as Record<string, unknown>;\n return (\n typeof p.wallet_pubkey === \"string\" &&\n p.wallet_pubkey.length > 0 &&\n typeof p.attestation_pda === \"string\" &&\n p.attestation_pda.length > 0 &&\n typeof p.tx_sig === \"string\" &&\n p.tx_sig.length > 0 &&\n typeof p.trust_score === \"number\" &&\n Number.isFinite(p.trust_score) &&\n p.trust_score >= 0 &&\n typeof p.cluster === \"string\" &&\n CLUSTERS.has(p.cluster)\n );\n}\n\nexport function isErrorPayload(payload: unknown): payload is ErrorPayload {\n if (typeof payload !== \"object\" || payload === null) return false;\n const p = payload as Record<string, unknown>;\n return typeof p.reason === \"string\" && ERROR_REASONS.has(p.reason);\n}\n\nexport function isHeartbeatPayload(payload: unknown): payload is HeartbeatPayload {\n if (typeof payload !== \"object\" || payload === null) return false;\n const p = payload as Record<string, unknown>;\n return typeof p.status === \"string\" && HEARTBEAT_STATUSES.has(p.status);\n}\n","/**\n * URL builders for the Entros verify popup.\n *\n * The component constructs the popup URL deterministically from the\n * integrator's props. The popup host validates every field server-side;\n * these helpers exist to fail loudly on the integrator's side when a\n * misconfiguration would have wasted a popup roundtrip.\n */\n\nimport type { Cluster } from \"./types\";\n\nconst VALID_INTEGRATOR_KEY = /^[a-z0-9_-]{1,64}$/;\nconst ORIGIN_PATTERN = /^https?:\\/\\/[^/]+$/;\n\nexport interface BuildPopupUrlOptions {\n /** entros.io base origin. Override for E2E testing only. */\n baseOrigin: string;\n integratorKey: string;\n /** Caller's window origin — popup posts back to this. */\n parentOrigin: string;\n cluster: Cluster;\n requestId: string;\n minTrustScore?: number;\n}\n\nexport function buildPopupUrl(opts: BuildPopupUrlOptions): string {\n if (opts.cluster !== \"devnet\") {\n throw new Error(\"Unsupported cluster: @entros/verify currently supports devnet only\");\n }\n if (!VALID_INTEGRATOR_KEY.test(opts.integratorKey)) {\n throw new Error(\n `Invalid integratorKey: must match /^[a-z0-9_-]{1,64}$/ (got \"${opts.integratorKey}\")`,\n );\n }\n if (!ORIGIN_PATTERN.test(opts.parentOrigin)) {\n throw new Error(\n `Invalid parentOrigin: must be a fully-qualified origin (got \"${opts.parentOrigin}\")`,\n );\n }\n if (opts.minTrustScore !== undefined) {\n if (\n !Number.isInteger(opts.minTrustScore) ||\n opts.minTrustScore < 0 ||\n opts.minTrustScore > 10000\n ) {\n throw new Error(\n `Invalid minTrustScore: must be an integer in [0, 10000] (got ${String(opts.minTrustScore)})`,\n );\n }\n }\n\n const url = new URL(\"/embed/verify-popup\", opts.baseOrigin);\n url.searchParams.set(\"integrator\", opts.integratorKey);\n url.searchParams.set(\"parent_origin\", opts.parentOrigin);\n url.searchParams.set(\"cluster\", opts.cluster);\n url.searchParams.set(\"request_id\", opts.requestId);\n if (opts.minTrustScore !== undefined) {\n url.searchParams.set(\"min_trust_score\", String(opts.minTrustScore));\n }\n return url.toString();\n}\n\n/**\n * Generates a cryptographically random request ID for replay protection.\n * Uses crypto.randomUUID when available (modern browsers + Node 19+).\n * Falls back to crypto.getRandomValues (broadly supported back to IE11)\n * formatted as a UUIDv4. Math.random is never used.\n */\nexport function generateRequestId(): string {\n if (typeof crypto === \"undefined\") {\n throw new Error(\n \"crypto is unavailable in this environment; @entros/verify requires a secure context\",\n );\n }\n if (typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n if (typeof crypto.getRandomValues !== \"function\") {\n throw new Error(\n \"crypto.getRandomValues is unavailable; @entros/verify requires a secure context\",\n );\n }\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n // RFC 4122 v4 framing: bits 6-7 of byte 8 are 0b10, bits 12-15 of byte 6\n // are 0b0100. The remaining bits are random.\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\"));\n return (\n hex.slice(0, 4).join(\"\") +\n \"-\" +\n hex.slice(4, 6).join(\"\") +\n \"-\" +\n hex.slice(6, 8).join(\"\") +\n \"-\" +\n hex.slice(8, 10).join(\"\") +\n \"-\" +\n hex.slice(10, 16).join(\"\")\n );\n}\n","/**\n * Popup-window state machine for `<EntrosVerify>`.\n *\n * Owns: window.open, postMessage listener, popup.closed polling, timeout.\n * Boundary with the React layer: open → returns a handle (or null if blocked).\n * Component is responsible for rendering the trigger button and the\n * popup-blocked fallback UI.\n *\n * Security model — every postMessage from the popup is treated as hostile\n * until proven otherwise. Validation order (skipping any step is a\n * regression):\n * 1. event.origin === expectedPopupOrigin\n * 2. event.source === popup (the window we opened, not a sibling tab)\n * 3. envelope shape matches `EntrosMessage` (version, source, type)\n * 4. event.data.request_id === this popup's request_id (replay defense)\n * 5. timestamp within drift window (90s)\n * 6. payload-specific guard for the message type\n */\n\nimport {\n isEntrosMessage,\n isErrorPayload,\n isFreshMessage,\n isHeartbeatPayload,\n isVerifiedPayload,\n} from \"./messaging\";\nimport type {\n Cluster,\n EntrosVerifyError,\n EntrosVerifyErrorReason,\n EntrosVerifyProgress,\n EntrosVerifyResult,\n} from \"./types\";\nimport { buildPopupUrl, generateRequestId } from \"./url\";\n\nconst DEFAULT_TIMEOUT_MS = 9 * 60 * 1000;\nconst POPUP_CLOSED_POLL_MS = 500;\n\n/**\n * Grace period after detecting popup.closed before firing user_canceled.\n * Lets the final `entros/verified` message arrive when the popup posts\n * and self-closes within the same event-loop turn.\n */\nconst POPUP_CLOSED_GRACE_MS = 1500;\n\n/**\n * After a popup-emitted outcome (`entros/verified` or `entros/error`),\n * the popup owns its own close — its success / failure surface renders\n * and either self-closes or waits for explicit user action (e.g., the\n * baseline-stale recovery surface). The parent only force-closes after\n * this defensive fallback in case the popup fails to close itself.\n * Generous enough to allow interactive failure surfaces to be read and\n * acted on; short enough that an abandoned popup eventually dies.\n */\nconst POPUP_OWNED_FALLBACK_CLOSE_MS = 30_000;\n\nexport interface OpenPopupOptions {\n baseOrigin: string;\n integratorKey: string;\n cluster: Cluster;\n minTrustScore?: number;\n popupWidth: number;\n popupHeight: number;\n timeoutMs?: number;\n onVerified: (result: EntrosVerifyResult) => void;\n onError: (error: EntrosVerifyError) => void;\n onProgress?: (progress: EntrosVerifyProgress) => void;\n}\n\nexport interface PopupHandle {\n /**\n * Force-cancel the popup. Closes the window if still open, fires\n * onError({reason: \"user_canceled\"}), and tears down listeners.\n * Idempotent.\n */\n cancel: () => void;\n}\n\nexport function openVerifyPopup(opts: OpenPopupOptions): PopupHandle | null {\n if (typeof window === \"undefined\") {\n throw new Error(\"openVerifyPopup must be called in a browser context\");\n }\n\n const requestId = generateRequestId();\n const parentOrigin = window.location.origin;\n const url = buildPopupUrl({\n baseOrigin: opts.baseOrigin,\n integratorKey: opts.integratorKey,\n parentOrigin,\n cluster: opts.cluster,\n requestId,\n minTrustScore: opts.minTrustScore,\n });\n\n const left = Math.max(\n 0,\n Math.floor((window.screen.availWidth - opts.popupWidth) / 2),\n );\n const top = Math.max(\n 0,\n Math.floor((window.screen.availHeight - opts.popupHeight) / 2),\n );\n const features = [\n `width=${opts.popupWidth}`,\n `height=${opts.popupHeight}`,\n `left=${left}`,\n `top=${top}`,\n \"menubar=no\",\n \"toolbar=no\",\n // location=yes lets the user verify entros.io in the URL bar.\n \"location=yes\",\n \"status=no\",\n \"resizable=yes\",\n \"scrollbars=yes\",\n ].join(\",\");\n\n // Unique window name per popup. A fixed name causes collision when an\n // integrator renders multiple <EntrosVerify> on one page — the second\n // window.open would reuse the existing popup.\n const popupName = `entros_verify_${requestId}`;\n const rawPopup = window.open(url, popupName, features);\n if (!rawPopup || rawPopup.closed) {\n return null;\n }\n // Narrow once so closures below see the non-null type.\n const popup: Window = rawPopup;\n\n const expectedPopupOrigin = new URL(opts.baseOrigin).origin;\n\n let settled = false;\n let pollTimerId: ReturnType<typeof setInterval> | null = null;\n let timeoutTimerId: ReturnType<typeof setTimeout> | null = null;\n let popupClosedAtMs: number | null = null;\n\n function clearListenersAndTimers(): void {\n window.removeEventListener(\"message\", onMessage);\n if (pollTimerId !== null) {\n clearInterval(pollTimerId);\n pollTimerId = null;\n }\n if (timeoutTimerId !== null) {\n clearTimeout(timeoutTimerId);\n timeoutTimerId = null;\n }\n }\n\n function forceClosePopup(): void {\n if (popup && !popup.closed) {\n try {\n popup.close();\n } catch {\n // Defensive only. We opened this window so we own the close permission;\n // this branch is for esoteric extension or browser-quirk edge cases.\n }\n }\n }\n\n function settleVerified(result: EntrosVerifyResult): void {\n if (settled) return;\n settled = true;\n // The popup owns its own close on the verified path so its\n // recognition surface (`Verified.` checkmark) is visible to the user\n // before the window dies. Parent only force-closes as a defensive\n // fallback in case the popup fails to close itself.\n clearListenersAndTimers();\n setTimeout(forceClosePopup, POPUP_OWNED_FALLBACK_CLOSE_MS);\n opts.onVerified(result);\n }\n\n /**\n * @param forceImmediateClose\n * - false (default) — error came from a popup-emitted `entros/error`\n * message; the popup is still alive and rendering its own\n * `PopupFailure` (auto-close) or interactive recovery surface\n * (e.g., baseline-stale). Parent waits the fallback window before\n * force-closing so the user sees the failure category.\n * - true — error came from the parent (timeout, user cancel, or\n * polling detected the popup already closed). No popup-side\n * surface to preserve; force-close immediately.\n */\n function settleError(\n reason: EntrosVerifyErrorReason,\n forceImmediateClose = false,\n ): void {\n if (settled) return;\n settled = true;\n clearListenersAndTimers();\n if (forceImmediateClose) {\n forceClosePopup();\n } else {\n setTimeout(forceClosePopup, POPUP_OWNED_FALLBACK_CLOSE_MS);\n }\n opts.onError({ reason });\n }\n\n function onMessage(event: MessageEvent): void {\n if (settled) return;\n\n // Origin gate — first and most important check.\n if (event.origin !== expectedPopupOrigin) return;\n\n // Source gate — defense-in-depth against another same-origin tab on\n // entros.io (e.g., the standalone /verify route open in a sibling tab)\n // posting a forged message. Only the popup we opened is authoritative.\n if (event.source !== popup) return;\n\n if (!isEntrosMessage(event.data)) return;\n\n // Replay protection — request_id must match this popup's ID.\n if (event.data.request_id !== requestId) return;\n\n if (!isFreshMessage(event.data)) return;\n\n switch (event.data.type) {\n case \"entros/verified\": {\n if (isVerifiedPayload(event.data.payload)) {\n settleVerified({\n walletPubkey: event.data.payload.wallet_pubkey,\n attestationPda: event.data.payload.attestation_pda,\n txSig: event.data.payload.tx_sig,\n trustScore: event.data.payload.trust_score,\n cluster: event.data.payload.cluster,\n });\n }\n break;\n }\n case \"entros/error\": {\n if (isErrorPayload(event.data.payload)) {\n settleError(event.data.payload.reason);\n }\n break;\n }\n case \"entros/heartbeat\": {\n if (isHeartbeatPayload(event.data.payload) && opts.onProgress) {\n opts.onProgress({ status: event.data.payload.status });\n }\n break;\n }\n }\n }\n\n function onPoll(): void {\n if (settled) return;\n if (popup.closed) {\n // Start the grace period the first time we observe the close.\n if (popupClosedAtMs === null) {\n popupClosedAtMs = Date.now();\n return;\n }\n if (Date.now() - popupClosedAtMs >= POPUP_CLOSED_GRACE_MS) {\n settleError(\"user_canceled\", true);\n }\n } else {\n popupClosedAtMs = null;\n }\n }\n\n function onTimeout(): void {\n settleError(\"timeout\", true);\n }\n\n window.addEventListener(\"message\", onMessage);\n pollTimerId = setInterval(onPoll, POPUP_CLOSED_POLL_MS);\n timeoutTimerId = setTimeout(onTimeout, opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n\n return {\n cancel: () => settleError(\"user_canceled\", true),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACWA,mBAAyD;;;ACiBzD,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AAA,IACN;AAAA,EACF,CAAC;AAED,QAAM,YAAY,MAAM,SAAS,aAAa,MAAM,SAAS;AAC7D,QAAM,eACJ,MAAM,SAAS,cAAc,MAAM,wBAAwB;AAE7D,SACE,6CAAC,SAAI,WAAU,2BAA0B,cAAY,MAAM,MACzD;AAAA;AAAA,MAAC;AAAA;AAAA,QACC,MAAK;AAAA,QACL,SAAS;AAAA,QACT,UAAU;AAAA,QACV,WAAW,MAAM;AAAA,QACjB,OAAO,MAAM;AAAA,QAEZ,sBACG,oBACC,MAAM,YAAY;AAAA;AAAA,IACzB;AAAA,IACC,gBACC,6CAAC,SAAI,MAAK,SAAQ,WAAU,yBAC1B;AAAA,kDAAC,UAAK,6BAAe;AAAA,MACrB,4CAAC,YAAO,MAAK,UAAS,SAAS,SAAS,WAAW,MAAM,WAAW,6CAEpE;AAAA,OACF;AAAA,KAEJ;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/EntrosVerify.tsx","../src/policy.ts","../src/messaging.ts","../src/url.ts","../src/popup-manager.ts"],"sourcesContent":["/**\n * `@entros/verify` — public surface.\n *\n * Drop-in React component for Entros verification. See\n * https://entros.io and https://docs.entros.io/integrate/verify.\n */\n\nexport { EntrosVerify } from \"./EntrosVerify\";\nexport type { EntrosVerifyProps } from \"./EntrosVerify\";\nexport type {\n PolicyRequestInput,\n PolicyRequest,\n PolicyResult,\n PolicyReason,\n} from \"./policy\";\nexport type {\n Cluster,\n EntrosVerifyError,\n EntrosVerifyErrorReason,\n EntrosVerifyProgress,\n EntrosVerifyProgressStatus,\n EntrosVerifyResult,\n} from \"./types\";\n","/**\n * <EntrosVerify> — drop-in trigger for the Entros verification popup.\n *\n * Renders a button. On click, opens a popup window to entros.io. User\n * completes wallet-connected verification inside the popup; the popup\n * posts the result back via postMessage; this component fires the\n * integrator's onVerified callback.\n *\n * See README and `EntrosVerifyProps` for usage.\n */\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { CSSProperties, ReactElement, ReactNode } from \"react\";\n\nimport { openVerifyPopup, type PopupHandle } from \"./popup-manager\";\nimport {\n normalizePolicyRequest,\n PolicyValidationError,\n type PolicyRequest,\n type PolicyRequestInput,\n} from \"./policy\";\nimport type {\n Cluster,\n EntrosVerifyError,\n EntrosVerifyErrorReason,\n EntrosVerifyProgress,\n EntrosVerifyResult,\n} from \"./types\";\n\nconst DEFAULT_BASE_ORIGIN = \"https://entros.io\";\nconst DEFAULT_POPUP_WIDTH = 480;\nconst DEFAULT_POPUP_HEIGHT = 720;\n/**\n * After a verification settles (done or error), state returns to idle so\n * the component is ready for re-use without consumer intervention. Long\n * enough to render the brief \"done\" / \"error\" UX without blocking re-clicks.\n */\nconst SETTLE_RESET_MS = 1500;\n\nexport interface EntrosVerifyProps {\n /** Integrator key registered with Entros. Required. */\n integratorKey: string;\n /** Solana cluster. Defaults to \"devnet\". v1 supports devnet only. */\n cluster?: Cluster;\n /**\n * Optional Trust Score floor. The popup runs the verification regardless\n * and reports the result; if `minTrustScore` is set and the resulting\n * score is below it, the popup posts `entros/error` with reason\n * `validation_failed` instead of `entros/verified`.\n */\n minTrustScore?: number;\n /** Application requirements. Missing policy uses the documented day/90-second defaults. */\n policy?: PolicyRequestInput;\n /** Called on successful verification. Required. */\n onVerified: (result: EntrosVerifyResult) => void;\n /** Called on any failure or cancellation. Optional. */\n onError?: (error: EntrosVerifyError) => void;\n /** Called on progress heartbeats from the popup. Optional. */\n onProgress?: (progress: EntrosVerifyProgress) => void;\n /** Popup width in CSS pixels. Defaults to 480. */\n popupWidth?: number;\n /** Popup height in CSS pixels. Defaults to 720. */\n popupHeight?: number;\n /** See README.md#full-api for timeout behavior and the default. */\n timeoutMs?: number;\n /** Custom button content. Defaults to \"Verify with Entros\". */\n children?: ReactNode;\n /** className applied to the trigger button. */\n className?: string;\n /** Inline style applied to the trigger button. */\n style?: CSSProperties;\n /**\n * If true, when the popup is blocked the component renders an inline\n * retry button. Clicking it triggers a fresh window.open from a confirmed\n * user gesture, which most browsers allow. Defaults to true.\n */\n popupBlockedFallback?: boolean;\n /**\n * INTERNAL: Override the entros.io base origin. Intended for end-to-end\n * testing against a localhost popup host. Production consumers should\n * not set this.\n */\n baseOrigin?: string;\n}\n\ntype State =\n | { kind: \"idle\" }\n | { kind: \"opening\" }\n | { kind: \"blocked\" }\n | { kind: \"waiting\" }\n | { kind: \"done\" }\n | { kind: \"error\"; reason: EntrosVerifyErrorReason };\n\nexport function EntrosVerify(props: EntrosVerifyProps): ReactElement {\n const [state, setState] = useState<State>({ kind: \"idle\" });\n const handleRef = useRef<PopupHandle | null>(null);\n const resetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n // Refs hold the latest callbacks so trigger stays stable across re-renders\n // even when consumers pass inline arrow functions. Avoids unnecessary\n // re-creation of the click handler on every parent render.\n const onVerifiedRef = useRef(props.onVerified);\n const onErrorRef = useRef(props.onError);\n const onProgressRef = useRef(props.onProgress);\n useEffect(() => {\n onVerifiedRef.current = props.onVerified;\n onErrorRef.current = props.onError;\n onProgressRef.current = props.onProgress;\n });\n\n // Tear down any in-flight popup + reset timer on unmount.\n useEffect(() => {\n return () => {\n if (handleRef.current) {\n handleRef.current.cancel();\n handleRef.current = null;\n }\n if (resetTimerRef.current !== null) {\n clearTimeout(resetTimerRef.current);\n resetTimerRef.current = null;\n }\n };\n }, []);\n\n const scheduleReset = useCallback(() => {\n if (resetTimerRef.current !== null) {\n clearTimeout(resetTimerRef.current);\n }\n resetTimerRef.current = setTimeout(() => {\n resetTimerRef.current = null;\n setState({ kind: \"idle\" });\n }, SETTLE_RESET_MS);\n }, []);\n\n const trigger = useCallback(() => {\n if (resetTimerRef.current !== null) {\n clearTimeout(resetTimerRef.current);\n resetTimerRef.current = null;\n }\n setState({ kind: \"opening\" });\n\n let policy: PolicyRequest;\n try {\n policy = normalizePolicyRequest(props.policy, props.minTrustScore);\n } catch (error) {\n const policyReason =\n error instanceof PolicyValidationError\n ? error.reason\n : \"unsupported_policy\";\n setState({ kind: \"error\", reason: \"validation_failed\" });\n onErrorRef.current?.({ reason: \"validation_failed\", policyReason });\n scheduleReset();\n return;\n }\n\n const handle = openVerifyPopup({\n baseOrigin: props.baseOrigin ?? DEFAULT_BASE_ORIGIN,\n integratorKey: props.integratorKey,\n cluster: props.cluster ?? \"devnet\",\n minTrustScore: props.minTrustScore,\n policy,\n popupWidth: props.popupWidth ?? DEFAULT_POPUP_WIDTH,\n popupHeight: props.popupHeight ?? DEFAULT_POPUP_HEIGHT,\n timeoutMs: props.timeoutMs,\n onVerified: (result) => {\n handleRef.current = null;\n setState({ kind: \"done\" });\n onVerifiedRef.current(result);\n scheduleReset();\n },\n onError: (error) => {\n handleRef.current = null;\n setState({ kind: \"error\", reason: error.reason });\n onErrorRef.current?.(error);\n scheduleReset();\n },\n onProgress: (progress) => {\n onProgressRef.current?.(progress);\n },\n });\n\n if (handle === null) {\n setState({ kind: \"blocked\" });\n onErrorRef.current?.({ reason: \"popup_blocked\" });\n return;\n }\n\n handleRef.current = handle;\n setState({ kind: \"waiting\" });\n }, [\n props.baseOrigin,\n props.cluster,\n props.integratorKey,\n props.minTrustScore,\n props.policy,\n props.popupHeight,\n props.popupWidth,\n props.timeoutMs,\n scheduleReset,\n ]);\n\n const isWaiting = state.kind === \"opening\" || state.kind === \"waiting\";\n const showFallback =\n state.kind === \"blocked\" && (props.popupBlockedFallback ?? true);\n\n return (\n <div className=\"entros-verify-container\" data-state={state.kind}>\n <button\n type=\"button\"\n onClick={trigger}\n disabled={isWaiting}\n className={props.className}\n style={props.style}\n >\n {isWaiting ? \"Verifying…\" : (props.children ?? \"Verify with Entros\")}\n </button>\n {showFallback && (\n <div role=\"alert\" className=\"entros-verify-blocked\">\n <span>Popup blocked. </span>\n <button type=\"button\" onClick={trigger} className={props.className}>\n Click here to open verification\n </button>\n </div>\n )}\n </div>\n );\n}\n","/** Pure policy evaluation. RPC evidence must come from a trusted account reader. */\nexport interface PolicyRequest {\n id: string;\n version: 1;\n minTrustScore: number;\n maxVerificationAgeSeconds: number;\n maxEvaluationAgeSeconds: number;\n requiredAssurance: \"browser_unattested\";\n uniquenessRequirement: \"allow_unmeasured\";\n requireAttestation: boolean;\n cluster: \"devnet\";\n}\n\nexport type PolicyRequestInput = Omit<\n PolicyRequest,\n \"maxEvaluationAgeSeconds\" | \"requireAttestation\"\n> &\n Partial<\n Pick<PolicyRequest, \"maxEvaluationAgeSeconds\" | \"requireAttestation\">\n >;\n\nexport interface PolicyProgramIds {\n anchor: string;\n verifier: string;\n registry: string;\n sas: string;\n credential: string;\n schema: string;\n}\n\nexport const POLICY_NETWORK = Object.freeze({\n genesisHash: \"EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG\",\n programIds: Object.freeze({\n anchor: \"GZYwTp2ozeuRA5Gof9vs4ya961aANcJBdUzB7LN6q4b2\",\n verifier: \"4F97jNoxQzT2qRbkWpW3ztC3Nz2TtKj3rnKG8ExgnrfV\",\n registry: \"6VBs3zr9KrfFPGd6j7aGBPQWwZa5tajVfA7HN6MMV9VW\",\n sas: \"22zoJMtdu4tQc2PzL74ZUT7FrwgB1Udec8DdW4yw4BdG\",\n credential: \"AMBtabCgRFwGLjoZ21Z2LhSKJ6c47NckxUkMogJ3Lpuw\",\n schema: \"5LNc7syFW7USPLveVLcNcjjY1xqS7QTXVjHZ7CQCbAMQ\",\n } satisfies PolicyProgramIds),\n});\n\nexport type PolicyAttestation =\n | {\n status: \"present\";\n address: string;\n readContextSlot: number;\n expiresAt: number | null;\n }\n | { status: \"missing\" | \"invalid\" | \"unavailable\" };\n\nexport interface PolicyEvidence {\n cluster: \"devnet\";\n genesisHash: string;\n programIds: PolicyProgramIds;\n assuranceTier: \"browser_unattested\";\n uniquenessStatus: \"unmeasured\";\n readContextSlot: number;\n identity: {\n walletPubkey: string;\n identityPda: string;\n creationTimestamp: number;\n lastVerificationTimestamp: number;\n verificationCount: number;\n trustScore: number;\n currentCommitment: string;\n projectionVersion: number;\n lastResetTimestamp: number;\n lastRebaselineTimestamp: number;\n mint: string;\n };\n transaction: {\n signature: string;\n slot: number;\n blockTime: number;\n commitment: string;\n kind: \"mint\" | \"update\" | \"rebaseline\";\n };\n attestation: PolicyAttestation;\n}\n\nexport type PolicyEvidenceReadResult =\n | { status: \"available\"; evidence: PolicyEvidence }\n | { status: \"invalid\" | \"unavailable\"; reason: string };\n\nexport type PolicyReason =\n | \"accepted\"\n | \"score_below_minimum\"\n | \"verification_stale\"\n | \"attestation_required\"\n | \"unsupported_policy\"\n | \"unsupported_assurance\"\n | \"unsupported_uniqueness\"\n | \"invalid_evidence\"\n | \"state_unavailable\";\n\ninterface PolicyResultBase {\n policyId: string;\n policyVersion: 1;\n requirements: PolicyRequest;\n evaluatedAt: number;\n expiresAt: number;\n evidenceTimestamp: number | null;\n evaluatedAgeSeconds: number | null;\n}\n\nexport type PolicyResult = PolicyResultBase &\n (\n | { decision: \"allow\"; reason: \"accepted\"; evidence: PolicyEvidence }\n | {\n decision: \"deny\";\n reason: Exclude<PolicyReason, \"accepted\" | \"state_unavailable\">;\n evidence: PolicyEvidence | null;\n }\n | {\n decision: \"unavailable\";\n reason: \"state_unavailable\";\n evidence: PolicyEvidence | null;\n }\n );\n\nexport class PolicyValidationError extends Error {\n constructor(public readonly reason: PolicyReason) {\n super(`Invalid verification policy: ${reason}`);\n this.name = \"PolicyValidationError\";\n }\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction exactKeys(\n value: Record<string, unknown>,\n keys: readonly string[],\n): boolean {\n return (\n Object.keys(value).length === keys.length &&\n keys.every((key) => Object.prototype.hasOwnProperty.call(value, key))\n );\n}\n\nfunction integer(\n value: unknown,\n minimum = 0,\n maximum = Number.MAX_SAFE_INTEGER,\n): value is number {\n return (\n typeof value === \"number\" &&\n Number.isSafeInteger(value) &&\n value >= minimum &&\n value <= maximum\n );\n}\n\nconst REQUEST_KEYS = [\n \"id\",\n \"version\",\n \"minTrustScore\",\n \"maxVerificationAgeSeconds\",\n \"maxEvaluationAgeSeconds\",\n \"requiredAssurance\",\n \"uniquenessRequirement\",\n \"requireAttestation\",\n \"cluster\",\n] as const;\n\n/** Canonical defaults are applied before a request leaves the consumer. */\nexport function normalizePolicyRequest(\n input?: unknown,\n legacyMinTrustScore?: number,\n): PolicyRequest {\n if (\n legacyMinTrustScore !== undefined &&\n !integer(legacyMinTrustScore, 0, 10000)\n ) {\n throw new PolicyValidationError(\"unsupported_policy\");\n }\n const value: unknown =\n input === undefined\n ? {\n id: \"entros-verify-default\",\n version: 1,\n minTrustScore: legacyMinTrustScore ?? 0,\n maxVerificationAgeSeconds: 86400,\n requiredAssurance: \"browser_unattested\",\n uniquenessRequirement: \"allow_unmeasured\",\n cluster: \"devnet\",\n }\n : input;\n if (\n !record(value) ||\n Object.keys(value).some(\n (key) => !REQUEST_KEYS.includes(key as (typeof REQUEST_KEYS)[number]),\n )\n ) {\n throw new PolicyValidationError(\"unsupported_policy\");\n }\n if (value.requiredAssurance !== \"browser_unattested\")\n throw new PolicyValidationError(\"unsupported_assurance\");\n if (value.uniquenessRequirement !== \"allow_unmeasured\")\n throw new PolicyValidationError(\"unsupported_uniqueness\");\n if (\n typeof value.id !== \"string\" ||\n !/^[A-Za-z0-9_-]{1,64}$/.test(value.id) ||\n value.version !== 1 ||\n !integer(value.minTrustScore, 0, 10000) ||\n !integer(value.maxVerificationAgeSeconds, 1, 31536000) ||\n !integer(\n value.maxEvaluationAgeSeconds === undefined\n ? 90\n : value.maxEvaluationAgeSeconds,\n 1,\n 90,\n ) ||\n (value.requireAttestation !== undefined &&\n typeof value.requireAttestation !== \"boolean\") ||\n value.cluster !== \"devnet\" ||\n (legacyMinTrustScore !== undefined &&\n value.minTrustScore !== legacyMinTrustScore)\n ) {\n throw new PolicyValidationError(\"unsupported_policy\");\n }\n return {\n id: value.id,\n version: 1,\n minTrustScore: value.minTrustScore,\n maxVerificationAgeSeconds: value.maxVerificationAgeSeconds,\n maxEvaluationAgeSeconds: (value.maxEvaluationAgeSeconds ?? 90) as number,\n requiredAssurance: \"browser_unattested\",\n uniquenessRequirement: \"allow_unmeasured\",\n requireAttestation: value.requireAttestation === true,\n cluster: \"devnet\",\n };\n}\n\nexport function encodePolicyRequest(request: PolicyRequest): string {\n return JSON.stringify(normalizePolicyRequest(request));\n}\n\n/** Legacy callers require a real attestation because their result type cannot represent absence. */\nexport function parsePolicyParameters(\n params: URLSearchParams,\n legacyMinTrustScore?: number,\n): { policy: PolicyRequest; negotiated: boolean } {\n for (const key of [\"policy\", \"policy_version\", \"min_trust_score\"]) {\n if (params.getAll(key).length > 1)\n throw new PolicyValidationError(\"unsupported_policy\");\n }\n const floorText = params.get(\"min_trust_score\");\n if (floorText !== null) {\n if (\n !/^(0|[1-9][0-9]{0,4})$/.test(floorText) ||\n !integer(Number(floorText), 0, 10000) ||\n (legacyMinTrustScore !== undefined &&\n legacyMinTrustScore !== Number(floorText))\n )\n throw new PolicyValidationError(\"unsupported_policy\");\n legacyMinTrustScore = Number(floorText);\n }\n const encoded = params.get(\"policy\");\n const marker = params.get(\"policy_version\");\n if (encoded === null && marker === null) {\n return {\n negotiated: false,\n policy: {\n ...normalizePolicyRequest(undefined, legacyMinTrustScore),\n requireAttestation: true,\n },\n };\n }\n if (marker !== \"1\" || encoded === null || encoded.length > 2048)\n throw new PolicyValidationError(\"unsupported_policy\");\n let raw: unknown;\n try {\n raw = JSON.parse(encoded);\n } catch {\n throw new PolicyValidationError(\"unsupported_policy\");\n }\n const policy = normalizePolicyRequest(raw, legacyMinTrustScore);\n if (encodePolicyRequest(policy) !== encoded)\n throw new PolicyValidationError(\"unsupported_policy\");\n return { negotiated: true, policy };\n}\n\nconst BASE58 = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\nfunction base58Bytes(value: unknown, expected: number): value is string {\n if (\n typeof value !== \"string\" ||\n value.length < 1 ||\n value.length > expected * 2\n )\n return false;\n let number = 0n;\n for (const character of value) {\n const digit = BASE58.indexOf(character);\n if (digit < 0) return false;\n number = number * 58n + BigInt(digit);\n }\n let bytes = 0;\n while (number > 0n) {\n bytes++;\n number >>= 8n;\n }\n let zeros = 0;\n while (value[zeros] === \"1\") zeros++;\n return bytes + zeros === expected;\n}\n\nfunction commitment(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n /^[0-9a-f]{64}$/.test(value) &&\n !/^0+$/.test(value)\n );\n}\n\nexport function isPolicyAttestation(\n value: unknown,\n): value is PolicyAttestation {\n if (!record(value)) return false;\n if (value.status === \"present\") {\n return (\n exactKeys(value, [\"status\", \"address\", \"readContextSlot\", \"expiresAt\"]) &&\n base58Bytes(value.address, 32) &&\n integer(value.readContextSlot) &&\n (value.expiresAt === null || integer(value.expiresAt, 1))\n );\n }\n return (\n exactKeys(value, [\"status\"]) &&\n [\"missing\", \"invalid\", \"unavailable\"].includes(String(value.status))\n );\n}\n\nexport function isPolicyEvidence(value: unknown): value is PolicyEvidence {\n if (\n !record(value) ||\n !exactKeys(value, [\n \"cluster\",\n \"genesisHash\",\n \"programIds\",\n \"assuranceTier\",\n \"uniquenessStatus\",\n \"readContextSlot\",\n \"identity\",\n \"transaction\",\n \"attestation\",\n ])\n )\n return false;\n if (\n value.cluster !== \"devnet\" ||\n value.genesisHash !== POLICY_NETWORK.genesisHash ||\n value.assuranceTier !== \"browser_unattested\" ||\n value.uniquenessStatus !== \"unmeasured\" ||\n !integer(value.readContextSlot)\n )\n return false;\n const programs = value.programIds;\n if (\n !record(programs) ||\n !exactKeys(programs, Object.keys(POLICY_NETWORK.programIds)) ||\n Object.entries(POLICY_NETWORK.programIds).some(\n ([key, id]) => programs[key] !== id,\n )\n )\n return false;\n const identity = value.identity;\n const transaction = value.transaction;\n if (\n !record(identity) ||\n !exactKeys(identity, [\n \"walletPubkey\",\n \"identityPda\",\n \"creationTimestamp\",\n \"lastVerificationTimestamp\",\n \"verificationCount\",\n \"trustScore\",\n \"currentCommitment\",\n \"projectionVersion\",\n \"lastResetTimestamp\",\n \"lastRebaselineTimestamp\",\n \"mint\",\n ]) ||\n !base58Bytes(identity.walletPubkey, 32) ||\n !base58Bytes(identity.identityPda, 32) ||\n !base58Bytes(identity.mint, 32) ||\n !integer(identity.creationTimestamp, 1) ||\n !integer(identity.lastVerificationTimestamp, identity.creationTimestamp) ||\n !integer(identity.verificationCount, 0, 0xffffffff) ||\n !integer(identity.trustScore, 0, 10000) ||\n !commitment(identity.currentCommitment) ||\n !integer(identity.projectionVersion, 0, 2) ||\n !integer(identity.lastResetTimestamp) ||\n !integer(identity.lastRebaselineTimestamp)\n )\n return false;\n if (\n !record(transaction) ||\n !exactKeys(transaction, [\n \"signature\",\n \"slot\",\n \"blockTime\",\n \"commitment\",\n \"kind\",\n ]) ||\n !base58Bytes(transaction.signature, 64) ||\n !integer(transaction.slot) ||\n !integer(transaction.blockTime, identity.creationTimestamp) ||\n !commitment(transaction.commitment) ||\n ![\"mint\", \"update\", \"rebaseline\"].includes(String(transaction.kind))\n )\n return false;\n return isPolicyAttestation(value.attestation);\n}\n\n/** Evaluates application requirements. It does not authenticate browser-supplied evidence. */\nexport function evaluatePolicy(\n request: PolicyRequest,\n observation: PolicyEvidenceReadResult,\n nowSeconds: number,\n): PolicyResult {\n const requirements = normalizePolicyRequest(request);\n if (\n !integer(nowSeconds, 1) ||\n nowSeconds > Number.MAX_SAFE_INTEGER - 31536000\n )\n throw new PolicyValidationError(\"invalid_evidence\");\n const base: PolicyResultBase = {\n policyId: requirements.id,\n policyVersion: 1,\n requirements,\n evaluatedAt: nowSeconds,\n expiresAt: nowSeconds,\n evidenceTimestamp: null,\n evaluatedAgeSeconds: null,\n };\n if (record(observation) && observation.status === \"unavailable\")\n return {\n ...base,\n decision: \"unavailable\",\n reason: \"state_unavailable\",\n evidence: null,\n };\n if (\n !record(observation) ||\n observation.status !== \"available\" ||\n !isPolicyEvidence(observation.evidence)\n ) {\n return {\n ...base,\n decision: \"deny\",\n reason: \"invalid_evidence\",\n evidence: null,\n };\n }\n const evidence = observation.evidence;\n const { identity, transaction, attestation } = evidence;\n const deny = (\n reason: Exclude<PolicyReason, \"accepted\" | \"state_unavailable\">,\n ): PolicyResult => ({ ...base, decision: \"deny\", reason, evidence });\n const freshMint =\n transaction.kind === \"mint\" &&\n identity.verificationCount === 0 &&\n identity.trustScore === 0 &&\n identity.creationTimestamp === transaction.blockTime &&\n identity.lastVerificationTimestamp === transaction.blockTime &&\n identity.lastResetTimestamp === 0 &&\n identity.lastRebaselineTimestamp === 0;\n if (\n (identity.verificationCount === 0 && !freshMint) ||\n identity.currentCommitment !== transaction.commitment ||\n identity.lastResetTimestamp >= transaction.blockTime ||\n identity.lastResetTimestamp > identity.lastVerificationTimestamp ||\n identity.lastRebaselineTimestamp > identity.lastVerificationTimestamp ||\n identity.lastRebaselineTimestamp > transaction.blockTime ||\n identity.lastVerificationTimestamp > nowSeconds ||\n transaction.blockTime > nowSeconds ||\n evidence.readContextSlot < transaction.slot ||\n attestation.status === \"invalid\" ||\n (attestation.status === \"present\" &&\n (attestation.readContextSlot < transaction.slot ||\n (attestation.expiresAt !== null &&\n attestation.expiresAt <= nowSeconds)))\n ) {\n return deny(\"invalid_evidence\");\n }\n base.evidenceTimestamp = Math.min(\n identity.lastVerificationTimestamp,\n transaction.blockTime,\n );\n base.evaluatedAgeSeconds = nowSeconds - base.evidenceTimestamp;\n base.expiresAt = Math.min(\n base.evidenceTimestamp + requirements.maxVerificationAgeSeconds,\n nowSeconds + requirements.maxEvaluationAgeSeconds,\n );\n if (\n requirements.requireAttestation &&\n attestation.status === \"present\" &&\n attestation.expiresAt !== null\n )\n base.expiresAt = Math.min(base.expiresAt, attestation.expiresAt);\n if (identity.trustScore < requirements.minTrustScore)\n return deny(\"score_below_minimum\");\n if (nowSeconds >= base.expiresAt) return deny(\"verification_stale\");\n if (requirements.requireAttestation && attestation.status === \"missing\")\n return deny(\"attestation_required\");\n if (requirements.requireAttestation && attestation.status === \"unavailable\")\n return {\n ...base,\n decision: \"unavailable\",\n reason: \"state_unavailable\",\n evidence,\n };\n return { ...base, decision: \"allow\", reason: \"accepted\", evidence };\n}\n\nexport interface PolicyWireResult {\n policy_id: string;\n policy_version: 1;\n decision: PolicyResult[\"decision\"];\n reason: PolicyReason;\n requirements: PolicyRequest;\n evaluated_at: number;\n expires_at: number;\n evidence_timestamp: number | null;\n evaluated_age_seconds: number | null;\n wallet_pubkey: string | null;\n identity_pda: string | null;\n verified_transaction: {\n signature: string;\n slot: number;\n block_time: number;\n commitment: string;\n kind: \"mint\" | \"update\" | \"rebaseline\";\n } | null;\n verification_timestamp: number | null;\n trust_score: number | null;\n anchor_created_at: number | null;\n verification_count: number | null;\n current_commitment: string | null;\n projection_version: number | null;\n last_reset_timestamp: number | null;\n last_rebaseline_timestamp: number | null;\n mint: string | null;\n uniqueness_status: \"unmeasured\" | null;\n assurance_tier: \"browser_unattested\" | null;\n cluster: \"devnet\" | null;\n genesis_hash: string | null;\n program_ids: PolicyProgramIds | null;\n read_context_slot: number | null;\n attestation:\n | {\n status: \"present\";\n address: string;\n read_context_slot: number;\n expires_at: number | null;\n }\n | { status: \"missing\" | \"invalid\" | \"unavailable\" }\n | null;\n}\n\nexport function policyResultToWire(result: PolicyResult): PolicyWireResult {\n const e = result.evidence;\n return {\n policy_id: result.policyId,\n policy_version: 1,\n decision: result.decision,\n reason: result.reason,\n requirements: result.requirements,\n evaluated_at: result.evaluatedAt,\n expires_at: result.expiresAt,\n evidence_timestamp: result.evidenceTimestamp,\n evaluated_age_seconds: result.evaluatedAgeSeconds,\n wallet_pubkey: e?.identity.walletPubkey ?? null,\n identity_pda: e?.identity.identityPda ?? null,\n verified_transaction: e\n ? {\n signature: e.transaction.signature,\n slot: e.transaction.slot,\n block_time: e.transaction.blockTime,\n commitment: e.transaction.commitment,\n kind: e.transaction.kind,\n }\n : null,\n verification_timestamp: e?.identity.lastVerificationTimestamp ?? null,\n trust_score: e?.identity.trustScore ?? null,\n anchor_created_at: e?.identity.creationTimestamp ?? null,\n verification_count: e?.identity.verificationCount ?? null,\n current_commitment: e?.identity.currentCommitment ?? null,\n projection_version: e?.identity.projectionVersion ?? null,\n last_reset_timestamp: e?.identity.lastResetTimestamp ?? null,\n last_rebaseline_timestamp: e?.identity.lastRebaselineTimestamp ?? null,\n mint: e?.identity.mint ?? null,\n uniqueness_status: e?.uniquenessStatus ?? null,\n assurance_tier: e?.assuranceTier ?? null,\n cluster: e?.cluster ?? null,\n genesis_hash: e?.genesisHash ?? null,\n program_ids: e?.programIds ?? null,\n read_context_slot: e?.readContextSlot ?? null,\n attestation: e\n ? e.attestation.status === \"present\"\n ? {\n status: \"present\",\n address: e.attestation.address,\n read_context_slot: e.attestation.readContextSlot,\n expires_at: e.attestation.expiresAt,\n }\n : e.attestation\n : null,\n };\n}\n\n/** Recompute every derived field before accepting a remote decision. */\nexport function parsePolicyWireResult(input: unknown): PolicyResult | null {\n if (!record(input) || !integer(input.evaluated_at, 1)) return null;\n try {\n const requirements = normalizePolicyRequest(input.requirements);\n let observation: PolicyEvidenceReadResult;\n if (input.wallet_pubkey === null) {\n observation =\n input.decision === \"unavailable\"\n ? { status: \"unavailable\", reason: \"state_unavailable\" }\n : { status: \"invalid\", reason: \"invalid_evidence\" };\n } else {\n const tx = input.verified_transaction;\n const sas = input.attestation;\n if (!record(tx) || !record(sas)) return null;\n const evidence: unknown = {\n cluster: input.cluster,\n genesisHash: input.genesis_hash,\n programIds: input.program_ids,\n assuranceTier: input.assurance_tier,\n uniquenessStatus: input.uniqueness_status,\n readContextSlot: input.read_context_slot,\n identity: {\n walletPubkey: input.wallet_pubkey,\n identityPda: input.identity_pda,\n creationTimestamp: input.anchor_created_at,\n lastVerificationTimestamp: input.verification_timestamp,\n verificationCount: input.verification_count,\n trustScore: input.trust_score,\n currentCommitment: input.current_commitment,\n projectionVersion: input.projection_version,\n lastResetTimestamp: input.last_reset_timestamp,\n lastRebaselineTimestamp: input.last_rebaseline_timestamp,\n mint: input.mint,\n },\n transaction: {\n signature: tx.signature,\n slot: tx.slot,\n blockTime: tx.block_time,\n commitment: tx.commitment,\n kind: tx.kind,\n },\n attestation:\n sas.status === \"present\"\n ? {\n status: \"present\",\n address: sas.address,\n readContextSlot: sas.read_context_slot,\n expiresAt: sas.expires_at,\n }\n : { status: sas.status },\n };\n if (!isPolicyEvidence(evidence)) return null;\n observation = { status: \"available\", evidence };\n }\n const result = evaluatePolicy(\n requirements,\n observation,\n input.evaluated_at,\n );\n return canonicalEqual(input, policyResultToWire(result)) ? result : null;\n } catch {\n return null;\n }\n}\n\nfunction canonicalEqual(left: unknown, right: unknown): boolean {\n if (left === right) return true;\n if (!record(left) || !record(right)) return false;\n return (\n exactKeys(left, Object.keys(right)) &&\n Object.keys(right).every((key) => canonicalEqual(left[key], right[key]))\n );\n}\n\nexport function isPolicyReason(value: unknown): value is PolicyReason {\n return (\n typeof value === \"string\" &&\n [\n \"accepted\",\n \"score_below_minimum\",\n \"verification_stale\",\n \"attestation_required\",\n \"unsupported_policy\",\n \"unsupported_assurance\",\n \"unsupported_uniqueness\",\n \"invalid_evidence\",\n \"state_unavailable\",\n ].includes(value)\n );\n}\n\nexport function validatePolicyVerifiedPayload(\n payload: unknown,\n requestedPolicy: PolicyRequest,\n nowSeconds: number,\n):\n | { ok: true; result: PolicyResult & { decision: \"allow\" } }\n | { ok: false; reason: PolicyReason } {\n if (!record(payload)) return { ok: false, reason: \"invalid_evidence\" };\n if (!Object.prototype.hasOwnProperty.call(payload, \"policy\"))\n return { ok: false, reason: \"unsupported_policy\" };\n const result = parsePolicyWireResult(payload.policy);\n if (\n !result ||\n !canonicalEqual(\n result.requirements,\n normalizePolicyRequest(requestedPolicy),\n )\n )\n return { ok: false, reason: \"invalid_evidence\" };\n if (result.decision !== \"allow\") return { ok: false, reason: result.reason };\n if (\n !integer(nowSeconds, 1) ||\n result.evaluatedAt > nowSeconds ||\n nowSeconds >= result.expiresAt\n )\n return { ok: false, reason: \"verification_stale\" };\n const current = evaluatePolicy(\n requestedPolicy,\n { status: \"available\", evidence: result.evidence },\n nowSeconds,\n );\n if (current.decision !== \"allow\")\n return { ok: false, reason: current.reason };\n const e = result.evidence;\n const address =\n e.attestation.status === \"present\" ? e.attestation.address : null;\n if (\n payload.wallet_pubkey !== e.identity.walletPubkey ||\n payload.trust_score !== e.identity.trustScore ||\n payload.cluster !== e.cluster ||\n payload.tx_sig !== e.transaction.signature ||\n payload.attestation_pda !== address\n )\n return { ok: false, reason: \"invalid_evidence\" };\n return { ok: true, result };\n}\n","/**\n * Type guards and validation for postMessage envelopes received from the\n * Entros verify popup. The component is the trust boundary — every message\n * arriving on `window` is hostile until proven otherwise.\n *\n * Validation order in popup-manager.ts:\n * 1. event.origin matches expected popup origin (caller's responsibility)\n * 2. isEntrosMessage(event.data)\n * 3. event.data.request_id matches the parent's expected ID\n * 4. isFreshMessage(event.data)\n * 5. payload-specific guard for the message type\n *\n * Skipping any step is a security regression.\n */\n\nimport type {\n EntrosMessage,\n ErrorPayload,\n HeartbeatPayload,\n VerifiedPayload,\n} from \"./types\";\nimport { isPolicyReason } from \"./policy\";\n\n/**\n * Maximum allowed clock drift between popup and parent. 90 seconds.\n *\n * The popup timestamps each message when it posts it. This window checks\n * delivery freshness and does not limit total verification duration.\n */\nconst MAX_TIMESTAMP_DRIFT_MS = 90 * 1000;\n\n/** Allowed error reason values on the wire. */\nconst ERROR_REASONS = new Set<string>([\n \"wallet_rejected\",\n \"validation_failed\",\n \"network_error\",\n \"user_canceled\",\n \"origin_invalid\",\n \"popup_blocked\",\n \"timeout\",\n \"unknown\",\n]);\n\nconst HEARTBEAT_STATUSES = new Set<string>([\n \"wallet_connecting\",\n \"capturing\",\n \"proving\",\n \"submitting\",\n \"attesting\",\n]);\n\nconst ENTROS_MESSAGE_TYPES = new Set<string>([\n \"entros/verified\",\n \"entros/error\",\n \"entros/heartbeat\",\n]);\n\nconst CLUSTERS = new Set<string>([\"devnet\"]);\n\nexport function isEntrosMessage(data: unknown): data is EntrosMessage {\n if (typeof data !== \"object\" || data === null) return false;\n const msg = data as Record<string, unknown>;\n return (\n msg.source === \"entros\" &&\n msg.version === 1 &&\n typeof msg.type === \"string\" &&\n ENTROS_MESSAGE_TYPES.has(msg.type) &&\n typeof msg.request_id === \"string\" &&\n msg.request_id.length > 0 &&\n typeof msg.timestamp === \"number\" &&\n Number.isFinite(msg.timestamp) &&\n \"payload\" in msg\n );\n}\n\nexport function isFreshMessage(\n msg: EntrosMessage,\n now: number = Date.now(),\n): boolean {\n return Math.abs(now - msg.timestamp) < MAX_TIMESTAMP_DRIFT_MS;\n}\n\nexport function isVerifiedPayload(\n payload: unknown,\n): payload is VerifiedPayload {\n if (typeof payload !== \"object\" || payload === null) return false;\n const p = payload as Record<string, unknown>;\n return (\n typeof p.wallet_pubkey === \"string\" &&\n p.wallet_pubkey.length > 0 &&\n typeof p.attestation_pda === \"string\" &&\n p.attestation_pda.length > 0 &&\n typeof p.tx_sig === \"string\" &&\n p.tx_sig.length > 0 &&\n typeof p.trust_score === \"number\" &&\n Number.isFinite(p.trust_score) &&\n p.trust_score >= 0 &&\n typeof p.cluster === \"string\" &&\n CLUSTERS.has(p.cluster)\n );\n}\n\nexport function isErrorPayload(payload: unknown): payload is ErrorPayload {\n if (typeof payload !== \"object\" || payload === null) return false;\n const p = payload as Record<string, unknown>;\n return (\n typeof p.reason === \"string\" &&\n ERROR_REASONS.has(p.reason) &&\n (p.policy_reason === undefined ||\n (isPolicyReason(p.policy_reason) && p.policy_reason !== \"accepted\"))\n );\n}\n\nexport function isHeartbeatPayload(\n payload: unknown,\n): payload is HeartbeatPayload {\n if (typeof payload !== \"object\" || payload === null) return false;\n const p = payload as Record<string, unknown>;\n return typeof p.status === \"string\" && HEARTBEAT_STATUSES.has(p.status);\n}\n","/**\n * URL builders for the Entros verify popup.\n *\n * The component constructs the popup URL deterministically from the\n * integrator's props. The popup host validates every field server-side;\n * these helpers exist to fail loudly on the integrator's side when a\n * misconfiguration would have wasted a popup roundtrip.\n */\n\nimport type { Cluster } from \"./types\";\nimport {\n encodePolicyRequest,\n normalizePolicyRequest,\n type PolicyRequestInput,\n} from \"./policy\";\n\nconst VALID_INTEGRATOR_KEY = /^[a-z0-9_-]{1,64}$/;\nconst ORIGIN_PATTERN = /^https?:\\/\\/[^/]+$/;\n\nexport interface BuildPopupUrlOptions {\n /** entros.io base origin. Override for E2E testing only. */\n baseOrigin: string;\n integratorKey: string;\n /** Caller's window origin — popup posts back to this. */\n parentOrigin: string;\n cluster: Cluster;\n requestId: string;\n minTrustScore?: number;\n policy?: PolicyRequestInput;\n}\n\nexport function buildPopupUrl(opts: BuildPopupUrlOptions): string {\n if (opts.cluster !== \"devnet\") {\n throw new Error(\n \"Unsupported cluster: @entros/verify currently supports devnet only\",\n );\n }\n if (!VALID_INTEGRATOR_KEY.test(opts.integratorKey)) {\n throw new Error(\n `Invalid integratorKey: must match /^[a-z0-9_-]{1,64}$/ (got \"${opts.integratorKey}\")`,\n );\n }\n if (!ORIGIN_PATTERN.test(opts.parentOrigin)) {\n throw new Error(\n `Invalid parentOrigin: must be a fully-qualified origin (got \"${opts.parentOrigin}\")`,\n );\n }\n if (opts.minTrustScore !== undefined) {\n if (\n !Number.isInteger(opts.minTrustScore) ||\n opts.minTrustScore < 0 ||\n opts.minTrustScore > 10000\n ) {\n throw new Error(\n `Invalid minTrustScore: must be an integer in [0, 10000] (got ${String(opts.minTrustScore)})`,\n );\n }\n }\n const policy = normalizePolicyRequest(opts.policy, opts.minTrustScore);\n\n const url = new URL(\"/embed/verify-popup\", opts.baseOrigin);\n url.searchParams.set(\"integrator\", opts.integratorKey);\n url.searchParams.set(\"parent_origin\", opts.parentOrigin);\n url.searchParams.set(\"cluster\", opts.cluster);\n url.searchParams.set(\"request_id\", opts.requestId);\n url.searchParams.set(\"policy_version\", \"1\");\n url.searchParams.set(\"policy\", encodePolicyRequest(policy));\n if (opts.minTrustScore !== undefined) {\n url.searchParams.set(\"min_trust_score\", String(opts.minTrustScore));\n }\n return url.toString();\n}\n\n/**\n * Generates a cryptographically random request ID for replay protection.\n * Uses crypto.randomUUID when available (modern browsers + Node 19+).\n * Falls back to crypto.getRandomValues (broadly supported back to IE11)\n * formatted as a UUIDv4. Math.random is never used.\n */\nexport function generateRequestId(): string {\n if (typeof crypto === \"undefined\") {\n throw new Error(\n \"crypto is unavailable in this environment; @entros/verify requires a secure context\",\n );\n }\n if (typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n if (typeof crypto.getRandomValues !== \"function\") {\n throw new Error(\n \"crypto.getRandomValues is unavailable; @entros/verify requires a secure context\",\n );\n }\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n // RFC 4122 v4 framing: bits 6-7 of byte 8 are 0b10, bits 12-15 of byte 6\n // are 0b0100. The remaining bits are random.\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\"));\n return (\n hex.slice(0, 4).join(\"\") +\n \"-\" +\n hex.slice(4, 6).join(\"\") +\n \"-\" +\n hex.slice(6, 8).join(\"\") +\n \"-\" +\n hex.slice(8, 10).join(\"\") +\n \"-\" +\n hex.slice(10, 16).join(\"\")\n );\n}\n","/**\n * Popup-window state machine for `<EntrosVerify>`.\n *\n * Owns: window.open, postMessage listener, popup.closed polling, timeout.\n * Boundary with the React layer: open → returns a handle (or null if blocked).\n * Component is responsible for rendering the trigger button and the\n * popup-blocked fallback UI.\n *\n * Security model — every postMessage from the popup is treated as hostile\n * until proven otherwise. Validation order (skipping any step is a\n * regression):\n * 1. event.origin === expectedPopupOrigin\n * 2. event.source === popup (the window we opened, not a sibling tab)\n * 3. envelope shape matches `EntrosMessage` (version, source, type)\n * 4. event.data.request_id === this popup's request_id (replay defense)\n * 5. timestamp within drift window (90s)\n * 6. payload-specific guard for the message type\n */\n\nimport {\n isEntrosMessage,\n isErrorPayload,\n isFreshMessage,\n isHeartbeatPayload,\n} from \"./messaging\";\nimport {\n normalizePolicyRequest,\n validatePolicyVerifiedPayload,\n type PolicyReason,\n type PolicyRequestInput,\n} from \"./policy\";\nimport type {\n Cluster,\n EntrosVerifyError,\n EntrosVerifyErrorReason,\n EntrosVerifyProgress,\n EntrosVerifyResult,\n} from \"./types\";\nimport { buildPopupUrl, generateRequestId } from \"./url\";\n\nconst DEFAULT_TIMEOUT_MS = 9 * 60 * 1000;\nconst POPUP_CLOSED_POLL_MS = 500;\n\n/**\n * Grace period after detecting popup.closed before firing user_canceled.\n * Lets the final `entros/verified` message arrive when the popup posts\n * and self-closes within the same event-loop turn.\n */\nconst POPUP_CLOSED_GRACE_MS = 1500;\n\n/**\n * After a popup-emitted outcome (`entros/verified` or `entros/error`),\n * the popup owns its own close — its success / failure surface renders\n * and either self-closes or waits for explicit user action (e.g., the\n * baseline-stale recovery surface). The parent only force-closes after\n * this defensive fallback in case the popup fails to close itself.\n * Generous enough to allow interactive failure surfaces to be read and\n * acted on; short enough that an abandoned popup eventually dies.\n */\nconst POPUP_OWNED_FALLBACK_CLOSE_MS = 30_000;\n\nexport interface OpenPopupOptions {\n baseOrigin: string;\n integratorKey: string;\n cluster: Cluster;\n minTrustScore?: number;\n policy?: PolicyRequestInput;\n popupWidth: number;\n popupHeight: number;\n timeoutMs?: number;\n onVerified: (result: EntrosVerifyResult) => void;\n onError: (error: EntrosVerifyError) => void;\n onProgress?: (progress: EntrosVerifyProgress) => void;\n}\n\nexport interface PopupHandle {\n /**\n * Force-cancel the popup. Closes the window if still open, fires\n * onError({reason: \"user_canceled\"}), and tears down listeners.\n * Idempotent.\n */\n cancel: () => void;\n}\n\nexport function openVerifyPopup(opts: OpenPopupOptions): PopupHandle | null {\n if (typeof window === \"undefined\") {\n throw new Error(\"openVerifyPopup must be called in a browser context\");\n }\n\n const requestId = generateRequestId();\n const requestedPolicy = normalizePolicyRequest(\n opts.policy,\n opts.minTrustScore,\n );\n const parentOrigin = window.location.origin;\n const url = buildPopupUrl({\n baseOrigin: opts.baseOrigin,\n integratorKey: opts.integratorKey,\n parentOrigin,\n cluster: opts.cluster,\n requestId,\n minTrustScore: opts.minTrustScore,\n policy: requestedPolicy,\n });\n\n const left = Math.max(\n 0,\n Math.floor((window.screen.availWidth - opts.popupWidth) / 2),\n );\n const top = Math.max(\n 0,\n Math.floor((window.screen.availHeight - opts.popupHeight) / 2),\n );\n const features = [\n `width=${opts.popupWidth}`,\n `height=${opts.popupHeight}`,\n `left=${left}`,\n `top=${top}`,\n \"menubar=no\",\n \"toolbar=no\",\n // location=yes lets the user verify entros.io in the URL bar.\n \"location=yes\",\n \"status=no\",\n \"resizable=yes\",\n \"scrollbars=yes\",\n ].join(\",\");\n\n // Unique window name per popup. A fixed name causes collision when an\n // integrator renders multiple <EntrosVerify> on one page — the second\n // window.open would reuse the existing popup.\n const popupName = `entros_verify_${requestId}`;\n const rawPopup = window.open(url, popupName, features);\n if (!rawPopup || rawPopup.closed) {\n return null;\n }\n // Narrow once so closures below see the non-null type.\n const popup: Window = rawPopup;\n\n const expectedPopupOrigin = new URL(opts.baseOrigin).origin;\n\n let settled = false;\n let pollTimerId: ReturnType<typeof setInterval> | null = null;\n let timeoutTimerId: ReturnType<typeof setTimeout> | null = null;\n let popupClosedAtMs: number | null = null;\n\n function clearListenersAndTimers(): void {\n window.removeEventListener(\"message\", onMessage);\n if (pollTimerId !== null) {\n clearInterval(pollTimerId);\n pollTimerId = null;\n }\n if (timeoutTimerId !== null) {\n clearTimeout(timeoutTimerId);\n timeoutTimerId = null;\n }\n }\n\n function forceClosePopup(): void {\n if (popup && !popup.closed) {\n try {\n popup.close();\n } catch {\n // Defensive only. We opened this window so we own the close permission;\n // this branch is for esoteric extension or browser-quirk edge cases.\n }\n }\n }\n\n function settleVerified(result: EntrosVerifyResult): void {\n if (settled) return;\n settled = true;\n // The popup owns its own close on the verified path so its\n // recognition surface (`Verified.` checkmark) is visible to the user\n // before the window dies. Parent only force-closes as a defensive\n // fallback in case the popup fails to close itself.\n clearListenersAndTimers();\n setTimeout(forceClosePopup, POPUP_OWNED_FALLBACK_CLOSE_MS);\n opts.onVerified(result);\n }\n\n /**\n * @param forceImmediateClose\n * - false (default) — error came from a popup-emitted `entros/error`\n * message; the popup is still alive and rendering its own\n * `PopupFailure` (auto-close) or interactive recovery surface\n * (e.g., baseline-stale). Parent waits the fallback window before\n * force-closing so the user sees the failure category.\n * - true — error came from the parent (timeout, user cancel, or\n * polling detected the popup already closed). No popup-side\n * surface to preserve; force-close immediately.\n */\n function settleError(\n reason: EntrosVerifyErrorReason,\n forceImmediateClose = false,\n policyReason?: PolicyReason,\n ): void {\n if (settled) return;\n settled = true;\n clearListenersAndTimers();\n if (forceImmediateClose) {\n forceClosePopup();\n } else {\n setTimeout(forceClosePopup, POPUP_OWNED_FALLBACK_CLOSE_MS);\n }\n opts.onError(\n policyReason === undefined ? { reason } : { reason, policyReason },\n );\n }\n\n function onMessage(event: MessageEvent): void {\n if (settled) return;\n\n // Origin gate — first and most important check.\n if (event.origin !== expectedPopupOrigin) return;\n\n // Source gate — defense-in-depth against another same-origin tab on\n // entros.io (e.g., the standalone /verify route open in a sibling tab)\n // posting a forged message. Only the popup we opened is authoritative.\n if (event.source !== popup) return;\n\n if (!isEntrosMessage(event.data)) return;\n\n // Replay protection — request_id must match this popup's ID.\n if (event.data.request_id !== requestId) return;\n\n if (!isFreshMessage(event.data)) return;\n\n switch (event.data.type) {\n case \"entros/verified\": {\n const validated = validatePolicyVerifiedPayload(\n event.data.payload,\n requestedPolicy,\n Math.floor(Date.now() / 1000),\n );\n if (!validated.ok) {\n settleError(\n validated.reason === \"state_unavailable\"\n ? \"network_error\"\n : \"validation_failed\",\n false,\n validated.reason,\n );\n break;\n }\n const evidence = validated.result.evidence;\n settleVerified({\n walletPubkey: evidence.identity.walletPubkey,\n attestationPda:\n evidence.attestation.status === \"present\"\n ? evidence.attestation.address\n : null,\n txSig: evidence.transaction.signature,\n trustScore: evidence.identity.trustScore,\n cluster: evidence.cluster,\n policy: validated.result,\n });\n break;\n }\n case \"entros/error\": {\n if (isErrorPayload(event.data.payload)) {\n settleError(\n event.data.payload.reason,\n false,\n event.data.payload.policy_reason,\n );\n }\n break;\n }\n case \"entros/heartbeat\": {\n if (isHeartbeatPayload(event.data.payload) && opts.onProgress) {\n opts.onProgress({ status: event.data.payload.status });\n }\n break;\n }\n }\n }\n\n function onPoll(): void {\n if (settled) return;\n if (popup.closed) {\n // Start the grace period the first time we observe the close.\n if (popupClosedAtMs === null) {\n popupClosedAtMs = Date.now();\n return;\n }\n if (Date.now() - popupClosedAtMs >= POPUP_CLOSED_GRACE_MS) {\n settleError(\"user_canceled\", true);\n }\n } else {\n popupClosedAtMs = null;\n }\n }\n\n function onTimeout(): void {\n settleError(\"timeout\", true);\n }\n\n window.addEventListener(\"message\", onMessage);\n pollTimerId = setInterval(onPoll, POPUP_CLOSED_POLL_MS);\n timeoutTimerId = setTimeout(onTimeout, opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n\n return {\n cancel: () => settleError(\"user_canceled\", true),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACWA,mBAAyD;;;ACmBlD,IAAM,iBAAiB,OAAO,OAAO;AAAA,EAC1C,aAAa;AAAA,EACb,YAAY,OAAO,OAAO;AAAA,IACxB,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,UAAU;AAAA,IACV,KAAK;AAAA,IACL,YAAY;AAAA,IACZ,QAAQ;AAAA,EACV,CAA4B;AAC9B,CAAC;AAiFM,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAC/C,YAA4B,QAAsB;AAChD,UAAM,gCAAgC,MAAM,EAAE;AADpB;AAE1B,SAAK,OAAO;AAAA,EACd;AACF;AAEA,SAAS,OAAO,OAAkD;AAChE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,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