@entros/verify 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
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,QA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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.d.mts CHANGED
@@ -1,5 +1,87 @@
1
1
  import { ReactNode, CSSProperties, ReactElement } from 'react';
2
2
 
3
+ /** Pure policy evaluation. RPC evidence must come from a trusted account reader. */
4
+ interface PolicyRequest {
5
+ id: string;
6
+ version: 1;
7
+ minTrustScore: number;
8
+ maxVerificationAgeSeconds: number;
9
+ maxEvaluationAgeSeconds: number;
10
+ requiredAssurance: "browser_unattested";
11
+ uniquenessRequirement: "allow_unmeasured";
12
+ requireAttestation: boolean;
13
+ cluster: "devnet";
14
+ }
15
+ type PolicyRequestInput = Omit<PolicyRequest, "maxEvaluationAgeSeconds" | "requireAttestation"> & Partial<Pick<PolicyRequest, "maxEvaluationAgeSeconds" | "requireAttestation">>;
16
+ interface PolicyProgramIds {
17
+ anchor: string;
18
+ verifier: string;
19
+ registry: string;
20
+ sas: string;
21
+ credential: string;
22
+ schema: string;
23
+ }
24
+ type PolicyAttestation = {
25
+ status: "present";
26
+ address: string;
27
+ readContextSlot: number;
28
+ expiresAt: number | null;
29
+ } | {
30
+ status: "missing" | "invalid" | "unavailable";
31
+ };
32
+ interface PolicyEvidence {
33
+ cluster: "devnet";
34
+ genesisHash: string;
35
+ programIds: PolicyProgramIds;
36
+ assuranceTier: "browser_unattested";
37
+ uniquenessStatus: "unmeasured";
38
+ readContextSlot: number;
39
+ identity: {
40
+ walletPubkey: string;
41
+ identityPda: string;
42
+ creationTimestamp: number;
43
+ lastVerificationTimestamp: number;
44
+ verificationCount: number;
45
+ trustScore: number;
46
+ currentCommitment: string;
47
+ projectionVersion: number;
48
+ lastResetTimestamp: number;
49
+ lastRebaselineTimestamp: number;
50
+ mint: string;
51
+ };
52
+ transaction: {
53
+ signature: string;
54
+ slot: number;
55
+ blockTime: number;
56
+ commitment: string;
57
+ kind: "mint" | "update" | "rebaseline";
58
+ };
59
+ attestation: PolicyAttestation;
60
+ }
61
+ type PolicyReason = "accepted" | "score_below_minimum" | "verification_stale" | "attestation_required" | "unsupported_policy" | "unsupported_assurance" | "unsupported_uniqueness" | "invalid_evidence" | "state_unavailable";
62
+ interface PolicyResultBase {
63
+ policyId: string;
64
+ policyVersion: 1;
65
+ requirements: PolicyRequest;
66
+ evaluatedAt: number;
67
+ expiresAt: number;
68
+ evidenceTimestamp: number | null;
69
+ evaluatedAgeSeconds: number | null;
70
+ }
71
+ type PolicyResult = PolicyResultBase & ({
72
+ decision: "allow";
73
+ reason: "accepted";
74
+ evidence: PolicyEvidence;
75
+ } | {
76
+ decision: "deny";
77
+ reason: Exclude<PolicyReason, "accepted" | "state_unavailable">;
78
+ evidence: PolicyEvidence | null;
79
+ } | {
80
+ decision: "unavailable";
81
+ reason: "state_unavailable";
82
+ evidence: PolicyEvidence | null;
83
+ });
84
+
3
85
  /**
4
86
  * Public type surface for `@entros/verify`.
5
87
  *
@@ -7,14 +89,18 @@ import { ReactNode, CSSProperties, ReactElement } from 'react';
7
89
  * (`wallet_pubkey`); the JS API surfaced to integrators uses camelCase
8
90
  * (`walletPubkey`). The popup-manager layer translates between them.
9
91
  */
92
+
10
93
  type Cluster = "devnet";
11
94
  /** Result delivered to the integrator's onVerified callback. */
12
95
  interface EntrosVerifyResult {
13
96
  walletPubkey: string;
14
- attestationPda: string;
97
+ attestationPda: string | null;
15
98
  txSig: string;
16
99
  trustScore: number;
17
100
  cluster: Cluster;
101
+ policy: PolicyResult & {
102
+ decision: "allow";
103
+ };
18
104
  }
