@entros/verify 0.3.0 → 0.4.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 +0,0 @@
1
- {"version":3,"sources":["../src/agent-permit.ts","../src/base58.ts","../src/policy.ts"],"sourcesContent":["/**\n * Agent Operator Permit v1. Pure grammar, signatures and settlement evaluation.\n * Chain reads come from a trusted reader such as `readAgentState` and\n * `readIntegratorEvidence` in `@entros/pulse-sdk`.\n */\nimport { ed25519 } from \"@noble/curves/ed25519\";\nimport { sha256 } from \"@noble/hashes/sha2\";\n\nimport { base58Decode, base58Encode, canonicalKeyBytes } from \"./base58\";\nimport {\n encodePolicyRequest,\n evaluatePolicy,\n normalizePolicyRequest,\n POLICY_NETWORK,\n type PolicyEvidenceReadResult,\n type PolicyRequest,\n type PolicyResult,\n} from \"./policy\";\n\nexport const AGENT_PERMIT_VERSION_LINE = \"Entros-Agent-Permit-v1\";\nexport const AGENT_PERMIT_NOTICE_LINE =\n \"Sign only to let this agent perform the action below. This is not a transaction.\";\nexport const AGENT_PERMIT_PRESENTATION_LINE =\n \"Entros-Agent-Permit-Presentation-v1\";\n\nexport const AGENT_PERMIT_NETWORK = Object.freeze({\n cluster: \"devnet\",\n genesisHash: POLICY_NETWORK.genesisHash,\n entrosAnchorProgram: POLICY_NETWORK.programIds.anchor,\n agentRegistryProgram: \"8oo4J9tBB3Hna1jRQ3rWvJjojqM5DYTDJo5cejUuJy3C\",\n agentCollection: \"6CTyGPcn8dMwKEqgtvx2XCpkGUd7uqCVK6937RSM5bhA\",\n coreProgram: \"CoREENxT6tW1HoK8ypY1SxRMZTcVPm7R94rH4PZNhX7d\",\n} as const);\n\nexport const AGENT_PERMIT_LIMITS = Object.freeze({\n minLifetimeSeconds: 30,\n maxLifetimeSeconds: 900,\n clockSkewSeconds: 30,\n maxAudienceLength: 200,\n maxLabelLength: 96,\n // 2000-01-01T00:00:00Z to 9999-12-31T23:59:59Z. `toISOString` writes six-digit years past 9999.\n minTimeSeconds: 946684800,\n maxTimeSeconds: 253402300799,\n});\n\nexport interface AgentPermitAction {\n label: string;\n /** Lowercase hex SHA-256 of the consumer's own action record. */\n sha256: string;\n}\n\nexport interface AgentPermitRequest {\n version: 1;\n agent: string;\n agentWallet: string;\n operator: string;\n audience: string;\n action: AgentPermitAction;\n policy: PolicyRequest;\n cluster: \"devnet\";\n genesisHash: string;\n entrosAnchorProgram: string;\n agentRegistryProgram: string;\n agentCollection: string;\n issuedAt: number;\n expiresAt: number;\n nonce: string;\n}\n\nexport interface CreateAgentPermitRequestInput {\n agent: string;\n agentWallet: string;\n operator: string;\n audience: string;\n action: AgentPermitAction;\n policy: PolicyRequest;\n issuedAt: number;\n lifetimeSeconds: number;\n /** Omit to draw 32 random bytes from `crypto.getRandomValues`. */\n nonce?: string;\n}\n\nexport type AgentWalletStatus = \"bound\" | \"unbound\" | \"stale\";\n\nexport interface AgentStateEvidence {\n cluster: \"devnet\";\n genesisHash: string;\n coreProgram: string;\n agentRegistryProgram: string;\n agentCollection: string;\n agent: string;\n agentAccount: string;\n /** Owner field of the Metaplex Core asset. The only owner source. */\n owner: string;\n /** Registry cache. Informational, and the agent wallet counts only when it matches. */\n cachedOwner: string;\n agentWallet: string | null;\n agentWalletStatus: AgentWalletStatus;\n readContextSlot: number;\n}\n\nexport type AgentStateFailureReason =\n | \"invalid_request\"\n | \"wrong_cluster\"\n | \"agent_missing\"\n | \"agent_invalid\"\n | \"agent_unregistered\"\n | \"rpc_unavailable\";\n\nexport type AgentStateReadResult =\n | { status: \"available\"; evidence: AgentStateEvidence }\n | { status: \"invalid\" | \"unavailable\"; reason: AgentStateFailureReason };\n\nexport type AgentPermitReason =\n | \"accepted\"\n | \"invalid_permit\"\n | \"permit_expired\"\n | \"invalid_signature\"\n | \"invalid_presentation\"\n | \"wrong_cluster\"\n | \"agent_missing\"\n | \"agent_invalid\"\n | \"agent_unregistered\"\n | \"agent_unavailable\"\n | \"owner_changed\"\n | \"agent_wallet_stale\"\n | \"agent_wallet_unbound\"\n | \"agent_wallet_changed\"\n | \"score_below_minimum\"\n | \"verification_stale\"\n | \"attestation_required\"\n | \"invalid_evidence\"\n | \"state_unavailable\";\n\nexport type AgentPermitDenyReason = Exclude<\n AgentPermitReason,\n \"accepted\" | \"agent_unavailable\" | \"state_unavailable\"\n>;\n\nexport type AgentPermitPrecheck =\n | { ok: true; request: AgentPermitRequest; permitId: string }\n | {\n ok: false;\n reason:\n | \"invalid_permit\"\n | \"permit_expired\"\n | \"invalid_signature\"\n | \"invalid_presentation\";\n request: AgentPermitRequest | null;\n permitId: string | null;\n };\n\ninterface AgentPermitResultBase {\n permitId: string | null;\n request: AgentPermitRequest | null;\n evaluatedAt: number;\n expiresAt: number | null;\n agentState: AgentStateEvidence | null;\n policy: PolicyResult | null;\n}\n\nexport type AgentPermitResult = AgentPermitResultBase &\n (\n | { decision: \"allow\"; reason: \"accepted\" }\n | { decision: \"deny\"; reason: AgentPermitDenyReason }\n | {\n decision: \"unavailable\";\n reason: \"agent_unavailable\" | \"state_unavailable\";\n }\n );\n\nexport interface AgentPermitSignatures {\n operatorSignature: string;\n presentationSignature: string;\n}\n\nexport interface AgentPermitEvaluationInput extends AgentPermitSignatures {\n request: AgentPermitRequest;\n agentState: AgentStateReadResult;\n operatorEvidence: PolicyEvidenceReadResult;\n nowSeconds: number;\n}\n\nexport interface AgentPermitApproval {\n version: 1;\n permitId: string;\n operatorSignature: string;\n verifiedTransaction: string;\n}\n\nexport interface AgentPermitSettlementBundle extends AgentPermitSignatures {\n version: 1;\n nonce: string;\n verifiedTransaction: string;\n}\n\nexport class AgentPermitValidationError extends Error {\n constructor(public readonly field: string) {\n super(`Invalid agent permit: ${field}`);\n this.name = \"AgentPermitValidationError\";\n }\n}\n\nconst FIELD_KEYS = [\n \"agent\",\n \"agent_wallet\",\n \"operator\",\n \"audience\",\n \"action\",\n \"action_sha256\",\n \"policy\",\n \"cluster\",\n \"genesis\",\n \"entros_anchor\",\n \"agent_registry\",\n \"agent_collection\",\n \"issued_at\",\n \"expires_at\",\n \"nonce\",\n] as const;\n\nconst REQUEST_KEYS = [\n \"version\",\n \"agent\",\n \"agentWallet\",\n \"operator\",\n \"audience\",\n \"action\",\n \"policy\",\n \"cluster\",\n \"genesisHash\",\n \"entrosAnchorProgram\",\n \"agentRegistryProgram\",\n \"agentCollection\",\n \"issuedAt\",\n \"expiresAt\",\n \"nonce\",\n] as const;\n\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst HEX128 = /^[0-9a-f]{128}$/;\nconst TIME = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})Z$/;\nconst LABEL = \"(?:[a-z0-9]|[a-z0-9][a-z0-9-]{0,61}[a-z0-9])\";\nconst FINAL = \"(?:[a-z]|[a-z][a-z0-9-]{0,61}[a-z0-9])\";\nconst PORT = \"(?::([1-9][0-9]{0,4}))?\";\nconst PATH = \"(/(?:[A-Za-z0-9._~-]+(?:/[A-Za-z0-9._~-]+)*/?)?)\";\nconst HTTPS_AUDIENCE = new RegExp(\n `^https://((?:${LABEL}\\\\.)+${FINAL})${PORT}${PATH}$`,\n);\nconst LOOPBACK_AUDIENCE = new RegExp(`^http://(127\\\\.0\\\\.0\\\\.1)${PORT}${PATH}$`);\nconst MAX_POLICY_LENGTH = 512;\nconst encoder = new TextEncoder();\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(value: unknown, minimum: number, maximum: number): value is number {\n return (\n typeof value === \"number\" &&\n Number.isSafeInteger(value) &&\n value >= minimum &&\n value <= maximum\n );\n}\n\nfunction hexToBytes(value: string): Uint8Array {\n const bytes = new Uint8Array(value.length / 2);\n for (let index = 0; index < bytes.length; index++) {\n bytes[index] = Number.parseInt(value.slice(index * 2, index * 2 + 2), 16);\n }\n return bytes;\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction printable(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n if (code < 0x20 || code > 0x7e) return false;\n }\n return true;\n}\n\nfunction digestHex(value: unknown): value is string {\n return typeof value === \"string\" && HEX64.test(value) && !/^0+$/.test(value);\n}\n\n/** A canonical Ed25519 point that is not of small order. */\nfunction strictPublicKey(bytes: Uint8Array): boolean {\n try {\n return !ed25519.Point.fromBytes(bytes, false).isSmallOrder();\n } catch {\n return false;\n }\n}\n\nfunction signingKey(value: unknown): value is string {\n if (typeof value !== \"string\") return false;\n const bytes = canonicalKeyBytes(value);\n return bytes !== null && strictPublicKey(bytes);\n}\n\nfunction address(value: unknown): value is string {\n return typeof value === \"string\" && canonicalKeyBytes(value) !== null;\n}\n\n/** Accepts only URLs that already equal their WHATWG `URL.href`. */\nexport function isAgentPermitAudience(value: unknown): value is string {\n if (\n typeof value !== \"string\" ||\n value.length > AGENT_PERMIT_LIMITS.maxAudienceLength\n )\n return false;\n const https = HTTPS_AUDIENCE.exec(value);\n const match = https ?? LOOPBACK_AUDIENCE.exec(value);\n if (!match) return false;\n const [, host, port, path] = match;\n if (host === undefined || path === undefined) return false;\n if (\n host\n .split(\".\")\n .some((label) => label.length >= 4 && label[2] === \"-\" && label[3] === \"-\")\n )\n return false;\n if (port !== undefined) {\n const number = Number(port);\n if (number > 65535 || number === (https ? 443 : 80)) return false;\n }\n return path.split(\"/\").every((segment) => segment !== \".\" && segment !== \"..\");\n}\n\nfunction actionLabel(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length >= 1 &&\n value.length <= AGENT_PERMIT_LIMITS.maxLabelLength &&\n printable(value) &&\n value === value.trim()\n );\n}\n\nfunction unixSeconds(value: unknown): value is number {\n return integer(\n value,\n AGENT_PERMIT_LIMITS.minTimeSeconds,\n AGENT_PERMIT_LIMITS.maxTimeSeconds,\n );\n}\n\nfunction formatTime(seconds: number): string {\n return new Date(seconds * 1000).toISOString().replace(\".000Z\", \"Z\");\n}\n\nfunction parseTime(value: string): number | null {\n if (!TIME.test(value)) return null;\n const milliseconds = Date.parse(value);\n if (!Number.isFinite(milliseconds) || milliseconds % 1000 !== 0) return null;\n const seconds = milliseconds / 1000;\n return unixSeconds(seconds) && formatTime(seconds) === value ? seconds : null;\n}\n\nfunction policyRequest(value: unknown): PolicyRequest | null {\n try {\n const policy = normalizePolicyRequest(value);\n return encodePolicyRequest(policy) === JSON.stringify(value) ? policy : null;\n } catch {\n return null;\n }\n}\n\n/** Validates every field and returns a detached copy. Throws `AgentPermitValidationError`. */\nexport function normalizeAgentPermitRequest(value: unknown): AgentPermitRequest {\n if (!record(value) || !exactKeys(value, REQUEST_KEYS))\n throw new AgentPermitValidationError(\"request\");\n const {\n version,\n agent,\n agentWallet,\n operator,\n audience,\n action,\n issuedAt,\n expiresAt,\n nonce,\n } = value;\n if (version !== 1) throw new AgentPermitValidationError(\"version\");\n if (!address(agent)) throw new AgentPermitValidationError(\"agent\");\n if (!signingKey(agentWallet)) throw new AgentPermitValidationError(\"agentWallet\");\n if (!signingKey(operator)) throw new AgentPermitValidationError(\"operator\");\n if (!isAgentPermitAudience(audience)) throw new AgentPermitValidationError(\"audience\");\n if (\n !record(action) ||\n !exactKeys(action, [\"label\", \"sha256\"]) ||\n !actionLabel(action.label) ||\n !digestHex(action.sha256)\n )\n throw new AgentPermitValidationError(\"action\");\n const policy = policyRequest(value.policy);\n if (!policy) throw new AgentPermitValidationError(\"policy\");\n if (\n value.cluster !== AGENT_PERMIT_NETWORK.cluster ||\n value.genesisHash !== AGENT_PERMIT_NETWORK.genesisHash ||\n value.entrosAnchorProgram !== AGENT_PERMIT_NETWORK.entrosAnchorProgram ||\n value.agentRegistryProgram !== AGENT_PERMIT_NETWORK.agentRegistryProgram ||\n value.agentCollection !== AGENT_PERMIT_NETWORK.agentCollection\n )\n throw new AgentPermitValidationError(\"deployment\");\n if (!unixSeconds(issuedAt) || !unixSeconds(expiresAt))\n throw new AgentPermitValidationError(\"time\");\n const lifetime = expiresAt - issuedAt;\n if (\n lifetime < AGENT_PERMIT_LIMITS.minLifetimeSeconds ||\n lifetime > AGENT_PERMIT_LIMITS.maxLifetimeSeconds\n )\n throw new AgentPermitValidationError(\"lifetime\");\n if (!digestHex(nonce)) throw new AgentPermitValidationError(\"nonce\");\n return {\n version: 1,\n agent,\n agentWallet,\n operator,\n audience,\n action: { label: action.label, sha256: action.sha256 },\n policy,\n cluster: AGENT_PERMIT_NETWORK.cluster,\n genesisHash: AGENT_PERMIT_NETWORK.genesisHash,\n entrosAnchorProgram: AGENT_PERMIT_NETWORK.entrosAnchorProgram,\n agentRegistryProgram: AGENT_PERMIT_NETWORK.agentRegistryProgram,\n agentCollection: AGENT_PERMIT_NETWORK.agentCollection,\n issuedAt,\n expiresAt,\n nonce,\n };\n}\n\nfunction randomNonce(): string {\n const cryptoApi = globalThis.crypto;\n if (!cryptoApi || typeof cryptoApi.getRandomValues !== \"function\")\n throw new AgentPermitValidationError(\"nonce\");\n const bytes = new Uint8Array(32);\n cryptoApi.getRandomValues(bytes);\n return bytesToHex(bytes);\n}\n\n/** Builds a permit request for the consumer to store and render. */\nexport function createAgentPermitRequest(\n input: CreateAgentPermitRequestInput,\n): AgentPermitRequest {\n if (!integer(input.lifetimeSeconds, 1, AGENT_PERMIT_LIMITS.maxLifetimeSeconds))\n throw new AgentPermitValidationError(\"lifetime\");\n return normalizeAgentPermitRequest({\n version: 1,\n agent: input.agent,\n agentWallet: input.agentWallet,\n operator: input.operator,\n audience: input.audience,\n action: { label: input.action.label, sha256: input.action.sha256 },\n policy: normalizePolicyRequest(input.policy),\n cluster: AGENT_PERMIT_NETWORK.cluster,\n genesisHash: AGENT_PERMIT_NETWORK.genesisHash,\n entrosAnchorProgram: AGENT_PERMIT_NETWORK.entrosAnchorProgram,\n agentRegistryProgram: AGENT_PERMIT_NETWORK.agentRegistryProgram,\n agentCollection: AGENT_PERMIT_NETWORK.agentCollection,\n issuedAt: input.issuedAt,\n expiresAt: input.issuedAt + input.lifetimeSeconds,\n nonce: input.nonce ?? randomNonce(),\n });\n}\n\nfunction renderNormalized(value: AgentPermitRequest): string {\n const fields = [\n value.agent,\n value.agentWallet,\n value.operator,\n value.audience,\n value.action.label,\n value.action.sha256,\n encodePolicyRequest(value.policy),\n value.cluster,\n value.genesisHash,\n value.entrosAnchorProgram,\n value.agentRegistryProgram,\n value.agentCollection,\n formatTime(value.issuedAt),\n formatTime(value.expiresAt),\n value.nonce,\n ];\n return [\n AGENT_PERMIT_VERSION_LINE,\n AGENT_PERMIT_NOTICE_LINE,\n ...FIELD_KEYS.map((key, index) => `${key}:${fields[index]}`),\n ].join(\"\\n\");\n}\n\nfunction permitIdOf(message: string): string {\n return bytesToHex(sha256(encoder.encode(message)));\n}\n\n/** Renders the seventeen-line text that the operator signs. */\nexport function renderAgentPermitMessage(request: AgentPermitRequest): string {\n return renderNormalized(normalizeAgentPermitRequest(request));\n}\n\n/** Parses a permit request and requires byte equality with its own rendering. */\nexport function parseAgentPermitMessage(text: unknown): AgentPermitRequest {\n if (typeof text !== \"string\" || text.length > 4096)\n throw new AgentPermitValidationError(\"message\");\n for (let index = 0; index < text.length; index++) {\n const code = text.charCodeAt(index);\n if (code !== 0x0a && (code < 0x20 || code > 0x7e))\n throw new AgentPermitValidationError(\"message\");\n }\n const lines = text.split(\"\\n\");\n if (\n lines.length !== FIELD_KEYS.length + 2 ||\n lines[0] !== AGENT_PERMIT_VERSION_LINE ||\n lines[1] !== AGENT_PERMIT_NOTICE_LINE\n )\n throw new AgentPermitValidationError(\"message\");\n const values = new Map<string, string>();\n FIELD_KEYS.forEach((key, index) => {\n const line = lines[index + 2] ?? \"\";\n if (!line.startsWith(`${key}:`))\n throw new AgentPermitValidationError(key);\n values.set(key, line.slice(key.length + 1));\n });\n const field = (key: (typeof FIELD_KEYS)[number]): string => values.get(key) ?? \"\";\n const policyText = field(\"policy\");\n if (policyText.length > MAX_POLICY_LENGTH)\n throw new AgentPermitValidationError(\"policy\");\n let policy: unknown;\n try {\n policy = JSON.parse(policyText);\n } catch {\n throw new AgentPermitValidationError(\"policy\");\n }\n const issuedAt = parseTime(field(\"issued_at\"));\n const expiresAt = parseTime(field(\"expires_at\"));\n if (issuedAt === null || expiresAt === null)\n throw new AgentPermitValidationError(\"time\");\n const request = normalizeAgentPermitRequest({\n version: 1,\n agent: field(\"agent\"),\n agentWallet: field(\"agent_wallet\"),\n operator: field(\"operator\"),\n audience: field(\"audience\"),\n action: { label: field(\"action\"), sha256: field(\"action_sha256\") },\n policy,\n cluster: field(\"cluster\"),\n genesisHash: field(\"genesis\"),\n entrosAnchorProgram: field(\"entros_anchor\"),\n agentRegistryProgram: field(\"agent_registry\"),\n agentCollection: field(\"agent_collection\"),\n issuedAt,\n expiresAt,\n nonce: field(\"nonce\"),\n });\n if (renderNormalized(request) !== text)\n throw new AgentPermitValidationError(\"message\");\n return request;\n}\n\n/** Lowercase hex SHA-256 of the permit request text. */\nexport function agentPermitId(request: AgentPermitRequest): string {\n return permitIdOf(renderAgentPermitMessage(request));\n}\n\n/** The two-line text that the agent wallet signs. */\nexport function renderAgentPermitPresentation(permitId: string): string {\n if (!HEX64.test(permitId)) throw new AgentPermitValidationError(\"permitId\");\n return `${AGENT_PERMIT_PRESENTATION_LINE}\\npermit:${permitId}`;\n}\n\nfunction strictVerify(\n signature: unknown,\n message: Uint8Array,\n publicKey: string,\n): boolean {\n if (typeof signature !== \"string\" || !HEX128.test(signature)) return false;\n const key = canonicalKeyBytes(publicKey);\n if (!key) return false;\n try {\n // The library default, zip215 true, accepts small-order keys that verify any message.\n return ed25519.verify(hexToBytes(signature), message, key, { zip215: false });\n } catch {\n return false;\n }\n}\n\nfunction verifyNormalized(\n value: AgentPermitRequest,\n signatures: { operatorSignature: unknown; presentationSignature: unknown },\n): { permitId: string; operator: boolean; presentation: boolean } {\n const message = renderNormalized(value);\n const permitId = permitIdOf(message);\n return {\n permitId,\n operator: strictVerify(\n signatures.operatorSignature,\n encoder.encode(message),\n value.operator,\n ),\n presentation: strictVerify(\n signatures.presentationSignature,\n encoder.encode(renderAgentPermitPresentation(permitId)),\n value.agentWallet,\n ),\n };\n}\n\n/** Checks the operator signature and the agent wallet presentation with strict rules. */\nexport function verifyAgentPermitSignatures(\n request: AgentPermitRequest,\n signatures: { operatorSignature: unknown; presentationSignature: unknown },\n): { operator: boolean; presentation: boolean } {\n const { operator, presentation } = verifyNormalized(\n normalizeAgentPermitRequest(request),\n signatures,\n );\n return { operator, presentation };\n}\n\nfunction settlementClock(nowSeconds: number): number {\n if (!integer(nowSeconds, 1, AGENT_PERMIT_LIMITS.maxTimeSeconds))\n throw new AgentPermitValidationError(\"clock\");\n return nowSeconds;\n}\n\n/**\n * Runs every check that needs no chain read: request shape, clock, expiry and both signatures.\n * Call it before reading chain state so an expired or forged permit costs no RPC request.\n */\nexport function precheckAgentPermit(input: {\n request: unknown;\n operatorSignature: unknown;\n presentationSignature: unknown;\n nowSeconds: number;\n}): AgentPermitPrecheck {\n const now = settlementClock(input.nowSeconds);\n let request: AgentPermitRequest;\n try {\n request = normalizeAgentPermitRequest(input.request);\n } catch {\n return { ok: false, reason: \"invalid_permit\", request: null, permitId: null };\n }\n const signatures = verifyNormalized(request, input);\n const { permitId } = signatures;\n if (request.issuedAt > now + AGENT_PERMIT_LIMITS.clockSkewSeconds)\n return { ok: false, reason: \"invalid_permit\", request, permitId };\n if (now >= request.expiresAt)\n return { ok: false, reason: \"permit_expired\", request, permitId };\n if (!signatures.operator)\n return { ok: false, reason: \"invalid_signature\", request, permitId };\n if (!signatures.presentation)\n return { ok: false, reason: \"invalid_presentation\", request, permitId };\n return { ok: true, request, permitId };\n}\n\n/** Strict shape check for agent state from a trusted reader. */\nexport function isAgentStateEvidence(value: unknown): value is AgentStateEvidence {\n if (\n !record(value) ||\n !exactKeys(value, [\n \"cluster\",\n \"genesisHash\",\n \"coreProgram\",\n \"agentRegistryProgram\",\n \"agentCollection\",\n \"agent\",\n \"agentAccount\",\n \"owner\",\n \"cachedOwner\",\n \"agentWallet\",\n \"agentWalletStatus\",\n \"readContextSlot\",\n ])\n )\n return false;\n if (\n value.cluster !== AGENT_PERMIT_NETWORK.cluster ||\n value.genesisHash !== AGENT_PERMIT_NETWORK.genesisHash ||\n value.coreProgram !== AGENT_PERMIT_NETWORK.coreProgram ||\n value.agentRegistryProgram !== AGENT_PERMIT_NETWORK.agentRegistryProgram ||\n value.agentCollection !== AGENT_PERMIT_NETWORK.agentCollection ||\n !address(value.agent) ||\n !address(value.agentAccount) ||\n !address(value.owner) ||\n !address(value.cachedOwner) ||\n (value.agentWallet !== null && !address(value.agentWallet)) ||\n !integer(value.readContextSlot, 0, Number.MAX_SAFE_INTEGER)\n )\n return false;\n const expected: AgentWalletStatus =\n value.cachedOwner !== value.owner\n ? \"stale\"\n : value.agentWallet === null\n ? \"unbound\"\n : \"bound\";\n return value.agentWalletStatus === expected;\n}\n\nfunction agentStateReason(\n reason: unknown,\n): \"wrong_cluster\" | \"agent_missing\" | \"agent_unregistered\" | \"agent_invalid\" {\n return reason === \"wrong_cluster\" ||\n reason === \"agent_missing\" ||\n reason === \"agent_unregistered\"\n ? reason\n : \"agent_invalid\";\n}\n\n/**\n * Evaluates a permit at settlement against agent state and operator evidence read after the\n * precheck. Pass a clock value sampled after those reads complete.\n */\nexport function evaluateAgentPermit(\n input: AgentPermitEvaluationInput,\n): AgentPermitResult {\n const now = settlementClock(input.nowSeconds);\n const precheck = precheckAgentPermit(input);\n const base: AgentPermitResultBase = {\n permitId: precheck.permitId,\n request: precheck.request,\n evaluatedAt: now,\n expiresAt: precheck.request?.expiresAt ?? null,\n agentState: null,\n policy: null,\n };\n const deny = (reason: AgentPermitDenyReason): AgentPermitResult => ({\n ...base,\n decision: \"deny\",\n reason,\n });\n if (!precheck.ok) return deny(precheck.reason);\n const { request } = precheck;\n\n const state: unknown = input.agentState;\n if (!record(state)) return deny(\"agent_invalid\");\n if (state.status === \"unavailable\")\n return { ...base, decision: \"unavailable\", reason: \"agent_unavailable\" };\n if (state.status !== \"available\") return deny(agentStateReason(state.reason));\n if (!isAgentStateEvidence(state.evidence) || state.evidence.agent !== request.agent)\n return deny(\"agent_invalid\");\n const evidence = state.evidence;\n base.agentState = evidence;\n if (evidence.owner !== request.operator) return deny(\"owner_changed\");\n if (evidence.agentWalletStatus === \"stale\") return deny(\"agent_wallet_stale\");\n if (evidence.agentWalletStatus === \"unbound\") return deny(\"agent_wallet_unbound\");\n if (evidence.agentWallet !== request.agentWallet)\n return deny(\"agent_wallet_changed\");\n\n let policy: PolicyResult;\n try {\n policy = evaluatePolicy(request.policy, input.operatorEvidence, now);\n } catch {\n return deny(\"invalid_evidence\");\n }\n base.policy = policy;\n if (policy.decision === \"unavailable\")\n return { ...base, decision: \"unavailable\", reason: \"state_unavailable\" };\n if (policy.decision === \"deny\") {\n const reason = policy.reason;\n return deny(\n reason === \"score_below_minimum\" ||\n reason === \"verification_stale\" ||\n reason === \"attestation_required\"\n ? reason\n : \"invalid_evidence\",\n );\n }\n if (policy.evidence.identity.walletPubkey !== request.operator)\n return deny(\"invalid_evidence\");\n base.expiresAt = Math.min(request.expiresAt, policy.expiresAt);\n if (now >= base.expiresAt) return deny(\"permit_expired\");\n return { ...base, decision: \"allow\", reason: \"accepted\" };\n}\n\nfunction transactionSignature(value: unknown): value is string {\n if (typeof value !== \"string\" || value.length < 64 || value.length > 88)\n return false;\n const bytes = base58Decode(value);\n return bytes !== null && bytes.length === 64 && base58Encode(bytes) === value;\n}\n\nfunction jsonRecord(input: unknown): Record<string, unknown> | null {\n let value: unknown = input;\n if (typeof input === \"string\") {\n if (input.length > 1024) return null;\n try {\n value = JSON.parse(input);\n } catch {\n return null;\n }\n }\n return record(value) ? value : null;\n}\n\n/** Serializes the approval that the signing page hands to the agent. */\nexport function encodeAgentPermitApproval(\n approval: Omit<AgentPermitApproval, \"version\">,\n): string {\n const value = parseAgentPermitApproval({ version: 1, ...approval });\n if (!value) throw new AgentPermitValidationError(\"approval\");\n return JSON.stringify({\n version: 1,\n permitId: value.permitId,\n operatorSignature: value.operatorSignature,\n verifiedTransaction: value.verifiedTransaction,\n });\n}\n\nexport function parseAgentPermitApproval(\n input: unknown,\n): AgentPermitApproval | null {\n const value = jsonRecord(input);\n if (\n !value ||\n !exactKeys(value, [\"version\", \"permitId\", \"operatorSignature\", \"verifiedTransaction\"]) ||\n value.version !== 1 ||\n typeof value.permitId !== \"string\" ||\n !HEX64.test(value.permitId) ||\n typeof value.operatorSignature !== \"string\" ||\n !HEX128.test(value.operatorSignature) ||\n !transactionSignature(value.verifiedTransaction)\n )\n return null;\n return {\n version: 1,\n permitId: value.permitId,\n operatorSignature: value.operatorSignature,\n verifiedTransaction: value.verifiedTransaction,\n };\n}\n\n/** Serializes the bundle that the agent sends to the consumer. */\nexport function encodeAgentPermitSettlement(\n bundle: Omit<AgentPermitSettlementBundle, \"version\">,\n): string {\n const value = parseAgentPermitSettlement({ version: 1, ...bundle });\n if (!value) throw new AgentPermitValidationError(\"settlement\");\n return JSON.stringify({\n version: 1,\n nonce: value.nonce,\n operatorSignature: value.operatorSignature,\n presentationSignature: value.presentationSignature,\n verifiedTransaction: value.verifiedTransaction,\n });\n}\n\nexport function parseAgentPermitSettlement(\n input: unknown,\n): AgentPermitSettlementBundle | null {\n const value = jsonRecord(input);\n if (\n !value ||\n !exactKeys(value, [\n \"version\",\n \"nonce\",\n \"operatorSignature\",\n \"presentationSignature\",\n \"verifiedTransaction\",\n ]) ||\n value.version !== 1 ||\n !digestHex(value.nonce) ||\n typeof value.operatorSignature !== \"string\" ||\n !HEX128.test(value.operatorSignature) ||\n typeof value.presentationSignature !== \"string\" ||\n !HEX128.test(value.presentationSignature) ||\n !transactionSignature(value.verifiedTransaction)\n )\n return null;\n return {\n version: 1,\n nonce: value.nonce,\n operatorSignature: value.operatorSignature,\n presentationSignature: value.presentationSignature,\n verifiedTransaction: value.verifiedTransaction,\n };\n}\n\nfunction base64UrlEncode(text: string): string {\n return btoa(text).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction base64UrlDecode(value: string): string | null {\n if (!/^[A-Za-z0-9_-]*$/.test(value) || value.length % 4 === 1) return null;\n try {\n const padded = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n return atob(padded + \"=\".repeat((4 - (padded.length % 4)) % 4));\n } catch {\n return null;\n }\n}\n\n/** URL fragment for the signing page, without the leading `#`. */\nexport function encodeAgentPermitFragment(request: AgentPermitRequest): string {\n return `request=${base64UrlEncode(renderAgentPermitMessage(request))}`;\n}\n\n/** Parses a `request=` fragment. Returns null for anything else. */\nexport function parseAgentPermitFragment(\n fragment: string,\n): { request: AgentPermitRequest; message: string } | null {\n const body = fragment.startsWith(\"#\") ? fragment.slice(1) : fragment;\n if (!body.startsWith(\"request=\") || body.length > 8192) return null;\n const message = base64UrlDecode(body.slice(\"request=\".length));\n if (message === null) return null;\n try {\n return { request: parseAgentPermitMessage(message), message };\n } catch {\n return null;\n }\n}\n","const ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\nexport function base58Encode(bytes: Uint8Array): string {\n let number = 0n;\n for (const byte of bytes) number = (number << 8n) | BigInt(byte);\n let text = \"\";\n while (number > 0n) {\n text = ALPHABET[Number(number % 58n)] + text;\n number /= 58n;\n }\n let zeros = 0;\n while (zeros < bytes.length && bytes[zeros] === 0) zeros++;\n return \"1\".repeat(zeros) + text;\n}\n\nexport function base58Decode(text: string): Uint8Array | null {\n if (text.length === 0) return null;\n let number = 0n;\n for (const character of text) {\n const digit = ALPHABET.indexOf(character);\n if (digit < 0) return null;\n number = number * 58n + BigInt(digit);\n }\n const body: number[] = [];\n while (number > 0n) {\n body.unshift(Number(number & 0xffn));\n number >>= 8n;\n }\n let zeros = 0;\n while (zeros < text.length && text[zeros] === \"1\") zeros++;\n return Uint8Array.from([...new Array<number>(zeros).fill(0), ...body]);\n}\n\n/** Decodes a 32-byte key and rejects any text that is not its canonical encoding. */\nexport function canonicalKeyBytes(text: string): Uint8Array | null {\n if (text.length < 32 || text.length > 44) return null;\n const bytes = base58Decode(text);\n if (!bytes || bytes.length !== 32 || base58Encode(bytes) !== text) return null;\n return bytes;\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"],"mappings":";AAKA,SAAS,eAAe;AACxB,SAAS,cAAc;;;ACNvB,IAAM,WAAW;AAEV,SAAS,aAAa,OAA2B;AACtD,MAAI,SAAS;AACb,aAAW,QAAQ,MAAO,UAAU,UAAU,KAAM,OAAO,IAAI;AAC/D,MAAI,OAAO;AACX,SAAO,SAAS,IAAI;AAClB,WAAO,SAAS,OAAO,SAAS,GAAG,CAAC,IAAI;AACxC,cAAU;AAAA,EACZ;AACA,MAAI,QAAQ;AACZ,SAAO,QAAQ,MAAM,UAAU,MAAM,KAAK,MAAM,EAAG;AACnD,SAAO,IAAI,OAAO,KAAK,IAAI;AAC7B;AAEO,SAAS,aAAa,MAAiC;AAC5D,MAAI,KAAK,WAAW,EAAG,QAAO;AAC9B,MAAI,SAAS;AACb,aAAW,aAAa,MAAM;AAC5B,UAAM,QAAQ,SAAS,QAA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gBAAgB,KAAK,MAAM,WAAW,MAAM,CAAC;AAC7D,MAAI,YAAY,KAAM,QAAO;AAC7B,MAAI;AACF,WAAO,EAAE,SAAS,wBAAwB,OAAO,GAAG,QAAQ;AAAA,EAC9D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":["REQUEST_KEYS","record","exactKeys","integer"]}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
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,UACP,OACA,MACS;AACT,SACE,OAAO,KAAK,KAAK,EAAE,WAAW,KAAK,UACnC,KAAK,MAAM,CAAC,QAAQ,OAAO,UAAU,eAAe,KAAK,OAAO,GAAG,CAAC;AAExE;AAEA,SAAS,QACP,OACA,UAAU,GACV,UAAU,OAAO,kBACA;AACjB,SACE,OAAO,UAAU,YACjB,OAAO,cAAc,KAAK,KAC1B,SAAS,WACT,SAAS;AAEb;AAEA,IAAM,eAAe;AAAA,EACnB;AAAA,EACA;AA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A;AAAA,QACC,MAAK;AAAA,QACL,SAAS;AAAA,QACT,UAAU;AAAA,QACV,WAAW,MAAM;AAAA,QACjB,OAAO,MAAM;AAAA,QAEZ,sBAAY,oBAAgB,MAAM,YAAY;AAAA;AAAA,IACjD;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 +0,0 @@
1
- {"version":3,"sources":["../src/EntrosVerify.tsx","../src/policy.ts","../src/messaging.ts","../src/url.ts","../src/popup-manager.ts"],"sourcesContent":["/**\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":";;;AAWA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;;;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,UACP,OACA,MACS;AACT,SACE,OAAO,KAAK,KAAK,EAAE,WAAW,KAAK,UACnC,KAAK,MAAM,CAAC,QAAQ,OAAO,UAAU,eAAe,KAAK,OAAO,GAAG,CAAC;AAExE;AAEA,SAAS,QACP,OACA,UAAU,GACV,UAAU,OAAO,kBACA;AACjB,SACE,OAAO,UAAU,YACjB,OAAO,cAAc,KAAK,KAC1B,SAAS,WACT,SAAS;AAEb;AAEA,IAAM,eAAe;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,SAAS,uBACd,OACA,qBACe;AACf,MACE,wBAAwB,UACxB,CAAC,QAAQ,qBAAqB,GAAG,GAAK,GACtC;AACA,UAAM,IAAI,sBAAsB,oBAAoB;AAAA,EACtD;AACA,QAAM,QACJ,UAAU,SACN;AAAA,IAC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