19
105
  /**
20
106
  * Opaque error categories. Specific server-side reason codes never reach
@@ -23,6 +109,7 @@ interface EntrosVerifyResult {
23
109
  type EntrosVerifyErrorReason = "wallet_rejected" | "validation_failed" | "network_error" | "user_canceled" | "origin_invalid" | "popup_blocked" | "timeout" | "unknown";
24
110
  interface EntrosVerifyError {
25
111
  reason: EntrosVerifyErrorReason;
112
+ policyReason?: PolicyReason;
26
113
  }
27
114
  type EntrosVerifyProgressStatus = "wallet_connecting" | "capturing" | "proving" | "submitting" | "attesting";
28
115
  interface EntrosVerifyProgress {
@@ -52,6 +139,8 @@ interface EntrosVerifyProps {
52
139
  * `validation_failed` instead of `entros/verified`.
53
140
  */
54
141
  minTrustScore?: number;
142
+ /** Application requirements. Missing policy uses the documented day/90-second defaults. */
143
+ policy?: PolicyRequestInput;
55
144
  /** Called on successful verification. Required. */
56
145
  onVerified: (result: EntrosVerifyResult) => void;
57
146
  /** Called on any failure or cancellation. Optional. */
@@ -85,4 +174,4 @@ interface EntrosVerifyProps {
85
174
  }
86
175
  declare function EntrosVerify(props: EntrosVerifyProps): ReactElement;
87
176
 
88
- export { type Cluster, EntrosVerify, type EntrosVerifyError, type EntrosVerifyErrorReason, type EntrosVerifyProgress, type EntrosVerifyProgressStatus, type EntrosVerifyProps, type EntrosVerifyResult };
177
+ export { type Cluster, EntrosVerify, type EntrosVerifyError, type EntrosVerifyErrorReason, type EntrosVerifyProgress, type EntrosVerifyProgressStatus, type EntrosVerifyProps, type EntrosVerifyResult, type PolicyReason, type PolicyRequest, type PolicyRequestInput, type PolicyResult };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,87 @@
1
1
  import { ReactNode, CSSProperties, ReactElement } from 'react';
2
2
 
3
+ /** Pure policy evaluation. RPC evidence must come from a trusted account reader. */
4
+ interface PolicyRequest {
5
+ id: string;
6
+ version: 1;
7
+ minTrustScore: number;
8
+ maxVerificationAgeSeconds: number;
9
+ maxEvaluationAgeSeconds: number;
10
+ requiredAssurance: "browser_unattested";
11
+ uniquenessRequirement: "allow_unmeasured";
12
+ requireAttestation: boolean;
13
+ cluster: "devnet";
14
+ }
15
+ type PolicyRequestInput = Omit<PolicyRequest, "maxEvaluationAgeSeconds" | "requireAttestation"> & Partial<Pick<PolicyRequest, "maxEvaluationAgeSeconds" | "requireAttestation">>;
16
+ interface PolicyProgramIds {
17
+ anchor: string;
18
+ verifier: string;
19
+ registry: string;
20
+ sas: string;
21
+ credential: string;
22
+ schema: string;
23
+ }
24
+ type PolicyAttestation = {
25
+ status: "present";
26
+ address: string;
27
+ readContextSlot: number;
28
+ expiresAt: number | null;
29
+ } | {
30
+ status: "missing" | "invalid" | "unavailable";
31
+ };
32
+ interface PolicyEvidence {
33
+ cluster: "devnet";
34
+ genesisHash: string;
35
+ programIds: PolicyProgramIds;
36
+ assuranceTier: "browser_unattested";
37
+ uniquenessStatus: "unmeasured";
38
+ readContextSlot: number;
39
+ identity: {
40
+ walletPubkey: string;
41
+ identityPda: string;
42
+ creationTimestamp: number;
43
+ lastVerificationTimestamp: number;
44
+ verificationCount: number;
45
+ trustScore: number;
46
+ currentCommitment: string;
47
+ projectionVersion: number;
48
+ lastResetTimestamp: number;
49
+ lastRebaselineTimestamp: number;
50
+ mint: string;
51
+ };
52
+ transaction: {
53
+ signature: string;
54
+ slot: number;
55
+ blockTime: number;
56
+ commitment: string;
57
+ kind: "mint" | "update" | "rebaseline";
58
+ };
59
+ attestation: PolicyAttestation;
60
+ }
61
+ type PolicyReason = "accepted" | "score_below_minimum" | "verification_stale" | "attestation_required" | "unsupported_policy" | "unsupported_assurance" | "unsupported_uniqueness" | "invalid_evidence" | "state_unavailable";
62
+ interface PolicyResultBase {
63
+ policyId: string;
64
+ policyVersion: 1;
65
+ requirements: PolicyRequest;
66
+ evaluatedAt: number;
67
+ expiresAt: number;
68
+ evidenceTimestamp: number | null;
69
+ evaluatedAgeSeconds: number | null;
70
+ }
71
+ type PolicyResult = PolicyResultBase & ({
72
+ decision: "allow";
73
+ reason: "accepted";
74
+ evidence: PolicyEvidence;
75
+ } | {
76
+ decision: "deny";
77
+ reason: Exclude<PolicyReason, "accepted" | "state_unavailable">;
78
+ evidence: PolicyEvidence | null;
79
+ } | {
80
+ decision: "unavailable";
81
+ reason: "state_unavailable";
82
+ evidence: PolicyEvidence | null;
83
+ });
84
+
3
85
  /**
4
86
  * Public type surface for `@entros/verify`.
5
87
  *
@@ -7,14 +89,18 @@ import { ReactNode, CSSProperties, ReactElement } from 'react';
7
89
  * (`wallet_pubkey`); the JS API surfaced to integrators uses camelCase
8
90
  * (`walletPubkey`). The popup-manager layer translates between them.
9
91
  */
92
+
10
93
  type Cluster = "devnet";
11
94
  /** Result delivered to the integrator's onVerified callback. */
12
95
  interface EntrosVerifyResult {
13
96
  walletPubkey: string;
14
- attestationPda: string;
97
+ attestationPda: string | null;
15
98
  txSig: string;
16
99
  trustScore: number;
17
100
  cluster: Cluster;
101
+ policy: PolicyResult & {
102
+ decision: "allow";
103
+ };
18
104
  }
19
105
  /**
20
106
  * Opaque error categories. Specific server-side reason codes never reach
@@ -23,6 +109,7 @@ interface EntrosVerifyResult {
23
109
  type EntrosVerifyErrorReason = "wallet_rejected" | "validation_failed" | "network_error" | "user_canceled" | "origin_invalid" | "popup_blocked" | "timeout" | "unknown";
24
110
  interface EntrosVerifyError {
25
111
  reason: EntrosVerifyErrorReason;
112
+ policyReason?: PolicyReason;
26
113
  }
27
114
  type EntrosVerifyProgressStatus = "wallet_connecting" | "capturing" | "proving" | "submitting" | "attesting";
28
115
  interface EntrosVerifyProgress {
@@ -52,6 +139,8 @@ interface EntrosVerifyProps {
52
139
  * `validation_failed` instead of `entros/verified`.
53
140
  */
54
141
  minTrustScore?: number;
142
+ /** Application requirements. Missing policy uses the documented day/90-second defaults. */
143
+ policy?: PolicyRequestInput;
55
144
  /** Called on successful verification. Required. */
56
145
  onVerified: (result: EntrosVerifyResult) => void;
57
146
  /** Called on any failure or cancellation. Optional. */
@@ -85,4 +174,4 @@ interface EntrosVerifyProps {
85
174
  }
86
175
  declare function EntrosVerify(props: EntrosVerifyProps): ReactElement;
87
176
 
88
- export { type Cluster, EntrosVerify, type EntrosVerifyError, type EntrosVerifyErrorReason, type EntrosVerifyProgress, type EntrosVerifyProgressStatus, type EntrosVerifyProps, type EntrosVerifyResult };
177
+ export { type Cluster, EntrosVerify, type EntrosVerifyError, type EntrosVerifyErrorReason, type EntrosVerifyProgress, type EntrosVerifyProgressStatus, type EntrosVerifyProps, type EntrosVerifyResult, type PolicyReason, type PolicyRequest, type PolicyRequestInput, type PolicyResult };