@entros/verify 0.4.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -1
- package/dist/agent-permit.d.mts +22 -2
- package/dist/agent-permit.d.ts +22 -2
- package/dist/agent-permit.js +1 -1
- package/dist/agent-permit.mjs +1 -1
- package/dist/index.d.mts +87 -6
- package/dist/index.d.ts +87 -6
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -60,6 +60,39 @@ Supplying conflicting `minTrustScore` and `policy.minTrustScore` values fails be
|
|
|
60
60
|
The result states `browser_unattested` assurance and `unmeasured` uniqueness.
|
|
61
61
|
These fields do not establish sensor provenance or population uniqueness.
|
|
62
62
|
|
|
63
|
+
## Warm policy reuse
|
|
64
|
+
|
|
65
|
+
Before starting browser capture, a host can check whether the wallet already satisfies the policy on devnet.
|
|
66
|
+
When existing evidence passes, verification completes at `0 SOL` and zero capture rounds.
|
|
67
|
+
Warm reuse preserves the original `verifiedAt` timestamp (`lastVerificationTimestamp`). It never refreshes evidence age.
|
|
68
|
+
|
|
69
|
+
`@entros/verify` exports `evaluateWarmPolicyReuse` without adding a dependency on `@entros/pulse-sdk`.
|
|
70
|
+
Supply either a pre-read observation or injected async readers backed by your configured RPC connection:
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
import { evaluateWarmPolicyReuse } from "@entros/verify";
|
|
74
|
+
|
|
75
|
+
const warm = await evaluateWarmPolicyReuse({
|
|
76
|
+
walletPubkey,
|
|
77
|
+
policy,
|
|
78
|
+
findVerification: ({ walletPubkey: wallet }) =>
|
|
79
|
+
findLatestVerificationTransaction({ walletPubkey: wallet, connection, verifiedAt }),
|
|
80
|
+
readEvidence: ({ walletPubkey: wallet, transactionSignature }) =>
|
|
81
|
+
readIntegratorEvidence({
|
|
82
|
+
walletPubkey: wallet,
|
|
83
|
+
transactionSignature: transactionSignature!,
|
|
84
|
+
connection,
|
|
85
|
+
nowSeconds: now,
|
|
86
|
+
}),
|
|
87
|
+
nowSeconds: now,
|
|
88
|
+
});
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`evaluateWarmPolicyReuse` normalizes the policy, rejects wallet mismatches, and returns `reused` only when `evaluatePolicy` returns `allow`.
|
|
92
|
+
Set `requireLegacyAttestation: true` when calling without a negotiated policy so reuse requires a present attestation.
|
|
93
|
+
Stale evidence, below-floor scores, reset identities, or missing evidence return `needs_capture` so the flow proceeds to capture.
|
|
94
|
+
Reused results retain `devnet`, `browser_unattested` assurance, and `unmeasured` population uniqueness.
|
|
95
|
+
|
|
63
96
|
## Result
|
|
64
97
|
|
|
65
98
|
```ts
|
|
@@ -184,7 +217,10 @@ const result = evaluateAgentPermit({
|
|
|
184
217
|
The precheck covers expiry and both signatures, so an expired or forged permit costs your service no chain read.
|
|
185
218
|
Sample the clock again after the reads, because a permit can expire while they run.
|
|
186
219
|
|
|
187
|
-
-
|
|
220
|
+
- Compare the request with what your service issued: at least the nonce and the terms. Passing the stored request as `request`, as above, does both.
|
|
221
|
+
A service that keeps only the nonce and some terms passes them as `expected: { nonce, audience, action, policy }`, with `agent` and `operator` when it stores them.
|
|
222
|
+
`evaluateAgentPermit` then denies a signed request with another nonce or other terms with `request_mismatch`.
|
|
223
|
+
Never take policy or RPC settings from the agent.
|
|
188
224
|
- Execute the stored action at settlement. Do not return a reusable credential to the presenter.
|
|
189
225
|
- The owner is the wallet in the Metaplex Core asset. The registry's cached owner and the `entros:human-operator` metadata grant nothing.
|
|
190
226
|
- A transfer after the settlement read can still land before your action. An on-chain action must check ownership inside its transaction.
|
|
@@ -193,6 +229,13 @@ Run the [agent-permit example](examples/agent-permit) to exercise issuance, both
|
|
|
193
229
|
|
|
194
230
|
A permit states current wallet control of a registered agent and the owner's Entros policy result. It does not establish legal ownership, population uniqueness, or hardware assurance.
|
|
195
231
|
|
|
232
|
+
## Reference consumer
|
|
233
|
+
|
|
234
|
+
Run the [reference-consumer example](examples/reference-consumer) to test a standalone application built against published npm packages.
|
|
235
|
+
It exercises warm policy reuse, Integrator Policy v1 settlement, Agent Operator Permit pause-and-approve, Realms voter-weight checks, and stage latency telemetry.
|
|
236
|
+
For Realms governance, the plugin enforces `one eligible wallet, one vote` with current-slot expiry and migration-slot checks against each proposal.
|
|
237
|
+
All demonstrations and tests run locally against synthetic devnet fixtures.
|
|
238
|
+
|
|
196
239
|
## Migration from `0.1.1`
|
|
197
240
|
|
|
198
241
|
Version `0.2.0` changes the callback contract:
|
package/dist/agent-permit.d.mts
CHANGED
|
@@ -79,7 +79,7 @@ type AgentStateReadResult = {
|
|
|
79
79
|
status: "invalid" | "unavailable";
|
|
80
80
|
reason: AgentStateFailureReason;
|
|
81
81
|
};
|
|
82
|
-
type AgentPermitReason = "accepted" | "invalid_permit" | "permit_expired" | "invalid_signature" | "invalid_presentation" | "wrong_cluster" | "agent_missing" | "agent_invalid" | "agent_unregistered" | "agent_unavailable" | "owner_changed" | "agent_wallet_stale" | "agent_wallet_unbound" | "agent_wallet_changed" | "score_below_minimum" | "verification_stale" | "attestation_required" | "invalid_evidence" | "state_unavailable";
|
|
82
|
+
type AgentPermitReason = "accepted" | "invalid_permit" | "permit_expired" | "invalid_signature" | "invalid_presentation" | "request_mismatch" | "wrong_cluster" | "agent_missing" | "agent_invalid" | "agent_unregistered" | "agent_unavailable" | "owner_changed" | "agent_wallet_stale" | "agent_wallet_unbound" | "agent_wallet_changed" | "score_below_minimum" | "verification_stale" | "attestation_required" | "invalid_evidence" | "state_unavailable";
|
|
83
83
|
type AgentPermitDenyReason = Exclude<AgentPermitReason, "accepted" | "agent_unavailable" | "state_unavailable">;
|
|
84
84
|
type AgentPermitPrecheck = {
|
|
85
85
|
ok: true;
|
|
@@ -113,11 +113,31 @@ interface AgentPermitSignatures {
|
|
|
113
113
|
operatorSignature: string;
|
|
114
114
|
presentationSignature: string;
|
|
115
115
|
}
|
|
116
|
+
/**
|
|
117
|
+
* What a service issued for a permit. The nonce is required: two issued permits can share
|
|
118
|
+
* every term, and only the nonce tells them apart, so terms alone would let one signed permit
|
|
119
|
+
* settle once per issue. Each term is optional, so a service pins the terms it stores.
|
|
120
|
+
*/
|
|
121
|
+
interface AgentPermitExpectation {
|
|
122
|
+
nonce: string;
|
|
123
|
+
agent?: string;
|
|
124
|
+
operator?: string;
|
|
125
|
+
audience?: string;
|
|
126
|
+
action?: AgentPermitAction;
|
|
127
|
+
policy?: PolicyRequest;
|
|
128
|
+
}
|
|
116
129
|
interface AgentPermitEvaluationInput extends AgentPermitSignatures {
|
|
117
130
|
request: AgentPermitRequest;
|
|
118
131
|
agentState: AgentStateReadResult;
|
|
119
132
|
operatorEvidence: PolicyEvidenceReadResult;
|
|
120
133
|
nowSeconds: number;
|
|
134
|
+
/**
|
|
135
|
+
* What the service issued for this permit. Both signatures cover `request` as the caller
|
|
136
|
+
* supplies it, so a service that does not evaluate its own stored request passes the nonce
|
|
137
|
+
* and the terms it issued here. A signed request with another nonce or other terms is denied
|
|
138
|
+
* with `request_mismatch`.
|
|
139
|
+
*/
|
|
140
|
+
expected?: AgentPermitExpectation;
|
|
121
141
|
}
|
|
122
142
|
interface AgentPermitApproval {
|
|
123
143
|
version: 1;
|
|
@@ -187,4 +207,4 @@ declare function parseAgentPermitFragment(fragment: string): {
|
|
|
187
207
|
message: string;
|
|
188
208
|
} | null;
|
|
189
209
|
|
|
190
|
-
export { AGENT_PERMIT_LIMITS, AGENT_PERMIT_NETWORK, AGENT_PERMIT_NOTICE_LINE, AGENT_PERMIT_PRESENTATION_LINE, AGENT_PERMIT_VERSION_LINE, type AgentPermitAction, type AgentPermitApproval, type AgentPermitDenyReason, type AgentPermitEvaluationInput, type AgentPermitPrecheck, type AgentPermitReason, type AgentPermitRequest, type AgentPermitResult, type AgentPermitSettlementBundle, type AgentPermitSignatures, AgentPermitValidationError, type AgentStateEvidence, type AgentStateFailureReason, type AgentStateReadResult, type AgentWalletStatus, type CreateAgentPermitRequestInput, agentPermitId, createAgentPermitRequest, encodeAgentPermitApproval, encodeAgentPermitFragment, encodeAgentPermitSettlement, evaluateAgentPermit, isAgentPermitAudience, isAgentStateEvidence, normalizeAgentPermitRequest, parseAgentPermitApproval, parseAgentPermitFragment, parseAgentPermitMessage, parseAgentPermitSettlement, precheckAgentPermit, renderAgentPermitMessage, renderAgentPermitPresentation, verifyAgentPermitSignatures };
|
|
210
|
+
export { AGENT_PERMIT_LIMITS, AGENT_PERMIT_NETWORK, AGENT_PERMIT_NOTICE_LINE, AGENT_PERMIT_PRESENTATION_LINE, AGENT_PERMIT_VERSION_LINE, type AgentPermitAction, type AgentPermitApproval, type AgentPermitDenyReason, type AgentPermitEvaluationInput, type AgentPermitExpectation, type AgentPermitPrecheck, type AgentPermitReason, type AgentPermitRequest, type AgentPermitResult, type AgentPermitSettlementBundle, type AgentPermitSignatures, AgentPermitValidationError, type AgentStateEvidence, type AgentStateFailureReason, type AgentStateReadResult, type AgentWalletStatus, type CreateAgentPermitRequestInput, agentPermitId, createAgentPermitRequest, encodeAgentPermitApproval, encodeAgentPermitFragment, encodeAgentPermitSettlement, evaluateAgentPermit, isAgentPermitAudience, isAgentStateEvidence, normalizeAgentPermitRequest, parseAgentPermitApproval, parseAgentPermitFragment, parseAgentPermitMessage, parseAgentPermitSettlement, precheckAgentPermit, renderAgentPermitMessage, renderAgentPermitPresentation, verifyAgentPermitSignatures };
|
package/dist/agent-permit.d.ts
CHANGED
|
@@ -79,7 +79,7 @@ type AgentStateReadResult = {
|
|
|
79
79
|
status: "invalid" | "unavailable";
|
|
80
80
|
reason: AgentStateFailureReason;
|
|
81
81
|
};
|
|
82
|
-
type AgentPermitReason = "accepted" | "invalid_permit" | "permit_expired" | "invalid_signature" | "invalid_presentation" | "wrong_cluster" | "agent_missing" | "agent_invalid" | "agent_unregistered" | "agent_unavailable" | "owner_changed" | "agent_wallet_stale" | "agent_wallet_unbound" | "agent_wallet_changed" | "score_below_minimum" | "verification_stale" | "attestation_required" | "invalid_evidence" | "state_unavailable";
|
|
82
|
+
type AgentPermitReason = "accepted" | "invalid_permit" | "permit_expired" | "invalid_signature" | "invalid_presentation" | "request_mismatch" | "wrong_cluster" | "agent_missing" | "agent_invalid" | "agent_unregistered" | "agent_unavailable" | "owner_changed" | "agent_wallet_stale" | "agent_wallet_unbound" | "agent_wallet_changed" | "score_below_minimum" | "verification_stale" | "attestation_required" | "invalid_evidence" | "state_unavailable";
|
|
83
83
|
type AgentPermitDenyReason = Exclude<AgentPermitReason, "accepted" | "agent_unavailable" | "state_unavailable">;
|
|
84
84
|
type AgentPermitPrecheck = {
|
|
85
85
|
ok: true;
|
|
@@ -113,11 +113,31 @@ interface AgentPermitSignatures {
|
|
|
113
113
|
operatorSignature: string;
|
|
114
114
|
presentationSignature: string;
|
|
115
115
|
}
|
|
116
|
+
/**
|
|
117
|
+
* What a service issued for a permit. The nonce is required: two issued permits can share
|
|
118
|
+
* every term, and only the nonce tells them apart, so terms alone would let one signed permit
|
|
119
|
+
* settle once per issue. Each term is optional, so a service pins the terms it stores.
|
|
120
|
+
*/
|
|
121
|
+
interface AgentPermitExpectation {
|
|
122
|
+
nonce: string;
|
|
123
|
+
agent?: string;
|
|
124
|
+
operator?: string;
|
|
125
|
+
audience?: string;
|
|
126
|
+
action?: AgentPermitAction;
|
|
127
|
+
policy?: PolicyRequest;
|
|
128
|
+
}
|
|
116
129
|
interface AgentPermitEvaluationInput extends AgentPermitSignatures {
|
|
117
130
|
request: AgentPermitRequest;
|
|
118
131
|
agentState: AgentStateReadResult;
|
|
119
132
|
operatorEvidence: PolicyEvidenceReadResult;
|
|
120
133
|
nowSeconds: number;
|
|
134
|
+
/**
|
|
135
|
+
* What the service issued for this permit. Both signatures cover `request` as the caller
|
|
136
|
+
* supplies it, so a service that does not evaluate its own stored request passes the nonce
|
|
137
|
+
* and the terms it issued here. A signed request with another nonce or other terms is denied
|
|
138
|
+
* with `request_mismatch`.
|
|
139
|
+
*/
|
|
140
|
+
expected?: AgentPermitExpectation;
|
|
121
141
|
}
|
|
122
142
|
interface AgentPermitApproval {
|
|
123
143
|
version: 1;
|
|
@@ -187,4 +207,4 @@ declare function parseAgentPermitFragment(fragment: string): {
|
|
|
187
207
|
message: string;
|
|
188
208
|
} | null;
|
|
189
209
|
|
|
190
|
-
export { AGENT_PERMIT_LIMITS, AGENT_PERMIT_NETWORK, AGENT_PERMIT_NOTICE_LINE, AGENT_PERMIT_PRESENTATION_LINE, AGENT_PERMIT_VERSION_LINE, type AgentPermitAction, type AgentPermitApproval, type AgentPermitDenyReason, type AgentPermitEvaluationInput, type AgentPermitPrecheck, type AgentPermitReason, type AgentPermitRequest, type AgentPermitResult, type AgentPermitSettlementBundle, type AgentPermitSignatures, AgentPermitValidationError, type AgentStateEvidence, type AgentStateFailureReason, type AgentStateReadResult, type AgentWalletStatus, type CreateAgentPermitRequestInput, agentPermitId, createAgentPermitRequest, encodeAgentPermitApproval, encodeAgentPermitFragment, encodeAgentPermitSettlement, evaluateAgentPermit, isAgentPermitAudience, isAgentStateEvidence, normalizeAgentPermitRequest, parseAgentPermitApproval, parseAgentPermitFragment, parseAgentPermitMessage, parseAgentPermitSettlement, precheckAgentPermit, renderAgentPermitMessage, renderAgentPermitPresentation, verifyAgentPermitSignatures };
|
|
210
|
+
export { AGENT_PERMIT_LIMITS, AGENT_PERMIT_NETWORK, AGENT_PERMIT_NOTICE_LINE, AGENT_PERMIT_PRESENTATION_LINE, AGENT_PERMIT_VERSION_LINE, type AgentPermitAction, type AgentPermitApproval, type AgentPermitDenyReason, type AgentPermitEvaluationInput, type AgentPermitExpectation, type AgentPermitPrecheck, type AgentPermitReason, type AgentPermitRequest, type AgentPermitResult, type AgentPermitSettlementBundle, type AgentPermitSignatures, AgentPermitValidationError, type AgentStateEvidence, type AgentStateFailureReason, type AgentStateReadResult, type AgentWalletStatus, type CreateAgentPermitRequestInput, agentPermitId, createAgentPermitRequest, encodeAgentPermitApproval, encodeAgentPermitFragment, encodeAgentPermitSettlement, evaluateAgentPermit, isAgentPermitAudience, isAgentStateEvidence, normalizeAgentPermitRequest, parseAgentPermitApproval, parseAgentPermitFragment, parseAgentPermitMessage, parseAgentPermitSettlement, precheckAgentPermit, renderAgentPermitMessage, renderAgentPermitPresentation, verifyAgentPermitSignatures };
|
package/dist/agent-permit.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var agent_permit_exports={};__export(agent_permit_exports,{AGENT_PERMIT_LIMITS:()=>AGENT_PERMIT_LIMITS,AGENT_PERMIT_NETWORK:()=>AGENT_PERMIT_NETWORK,AGENT_PERMIT_NOTICE_LINE:()=>AGENT_PERMIT_NOTICE_LINE,AGENT_PERMIT_PRESENTATION_LINE:()=>AGENT_PERMIT_PRESENTATION_LINE,AGENT_PERMIT_VERSION_LINE:()=>AGENT_PERMIT_VERSION_LINE,AgentPermitValidationError:()=>AgentPermitValidationError,agentPermitId:()=>agentPermitId,createAgentPermitRequest:()=>createAgentPermitRequest,encodeAgentPermitApproval:()=>encodeAgentPermitApproval,encodeAgentPermitFragment:()=>encodeAgentPermitFragment,encodeAgentPermitSettlement:()=>encodeAgentPermitSettlement,evaluateAgentPermit:()=>evaluateAgentPermit,isAgentPermitAudience:()=>isAgentPermitAudience,isAgentStateEvidence:()=>isAgentStateEvidence,normalizeAgentPermitRequest:()=>normalizeAgentPermitRequest,parseAgentPermitApproval:()=>parseAgentPermitApproval,parseAgentPermitFragment:()=>parseAgentPermitFragment,parseAgentPermitMessage:()=>parseAgentPermitMessage,parseAgentPermitSettlement:()=>parseAgentPermitSettlement,precheckAgentPermit:()=>precheckAgentPermit,renderAgentPermitMessage:()=>renderAgentPermitMessage,renderAgentPermitPresentation:()=>renderAgentPermitPresentation,verifyAgentPermitSignatures:()=>verifyAgentPermitSignatures});module.exports=__toCommonJS(agent_permit_exports);var import_ed25519=require("@noble/curves/ed25519"),import_sha2=require("@noble/hashes/sha2");var ALPHABET="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function base58Encode(bytes){let number=0n;for(let byte of bytes)number=number<<8n|BigInt(byte);let text="";for(;number>0n;)text=ALPHABET[Number(number%58n)]+text,number/=58n;let zeros=0;for(;zeros<bytes.length&&bytes[zeros]===0;)zeros++;return"1".repeat(zeros)+text}function base58Decode(text){if(text.length===0)return null;let number=0n;for(let character of text){let digit=ALPHABET.indexOf(character);if(digit<0)return null;number=number*58n+BigInt(digit)}let body=[];for(;number>0n;)body.unshift(Number(number&0xffn)),number>>=8n;let zeros=0;for(;zeros<text.length&&text[zeros]==="1";)zeros++;return Uint8Array.from([...new Array(zeros).fill(0),...body])}function canonicalKeyBytes(text){if(text.length<32||text.length>44)return null;let bytes=base58Decode(text);return!bytes||bytes.length!==32||base58Encode(bytes)!==text?null:bytes}var POLICY_NETWORK=Object.freeze({genesisHash:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG",programIds:Object.freeze({anchor:"GZYwTp2ozeuRA5Gof9vs4ya961aANcJBdUzB7LN6q4b2",verifier:"4F97jNoxQzT2qRbkWpW3ztC3Nz2TtKj3rnKG8ExgnrfV",registry:"6VBs3zr9KrfFPGd6j7aGBPQWwZa5tajVfA7HN6MMV9VW",sas:"22zoJMtdu4tQc2PzL74ZUT7FrwgB1Udec8DdW4yw4BdG",credential:"AMBtabCgRFwGLjoZ21Z2LhSKJ6c47NckxUkMogJ3Lpuw",schema:"5LNc7syFW7USPLveVLcNcjjY1xqS7QTXVjHZ7CQCbAMQ"})}),PolicyValidationError=class extends Error{constructor(reason){super(`Invalid verification policy: ${reason}`);this.reason=reason;this.name="PolicyValidationError"}};function record(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function exactKeys(value,keys){return Object.keys(value).length===keys.length&&keys.every(key=>Object.prototype.hasOwnProperty.call(value,key))}var BLOCK_TIME_TOLERANCE_SECONDS=2;function integer(value,minimum=0,maximum=Number.MAX_SAFE_INTEGER){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=minimum&&value<=maximum}var REQUEST_KEYS=["id","version","minTrustScore","maxVerificationAgeSeconds","maxEvaluationAgeSeconds","requiredAssurance","uniquenessRequirement","requireAttestation","cluster"];function normalizePolicyRequest(input,legacyMinTrustScore){if(legacyMinTrustScore!==void 0&&!integer(legacyMinTrustScore,0,1e4))throw new PolicyValidationError("unsupported_policy");let value=input===void 0?{id:"entros-verify-default",version:1,minTrustScore:legacyMinTrustScore??0,maxVerificationAgeSeconds:86400,requiredAssurance:"browser_unattested",uniquenessRequirement:"allow_unmeasured",cluster:"devnet"}:input;if(!record(value)||Object.keys(value).some(key=>!REQUEST_KEYS.includes(key)))throw new PolicyValidationError("unsupported_policy");if(value.requiredAssurance!=="browser_unattested")throw new PolicyValidationError("unsupported_assurance");if(value.uniquenessRequirement!=="allow_unmeasured")throw new PolicyValidationError("unsupported_uniqueness");if(typeof value.id!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(value.id)||value.version!==1||!integer(value.minTrustScore,0,1e4)||!integer(value.maxVerificationAgeSeconds,1,31536e3)||!integer(value.maxEvaluationAgeSeconds===void 0?90:value.maxEvaluationAgeSeconds,1,90)||value.requireAttestation!==void 0&&typeof value.requireAttestation!="boolean"||value.cluster!=="devnet"||legacyMinTrustScore!==void 0&&value.minTrustScore!==legacyMinTrustScore)throw new PolicyValidationError("unsupported_policy");return{id:value.id,version:1,minTrustScore:value.minTrustScore,maxVerificationAgeSeconds:value.maxVerificationAgeSeconds,maxEvaluationAgeSeconds:value.maxEvaluationAgeSeconds??90,requiredAssurance:"browser_unattested",uniquenessRequirement:"allow_unmeasured",requireAttestation:value.requireAttestation===!0,cluster:"devnet"}}function encodePolicyRequest(request){return JSON.stringify(normalizePolicyRequest(request))}var BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function base58Bytes(value,expected){if(typeof value!="string"||value.length<1||value.length>expected*2)return!1;let number=0n;for(let character of value){let digit=BASE58.indexOf(character);if(digit<0)return!1;number=number*58n+BigInt(digit)}let bytes=0;for(;number>0n;)bytes++,number>>=8n;let zeros=0;for(;value[zeros]==="1";)zeros++;return bytes+zeros===expected}function commitment(value){return typeof value=="string"&&/^[0-9a-f]{64}$/.test(value)&&!/^0+$/.test(value)}function isPolicyAttestation(value){return record(value)?value.status==="present"?exactKeys(value,["status","address","readContextSlot","expiresAt"])&&base58Bytes(value.address,32)&&integer(value.readContextSlot)&&(value.expiresAt===null||integer(value.expiresAt,1)):exactKeys(value,["status"])&&["missing","invalid","unavailable"].includes(String(value.status)):!1}function isPolicyEvidence(value){if(!record(value)||!exactKeys(value,["cluster","genesisHash","programIds","assuranceTier","uniquenessStatus","readContextSlot","identity","transaction","attestation"])||value.cluster!=="devnet"||value.genesisHash!==POLICY_NETWORK.genesisHash||value.assuranceTier!=="browser_unattested"||value.uniquenessStatus!=="unmeasured"||!integer(value.readContextSlot))return!1;let programs=value.programIds;if(!record(programs)||!exactKeys(programs,Object.keys(POLICY_NETWORK.programIds))||Object.entries(POLICY_NETWORK.programIds).some(([key,id])=>programs[key]!==id))return!1;let identity=value.identity,transaction=value.transaction;return!record(identity)||!exactKeys(identity,["walletPubkey","identityPda","creationTimestamp","lastVerificationTimestamp","verificationCount","trustScore","currentCommitment","projectionVersion","lastResetTimestamp","lastRebaselineTimestamp","mint"])||!base58Bytes(identity.walletPubkey,32)||!base58Bytes(identity.identityPda,32)||!base58Bytes(identity.mint,32)||!integer(identity.creationTimestamp,1)||!integer(identity.lastVerificationTimestamp,identity.creationTimestamp)||!integer(identity.verificationCount,0,4294967295)||!integer(identity.trustScore,0,1e4)||!commitment(identity.currentCommitment)||!integer(identity.projectionVersion,0,2)||!integer(identity.lastResetTimestamp)||!integer(identity.lastRebaselineTimestamp)||!record(transaction)||!exactKeys(transaction,["signature","slot","blockTime","commitment","kind"])||!base58Bytes(transaction.signature,64)||!integer(transaction.slot)||!integer(transaction.blockTime,identity.creationTimestamp-BLOCK_TIME_TOLERANCE_SECONDS)||!commitment(transaction.commitment)||!["mint","update","rebaseline"].includes(String(transaction.kind))?!1:isPolicyAttestation(value.attestation)}function evaluatePolicy(request,observation,nowSeconds){let requirements=normalizePolicyRequest(request);if(!integer(nowSeconds,1)||nowSeconds>Number.MAX_SAFE_INTEGER-31536e3)throw new PolicyValidationError("invalid_evidence");let base={policyId:requirements.id,policyVersion:1,requirements,evaluatedAt:nowSeconds,expiresAt:nowSeconds,evidenceTimestamp:null,evaluatedAgeSeconds:null};if(record(observation)&&observation.status==="unavailable")return{...base,decision:"unavailable",reason:"state_unavailable",evidence:null};if(!record(observation)||observation.status!=="available"||!isPolicyEvidence(observation.evidence))return{...base,decision:"deny",reason:"invalid_evidence",evidence:null};let evidence=observation.evidence,{identity,transaction,attestation}=evidence,deny=reason=>({...base,decision:"deny",reason,evidence}),earliestClock=transaction.blockTime-BLOCK_TIME_TOLERANCE_SECONDS,latestClock=transaction.blockTime+BLOCK_TIME_TOLERANCE_SECONDS,freshMint=transaction.kind==="mint"&&identity.verificationCount===0&&identity.trustScore===0&&identity.creationTimestamp===identity.lastVerificationTimestamp&&identity.lastVerificationTimestamp>=earliestClock&&identity.lastVerificationTimestamp<=latestClock&&identity.lastResetTimestamp===0&&identity.lastRebaselineTimestamp===0;return identity.verificationCount===0&&!freshMint||identity.currentCommitment!==transaction.commitment||identity.lastResetTimestamp>=earliestClock||identity.lastResetTimestamp>identity.lastVerificationTimestamp||identity.lastRebaselineTimestamp>identity.lastVerificationTimestamp||identity.lastRebaselineTimestamp>(transaction.kind==="rebaseline"?latestClock:earliestClock)||identity.lastVerificationTimestamp>nowSeconds||transaction.blockTime>nowSeconds||evidence.readContextSlot<transaction.slot||attestation.status==="invalid"||attestation.status==="present"&&(attestation.readContextSlot<transaction.slot||attestation.expiresAt!==null&&attestation.expiresAt<=nowSeconds)?deny("invalid_evidence"):(base.evidenceTimestamp=Math.min(identity.lastVerificationTimestamp,transaction.blockTime),base.evaluatedAgeSeconds=nowSeconds-base.evidenceTimestamp,base.expiresAt=Math.min(base.evidenceTimestamp+requirements.maxVerificationAgeSeconds,nowSeconds+requirements.maxEvaluationAgeSeconds),requirements.requireAttestation&&attestation.status==="present"&&attestation.expiresAt!==null&&(base.expiresAt=Math.min(base.expiresAt,attestation.expiresAt)),identity.trustScore<requirements.minTrustScore?deny("score_below_minimum"):nowSeconds>=base.expiresAt?deny("verification_stale"):requirements.requireAttestation&&attestation.status==="missing"?deny("attestation_required"):requirements.requireAttestation&&attestation.status==="unavailable"?{...base,decision:"unavailable",reason:"state_unavailable",evidence}:{...base,decision:"allow",reason:"accepted",evidence})}var AGENT_PERMIT_VERSION_LINE="Entros-Agent-Permit-v1",AGENT_PERMIT_NOTICE_LINE="Sign only to let this agent perform the action below. This is not a transaction.",AGENT_PERMIT_PRESENTATION_LINE="Entros-Agent-Permit-Presentation-v1",AGENT_PERMIT_NETWORK=Object.freeze({cluster:"devnet",genesisHash:POLICY_NETWORK.genesisHash,entrosAnchorProgram:POLICY_NETWORK.programIds.anchor,agentRegistryProgram:"8oo4J9tBB3Hna1jRQ3rWvJjojqM5DYTDJo5cejUuJy3C",agentCollection:"6CTyGPcn8dMwKEqgtvx2XCpkGUd7uqCVK6937RSM5bhA",coreProgram:"CoREENxT6tW1HoK8ypY1SxRMZTcVPm7R94rH4PZNhX7d"}),AGENT_PERMIT_LIMITS=Object.freeze({minLifetimeSeconds:30,maxLifetimeSeconds:900,clockSkewSeconds:30,maxAudienceLength:200,maxLabelLength:96,minTimeSeconds:946684800,maxTimeSeconds:253402300799}),AgentPermitValidationError=class extends Error{constructor(field){super(`Invalid agent permit: ${field}`);this.field=field;this.name="AgentPermitValidationError"}},FIELD_KEYS=["agent","agent_wallet","operator","audience","action","action_sha256","policy","cluster","genesis","entros_anchor","agent_registry","agent_collection","issued_at","expires_at","nonce"],REQUEST_KEYS2=["version","agent","agentWallet","operator","audience","action","policy","cluster","genesisHash","entrosAnchorProgram","agentRegistryProgram","agentCollection","issuedAt","expiresAt","nonce"],HEX64=/^[0-9a-f]{64}$/,HEX128=/^[0-9a-f]{128}$/,TIME=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/,LABEL="(?:[a-z0-9]|[a-z0-9][a-z0-9-]{0,61}[a-z0-9])",FINAL="(?:[a-z]|[a-z][a-z0-9-]{0,61}[a-z0-9])",PORT="(?::([1-9][0-9]{0,4}))?",PATH="(/(?:[A-Za-z0-9._~-]+(?:/[A-Za-z0-9._~-]+)*/?)?)",HTTPS_AUDIENCE=new RegExp(`^https://((?:${LABEL}\\.)+${FINAL})${PORT}${PATH}$`),LOOPBACK_AUDIENCE=new RegExp(`^http://(127\\.0\\.0\\.1)${PORT}${PATH}$`),MAX_POLICY_LENGTH=512,encoder=new TextEncoder;function record2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function exactKeys2(value,keys){return Object.keys(value).length===keys.length&&keys.every(key=>Object.prototype.hasOwnProperty.call(value,key))}function integer2(value,minimum,maximum){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=minimum&&value<=maximum}function hexToBytes(value){let bytes=new Uint8Array(value.length/2);for(let index=0;index<bytes.length;index++)bytes[index]=Number.parseInt(value.slice(index*2,index*2+2),16);return bytes}function bytesToHex(bytes){return Array.from(bytes,byte=>byte.toString(16).padStart(2,"0")).join("")}function printable(value){for(let index=0;index<value.length;index++){let code=value.charCodeAt(index);if(code<32||code>126)return!1}return!0}function digestHex(value){return typeof value=="string"&&HEX64.test(value)&&!/^0+$/.test(value)}function strictPublicKey(bytes){try{return!import_ed25519.ed25519.Point.fromBytes(bytes,!1).isSmallOrder()}catch{return!1}}function signingKey(value){if(typeof value!="string")return!1;let bytes=canonicalKeyBytes(value);return bytes!==null&&strictPublicKey(bytes)}function address(value){return typeof value=="string"&&canonicalKeyBytes(value)!==null}function isAgentPermitAudience(value){if(typeof value!="string"||value.length>AGENT_PERMIT_LIMITS.maxAudienceLength)return!1;let https=HTTPS_AUDIENCE.exec(value),match=https??LOOPBACK_AUDIENCE.exec(value);if(!match)return!1;let[,host,port,path]=match;if(host===void 0||path===void 0||host.split(".").some(label=>label.length>=4&&label[2]==="-"&&label[3]==="-"))return!1;if(port!==void 0){let number=Number(port);if(number>65535||number===(https?443:80))return!1}return path.split("/").every(segment=>segment!=="."&&segment!=="..")}function actionLabel(value){return typeof value=="string"&&value.length>=1&&value.length<=AGENT_PERMIT_LIMITS.maxLabelLength&&printable(value)&&value===value.trim()}function unixSeconds(value){return integer2(value,AGENT_PERMIT_LIMITS.minTimeSeconds,AGENT_PERMIT_LIMITS.maxTimeSeconds)}function formatTime(seconds){return new Date(seconds*1e3).toISOString().replace(".000Z","Z")}function parseTime(value){if(!TIME.test(value))return null;let milliseconds=Date.parse(value);if(!Number.isFinite(milliseconds)||milliseconds%1e3!==0)return null;let seconds=milliseconds/1e3;return unixSeconds(seconds)&&formatTime(seconds)===value?seconds:null}function policyRequest(value){try{let policy=normalizePolicyRequest(value);return encodePolicyRequest(policy)===JSON.stringify(value)?policy:null}catch{return null}}function normalizeAgentPermitRequest(value){if(!record2(value)||!exactKeys2(value,REQUEST_KEYS2))throw new AgentPermitValidationError("request");let{version,agent,agentWallet,operator,audience,action,issuedAt,expiresAt,nonce}=value;if(version!==1)throw new AgentPermitValidationError("version");if(!address(agent))throw new AgentPermitValidationError("agent");if(!signingKey(agentWallet))throw new AgentPermitValidationError("agentWallet");if(!signingKey(operator))throw new AgentPermitValidationError("operator");if(!isAgentPermitAudience(audience))throw new AgentPermitValidationError("audience");if(!record2(action)||!exactKeys2(action,["label","sha256"])||!actionLabel(action.label)||!digestHex(action.sha256))throw new AgentPermitValidationError("action");let policy=policyRequest(value.policy);if(!policy)throw new AgentPermitValidationError("policy");if(value.cluster!==AGENT_PERMIT_NETWORK.cluster||value.genesisHash!==AGENT_PERMIT_NETWORK.genesisHash||value.entrosAnchorProgram!==AGENT_PERMIT_NETWORK.entrosAnchorProgram||value.agentRegistryProgram!==AGENT_PERMIT_NETWORK.agentRegistryProgram||value.agentCollection!==AGENT_PERMIT_NETWORK.agentCollection)throw new AgentPermitValidationError("deployment");if(!unixSeconds(issuedAt)||!unixSeconds(expiresAt))throw new AgentPermitValidationError("time");let lifetime=expiresAt-issuedAt;if(lifetime<AGENT_PERMIT_LIMITS.minLifetimeSeconds||lifetime>AGENT_PERMIT_LIMITS.maxLifetimeSeconds)throw new AgentPermitValidationError("lifetime");if(!digestHex(nonce))throw new AgentPermitValidationError("nonce");return{version:1,agent,agentWallet,operator,audience,action:{label:action.label,sha256:action.sha256},policy,cluster:AGENT_PERMIT_NETWORK.cluster,genesisHash:AGENT_PERMIT_NETWORK.genesisHash,entrosAnchorProgram:AGENT_PERMIT_NETWORK.entrosAnchorProgram,agentRegistryProgram:AGENT_PERMIT_NETWORK.agentRegistryProgram,agentCollection:AGENT_PERMIT_NETWORK.agentCollection,issuedAt,expiresAt,nonce}}function randomNonce(){let cryptoApi=globalThis.crypto;if(!cryptoApi||typeof cryptoApi.getRandomValues!="function")throw new AgentPermitValidationError("nonce");let bytes=new Uint8Array(32);return cryptoApi.getRandomValues(bytes),bytesToHex(bytes)}function createAgentPermitRequest(input){if(!integer2(input.lifetimeSeconds,1,AGENT_PERMIT_LIMITS.maxLifetimeSeconds))throw new AgentPermitValidationError("lifetime");return normalizeAgentPermitRequest({version:1,agent:input.agent,agentWallet:input.agentWallet,operator:input.operator,audience:input.audience,action:{label:input.action.label,sha256:input.action.sha256},policy:normalizePolicyRequest(input.policy),cluster:AGENT_PERMIT_NETWORK.cluster,genesisHash:AGENT_PERMIT_NETWORK.genesisHash,entrosAnchorProgram:AGENT_PERMIT_NETWORK.entrosAnchorProgram,agentRegistryProgram:AGENT_PERMIT_NETWORK.agentRegistryProgram,agentCollection:AGENT_PERMIT_NETWORK.agentCollection,issuedAt:input.issuedAt,expiresAt:input.issuedAt+input.lifetimeSeconds,nonce:input.nonce??randomNonce()})}function renderNormalized(value){let fields=[value.agent,value.agentWallet,value.operator,value.audience,value.action.label,value.action.sha256,encodePolicyRequest(value.policy),value.cluster,value.genesisHash,value.entrosAnchorProgram,value.agentRegistryProgram,value.agentCollection,formatTime(value.issuedAt),formatTime(value.expiresAt),value.nonce];return[AGENT_PERMIT_VERSION_LINE,AGENT_PERMIT_NOTICE_LINE,...FIELD_KEYS.map((key,index)=>`${key}:${fields[index]}`)].join(`
|
|
2
2
|
`)}function permitIdOf(message){return bytesToHex((0,import_sha2.sha256)(encoder.encode(message)))}function renderAgentPermitMessage(request){return renderNormalized(normalizeAgentPermitRequest(request))}function parseAgentPermitMessage(text){if(typeof text!="string"||text.length>4096)throw new AgentPermitValidationError("message");for(let index=0;index<text.length;index++){let code=text.charCodeAt(index);if(code!==10&&(code<32||code>126))throw new AgentPermitValidationError("message")}let lines=text.split(`
|
|
3
3
|
`);if(lines.length!==FIELD_KEYS.length+2||lines[0]!==AGENT_PERMIT_VERSION_LINE||lines[1]!==AGENT_PERMIT_NOTICE_LINE)throw new AgentPermitValidationError("message");let values=new Map;FIELD_KEYS.forEach((key,index)=>{let line=lines[index+2]??"";if(!line.startsWith(`${key}:`))throw new AgentPermitValidationError(key);values.set(key,line.slice(key.length+1))});let field=key=>values.get(key)??"",policyText=field("policy");if(policyText.length>MAX_POLICY_LENGTH)throw new AgentPermitValidationError("policy");let policy;try{policy=JSON.parse(policyText)}catch{throw new AgentPermitValidationError("policy")}let issuedAt=parseTime(field("issued_at")),expiresAt=parseTime(field("expires_at"));if(issuedAt===null||expiresAt===null)throw new AgentPermitValidationError("time");let request=normalizeAgentPermitRequest({version:1,agent:field("agent"),agentWallet:field("agent_wallet"),operator:field("operator"),audience:field("audience"),action:{label:field("action"),sha256:field("action_sha256")},policy,cluster:field("cluster"),genesisHash:field("genesis"),entrosAnchorProgram:field("entros_anchor"),agentRegistryProgram:field("agent_registry"),agentCollection:field("agent_collection"),issuedAt,expiresAt,nonce:field("nonce")});if(renderNormalized(request)!==text)throw new AgentPermitValidationError("message");return request}function agentPermitId(request){return permitIdOf(renderAgentPermitMessage(request))}function renderAgentPermitPresentation(permitId){if(!HEX64.test(permitId))throw new AgentPermitValidationError("permitId");return`${AGENT_PERMIT_PRESENTATION_LINE}
|
|
4
|
-
permit:${permitId}`}function strictVerify(signature,message,publicKey){if(typeof signature!="string"||!HEX128.test(signature))return!1;let key=canonicalKeyBytes(publicKey);if(!key)return!1;try{return import_ed25519.ed25519.verify(hexToBytes(signature),message,key,{zip215:!1})}catch{return!1}}function verifyNormalized(value,signatures){let message=renderNormalized(value),permitId=permitIdOf(message);return{permitId,operator:strictVerify(signatures.operatorSignature,encoder.encode(message),value.operator),presentation:strictVerify(signatures.presentationSignature,encoder.encode(renderAgentPermitPresentation(permitId)),value.agentWallet)}}function verifyAgentPermitSignatures(request,signatures){let{operator,presentation}=verifyNormalized(normalizeAgentPermitRequest(request),signatures);return{operator,presentation}}function settlementClock(nowSeconds){if(!integer2(nowSeconds,1,AGENT_PERMIT_LIMITS.maxTimeSeconds))throw new AgentPermitValidationError("clock");return nowSeconds}function precheckAgentPermit(input){let now=settlementClock(input.nowSeconds),request;try{request=normalizeAgentPermitRequest(input.request)}catch{return{ok:!1,reason:"invalid_permit",request:null,permitId:null}}let signatures=verifyNormalized(request,input),{permitId}=signatures;return request.issuedAt>now+AGENT_PERMIT_LIMITS.clockSkewSeconds?{ok:!1,reason:"invalid_permit",request,permitId}:now>=request.expiresAt?{ok:!1,reason:"permit_expired",request,permitId}:signatures.operator?signatures.presentation?{ok:!0,request,permitId}:{ok:!1,reason:"invalid_presentation",request,permitId}:{ok:!1,reason:"invalid_signature",request,permitId}}function isAgentStateEvidence(value){if(!record2(value)||!exactKeys2(value,["cluster","genesisHash","coreProgram","agentRegistryProgram","agentCollection","agent","agentAccount","owner","cachedOwner","agentWallet","agentWalletStatus","readContextSlot"])||value.cluster!==AGENT_PERMIT_NETWORK.cluster||value.genesisHash!==AGENT_PERMIT_NETWORK.genesisHash||value.coreProgram!==AGENT_PERMIT_NETWORK.coreProgram||value.agentRegistryProgram!==AGENT_PERMIT_NETWORK.agentRegistryProgram||value.agentCollection!==AGENT_PERMIT_NETWORK.agentCollection||!address(value.agent)||!address(value.agentAccount)||!address(value.owner)||!address(value.cachedOwner)||value.agentWallet!==null&&!address(value.agentWallet)||!integer2(value.readContextSlot,0,Number.MAX_SAFE_INTEGER))return!1;let expected=value.cachedOwner!==value.owner?"stale":value.agentWallet===null?"unbound":"bound";return value.agentWalletStatus===expected}function agentStateReason(reason){return reason==="wrong_cluster"||reason==="agent_missing"||reason==="agent_unregistered"?reason:"agent_invalid"}function evaluateAgentPermit(input){let now=settlementClock(input.nowSeconds),precheck=precheckAgentPermit(input),base={permitId:precheck.permitId,request:precheck.request,evaluatedAt:now,expiresAt:precheck.request?.expiresAt??null,agentState:null,policy:null},deny=reason=>({...base,decision:"deny",reason});if(!precheck.ok)return deny(precheck.reason);let{request}=precheck,state=input.agentState;if(!record2(state))return deny("agent_invalid");if(state.status==="unavailable")return{...base,decision:"unavailable",reason:"agent_unavailable"};if(state.status!=="available")return deny(agentStateReason(state.reason));if(!isAgentStateEvidence(state.evidence)||state.evidence.agent!==request.agent)return deny("agent_invalid");let evidence=state.evidence;if(base.agentState=evidence,evidence.owner!==request.operator)return deny("owner_changed");if(evidence.agentWalletStatus==="stale")return deny("agent_wallet_stale");if(evidence.agentWalletStatus==="unbound")return deny("agent_wallet_unbound");if(evidence.agentWallet!==request.agentWallet)return deny("agent_wallet_changed");let policy;try{policy=evaluatePolicy(request.policy,input.operatorEvidence,now)}catch{return deny("invalid_evidence")}if(base.policy=policy,policy.decision==="unavailable")return{...base,decision:"unavailable",reason:"state_unavailable"};if(policy.decision==="deny"){let reason=policy.reason;return deny(reason==="score_below_minimum"||reason==="verification_stale"||reason==="attestation_required"?reason:"invalid_evidence")}return policy.evidence.identity.walletPubkey!==request.operator?deny("invalid_evidence"):(base.expiresAt=Math.min(request.expiresAt,policy.expiresAt),now>=base.expiresAt?deny("permit_expired"):{...base,decision:"allow",reason:"accepted"})}function transactionSignature(value){if(typeof value!="string"||value.length<64||value.length>88)return!1;let bytes=base58Decode(value);return bytes!==null&&bytes.length===64&&base58Encode(bytes)===value}function jsonRecord(input){let value=input;if(typeof input=="string"){if(input.length>1024)return null;try{value=JSON.parse(input)}catch{return null}}return record2(value)?value:null}function encodeAgentPermitApproval(approval){let value=parseAgentPermitApproval({version:1,...approval});if(!value)throw new AgentPermitValidationError("approval");return JSON.stringify({version:1,permitId:value.permitId,operatorSignature:value.operatorSignature,verifiedTransaction:value.verifiedTransaction})}function parseAgentPermitApproval(input){let value=jsonRecord(input);return!value||!exactKeys2(value,["version","permitId","operatorSignature","verifiedTransaction"])||value.version!==1||typeof value.permitId!="string"||!HEX64.test(value.permitId)||typeof value.operatorSignature!="string"||!HEX128.test(value.operatorSignature)||!transactionSignature(value.verifiedTransaction)?null:{version:1,permitId:value.permitId,operatorSignature:value.operatorSignature,verifiedTransaction:value.verifiedTransaction}}function encodeAgentPermitSettlement(bundle){let value=parseAgentPermitSettlement({version:1,...bundle});if(!value)throw new AgentPermitValidationError("settlement");return JSON.stringify({version:1,nonce:value.nonce,operatorSignature:value.operatorSignature,presentationSignature:value.presentationSignature,verifiedTransaction:value.verifiedTransaction})}function parseAgentPermitSettlement(input){let value=jsonRecord(input);return!value||!exactKeys2(value,["version","nonce","operatorSignature","presentationSignature","verifiedTransaction"])||value.version!==1||!digestHex(value.nonce)||typeof value.operatorSignature!="string"||!HEX128.test(value.operatorSignature)||typeof value.presentationSignature!="string"||!HEX128.test(value.presentationSignature)||!transactionSignature(value.verifiedTransaction)?null:{version:1,nonce:value.nonce,operatorSignature:value.operatorSignature,presentationSignature:value.presentationSignature,verifiedTransaction:value.verifiedTransaction}}function base64UrlEncode(text){return btoa(text).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function base64UrlDecode(value){if(!/^[A-Za-z0-9_-]*$/.test(value)||value.length%4===1)return null;try{let padded=value.replace(/-/g,"+").replace(/_/g,"/");return atob(padded+"=".repeat((4-padded.length%4)%4))}catch{return null}}function encodeAgentPermitFragment(request){return`request=${base64UrlEncode(renderAgentPermitMessage(request))}`}function parseAgentPermitFragment(fragment){let body=fragment.startsWith("#")?fragment.slice(1):fragment;if(!body.startsWith("request=")||body.length>8192)return null;let message=base64UrlDecode(body.slice(8));if(message===null)return null;try{return{request:parseAgentPermitMessage(message),message}}catch{return null}}0&&(module.exports={AGENT_PERMIT_LIMITS,AGENT_PERMIT_NETWORK,AGENT_PERMIT_NOTICE_LINE,AGENT_PERMIT_PRESENTATION_LINE,AGENT_PERMIT_VERSION_LINE,AgentPermitValidationError,agentPermitId,createAgentPermitRequest,encodeAgentPermitApproval,encodeAgentPermitFragment,encodeAgentPermitSettlement,evaluateAgentPermit,isAgentPermitAudience,isAgentStateEvidence,normalizeAgentPermitRequest,parseAgentPermitApproval,parseAgentPermitFragment,parseAgentPermitMessage,parseAgentPermitSettlement,precheckAgentPermit,renderAgentPermitMessage,renderAgentPermitPresentation,verifyAgentPermitSignatures});
|
|
4
|
+
permit:${permitId}`}function strictVerify(signature,message,publicKey){if(typeof signature!="string"||!HEX128.test(signature))return!1;let key=canonicalKeyBytes(publicKey);if(!key)return!1;try{return import_ed25519.ed25519.verify(hexToBytes(signature),message,key,{zip215:!1})}catch{return!1}}function verifyNormalized(value,signatures){let message=renderNormalized(value),permitId=permitIdOf(message);return{permitId,operator:strictVerify(signatures.operatorSignature,encoder.encode(message),value.operator),presentation:strictVerify(signatures.presentationSignature,encoder.encode(renderAgentPermitPresentation(permitId)),value.agentWallet)}}function verifyAgentPermitSignatures(request,signatures){let{operator,presentation}=verifyNormalized(normalizeAgentPermitRequest(request),signatures);return{operator,presentation}}function settlementClock(nowSeconds){if(!integer2(nowSeconds,1,AGENT_PERMIT_LIMITS.maxTimeSeconds))throw new AgentPermitValidationError("clock");return nowSeconds}function precheckAgentPermit(input){let now=settlementClock(input.nowSeconds),request;try{request=normalizeAgentPermitRequest(input.request)}catch{return{ok:!1,reason:"invalid_permit",request:null,permitId:null}}let signatures=verifyNormalized(request,input),{permitId}=signatures;return request.issuedAt>now+AGENT_PERMIT_LIMITS.clockSkewSeconds?{ok:!1,reason:"invalid_permit",request,permitId}:now>=request.expiresAt?{ok:!1,reason:"permit_expired",request,permitId}:signatures.operator?signatures.presentation?{ok:!0,request,permitId}:{ok:!1,reason:"invalid_presentation",request,permitId}:{ok:!1,reason:"invalid_signature",request,permitId}}function isAgentStateEvidence(value){if(!record2(value)||!exactKeys2(value,["cluster","genesisHash","coreProgram","agentRegistryProgram","agentCollection","agent","agentAccount","owner","cachedOwner","agentWallet","agentWalletStatus","readContextSlot"])||value.cluster!==AGENT_PERMIT_NETWORK.cluster||value.genesisHash!==AGENT_PERMIT_NETWORK.genesisHash||value.coreProgram!==AGENT_PERMIT_NETWORK.coreProgram||value.agentRegistryProgram!==AGENT_PERMIT_NETWORK.agentRegistryProgram||value.agentCollection!==AGENT_PERMIT_NETWORK.agentCollection||!address(value.agent)||!address(value.agentAccount)||!address(value.owner)||!address(value.cachedOwner)||value.agentWallet!==null&&!address(value.agentWallet)||!integer2(value.readContextSlot,0,Number.MAX_SAFE_INTEGER))return!1;let expected=value.cachedOwner!==value.owner?"stale":value.agentWallet===null?"unbound":"bound";return value.agentWalletStatus===expected}function agentStateReason(reason){return reason==="wrong_cluster"||reason==="agent_missing"||reason==="agent_unregistered"?reason:"agent_invalid"}function evaluateAgentPermit(input){let now=settlementClock(input.nowSeconds),precheck=precheckAgentPermit(input),base={permitId:precheck.permitId,request:precheck.request,evaluatedAt:now,expiresAt:precheck.request?.expiresAt??null,agentState:null,policy:null},deny=reason=>({...base,decision:"deny",reason});if(!precheck.ok)return deny(precheck.reason);let{request}=precheck;if(input.expected!==void 0&&!matchesExpectation(request,input.expected))return deny("request_mismatch");let state=input.agentState;if(!record2(state))return deny("agent_invalid");if(state.status==="unavailable")return{...base,decision:"unavailable",reason:"agent_unavailable"};if(state.status!=="available")return deny(agentStateReason(state.reason));if(!isAgentStateEvidence(state.evidence)||state.evidence.agent!==request.agent)return deny("agent_invalid");let evidence=state.evidence;if(base.agentState=evidence,evidence.owner!==request.operator)return deny("owner_changed");if(evidence.agentWalletStatus==="stale")return deny("agent_wallet_stale");if(evidence.agentWalletStatus==="unbound")return deny("agent_wallet_unbound");if(evidence.agentWallet!==request.agentWallet)return deny("agent_wallet_changed");let policy;try{policy=evaluatePolicy(request.policy,input.operatorEvidence,now)}catch{return deny("invalid_evidence")}if(base.policy=policy,policy.decision==="unavailable")return{...base,decision:"unavailable",reason:"state_unavailable"};if(policy.decision==="deny"){let reason=policy.reason;return deny(reason==="score_below_minimum"||reason==="verification_stale"||reason==="attestation_required"?reason:"invalid_evidence")}return policy.evidence.identity.walletPubkey!==request.operator?deny("invalid_evidence"):(base.expiresAt=Math.min(request.expiresAt,policy.expiresAt),now>=base.expiresAt?deny("permit_expired"):{...base,decision:"allow",reason:"accepted"})}function matchesExpectation(request,expected){if(!record2(expected))return!1;let{nonce,agent,operator,audience,action,policy}=expected;if(typeof nonce!="string"||nonce!==request.nonce||agent!==void 0&&agent!==request.agent||operator!==void 0&&operator!==request.operator||audience!==void 0&&audience!==request.audience||action!==void 0&&(!record2(action)||action.label!==request.action.label||action.sha256!==request.action.sha256))return!1;if(policy!==void 0)try{if(encodePolicyRequest(policy)!==encodePolicyRequest(request.policy))return!1}catch{return!1}return!0}function transactionSignature(value){if(typeof value!="string"||value.length<64||value.length>88)return!1;let bytes=base58Decode(value);return bytes!==null&&bytes.length===64&&base58Encode(bytes)===value}function jsonRecord(input){let value=input;if(typeof input=="string"){if(input.length>1024)return null;try{value=JSON.parse(input)}catch{return null}}return record2(value)?value:null}function encodeAgentPermitApproval(approval){let value=parseAgentPermitApproval({version:1,...approval});if(!value)throw new AgentPermitValidationError("approval");return JSON.stringify({version:1,permitId:value.permitId,operatorSignature:value.operatorSignature,verifiedTransaction:value.verifiedTransaction})}function parseAgentPermitApproval(input){let value=jsonRecord(input);return!value||!exactKeys2(value,["version","permitId","operatorSignature","verifiedTransaction"])||value.version!==1||typeof value.permitId!="string"||!HEX64.test(value.permitId)||typeof value.operatorSignature!="string"||!HEX128.test(value.operatorSignature)||!transactionSignature(value.verifiedTransaction)?null:{version:1,permitId:value.permitId,operatorSignature:value.operatorSignature,verifiedTransaction:value.verifiedTransaction}}function encodeAgentPermitSettlement(bundle){let value=parseAgentPermitSettlement({version:1,...bundle});if(!value)throw new AgentPermitValidationError("settlement");return JSON.stringify({version:1,nonce:value.nonce,operatorSignature:value.operatorSignature,presentationSignature:value.presentationSignature,verifiedTransaction:value.verifiedTransaction})}function parseAgentPermitSettlement(input){let value=jsonRecord(input);return!value||!exactKeys2(value,["version","nonce","operatorSignature","presentationSignature","verifiedTransaction"])||value.version!==1||!digestHex(value.nonce)||typeof value.operatorSignature!="string"||!HEX128.test(value.operatorSignature)||typeof value.presentationSignature!="string"||!HEX128.test(value.presentationSignature)||!transactionSignature(value.verifiedTransaction)?null:{version:1,nonce:value.nonce,operatorSignature:value.operatorSignature,presentationSignature:value.presentationSignature,verifiedTransaction:value.verifiedTransaction}}function base64UrlEncode(text){return btoa(text).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function base64UrlDecode(value){if(!/^[A-Za-z0-9_-]*$/.test(value)||value.length%4===1)return null;try{let padded=value.replace(/-/g,"+").replace(/_/g,"/");return atob(padded+"=".repeat((4-padded.length%4)%4))}catch{return null}}function encodeAgentPermitFragment(request){return`request=${base64UrlEncode(renderAgentPermitMessage(request))}`}function parseAgentPermitFragment(fragment){let body=fragment.startsWith("#")?fragment.slice(1):fragment;if(!body.startsWith("request=")||body.length>8192)return null;let message=base64UrlDecode(body.slice(8));if(message===null)return null;try{return{request:parseAgentPermitMessage(message),message}}catch{return null}}0&&(module.exports={AGENT_PERMIT_LIMITS,AGENT_PERMIT_NETWORK,AGENT_PERMIT_NOTICE_LINE,AGENT_PERMIT_PRESENTATION_LINE,AGENT_PERMIT_VERSION_LINE,AgentPermitValidationError,agentPermitId,createAgentPermitRequest,encodeAgentPermitApproval,encodeAgentPermitFragment,encodeAgentPermitSettlement,evaluateAgentPermit,isAgentPermitAudience,isAgentStateEvidence,normalizeAgentPermitRequest,parseAgentPermitApproval,parseAgentPermitFragment,parseAgentPermitMessage,parseAgentPermitSettlement,precheckAgentPermit,renderAgentPermitMessage,renderAgentPermitPresentation,verifyAgentPermitSignatures});
|
package/dist/agent-permit.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import{ed25519}from"@noble/curves/ed25519";import{sha256}from"@noble/hashes/sha2";var ALPHABET="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function base58Encode(bytes){let number=0n;for(let byte of bytes)number=number<<8n|BigInt(byte);let text="";for(;number>0n;)text=ALPHABET[Number(number%58n)]+text,number/=58n;let zeros=0;for(;zeros<bytes.length&&bytes[zeros]===0;)zeros++;return"1".repeat(zeros)+text}function base58Decode(text){if(text.length===0)return null;let number=0n;for(let character of text){let digit=ALPHABET.indexOf(character);if(digit<0)return null;number=number*58n+BigInt(digit)}let body=[];for(;number>0n;)body.unshift(Number(number&0xffn)),number>>=8n;let zeros=0;for(;zeros<text.length&&text[zeros]==="1";)zeros++;return Uint8Array.from([...new Array(zeros).fill(0),...body])}function canonicalKeyBytes(text){if(text.length<32||text.length>44)return null;let bytes=base58Decode(text);return!bytes||bytes.length!==32||base58Encode(bytes)!==text?null:bytes}var POLICY_NETWORK=Object.freeze({genesisHash:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG",programIds:Object.freeze({anchor:"GZYwTp2ozeuRA5Gof9vs4ya961aANcJBdUzB7LN6q4b2",verifier:"4F97jNoxQzT2qRbkWpW3ztC3Nz2TtKj3rnKG8ExgnrfV",registry:"6VBs3zr9KrfFPGd6j7aGBPQWwZa5tajVfA7HN6MMV9VW",sas:"22zoJMtdu4tQc2PzL74ZUT7FrwgB1Udec8DdW4yw4BdG",credential:"AMBtabCgRFwGLjoZ21Z2LhSKJ6c47NckxUkMogJ3Lpuw",schema:"5LNc7syFW7USPLveVLcNcjjY1xqS7QTXVjHZ7CQCbAMQ"})}),PolicyValidationError=class extends Error{constructor(reason){super(`Invalid verification policy: ${reason}`);this.reason=reason;this.name="PolicyValidationError"}};function record(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function exactKeys(value,keys){return Object.keys(value).length===keys.length&&keys.every(key=>Object.prototype.hasOwnProperty.call(value,key))}var BLOCK_TIME_TOLERANCE_SECONDS=2;function integer(value,minimum=0,maximum=Number.MAX_SAFE_INTEGER){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=minimum&&value<=maximum}var REQUEST_KEYS=["id","version","minTrustScore","maxVerificationAgeSeconds","maxEvaluationAgeSeconds","requiredAssurance","uniquenessRequirement","requireAttestation","cluster"];function normalizePolicyRequest(input,legacyMinTrustScore){if(legacyMinTrustScore!==void 0&&!integer(legacyMinTrustScore,0,1e4))throw new PolicyValidationError("unsupported_policy");let value=input===void 0?{id:"entros-verify-default",version:1,minTrustScore:legacyMinTrustScore??0,maxVerificationAgeSeconds:86400,requiredAssurance:"browser_unattested",uniquenessRequirement:"allow_unmeasured",cluster:"devnet"}:input;if(!record(value)||Object.keys(value).some(key=>!REQUEST_KEYS.includes(key)))throw new PolicyValidationError("unsupported_policy");if(value.requiredAssurance!=="browser_unattested")throw new PolicyValidationError("unsupported_assurance");if(value.uniquenessRequirement!=="allow_unmeasured")throw new PolicyValidationError("unsupported_uniqueness");if(typeof value.id!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(value.id)||value.version!==1||!integer(value.minTrustScore,0,1e4)||!integer(value.maxVerificationAgeSeconds,1,31536e3)||!integer(value.maxEvaluationAgeSeconds===void 0?90:value.maxEvaluationAgeSeconds,1,90)||value.requireAttestation!==void 0&&typeof value.requireAttestation!="boolean"||value.cluster!=="devnet"||legacyMinTrustScore!==void 0&&value.minTrustScore!==legacyMinTrustScore)throw new PolicyValidationError("unsupported_policy");return{id:value.id,version:1,minTrustScore:value.minTrustScore,maxVerificationAgeSeconds:value.maxVerificationAgeSeconds,maxEvaluationAgeSeconds:value.maxEvaluationAgeSeconds??90,requiredAssurance:"browser_unattested",uniquenessRequirement:"allow_unmeasured",requireAttestation:value.requireAttestation===!0,cluster:"devnet"}}function encodePolicyRequest(request){return JSON.stringify(normalizePolicyRequest(request))}var BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function base58Bytes(value,expected){if(typeof value!="string"||value.length<1||value.length>expected*2)return!1;let number=0n;for(let character of value){let digit=BASE58.indexOf(character);if(digit<0)return!1;number=number*58n+BigInt(digit)}let bytes=0;for(;number>0n;)bytes++,number>>=8n;let zeros=0;for(;value[zeros]==="1";)zeros++;return bytes+zeros===expected}function commitment(value){return typeof value=="string"&&/^[0-9a-f]{64}$/.test(value)&&!/^0+$/.test(value)}function isPolicyAttestation(value){return record(value)?value.status==="present"?exactKeys(value,["status","address","readContextSlot","expiresAt"])&&base58Bytes(value.address,32)&&integer(value.readContextSlot)&&(value.expiresAt===null||integer(value.expiresAt,1)):exactKeys(value,["status"])&&["missing","invalid","unavailable"].includes(String(value.status)):!1}function isPolicyEvidence(value){if(!record(value)||!exactKeys(value,["cluster","genesisHash","programIds","assuranceTier","uniquenessStatus","readContextSlot","identity","transaction","attestation"])||value.cluster!=="devnet"||value.genesisHash!==POLICY_NETWORK.genesisHash||value.assuranceTier!=="browser_unattested"||value.uniquenessStatus!=="unmeasured"||!integer(value.readContextSlot))return!1;let programs=value.programIds;if(!record(programs)||!exactKeys(programs,Object.keys(POLICY_NETWORK.programIds))||Object.entries(POLICY_NETWORK.programIds).some(([key,id])=>programs[key]!==id))return!1;let identity=value.identity,transaction=value.transaction;return!record(identity)||!exactKeys(identity,["walletPubkey","identityPda","creationTimestamp","lastVerificationTimestamp","verificationCount","trustScore","currentCommitment","projectionVersion","lastResetTimestamp","lastRebaselineTimestamp","mint"])||!base58Bytes(identity.walletPubkey,32)||!base58Bytes(identity.identityPda,32)||!base58Bytes(identity.mint,32)||!integer(identity.creationTimestamp,1)||!integer(identity.lastVerificationTimestamp,identity.creationTimestamp)||!integer(identity.verificationCount,0,4294967295)||!integer(identity.trustScore,0,1e4)||!commitment(identity.currentCommitment)||!integer(identity.projectionVersion,0,2)||!integer(identity.lastResetTimestamp)||!integer(identity.lastRebaselineTimestamp)||!record(transaction)||!exactKeys(transaction,["signature","slot","blockTime","commitment","kind"])||!base58Bytes(transaction.signature,64)||!integer(transaction.slot)||!integer(transaction.blockTime,identity.creationTimestamp-BLOCK_TIME_TOLERANCE_SECONDS)||!commitment(transaction.commitment)||!["mint","update","rebaseline"].includes(String(transaction.kind))?!1:isPolicyAttestation(value.attestation)}function evaluatePolicy(request,observation,nowSeconds){let requirements=normalizePolicyRequest(request);if(!integer(nowSeconds,1)||nowSeconds>Number.MAX_SAFE_INTEGER-31536e3)throw new PolicyValidationError("invalid_evidence");let base={policyId:requirements.id,policyVersion:1,requirements,evaluatedAt:nowSeconds,expiresAt:nowSeconds,evidenceTimestamp:null,evaluatedAgeSeconds:null};if(record(observation)&&observation.status==="unavailable")return{...base,decision:"unavailable",reason:"state_unavailable",evidence:null};if(!record(observation)||observation.status!=="available"||!isPolicyEvidence(observation.evidence))return{...base,decision:"deny",reason:"invalid_evidence",evidence:null};let evidence=observation.evidence,{identity,transaction,attestation}=evidence,deny=reason=>({...base,decision:"deny",reason,evidence}),earliestClock=transaction.blockTime-BLOCK_TIME_TOLERANCE_SECONDS,latestClock=transaction.blockTime+BLOCK_TIME_TOLERANCE_SECONDS,freshMint=transaction.kind==="mint"&&identity.verificationCount===0&&identity.trustScore===0&&identity.creationTimestamp===identity.lastVerificationTimestamp&&identity.lastVerificationTimestamp>=earliestClock&&identity.lastVerificationTimestamp<=latestClock&&identity.lastResetTimestamp===0&&identity.lastRebaselineTimestamp===0;return identity.verificationCount===0&&!freshMint||identity.currentCommitment!==transaction.commitment||identity.lastResetTimestamp>=earliestClock||identity.lastResetTimestamp>identity.lastVerificationTimestamp||identity.lastRebaselineTimestamp>identity.lastVerificationTimestamp||identity.lastRebaselineTimestamp>(transaction.kind==="rebaseline"?latestClock:earliestClock)||identity.lastVerificationTimestamp>nowSeconds||transaction.blockTime>nowSeconds||evidence.readContextSlot<transaction.slot||attestation.status==="invalid"||attestation.status==="present"&&(attestation.readContextSlot<transaction.slot||attestation.expiresAt!==null&&attestation.expiresAt<=nowSeconds)?deny("invalid_evidence"):(base.evidenceTimestamp=Math.min(identity.lastVerificationTimestamp,transaction.blockTime),base.evaluatedAgeSeconds=nowSeconds-base.evidenceTimestamp,base.expiresAt=Math.min(base.evidenceTimestamp+requirements.maxVerificationAgeSeconds,nowSeconds+requirements.maxEvaluationAgeSeconds),requirements.requireAttestation&&attestation.status==="present"&&attestation.expiresAt!==null&&(base.expiresAt=Math.min(base.expiresAt,attestation.expiresAt)),identity.trustScore<requirements.minTrustScore?deny("score_below_minimum"):nowSeconds>=base.expiresAt?deny("verification_stale"):requirements.requireAttestation&&attestation.status==="missing"?deny("attestation_required"):requirements.requireAttestation&&attestation.status==="unavailable"?{...base,decision:"unavailable",reason:"state_unavailable",evidence}:{...base,decision:"allow",reason:"accepted",evidence})}var AGENT_PERMIT_VERSION_LINE="Entros-Agent-Permit-v1",AGENT_PERMIT_NOTICE_LINE="Sign only to let this agent perform the action below. This is not a transaction.",AGENT_PERMIT_PRESENTATION_LINE="Entros-Agent-Permit-Presentation-v1",AGENT_PERMIT_NETWORK=Object.freeze({cluster:"devnet",genesisHash:POLICY_NETWORK.genesisHash,entrosAnchorProgram:POLICY_NETWORK.programIds.anchor,agentRegistryProgram:"8oo4J9tBB3Hna1jRQ3rWvJjojqM5DYTDJo5cejUuJy3C",agentCollection:"6CTyGPcn8dMwKEqgtvx2XCpkGUd7uqCVK6937RSM5bhA",coreProgram:"CoREENxT6tW1HoK8ypY1SxRMZTcVPm7R94rH4PZNhX7d"}),AGENT_PERMIT_LIMITS=Object.freeze({minLifetimeSeconds:30,maxLifetimeSeconds:900,clockSkewSeconds:30,maxAudienceLength:200,maxLabelLength:96,minTimeSeconds:946684800,maxTimeSeconds:253402300799}),AgentPermitValidationError=class extends Error{constructor(field){super(`Invalid agent permit: ${field}`);this.field=field;this.name="AgentPermitValidationError"}},FIELD_KEYS=["agent","agent_wallet","operator","audience","action","action_sha256","policy","cluster","genesis","entros_anchor","agent_registry","agent_collection","issued_at","expires_at","nonce"],REQUEST_KEYS2=["version","agent","agentWallet","operator","audience","action","policy","cluster","genesisHash","entrosAnchorProgram","agentRegistryProgram","agentCollection","issuedAt","expiresAt","nonce"],HEX64=/^[0-9a-f]{64}$/,HEX128=/^[0-9a-f]{128}$/,TIME=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/,LABEL="(?:[a-z0-9]|[a-z0-9][a-z0-9-]{0,61}[a-z0-9])",FINAL="(?:[a-z]|[a-z][a-z0-9-]{0,61}[a-z0-9])",PORT="(?::([1-9][0-9]{0,4}))?",PATH="(/(?:[A-Za-z0-9._~-]+(?:/[A-Za-z0-9._~-]+)*/?)?)",HTTPS_AUDIENCE=new RegExp(`^https://((?:${LABEL}\\.)+${FINAL})${PORT}${PATH}$`),LOOPBACK_AUDIENCE=new RegExp(`^http://(127\\.0\\.0\\.1)${PORT}${PATH}$`),MAX_POLICY_LENGTH=512,encoder=new TextEncoder;function record2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function exactKeys2(value,keys){return Object.keys(value).length===keys.length&&keys.every(key=>Object.prototype.hasOwnProperty.call(value,key))}function integer2(value,minimum,maximum){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=minimum&&value<=maximum}function hexToBytes(value){let bytes=new Uint8Array(value.length/2);for(let index=0;index<bytes.length;index++)bytes[index]=Number.parseInt(value.slice(index*2,index*2+2),16);return bytes}function bytesToHex(bytes){return Array.from(bytes,byte=>byte.toString(16).padStart(2,"0")).join("")}function printable(value){for(let index=0;index<value.length;index++){let code=value.charCodeAt(index);if(code<32||code>126)return!1}return!0}function digestHex(value){return typeof value=="string"&&HEX64.test(value)&&!/^0+$/.test(value)}function strictPublicKey(bytes){try{return!ed25519.Point.fromBytes(bytes,!1).isSmallOrder()}catch{return!1}}function signingKey(value){if(typeof value!="string")return!1;let bytes=canonicalKeyBytes(value);return bytes!==null&&strictPublicKey(bytes)}function address(value){return typeof value=="string"&&canonicalKeyBytes(value)!==null}function isAgentPermitAudience(value){if(typeof value!="string"||value.length>AGENT_PERMIT_LIMITS.maxAudienceLength)return!1;let https=HTTPS_AUDIENCE.exec(value),match=https??LOOPBACK_AUDIENCE.exec(value);if(!match)return!1;let[,host,port,path]=match;if(host===void 0||path===void 0||host.split(".").some(label=>label.length>=4&&label[2]==="-"&&label[3]==="-"))return!1;if(port!==void 0){let number=Number(port);if(number>65535||number===(https?443:80))return!1}return path.split("/").every(segment=>segment!=="."&&segment!=="..")}function actionLabel(value){return typeof value=="string"&&value.length>=1&&value.length<=AGENT_PERMIT_LIMITS.maxLabelLength&&printable(value)&&value===value.trim()}function unixSeconds(value){return integer2(value,AGENT_PERMIT_LIMITS.minTimeSeconds,AGENT_PERMIT_LIMITS.maxTimeSeconds)}function formatTime(seconds){return new Date(seconds*1e3).toISOString().replace(".000Z","Z")}function parseTime(value){if(!TIME.test(value))return null;let milliseconds=Date.parse(value);if(!Number.isFinite(milliseconds)||milliseconds%1e3!==0)return null;let seconds=milliseconds/1e3;return unixSeconds(seconds)&&formatTime(seconds)===value?seconds:null}function policyRequest(value){try{let policy=normalizePolicyRequest(value);return encodePolicyRequest(policy)===JSON.stringify(value)?policy:null}catch{return null}}function normalizeAgentPermitRequest(value){if(!record2(value)||!exactKeys2(value,REQUEST_KEYS2))throw new AgentPermitValidationError("request");let{version,agent,agentWallet,operator,audience,action,issuedAt,expiresAt,nonce}=value;if(version!==1)throw new AgentPermitValidationError("version");if(!address(agent))throw new AgentPermitValidationError("agent");if(!signingKey(agentWallet))throw new AgentPermitValidationError("agentWallet");if(!signingKey(operator))throw new AgentPermitValidationError("operator");if(!isAgentPermitAudience(audience))throw new AgentPermitValidationError("audience");if(!record2(action)||!exactKeys2(action,["label","sha256"])||!actionLabel(action.label)||!digestHex(action.sha256))throw new AgentPermitValidationError("action");let policy=policyRequest(value.policy);if(!policy)throw new AgentPermitValidationError("policy");if(value.cluster!==AGENT_PERMIT_NETWORK.cluster||value.genesisHash!==AGENT_PERMIT_NETWORK.genesisHash||value.entrosAnchorProgram!==AGENT_PERMIT_NETWORK.entrosAnchorProgram||value.agentRegistryProgram!==AGENT_PERMIT_NETWORK.agentRegistryProgram||value.agentCollection!==AGENT_PERMIT_NETWORK.agentCollection)throw new AgentPermitValidationError("deployment");if(!unixSeconds(issuedAt)||!unixSeconds(expiresAt))throw new AgentPermitValidationError("time");let lifetime=expiresAt-issuedAt;if(lifetime<AGENT_PERMIT_LIMITS.minLifetimeSeconds||lifetime>AGENT_PERMIT_LIMITS.maxLifetimeSeconds)throw new AgentPermitValidationError("lifetime");if(!digestHex(nonce))throw new AgentPermitValidationError("nonce");return{version:1,agent,agentWallet,operator,audience,action:{label:action.label,sha256:action.sha256},policy,cluster:AGENT_PERMIT_NETWORK.cluster,genesisHash:AGENT_PERMIT_NETWORK.genesisHash,entrosAnchorProgram:AGENT_PERMIT_NETWORK.entrosAnchorProgram,agentRegistryProgram:AGENT_PERMIT_NETWORK.agentRegistryProgram,agentCollection:AGENT_PERMIT_NETWORK.agentCollection,issuedAt,expiresAt,nonce}}function randomNonce(){let cryptoApi=globalThis.crypto;if(!cryptoApi||typeof cryptoApi.getRandomValues!="function")throw new AgentPermitValidationError("nonce");let bytes=new Uint8Array(32);return cryptoApi.getRandomValues(bytes),bytesToHex(bytes)}function createAgentPermitRequest(input){if(!integer2(input.lifetimeSeconds,1,AGENT_PERMIT_LIMITS.maxLifetimeSeconds))throw new AgentPermitValidationError("lifetime");return normalizeAgentPermitRequest({version:1,agent:input.agent,agentWallet:input.agentWallet,operator:input.operator,audience:input.audience,action:{label:input.action.label,sha256:input.action.sha256},policy:normalizePolicyRequest(input.policy),cluster:AGENT_PERMIT_NETWORK.cluster,genesisHash:AGENT_PERMIT_NETWORK.genesisHash,entrosAnchorProgram:AGENT_PERMIT_NETWORK.entrosAnchorProgram,agentRegistryProgram:AGENT_PERMIT_NETWORK.agentRegistryProgram,agentCollection:AGENT_PERMIT_NETWORK.agentCollection,issuedAt:input.issuedAt,expiresAt:input.issuedAt+input.lifetimeSeconds,nonce:input.nonce??randomNonce()})}function renderNormalized(value){let fields=[value.agent,value.agentWallet,value.operator,value.audience,value.action.label,value.action.sha256,encodePolicyRequest(value.policy),value.cluster,value.genesisHash,value.entrosAnchorProgram,value.agentRegistryProgram,value.agentCollection,formatTime(value.issuedAt),formatTime(value.expiresAt),value.nonce];return[AGENT_PERMIT_VERSION_LINE,AGENT_PERMIT_NOTICE_LINE,...FIELD_KEYS.map((key,index)=>`${key}:${fields[index]}`)].join(`
|
|
2
2
|
`)}function permitIdOf(message){return bytesToHex(sha256(encoder.encode(message)))}function renderAgentPermitMessage(request){return renderNormalized(normalizeAgentPermitRequest(request))}function parseAgentPermitMessage(text){if(typeof text!="string"||text.length>4096)throw new AgentPermitValidationError("message");for(let index=0;index<text.length;index++){let code=text.charCodeAt(index);if(code!==10&&(code<32||code>126))throw new AgentPermitValidationError("message")}let lines=text.split(`
|
|
3
3
|
`);if(lines.length!==FIELD_KEYS.length+2||lines[0]!==AGENT_PERMIT_VERSION_LINE||lines[1]!==AGENT_PERMIT_NOTICE_LINE)throw new AgentPermitValidationError("message");let values=new Map;FIELD_KEYS.forEach((key,index)=>{let line=lines[index+2]??"";if(!line.startsWith(`${key}:`))throw new AgentPermitValidationError(key);values.set(key,line.slice(key.length+1))});let field=key=>values.get(key)??"",policyText=field("policy");if(policyText.length>MAX_POLICY_LENGTH)throw new AgentPermitValidationError("policy");let policy;try{policy=JSON.parse(policyText)}catch{throw new AgentPermitValidationError("policy")}let issuedAt=parseTime(field("issued_at")),expiresAt=parseTime(field("expires_at"));if(issuedAt===null||expiresAt===null)throw new AgentPermitValidationError("time");let request=normalizeAgentPermitRequest({version:1,agent:field("agent"),agentWallet:field("agent_wallet"),operator:field("operator"),audience:field("audience"),action:{label:field("action"),sha256:field("action_sha256")},policy,cluster:field("cluster"),genesisHash:field("genesis"),entrosAnchorProgram:field("entros_anchor"),agentRegistryProgram:field("agent_registry"),agentCollection:field("agent_collection"),issuedAt,expiresAt,nonce:field("nonce")});if(renderNormalized(request)!==text)throw new AgentPermitValidationError("message");return request}function agentPermitId(request){return permitIdOf(renderAgentPermitMessage(request))}function renderAgentPermitPresentation(permitId){if(!HEX64.test(permitId))throw new AgentPermitValidationError("permitId");return`${AGENT_PERMIT_PRESENTATION_LINE}
|
|
4
|
-
permit:${permitId}`}function strictVerify(signature,message,publicKey){if(typeof signature!="string"||!HEX128.test(signature))return!1;let key=canonicalKeyBytes(publicKey);if(!key)return!1;try{return ed25519.verify(hexToBytes(signature),message,key,{zip215:!1})}catch{return!1}}function verifyNormalized(value,signatures){let message=renderNormalized(value),permitId=permitIdOf(message);return{permitId,operator:strictVerify(signatures.operatorSignature,encoder.encode(message),value.operator),presentation:strictVerify(signatures.presentationSignature,encoder.encode(renderAgentPermitPresentation(permitId)),value.agentWallet)}}function verifyAgentPermitSignatures(request,signatures){let{operator,presentation}=verifyNormalized(normalizeAgentPermitRequest(request),signatures);return{operator,presentation}}function settlementClock(nowSeconds){if(!integer2(nowSeconds,1,AGENT_PERMIT_LIMITS.maxTimeSeconds))throw new AgentPermitValidationError("clock");return nowSeconds}function precheckAgentPermit(input){let now=settlementClock(input.nowSeconds),request;try{request=normalizeAgentPermitRequest(input.request)}catch{return{ok:!1,reason:"invalid_permit",request:null,permitId:null}}let signatures=verifyNormalized(request,input),{permitId}=signatures;return request.issuedAt>now+AGENT_PERMIT_LIMITS.clockSkewSeconds?{ok:!1,reason:"invalid_permit",request,permitId}:now>=request.expiresAt?{ok:!1,reason:"permit_expired",request,permitId}:signatures.operator?signatures.presentation?{ok:!0,request,permitId}:{ok:!1,reason:"invalid_presentation",request,permitId}:{ok:!1,reason:"invalid_signature",request,permitId}}function isAgentStateEvidence(value){if(!record2(value)||!exactKeys2(value,["cluster","genesisHash","coreProgram","agentRegistryProgram","agentCollection","agent","agentAccount","owner","cachedOwner","agentWallet","agentWalletStatus","readContextSlot"])||value.cluster!==AGENT_PERMIT_NETWORK.cluster||value.genesisHash!==AGENT_PERMIT_NETWORK.genesisHash||value.coreProgram!==AGENT_PERMIT_NETWORK.coreProgram||value.agentRegistryProgram!==AGENT_PERMIT_NETWORK.agentRegistryProgram||value.agentCollection!==AGENT_PERMIT_NETWORK.agentCollection||!address(value.agent)||!address(value.agentAccount)||!address(value.owner)||!address(value.cachedOwner)||value.agentWallet!==null&&!address(value.agentWallet)||!integer2(value.readContextSlot,0,Number.MAX_SAFE_INTEGER))return!1;let expected=value.cachedOwner!==value.owner?"stale":value.agentWallet===null?"unbound":"bound";return value.agentWalletStatus===expected}function agentStateReason(reason){return reason==="wrong_cluster"||reason==="agent_missing"||reason==="agent_unregistered"?reason:"agent_invalid"}function evaluateAgentPermit(input){let now=settlementClock(input.nowSeconds),precheck=precheckAgentPermit(input),base={permitId:precheck.permitId,request:precheck.request,evaluatedAt:now,expiresAt:precheck.request?.expiresAt??null,agentState:null,policy:null},deny=reason=>({...base,decision:"deny",reason});if(!precheck.ok)return deny(precheck.reason);let{request}=precheck,state=input.agentState;if(!record2(state))return deny("agent_invalid");if(state.status==="unavailable")return{...base,decision:"unavailable",reason:"agent_unavailable"};if(state.status!=="available")return deny(agentStateReason(state.reason));if(!isAgentStateEvidence(state.evidence)||state.evidence.agent!==request.agent)return deny("agent_invalid");let evidence=state.evidence;if(base.agentState=evidence,evidence.owner!==request.operator)return deny("owner_changed");if(evidence.agentWalletStatus==="stale")return deny("agent_wallet_stale");if(evidence.agentWalletStatus==="unbound")return deny("agent_wallet_unbound");if(evidence.agentWallet!==request.agentWallet)return deny("agent_wallet_changed");let policy;try{policy=evaluatePolicy(request.policy,input.operatorEvidence,now)}catch{return deny("invalid_evidence")}if(base.policy=policy,policy.decision==="unavailable")return{...base,decision:"unavailable",reason:"state_unavailable"};if(policy.decision==="deny"){let reason=policy.reason;return deny(reason==="score_below_minimum"||reason==="verification_stale"||reason==="attestation_required"?reason:"invalid_evidence")}return policy.evidence.identity.walletPubkey!==request.operator?deny("invalid_evidence"):(base.expiresAt=Math.min(request.expiresAt,policy.expiresAt),now>=base.expiresAt?deny("permit_expired"):{...base,decision:"allow",reason:"accepted"})}function transactionSignature(value){if(typeof value!="string"||value.length<64||value.length>88)return!1;let bytes=base58Decode(value);return bytes!==null&&bytes.length===64&&base58Encode(bytes)===value}function jsonRecord(input){let value=input;if(typeof input=="string"){if(input.length>1024)return null;try{value=JSON.parse(input)}catch{return null}}return record2(value)?value:null}function encodeAgentPermitApproval(approval){let value=parseAgentPermitApproval({version:1,...approval});if(!value)throw new AgentPermitValidationError("approval");return JSON.stringify({version:1,permitId:value.permitId,operatorSignature:value.operatorSignature,verifiedTransaction:value.verifiedTransaction})}function parseAgentPermitApproval(input){let value=jsonRecord(input);return!value||!exactKeys2(value,["version","permitId","operatorSignature","verifiedTransaction"])||value.version!==1||typeof value.permitId!="string"||!HEX64.test(value.permitId)||typeof value.operatorSignature!="string"||!HEX128.test(value.operatorSignature)||!transactionSignature(value.verifiedTransaction)?null:{version:1,permitId:value.permitId,operatorSignature:value.operatorSignature,verifiedTransaction:value.verifiedTransaction}}function encodeAgentPermitSettlement(bundle){let value=parseAgentPermitSettlement({version:1,...bundle});if(!value)throw new AgentPermitValidationError("settlement");return JSON.stringify({version:1,nonce:value.nonce,operatorSignature:value.operatorSignature,presentationSignature:value.presentationSignature,verifiedTransaction:value.verifiedTransaction})}function parseAgentPermitSettlement(input){let value=jsonRecord(input);return!value||!exactKeys2(value,["version","nonce","operatorSignature","presentationSignature","verifiedTransaction"])||value.version!==1||!digestHex(value.nonce)||typeof value.operatorSignature!="string"||!HEX128.test(value.operatorSignature)||typeof value.presentationSignature!="string"||!HEX128.test(value.presentationSignature)||!transactionSignature(value.verifiedTransaction)?null:{version:1,nonce:value.nonce,operatorSignature:value.operatorSignature,presentationSignature:value.presentationSignature,verifiedTransaction:value.verifiedTransaction}}function base64UrlEncode(text){return btoa(text).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function base64UrlDecode(value){if(!/^[A-Za-z0-9_-]*$/.test(value)||value.length%4===1)return null;try{let padded=value.replace(/-/g,"+").replace(/_/g,"/");return atob(padded+"=".repeat((4-padded.length%4)%4))}catch{return null}}function encodeAgentPermitFragment(request){return`request=${base64UrlEncode(renderAgentPermitMessage(request))}`}function parseAgentPermitFragment(fragment){let body=fragment.startsWith("#")?fragment.slice(1):fragment;if(!body.startsWith("request=")||body.length>8192)return null;let message=base64UrlDecode(body.slice(8));if(message===null)return null;try{return{request:parseAgentPermitMessage(message),message}}catch{return null}}export{AGENT_PERMIT_LIMITS,AGENT_PERMIT_NETWORK,AGENT_PERMIT_NOTICE_LINE,AGENT_PERMIT_PRESENTATION_LINE,AGENT_PERMIT_VERSION_LINE,AgentPermitValidationError,agentPermitId,createAgentPermitRequest,encodeAgentPermitApproval,encodeAgentPermitFragment,encodeAgentPermitSettlement,evaluateAgentPermit,isAgentPermitAudience,isAgentStateEvidence,normalizeAgentPermitRequest,parseAgentPermitApproval,parseAgentPermitFragment,parseAgentPermitMessage,parseAgentPermitSettlement,precheckAgentPermit,renderAgentPermitMessage,renderAgentPermitPresentation,verifyAgentPermitSignatures};
|
|
4
|
+
permit:${permitId}`}function strictVerify(signature,message,publicKey){if(typeof signature!="string"||!HEX128.test(signature))return!1;let key=canonicalKeyBytes(publicKey);if(!key)return!1;try{return ed25519.verify(hexToBytes(signature),message,key,{zip215:!1})}catch{return!1}}function verifyNormalized(value,signatures){let message=renderNormalized(value),permitId=permitIdOf(message);return{permitId,operator:strictVerify(signatures.operatorSignature,encoder.encode(message),value.operator),presentation:strictVerify(signatures.presentationSignature,encoder.encode(renderAgentPermitPresentation(permitId)),value.agentWallet)}}function verifyAgentPermitSignatures(request,signatures){let{operator,presentation}=verifyNormalized(normalizeAgentPermitRequest(request),signatures);return{operator,presentation}}function settlementClock(nowSeconds){if(!integer2(nowSeconds,1,AGENT_PERMIT_LIMITS.maxTimeSeconds))throw new AgentPermitValidationError("clock");return nowSeconds}function precheckAgentPermit(input){let now=settlementClock(input.nowSeconds),request;try{request=normalizeAgentPermitRequest(input.request)}catch{return{ok:!1,reason:"invalid_permit",request:null,permitId:null}}let signatures=verifyNormalized(request,input),{permitId}=signatures;return request.issuedAt>now+AGENT_PERMIT_LIMITS.clockSkewSeconds?{ok:!1,reason:"invalid_permit",request,permitId}:now>=request.expiresAt?{ok:!1,reason:"permit_expired",request,permitId}:signatures.operator?signatures.presentation?{ok:!0,request,permitId}:{ok:!1,reason:"invalid_presentation",request,permitId}:{ok:!1,reason:"invalid_signature",request,permitId}}function isAgentStateEvidence(value){if(!record2(value)||!exactKeys2(value,["cluster","genesisHash","coreProgram","agentRegistryProgram","agentCollection","agent","agentAccount","owner","cachedOwner","agentWallet","agentWalletStatus","readContextSlot"])||value.cluster!==AGENT_PERMIT_NETWORK.cluster||value.genesisHash!==AGENT_PERMIT_NETWORK.genesisHash||value.coreProgram!==AGENT_PERMIT_NETWORK.coreProgram||value.agentRegistryProgram!==AGENT_PERMIT_NETWORK.agentRegistryProgram||value.agentCollection!==AGENT_PERMIT_NETWORK.agentCollection||!address(value.agent)||!address(value.agentAccount)||!address(value.owner)||!address(value.cachedOwner)||value.agentWallet!==null&&!address(value.agentWallet)||!integer2(value.readContextSlot,0,Number.MAX_SAFE_INTEGER))return!1;let expected=value.cachedOwner!==value.owner?"stale":value.agentWallet===null?"unbound":"bound";return value.agentWalletStatus===expected}function agentStateReason(reason){return reason==="wrong_cluster"||reason==="agent_missing"||reason==="agent_unregistered"?reason:"agent_invalid"}function evaluateAgentPermit(input){let now=settlementClock(input.nowSeconds),precheck=precheckAgentPermit(input),base={permitId:precheck.permitId,request:precheck.request,evaluatedAt:now,expiresAt:precheck.request?.expiresAt??null,agentState:null,policy:null},deny=reason=>({...base,decision:"deny",reason});if(!precheck.ok)return deny(precheck.reason);let{request}=precheck;if(input.expected!==void 0&&!matchesExpectation(request,input.expected))return deny("request_mismatch");let state=input.agentState;if(!record2(state))return deny("agent_invalid");if(state.status==="unavailable")return{...base,decision:"unavailable",reason:"agent_unavailable"};if(state.status!=="available")return deny(agentStateReason(state.reason));if(!isAgentStateEvidence(state.evidence)||state.evidence.agent!==request.agent)return deny("agent_invalid");let evidence=state.evidence;if(base.agentState=evidence,evidence.owner!==request.operator)return deny("owner_changed");if(evidence.agentWalletStatus==="stale")return deny("agent_wallet_stale");if(evidence.agentWalletStatus==="unbound")return deny("agent_wallet_unbound");if(evidence.agentWallet!==request.agentWallet)return deny("agent_wallet_changed");let policy;try{policy=evaluatePolicy(request.policy,input.operatorEvidence,now)}catch{return deny("invalid_evidence")}if(base.policy=policy,policy.decision==="unavailable")return{...base,decision:"unavailable",reason:"state_unavailable"};if(policy.decision==="deny"){let reason=policy.reason;return deny(reason==="score_below_minimum"||reason==="verification_stale"||reason==="attestation_required"?reason:"invalid_evidence")}return policy.evidence.identity.walletPubkey!==request.operator?deny("invalid_evidence"):(base.expiresAt=Math.min(request.expiresAt,policy.expiresAt),now>=base.expiresAt?deny("permit_expired"):{...base,decision:"allow",reason:"accepted"})}function matchesExpectation(request,expected){if(!record2(expected))return!1;let{nonce,agent,operator,audience,action,policy}=expected;if(typeof nonce!="string"||nonce!==request.nonce||agent!==void 0&&agent!==request.agent||operator!==void 0&&operator!==request.operator||audience!==void 0&&audience!==request.audience||action!==void 0&&(!record2(action)||action.label!==request.action.label||action.sha256!==request.action.sha256))return!1;if(policy!==void 0)try{if(encodePolicyRequest(policy)!==encodePolicyRequest(request.policy))return!1}catch{return!1}return!0}function transactionSignature(value){if(typeof value!="string"||value.length<64||value.length>88)return!1;let bytes=base58Decode(value);return bytes!==null&&bytes.length===64&&base58Encode(bytes)===value}function jsonRecord(input){let value=input;if(typeof input=="string"){if(input.length>1024)return null;try{value=JSON.parse(input)}catch{return null}}return record2(value)?value:null}function encodeAgentPermitApproval(approval){let value=parseAgentPermitApproval({version:1,...approval});if(!value)throw new AgentPermitValidationError("approval");return JSON.stringify({version:1,permitId:value.permitId,operatorSignature:value.operatorSignature,verifiedTransaction:value.verifiedTransaction})}function parseAgentPermitApproval(input){let value=jsonRecord(input);return!value||!exactKeys2(value,["version","permitId","operatorSignature","verifiedTransaction"])||value.version!==1||typeof value.permitId!="string"||!HEX64.test(value.permitId)||typeof value.operatorSignature!="string"||!HEX128.test(value.operatorSignature)||!transactionSignature(value.verifiedTransaction)?null:{version:1,permitId:value.permitId,operatorSignature:value.operatorSignature,verifiedTransaction:value.verifiedTransaction}}function encodeAgentPermitSettlement(bundle){let value=parseAgentPermitSettlement({version:1,...bundle});if(!value)throw new AgentPermitValidationError("settlement");return JSON.stringify({version:1,nonce:value.nonce,operatorSignature:value.operatorSignature,presentationSignature:value.presentationSignature,verifiedTransaction:value.verifiedTransaction})}function parseAgentPermitSettlement(input){let value=jsonRecord(input);return!value||!exactKeys2(value,["version","nonce","operatorSignature","presentationSignature","verifiedTransaction"])||value.version!==1||!digestHex(value.nonce)||typeof value.operatorSignature!="string"||!HEX128.test(value.operatorSignature)||typeof value.presentationSignature!="string"||!HEX128.test(value.presentationSignature)||!transactionSignature(value.verifiedTransaction)?null:{version:1,nonce:value.nonce,operatorSignature:value.operatorSignature,presentationSignature:value.presentationSignature,verifiedTransaction:value.verifiedTransaction}}function base64UrlEncode(text){return btoa(text).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function base64UrlDecode(value){if(!/^[A-Za-z0-9_-]*$/.test(value)||value.length%4===1)return null;try{let padded=value.replace(/-/g,"+").replace(/_/g,"/");return atob(padded+"=".repeat((4-padded.length%4)%4))}catch{return null}}function encodeAgentPermitFragment(request){return`request=${base64UrlEncode(renderAgentPermitMessage(request))}`}function parseAgentPermitFragment(fragment){let body=fragment.startsWith("#")?fragment.slice(1):fragment;if(!body.startsWith("request=")||body.length>8192)return null;let message=base64UrlDecode(body.slice(8));if(message===null)return null;try{return{request:parseAgentPermitMessage(message),message}}catch{return null}}export{AGENT_PERMIT_LIMITS,AGENT_PERMIT_NETWORK,AGENT_PERMIT_NOTICE_LINE,AGENT_PERMIT_PRESENTATION_LINE,AGENT_PERMIT_VERSION_LINE,AgentPermitValidationError,agentPermitId,createAgentPermitRequest,encodeAgentPermitApproval,encodeAgentPermitFragment,encodeAgentPermitSettlement,evaluateAgentPermit,isAgentPermitAudience,isAgentStateEvidence,normalizeAgentPermitRequest,parseAgentPermitApproval,parseAgentPermitFragment,parseAgentPermitMessage,parseAgentPermitSettlement,precheckAgentPermit,renderAgentPermitMessage,renderAgentPermitPresentation,verifyAgentPermitSignatures};
|
package/dist/index.d.mts
CHANGED
|
@@ -58,6 +58,13 @@ interface PolicyEvidence {
|
|
|
58
58
|
};
|
|
59
59
|
attestation: PolicyAttestation;
|
|
60
60
|
}
|
|
61
|
+
type PolicyEvidenceReadResult = {
|
|
62
|
+
status: "available";
|
|
63
|
+
evidence: PolicyEvidence;
|
|
64
|
+
} | {
|
|
65
|
+
status: "invalid" | "unavailable";
|
|
66
|
+
reason: string;
|
|
67
|
+
};
|
|
61
68
|
type PolicyReason = "accepted" | "score_below_minimum" | "verification_stale" | "attestation_required" | "unsupported_policy" | "unsupported_assurance" | "unsupported_uniqueness" | "invalid_evidence" | "state_unavailable";
|
|
62
69
|
interface PolicyResultBase {
|
|
63
70
|
policyId: string;
|
|
@@ -117,12 +124,14 @@ interface EntrosVerifyProgress {
|
|
|
117
124
|
}
|
|
118
125
|
|
|
119
126
|
/**
|
|
120
|
-
* <EntrosVerify>
|
|
127
|
+
* <EntrosVerify> renders a trigger button for the Entros verification popup.
|
|
121
128
|
*
|
|
122
|
-
*
|
|
123
|
-
*
|
|
124
|
-
*
|
|
125
|
-
*
|
|
129
|
+
* Clicking the button opens a popup window to entros.io. When the connected
|
|
130
|
+
* wallet already holds on-chain evidence that satisfies the requested policy,
|
|
131
|
+
* the hosted popup can complete via warm policy reuse at 0 SOL and zero
|
|
132
|
+
* capture rounds while preserving the original `verifiedAt` timestamp.
|
|
133
|
+
* Otherwise the user completes wallet-connected capture in the popup, and this
|
|
134
|
+
* component checks the returned policy result before calling `onVerified`.
|
|
126
135
|
*
|
|
127
136
|
* See README and `EntrosVerifyProps` for usage.
|
|
128
137
|
*/
|
|
@@ -174,4 +183,76 @@ interface EntrosVerifyProps {
|
|
|
174
183
|
}
|
|
175
184
|
declare function EntrosVerify(props: EntrosVerifyProps): ReactElement;
|
|
176
185
|
|
|
177
|
-
|
|
186
|
+
/**
|
|
187
|
+
* Warm policy reuse helper for `@entros/verify`.
|
|
188
|
+
*
|
|
189
|
+
* Evaluates current chain evidence before browser capture starts. When existing
|
|
190
|
+
* evidence already satisfies the policy, the caller completes verification at
|
|
191
|
+
* 0 SOL and zero capture rounds while preserving the original verification time.
|
|
192
|
+
*/
|
|
193
|
+
|
|
194
|
+
type WarmVerificationLookup = {
|
|
195
|
+
status: "found";
|
|
196
|
+
signature: string;
|
|
197
|
+
} | {
|
|
198
|
+
status: "none" | "invalid" | "unavailable";
|
|
199
|
+
};
|
|
200
|
+
interface WarmPolicyReuseBaseInput {
|
|
201
|
+
/** Base58 Solana wallet address requesting verification. */
|
|
202
|
+
walletPubkey: string;
|
|
203
|
+
/** Application policy requirements. Omitting this uses the default policy. */
|
|
204
|
+
policy?: PolicyRequestInput;
|
|
205
|
+
/** Legacy Trust Score floor. Must match `policy.minTrustScore` when both exist. */
|
|
206
|
+
minTrustScore?: number;
|
|
207
|
+
/**
|
|
208
|
+
* Current Unix timestamp in seconds, or a clock callback sampled after
|
|
209
|
+
* asynchronous chain reads complete.
|
|
210
|
+
*/
|
|
211
|
+
nowSeconds: number | (() => number);
|
|
212
|
+
/**
|
|
213
|
+
* Legacy callers without a negotiated policy cannot represent an absent
|
|
214
|
+
* attestation. When true and `policy` is omitted, reuse requires a present
|
|
215
|
+
* attestation.
|
|
216
|
+
*/
|
|
217
|
+
requireLegacyAttestation?: boolean;
|
|
218
|
+
}
|
|
219
|
+
type WarmPolicyReuseObservationInput = WarmPolicyReuseBaseInput & {
|
|
220
|
+
/** Evidence observation from a trusted chain reader, or null when absent. */
|
|
221
|
+
observation: PolicyEvidenceReadResult | null;
|
|
222
|
+
findVerification?: never;
|
|
223
|
+
readEvidence?: never;
|
|
224
|
+
};
|
|
225
|
+
type WarmPolicyReuseReaderInput = WarmPolicyReuseBaseInput & {
|
|
226
|
+
observation?: never;
|
|
227
|
+
/**
|
|
228
|
+
* Optional lookup for the wallet's newest qualifying verification transaction.
|
|
229
|
+
* Accepts a lookup status object or a transaction signature string.
|
|
230
|
+
*/
|
|
231
|
+
findVerification?: (input: {
|
|
232
|
+
walletPubkey: string;
|
|
233
|
+
}) => Promise<WarmVerificationLookup | string | null>;
|
|
234
|
+
/** Reads current on-chain evidence from a trusted RPC connection. */
|
|
235
|
+
readEvidence: (input: {
|
|
236
|
+
walletPubkey: string;
|
|
237
|
+
transactionSignature?: string;
|
|
238
|
+
}) => Promise<PolicyEvidenceReadResult | null>;
|
|
239
|
+
};
|
|
240
|
+
type WarmPolicyReuseInput = WarmPolicyReuseObservationInput | WarmPolicyReuseReaderInput;
|
|
241
|
+
type WarmPolicyReuseResult = {
|
|
242
|
+
status: "reused";
|
|
243
|
+
policy: PolicyResult & {
|
|
244
|
+
decision: "allow";
|
|
245
|
+
};
|
|
246
|
+
evidence: PolicyEvidence;
|
|
247
|
+
} | {
|
|
248
|
+
status: "needs_capture";
|
|
249
|
+
policy: PolicyResult | null;
|
|
250
|
+
reason: PolicyReason | "evidence_not_found";
|
|
251
|
+
};
|
|
252
|
+
/**
|
|
253
|
+
* Checks whether existing on-chain verification evidence already satisfies an
|
|
254
|
+
* application policy without running browser capture or refreshing `verifiedAt`.
|
|
255
|
+
*/
|
|
256
|
+
declare function evaluateWarmPolicyReuse(input: WarmPolicyReuseInput): Promise<WarmPolicyReuseResult>;
|
|
257
|
+
|
|
258
|
+
export { type Cluster, EntrosVerify, type EntrosVerifyError, type EntrosVerifyErrorReason, type EntrosVerifyProgress, type EntrosVerifyProgressStatus, type EntrosVerifyProps, type EntrosVerifyResult, type PolicyReason, type PolicyRequest, type PolicyRequestInput, type PolicyResult, type WarmPolicyReuseBaseInput, type WarmPolicyReuseInput, type WarmPolicyReuseObservationInput, type WarmPolicyReuseReaderInput, type WarmPolicyReuseResult, type WarmVerificationLookup, evaluateWarmPolicyReuse };
|
package/dist/index.d.ts
CHANGED
|
@@ -58,6 +58,13 @@ interface PolicyEvidence {
|
|
|
58
58
|
};
|
|
59
59
|
attestation: PolicyAttestation;
|
|
60
60
|
}
|
|
61
|
+
type PolicyEvidenceReadResult = {
|
|
62
|
+
status: "available";
|
|
63
|
+
evidence: PolicyEvidence;
|
|
64
|
+
} | {
|
|
65
|
+
status: "invalid" | "unavailable";
|
|
66
|
+
reason: string;
|
|
67
|
+
};
|
|
61
68
|
type PolicyReason = "accepted" | "score_below_minimum" | "verification_stale" | "attestation_required" | "unsupported_policy" | "unsupported_assurance" | "unsupported_uniqueness" | "invalid_evidence" | "state_unavailable";
|
|
62
69
|
interface PolicyResultBase {
|
|
63
70
|
policyId: string;
|
|
@@ -117,12 +124,14 @@ interface EntrosVerifyProgress {
|
|
|
117
124
|
}
|
|
118
125
|
|
|
119
126
|
/**
|
|
120
|
-
* <EntrosVerify>
|
|
127
|
+
* <EntrosVerify> renders a trigger button for the Entros verification popup.
|
|
121
128
|
*
|
|
122
|
-
*
|
|
123
|
-
*
|
|
124
|
-
*
|
|
125
|
-
*
|
|
129
|
+
* Clicking the button opens a popup window to entros.io. When the connected
|
|
130
|
+
* wallet already holds on-chain evidence that satisfies the requested policy,
|
|
131
|
+
* the hosted popup can complete via warm policy reuse at 0 SOL and zero
|
|
132
|
+
* capture rounds while preserving the original `verifiedAt` timestamp.
|
|
133
|
+
* Otherwise the user completes wallet-connected capture in the popup, and this
|
|
134
|
+
* component checks the returned policy result before calling `onVerified`.
|
|
126
135
|
*
|
|
127
136
|
* See README and `EntrosVerifyProps` for usage.
|
|
128
137
|
*/
|
|
@@ -174,4 +183,76 @@ interface EntrosVerifyProps {
|
|
|
174
183
|
}
|
|
175
184
|
declare function EntrosVerify(props: EntrosVerifyProps): ReactElement;
|
|
176
185
|
|
|
177
|
-
|
|
186
|
+
/**
|
|
187
|
+
* Warm policy reuse helper for `@entros/verify`.
|
|
188
|
+
*
|
|
189
|
+
* Evaluates current chain evidence before browser capture starts. When existing
|
|
190
|
+
* evidence already satisfies the policy, the caller completes verification at
|
|
191
|
+
* 0 SOL and zero capture rounds while preserving the original verification time.
|
|
192
|
+
*/
|
|
193
|
+
|
|
194
|
+
type WarmVerificationLookup = {
|
|
195
|
+
status: "found";
|
|
196
|
+
signature: string;
|
|
197
|
+
} | {
|
|
198
|
+
status: "none" | "invalid" | "unavailable";
|
|
199
|
+
};
|
|
200
|
+
interface WarmPolicyReuseBaseInput {
|
|
201
|
+
/** Base58 Solana wallet address requesting verification. */
|
|
202
|
+
walletPubkey: string;
|
|
203
|
+
/** Application policy requirements. Omitting this uses the default policy. */
|
|
204
|
+
policy?: PolicyRequestInput;
|
|
205
|
+
/** Legacy Trust Score floor. Must match `policy.minTrustScore` when both exist. */
|
|
206
|
+
minTrustScore?: number;
|
|
207
|
+
/**
|
|
208
|
+
* Current Unix timestamp in seconds, or a clock callback sampled after
|
|
209
|
+
* asynchronous chain reads complete.
|
|
210
|
+
*/
|
|
211
|
+
nowSeconds: number | (() => number);
|
|
212
|
+
/**
|
|
213
|
+
* Legacy callers without a negotiated policy cannot represent an absent
|
|
214
|
+
* attestation. When true and `policy` is omitted, reuse requires a present
|
|
215
|
+
* attestation.
|
|
216
|
+
*/
|
|
217
|
+
requireLegacyAttestation?: boolean;
|
|
218
|
+
}
|
|
219
|
+
type WarmPolicyReuseObservationInput = WarmPolicyReuseBaseInput & {
|
|
220
|
+
/** Evidence observation from a trusted chain reader, or null when absent. */
|
|
221
|
+
observation: PolicyEvidenceReadResult | null;
|
|
222
|
+
findVerification?: never;
|
|
223
|
+
readEvidence?: never;
|
|
224
|
+
};
|
|
225
|
+
type WarmPolicyReuseReaderInput = WarmPolicyReuseBaseInput & {
|
|
226
|
+
observation?: never;
|
|
227
|
+
/**
|
|
228
|
+
* Optional lookup for the wallet's newest qualifying verification transaction.
|
|
229
|
+
* Accepts a lookup status object or a transaction signature string.
|
|
230
|
+
*/
|
|
231
|
+
findVerification?: (input: {
|
|
232
|
+
walletPubkey: string;
|
|
233
|
+
}) => Promise<WarmVerificationLookup | string | null>;
|
|
234
|
+
/** Reads current on-chain evidence from a trusted RPC connection. */
|
|
235
|
+
readEvidence: (input: {
|
|
236
|
+
walletPubkey: string;
|
|
237
|
+
transactionSignature?: string;
|
|
238
|
+
}) => Promise<PolicyEvidenceReadResult | null>;
|
|
239
|
+
};
|
|
240
|
+
type WarmPolicyReuseInput = WarmPolicyReuseObservationInput | WarmPolicyReuseReaderInput;
|
|
241
|
+
type WarmPolicyReuseResult = {
|
|
242
|
+
status: "reused";
|
|
243
|
+
policy: PolicyResult & {
|
|
244
|
+
decision: "allow";
|
|
245
|
+
};
|
|
246
|
+
evidence: PolicyEvidence;
|
|
247
|
+
} | {
|
|
248
|
+
status: "needs_capture";
|
|
249
|
+
policy: PolicyResult | null;
|
|
250
|
+
reason: PolicyReason | "evidence_not_found";
|
|
251
|
+
};
|
|
252
|
+
/**
|
|
253
|
+
* Checks whether existing on-chain verification evidence already satisfies an
|
|
254
|
+
* application policy without running browser capture or refreshing `verifiedAt`.
|
|
255
|
+
*/
|
|
256
|
+
declare function evaluateWarmPolicyReuse(input: WarmPolicyReuseInput): Promise<WarmPolicyReuseResult>;
|
|
257
|
+
|
|
258
|
+
export { type Cluster, EntrosVerify, type EntrosVerifyError, type EntrosVerifyErrorReason, type EntrosVerifyProgress, type EntrosVerifyProgressStatus, type EntrosVerifyProps, type EntrosVerifyResult, type PolicyReason, type PolicyRequest, type PolicyRequestInput, type PolicyResult, type WarmPolicyReuseBaseInput, type WarmPolicyReuseInput, type WarmPolicyReuseObservationInput, type WarmPolicyReuseReaderInput, type WarmPolicyReuseResult, type WarmVerificationLookup, evaluateWarmPolicyReuse };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var index_exports={};__export(index_exports,{EntrosVerify:()=>EntrosVerify});module.exports=__toCommonJS(index_exports);var import_react=require("react");var POLICY_NETWORK=Object.freeze({genesisHash:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG",programIds:Object.freeze({anchor:"GZYwTp2ozeuRA5Gof9vs4ya961aANcJBdUzB7LN6q4b2",verifier:"4F97jNoxQzT2qRbkWpW3ztC3Nz2TtKj3rnKG8ExgnrfV",registry:"6VBs3zr9KrfFPGd6j7aGBPQWwZa5tajVfA7HN6MMV9VW",sas:"22zoJMtdu4tQc2PzL74ZUT7FrwgB1Udec8DdW4yw4BdG",credential:"AMBtabCgRFwGLjoZ21Z2LhSKJ6c47NckxUkMogJ3Lpuw",schema:"5LNc7syFW7USPLveVLcNcjjY1xqS7QTXVjHZ7CQCbAMQ"})}),PolicyValidationError=class extends Error{constructor(reason){super(`Invalid verification policy: ${reason}`);this.reason=reason;this.name="PolicyValidationError"}};function record(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function exactKeys(value,keys){return Object.keys(value).length===keys.length&&keys.every(key=>Object.prototype.hasOwnProperty.call(value,key))}var BLOCK_TIME_TOLERANCE_SECONDS=2;function integer(value,minimum=0,maximum=Number.MAX_SAFE_INTEGER){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=minimum&&value<=maximum}var REQUEST_KEYS=["id","version","minTrustScore","maxVerificationAgeSeconds","maxEvaluationAgeSeconds","requiredAssurance","uniquenessRequirement","requireAttestation","cluster"];function normalizePolicyRequest(input,legacyMinTrustScore){if(legacyMinTrustScore!==void 0&&!integer(legacyMinTrustScore,0,1e4))throw new PolicyValidationError("unsupported_policy");let value=input===void 0?{id:"entros-verify-default",version:1,minTrustScore:legacyMinTrustScore??0,maxVerificationAgeSeconds:86400,requiredAssurance:"browser_unattested",uniquenessRequirement:"allow_unmeasured",cluster:"devnet"}:input;if(!record(value)||Object.keys(value).some(key=>!REQUEST_KEYS.includes(key)))throw new PolicyValidationError("unsupported_policy");if(value.requiredAssurance!=="browser_unattested")throw new PolicyValidationError("unsupported_assurance");if(value.uniquenessRequirement!=="allow_unmeasured")throw new PolicyValidationError("unsupported_uniqueness");if(typeof value.id!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(value.id)||value.version!==1||!integer(value.minTrustScore,0,1e4)||!integer(value.maxVerificationAgeSeconds,1,31536e3)||!integer(value.maxEvaluationAgeSeconds===void 0?90:value.maxEvaluationAgeSeconds,1,90)||value.requireAttestation!==void 0&&typeof value.requireAttestation!="boolean"||value.cluster!=="devnet"||legacyMinTrustScore!==void 0&&value.minTrustScore!==legacyMinTrustScore)throw new PolicyValidationError("unsupported_policy");return{id:value.id,version:1,minTrustScore:value.minTrustScore,maxVerificationAgeSeconds:value.maxVerificationAgeSeconds,maxEvaluationAgeSeconds:value.maxEvaluationAgeSeconds??90,requiredAssurance:"browser_unattested",uniquenessRequirement:"allow_unmeasured",requireAttestation:value.requireAttestation===!0,cluster:"devnet"}}function encodePolicyRequest(request){return JSON.stringify(normalizePolicyRequest(request))}var BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function base58Bytes(value,expected){if(typeof value!="string"||value.length<1||value.length>expected*2)return!1;let number=0n;for(let character of value){let digit=BASE58.indexOf(character);if(digit<0)return!1;number=number*58n+BigInt(digit)}let bytes=0;for(;number>0n;)bytes++,number>>=8n;let zeros=0;for(;value[zeros]==="1";)zeros++;return bytes+zeros===expected}function commitment(value){return typeof value=="string"&&/^[0-9a-f]{64}$/.test(value)&&!/^0+$/.test(value)}function isPolicyAttestation(value){return record(value)?value.status==="present"?exactKeys(value,["status","address","readContextSlot","expiresAt"])&&base58Bytes(value.address,32)&&integer(value.readContextSlot)&&(value.expiresAt===null||integer(value.expiresAt,1)):exactKeys(value,["status"])&&["missing","invalid","unavailable"].includes(String(value.status)):!1}function isPolicyEvidence(value){if(!record(value)||!exactKeys(value,["cluster","genesisHash","programIds","assuranceTier","uniquenessStatus","readContextSlot","identity","transaction","attestation"])||value.cluster!=="devnet"||value.genesisHash!==POLICY_NETWORK.genesisHash||value.assuranceTier!=="browser_unattested"||value.uniquenessStatus!=="unmeasured"||!integer(value.readContextSlot))return!1;let programs=value.programIds;if(!record(programs)||!exactKeys(programs,Object.keys(POLICY_NETWORK.programIds))||Object.entries(POLICY_NETWORK.programIds).some(([key,id])=>programs[key]!==id))return!1;let identity=value.identity,transaction=value.transaction;return!record(identity)||!exactKeys(identity,["walletPubkey","identityPda","creationTimestamp","lastVerificationTimestamp","verificationCount","trustScore","currentCommitment","projectionVersion","lastResetTimestamp","lastRebaselineTimestamp","mint"])||!base58Bytes(identity.walletPubkey,32)||!base58Bytes(identity.identityPda,32)||!base58Bytes(identity.mint,32)||!integer(identity.creationTimestamp,1)||!integer(identity.lastVerificationTimestamp,identity.creationTimestamp)||!integer(identity.verificationCount,0,4294967295)||!integer(identity.trustScore,0,1e4)||!commitment(identity.currentCommitment)||!integer(identity.projectionVersion,0,2)||!integer(identity.lastResetTimestamp)||!integer(identity.lastRebaselineTimestamp)||!record(transaction)||!exactKeys(transaction,["signature","slot","blockTime","commitment","kind"])||!base58Bytes(transaction.signature,64)||!integer(transaction.slot)||!integer(transaction.blockTime,identity.creationTimestamp-BLOCK_TIME_TOLERANCE_SECONDS)||!commitment(transaction.commitment)||!["mint","update","rebaseline"].includes(String(transaction.kind))?!1:isPolicyAttestation(value.attestation)}function evaluatePolicy(request,observation,nowSeconds){let requirements=normalizePolicyRequest(request);if(!integer(nowSeconds,1)||nowSeconds>Number.MAX_SAFE_INTEGER-31536e3)throw new PolicyValidationError("invalid_evidence");let base={policyId:requirements.id,policyVersion:1,requirements,evaluatedAt:nowSeconds,expiresAt:nowSeconds,evidenceTimestamp:null,evaluatedAgeSeconds:null};if(record(observation)&&observation.status==="unavailable")return{...base,decision:"unavailable",reason:"state_unavailable",evidence:null};if(!record(observation)||observation.status!=="available"||!isPolicyEvidence(observation.evidence))return{...base,decision:"deny",reason:"invalid_evidence",evidence:null};let evidence=observation.evidence,{identity,transaction,attestation}=evidence,deny=reason=>({...base,decision:"deny",reason,evidence}),earliestClock=transaction.blockTime-BLOCK_TIME_TOLERANCE_SECONDS,latestClock=transaction.blockTime+BLOCK_TIME_TOLERANCE_SECONDS,freshMint=transaction.kind==="mint"&&identity.verificationCount===0&&identity.trustScore===0&&identity.creationTimestamp===identity.lastVerificationTimestamp&&identity.lastVerificationTimestamp>=earliestClock&&identity.lastVerificationTimestamp<=latestClock&&identity.lastResetTimestamp===0&&identity.lastRebaselineTimestamp===0;return identity.verificationCount===0&&!freshMint||identity.currentCommitment!==transaction.commitment||identity.lastResetTimestamp>=earliestClock||identity.lastResetTimestamp>identity.lastVerificationTimestamp||identity.lastRebaselineTimestamp>identity.lastVerificationTimestamp||identity.lastRebaselineTimestamp>(transaction.kind==="rebaseline"?latestClock:earliestClock)||identity.lastVerificationTimestamp>nowSeconds||transaction.blockTime>nowSeconds||evidence.readContextSlot<transaction.slot||attestation.status==="invalid"||attestation.status==="present"&&(attestation.readContextSlot<transaction.slot||attestation.expiresAt!==null&&attestation.expiresAt<=nowSeconds)?deny("invalid_evidence"):(base.evidenceTimestamp=Math.min(identity.lastVerificationTimestamp,transaction.blockTime),base.evaluatedAgeSeconds=nowSeconds-base.evidenceTimestamp,base.expiresAt=Math.min(base.evidenceTimestamp+requirements.maxVerificationAgeSeconds,nowSeconds+requirements.maxEvaluationAgeSeconds),requirements.requireAttestation&&attestation.status==="present"&&attestation.expiresAt!==null&&(base.expiresAt=Math.min(base.expiresAt,attestation.expiresAt)),identity.trustScore<requirements.minTrustScore?deny("score_below_minimum"):nowSeconds>=base.expiresAt?deny("verification_stale"):requirements.requireAttestation&&attestation.status==="missing"?deny("attestation_required"):requirements.requireAttestation&&attestation.status==="unavailable"?{...base,decision:"unavailable",reason:"state_unavailable",evidence}:{...base,decision:"allow",reason:"accepted",evidence})}function policyResultToWire(result){let e=result.evidence;return{policy_id:result.policyId,policy_version:1,decision:result.decision,reason:result.reason,requirements:result.requirements,evaluated_at:result.evaluatedAt,expires_at:result.expiresAt,evidence_timestamp:result.evidenceTimestamp,evaluated_age_seconds:result.evaluatedAgeSeconds,wallet_pubkey:e?.identity.walletPubkey??null,identity_pda:e?.identity.identityPda??null,verified_transaction:e?{signature:e.transaction.signature,slot:e.transaction.slot,block_time:e.transaction.blockTime,commitment:e.transaction.commitment,kind:e.transaction.kind}:null,verification_timestamp:e?.identity.lastVerificationTimestamp??null,trust_score:e?.identity.trustScore??null,anchor_created_at:e?.identity.creationTimestamp??null,verification_count:e?.identity.verificationCount??null,current_commitment:e?.identity.currentCommitment??null,projection_version:e?.identity.projectionVersion??null,last_reset_timestamp:e?.identity.lastResetTimestamp??null,last_rebaseline_timestamp:e?.identity.lastRebaselineTimestamp??null,mint:e?.identity.mint??null,uniqueness_status:e?.uniquenessStatus??null,assurance_tier:e?.assuranceTier??null,cluster:e?.cluster??null,genesis_hash:e?.genesisHash??null,program_ids:e?.programIds??null,read_context_slot:e?.readContextSlot??null,attestation:e?e.attestation.status==="present"?{status:"present",address:e.attestation.address,read_context_slot:e.attestation.readContextSlot,expires_at:e.attestation.expiresAt}:e.attestation:null}}function parsePolicyWireResult(input){if(!record(input)||!integer(input.evaluated_at,1))return null;try{let requirements=normalizePolicyRequest(input.requirements),observation;if(input.wallet_pubkey===null)observation=input.decision==="unavailable"?{status:"unavailable",reason:"state_unavailable"}:{status:"invalid",reason:"invalid_evidence"};else{let tx=input.verified_transaction,sas=input.attestation;if(!record(tx)||!record(sas))return null;let evidence={cluster:input.cluster,genesisHash:input.genesis_hash,programIds:input.program_ids,assuranceTier:input.assurance_tier,uniquenessStatus:input.uniqueness_status,readContextSlot:input.read_context_slot,identity:{walletPubkey:input.wallet_pubkey,identityPda:input.identity_pda,creationTimestamp:input.anchor_created_at,lastVerificationTimestamp:input.verification_timestamp,verificationCount:input.verification_count,trustScore:input.trust_score,currentCommitment:input.current_commitment,projectionVersion:input.projection_version,lastResetTimestamp:input.last_reset_timestamp,lastRebaselineTimestamp:input.last_rebaseline_timestamp,mint:input.mint},transaction:{signature:tx.signature,slot:tx.slot,blockTime:tx.block_time,commitment:tx.commitment,kind:tx.kind},attestation:sas.status==="present"?{status:"present",address:sas.address,readContextSlot:sas.read_context_slot,expiresAt:sas.expires_at}:{status:sas.status}};if(!isPolicyEvidence(evidence))return null;observation={status:"available",evidence}}let result=evaluatePolicy(requirements,observation,input.evaluated_at);return canonicalEqual(input,policyResultToWire(result))?result:null}catch{return null}}function canonicalEqual(left,right){return left===right?!0:!record(left)||!record(right)?!1:exactKeys(left,Object.keys(right))&&Object.keys(right).every(key=>canonicalEqual(left[key],right[key]))}function isPolicyReason(value){return typeof value=="string"&&["accepted","score_below_minimum","verification_stale","attestation_required","unsupported_policy","unsupported_assurance","unsupported_uniqueness","invalid_evidence","state_unavailable"].includes(value)}function validatePolicyVerifiedPayload(payload,requestedPolicy,nowSeconds){if(!record(payload))return{ok:!1,reason:"invalid_evidence"};if(!Object.prototype.hasOwnProperty.call(payload,"policy"))return{ok:!1,reason:"unsupported_policy"};let result=parsePolicyWireResult(payload.policy);if(!result||!canonicalEqual(result.requirements,normalizePolicyRequest(requestedPolicy)))return{ok:!1,reason:"invalid_evidence"};if(result.decision!=="allow")return{ok:!1,reason:result.reason};if(!integer(nowSeconds,1)||result.evaluatedAt>nowSeconds||nowSeconds>=result.expiresAt)return{ok:!1,reason:"verification_stale"};let current=evaluatePolicy(requestedPolicy,{status:"available",evidence:result.evidence},nowSeconds);if(current.decision!=="allow")return{ok:!1,reason:current.reason};let e=result.evidence,address=e.attestation.status==="present"?e.attestation.address:null;return payload.wallet_pubkey!==e.identity.walletPubkey||payload.trust_score!==e.identity.trustScore||payload.cluster!==e.cluster||payload.tx_sig!==e.transaction.signature||payload.attestation_pda!==address?{ok:!1,reason:"invalid_evidence"}:{ok:!0,result}}var MAX_TIMESTAMP_DRIFT_MS=90*1e3,ERROR_REASONS=new Set(["wallet_rejected","validation_failed","network_error","user_canceled","origin_invalid","popup_blocked","timeout","unknown"]),HEARTBEAT_STATUSES=new Set(["wallet_connecting","capturing","proving","submitting","attesting"]),ENTROS_MESSAGE_TYPES=new Set(["entros/verified","entros/error","entros/heartbeat"]);function isEntrosMessage(data){if(typeof data!="object"||data===null)return!1;let msg=data;return msg.source==="entros"&&msg.version===1&&typeof msg.type=="string"&&ENTROS_MESSAGE_TYPES.has(msg.type)&&typeof msg.request_id=="string"&&msg.request_id.length>0&&typeof msg.timestamp=="number"&&Number.isFinite(msg.timestamp)&&"payload"in msg}function isFreshMessage(msg,now=Date.now()){return Math.abs(now-msg.timestamp)<MAX_TIMESTAMP_DRIFT_MS}function isErrorPayload(payload){if(typeof payload!="object"||payload===null)return!1;let p=payload;return typeof p.reason=="string"&&ERROR_REASONS.has(p.reason)&&(p.policy_reason===void 0||isPolicyReason(p.policy_reason)&&p.policy_reason!=="accepted")}function isHeartbeatPayload(payload){if(typeof payload!="object"||payload===null)return!1;let p=payload;return typeof p.status=="string"&&HEARTBEAT_STATUSES.has(p.status)}var VALID_INTEGRATOR_KEY=/^[a-z0-9_-]{1,64}$/,ORIGIN_PATTERN=/^https?:\/\/[^/]+$/;function buildPopupUrl(opts){if(opts.cluster!=="devnet")throw new Error("Unsupported cluster: @entros/verify currently supports devnet only");if(!VALID_INTEGRATOR_KEY.test(opts.integratorKey))throw new Error(`Invalid integratorKey: must match /^[a-z0-9_-]{1,64}$/ (got "${opts.integratorKey}")`);if(!ORIGIN_PATTERN.test(opts.parentOrigin))throw new Error(`Invalid parentOrigin: must be a fully-qualified origin (got "${opts.parentOrigin}")`);if(opts.minTrustScore!==void 0&&(!Number.isInteger(opts.minTrustScore)||opts.minTrustScore<0||opts.minTrustScore>1e4))throw new Error(`Invalid minTrustScore: must be an integer in [0, 10000] (got ${String(opts.minTrustScore)})`);let policy=normalizePolicyRequest(opts.policy,opts.minTrustScore),url=new URL("/embed/verify-popup",opts.baseOrigin);return url.searchParams.set("integrator",opts.integratorKey),url.searchParams.set("parent_origin",opts.parentOrigin),url.searchParams.set("cluster",opts.cluster),url.searchParams.set("request_id",opts.requestId),url.searchParams.set("policy_version","1"),url.searchParams.set("policy",encodePolicyRequest(policy)),opts.minTrustScore!==void 0&&url.searchParams.set("min_trust_score",String(opts.minTrustScore)),url.toString()}function generateRequestId(){if(typeof crypto>"u")throw new Error("crypto is unavailable in this environment; @entros/verify requires a secure context");if(typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto.getRandomValues!="function")throw new Error("crypto.getRandomValues is unavailable; @entros/verify requires a secure context");let bytes=new Uint8Array(16);crypto.getRandomValues(bytes),bytes[6]=(bytes[6]??0)&15|64,bytes[8]=(bytes[8]??0)&63|128;let hex=Array.from(bytes,b=>b.toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}var DEFAULT_TIMEOUT_MS=540*1e3,POPUP_CLOSED_POLL_MS=500,POPUP_CLOSED_GRACE_MS=1500,POPUP_OWNED_FALLBACK_CLOSE_MS=3e4;function openVerifyPopup(opts){if(typeof window>"u")throw new Error("openVerifyPopup must be called in a browser context");let requestId=generateRequestId(),requestedPolicy=normalizePolicyRequest(opts.policy,opts.minTrustScore),parentOrigin=window.location.origin,url=buildPopupUrl({baseOrigin:opts.baseOrigin,integratorKey:opts.integratorKey,parentOrigin,cluster:opts.cluster,requestId,minTrustScore:opts.minTrustScore,policy:requestedPolicy}),left=Math.max(0,Math.floor((window.screen.availWidth-opts.popupWidth)/2)),top=Math.max(0,Math.floor((window.screen.availHeight-opts.popupHeight)/2)),features=[`width=${opts.popupWidth}`,`height=${opts.popupHeight}`,`left=${left}`,`top=${top}`,"menubar=no","toolbar=no","location=yes","status=no","resizable=yes","scrollbars=yes"].join(","),popupName=`entros_verify_${requestId}`,rawPopup=window.open(url,popupName,features);if(!rawPopup||rawPopup.closed)return null;let popup=rawPopup,expectedPopupOrigin=new URL(opts.baseOrigin).origin,settled=!1,pollTimerId=null,timeoutTimerId=null,popupClosedAtMs=null;function clearListenersAndTimers(){window.removeEventListener("message",onMessage),pollTimerId!==null&&(clearInterval(pollTimerId),pollTimerId=null),timeoutTimerId!==null&&(clearTimeout(timeoutTimerId),timeoutTimerId=null)}function forceClosePopup(){if(popup&&!popup.closed)try{popup.close()}catch{}}function settleVerified(result){settled||(settled=!0,clearListenersAndTimers(),setTimeout(forceClosePopup,POPUP_OWNED_FALLBACK_CLOSE_MS),opts.onVerified(result))}function settleError(reason,forceImmediateClose=!1,policyReason){settled||(settled=!0,clearListenersAndTimers(),forceImmediateClose?forceClosePopup():setTimeout(forceClosePopup,POPUP_OWNED_FALLBACK_CLOSE_MS),opts.onError(policyReason===void 0?{reason}:{reason,policyReason}))}function onMessage(event){if(!settled&&event.origin===expectedPopupOrigin&&event.source===popup&&isEntrosMessage(event.data)&&event.data.request_id===requestId&&isFreshMessage(event.data))switch(event.data.type){case"entros/verified":{let validated=validatePolicyVerifiedPayload(event.data.payload,requestedPolicy,Math.floor(Date.now()/1e3));if(!validated.ok){settleError(validated.reason==="state_unavailable"?"network_error":"validation_failed",!1,validated.reason);break}let evidence=validated.result.evidence;settleVerified({walletPubkey:evidence.identity.walletPubkey,attestationPda:evidence.attestation.status==="present"?evidence.attestation.address:null,txSig:evidence.transaction.signature,trustScore:evidence.identity.trustScore,cluster:evidence.cluster,policy:validated.result});break}case"entros/error":{isErrorPayload(event.data.payload)&&settleError(event.data.payload.reason,!1,event.data.payload.policy_reason);break}case"entros/heartbeat":{isHeartbeatPayload(event.data.payload)&&opts.onProgress&&opts.onProgress({status:event.data.payload.status});break}}}function onPoll(){if(!settled)if(popup.closed){if(popupClosedAtMs===null){popupClosedAtMs=Date.now();return}Date.now()-popupClosedAtMs>=POPUP_CLOSED_GRACE_MS&&settleError("user_canceled",!0)}else popupClosedAtMs=null}function onTimeout(){settleError("timeout",!0)}return window.addEventListener("message",onMessage),pollTimerId=setInterval(onPoll,POPUP_CLOSED_POLL_MS),timeoutTimerId=setTimeout(onTimeout,opts.timeoutMs??DEFAULT_TIMEOUT_MS),{cancel:()=>settleError("user_canceled",!0)}}var import_jsx_runtime=require("react/jsx-runtime"),DEFAULT_BASE_ORIGIN="https://entros.io",DEFAULT_POPUP_WIDTH=480,DEFAULT_POPUP_HEIGHT=800,SETTLE_RESET_MS=1500;function EntrosVerify(props){let[state,setState]=(0,import_react.useState)({kind:"idle"}),handleRef=(0,import_react.useRef)(null),resetTimerRef=(0,import_react.useRef)(null),onVerifiedRef=(0,import_react.useRef)(props.onVerified),onErrorRef=(0,import_react.useRef)(props.onError),onProgressRef=(0,import_react.useRef)(props.onProgress);(0,import_react.useEffect)(()=>{onVerifiedRef.current=props.onVerified,onErrorRef.current=props.onError,onProgressRef.current=props.onProgress}),(0,import_react.useEffect)(()=>()=>{handleRef.current&&(handleRef.current.cancel(),handleRef.current=null),resetTimerRef.current!==null&&(clearTimeout(resetTimerRef.current),resetTimerRef.current=null)},[]);let scheduleReset=(0,import_react.useCallback)(()=>{resetTimerRef.current!==null&&clearTimeout(resetTimerRef.current),resetTimerRef.current=setTimeout(()=>{resetTimerRef.current=null,setState({kind:"idle"})},SETTLE_RESET_MS)},[]),trigger=(0,import_react.useCallback)(()=>{resetTimerRef.current!==null&&(clearTimeout(resetTimerRef.current),resetTimerRef.current=null),setState({kind:"opening"});let policy;try{policy=normalizePolicyRequest(props.policy,props.minTrustScore)}catch(error){let policyReason=error instanceof PolicyValidationError?error.reason:"unsupported_policy";setState({kind:"error",reason:"validation_failed"}),onErrorRef.current?.({reason:"validation_failed",policyReason}),scheduleReset();return}let handle=openVerifyPopup({baseOrigin:props.baseOrigin??DEFAULT_BASE_ORIGIN,integratorKey:props.integratorKey,cluster:props.cluster??"devnet",minTrustScore:props.minTrustScore,policy,popupWidth:props.popupWidth??DEFAULT_POPUP_WIDTH,popupHeight:props.popupHeight??DEFAULT_POPUP_HEIGHT,timeoutMs:props.timeoutMs,onVerified:result=>{handleRef.current=null,setState({kind:"done"}),onVerifiedRef.current(result),scheduleReset()},onError:error=>{handleRef.current=null,setState({kind:"error",reason:error.reason}),onErrorRef.current?.(error),scheduleReset()},onProgress:progress=>{onProgressRef.current?.(progress)}});if(handle===null){setState({kind:"blocked"}),onErrorRef.current?.({reason:"popup_blocked"});return}handleRef.current=handle,setState({kind:"waiting"})},[props.baseOrigin,props.cluster,props.integratorKey,props.minTrustScore,props.policy,props.popupHeight,props.popupWidth,props.timeoutMs,scheduleReset]),isWaiting=state.kind==="opening"||state.kind==="waiting",showFallback=state.kind==="blocked"&&(props.popupBlockedFallback??!0);return(0,import_jsx_runtime.jsxs)("div",{className:"entros-verify-container","data-state":state.kind,children:[(0,import_jsx_runtime.jsx)("button",{type:"button",onClick:trigger,disabled:isWaiting,className:props.className,style:props.style,children:isWaiting?"Verifying\u2026":props.children??"Verify with Entros"}),showFallback&&(0,import_jsx_runtime.jsxs)("div",{role:"alert",className:"entros-verify-blocked",children:[(0,import_jsx_runtime.jsx)("span",{children:"Popup blocked. "}),(0,import_jsx_runtime.jsx)("button",{type:"button",onClick:trigger,className:props.className,children:"Click here to open verification"})]})]})}0&&(module.exports={EntrosVerify});
|
|
2
|
+
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var index_exports={};__export(index_exports,{EntrosVerify:()=>EntrosVerify,evaluateWarmPolicyReuse:()=>evaluateWarmPolicyReuse});module.exports=__toCommonJS(index_exports);var import_react=require("react");var POLICY_NETWORK=Object.freeze({genesisHash:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG",programIds:Object.freeze({anchor:"GZYwTp2ozeuRA5Gof9vs4ya961aANcJBdUzB7LN6q4b2",verifier:"4F97jNoxQzT2qRbkWpW3ztC3Nz2TtKj3rnKG8ExgnrfV",registry:"6VBs3zr9KrfFPGd6j7aGBPQWwZa5tajVfA7HN6MMV9VW",sas:"22zoJMtdu4tQc2PzL74ZUT7FrwgB1Udec8DdW4yw4BdG",credential:"AMBtabCgRFwGLjoZ21Z2LhSKJ6c47NckxUkMogJ3Lpuw",schema:"5LNc7syFW7USPLveVLcNcjjY1xqS7QTXVjHZ7CQCbAMQ"})}),PolicyValidationError=class extends Error{constructor(reason){super(`Invalid verification policy: ${reason}`);this.reason=reason;this.name="PolicyValidationError"}};function record(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function exactKeys(value,keys){return Object.keys(value).length===keys.length&&keys.every(key=>Object.prototype.hasOwnProperty.call(value,key))}var BLOCK_TIME_TOLERANCE_SECONDS=2;function integer(value,minimum=0,maximum=Number.MAX_SAFE_INTEGER){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=minimum&&value<=maximum}var REQUEST_KEYS=["id","version","minTrustScore","maxVerificationAgeSeconds","maxEvaluationAgeSeconds","requiredAssurance","uniquenessRequirement","requireAttestation","cluster"];function normalizePolicyRequest(input,legacyMinTrustScore){if(legacyMinTrustScore!==void 0&&!integer(legacyMinTrustScore,0,1e4))throw new PolicyValidationError("unsupported_policy");let value=input===void 0?{id:"entros-verify-default",version:1,minTrustScore:legacyMinTrustScore??0,maxVerificationAgeSeconds:86400,requiredAssurance:"browser_unattested",uniquenessRequirement:"allow_unmeasured",cluster:"devnet"}:input;if(!record(value)||Object.keys(value).some(key=>!REQUEST_KEYS.includes(key)))throw new PolicyValidationError("unsupported_policy");if(value.requiredAssurance!=="browser_unattested")throw new PolicyValidationError("unsupported_assurance");if(value.uniquenessRequirement!=="allow_unmeasured")throw new PolicyValidationError("unsupported_uniqueness");if(typeof value.id!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(value.id)||value.version!==1||!integer(value.minTrustScore,0,1e4)||!integer(value.maxVerificationAgeSeconds,1,31536e3)||!integer(value.maxEvaluationAgeSeconds===void 0?90:value.maxEvaluationAgeSeconds,1,90)||value.requireAttestation!==void 0&&typeof value.requireAttestation!="boolean"||value.cluster!=="devnet"||legacyMinTrustScore!==void 0&&value.minTrustScore!==legacyMinTrustScore)throw new PolicyValidationError("unsupported_policy");return{id:value.id,version:1,minTrustScore:value.minTrustScore,maxVerificationAgeSeconds:value.maxVerificationAgeSeconds,maxEvaluationAgeSeconds:value.maxEvaluationAgeSeconds??90,requiredAssurance:"browser_unattested",uniquenessRequirement:"allow_unmeasured",requireAttestation:value.requireAttestation===!0,cluster:"devnet"}}function encodePolicyRequest(request){return JSON.stringify(normalizePolicyRequest(request))}var BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function base58Bytes(value,expected){if(typeof value!="string"||value.length<1||value.length>expected*2)return!1;let number=0n;for(let character of value){let digit=BASE58.indexOf(character);if(digit<0)return!1;number=number*58n+BigInt(digit)}let bytes=0;for(;number>0n;)bytes++,number>>=8n;let zeros=0;for(;value[zeros]==="1";)zeros++;return bytes+zeros===expected}function commitment(value){return typeof value=="string"&&/^[0-9a-f]{64}$/.test(value)&&!/^0+$/.test(value)}function isPolicyAttestation(value){return record(value)?value.status==="present"?exactKeys(value,["status","address","readContextSlot","expiresAt"])&&base58Bytes(value.address,32)&&integer(value.readContextSlot)&&(value.expiresAt===null||integer(value.expiresAt,1)):exactKeys(value,["status"])&&["missing","invalid","unavailable"].includes(String(value.status)):!1}function isPolicyEvidence(value){if(!record(value)||!exactKeys(value,["cluster","genesisHash","programIds","assuranceTier","uniquenessStatus","readContextSlot","identity","transaction","attestation"])||value.cluster!=="devnet"||value.genesisHash!==POLICY_NETWORK.genesisHash||value.assuranceTier!=="browser_unattested"||value.uniquenessStatus!=="unmeasured"||!integer(value.readContextSlot))return!1;let programs=value.programIds;if(!record(programs)||!exactKeys(programs,Object.keys(POLICY_NETWORK.programIds))||Object.entries(POLICY_NETWORK.programIds).some(([key,id])=>programs[key]!==id))return!1;let identity=value.identity,transaction=value.transaction;return!record(identity)||!exactKeys(identity,["walletPubkey","identityPda","creationTimestamp","lastVerificationTimestamp","verificationCount","trustScore","currentCommitment","projectionVersion","lastResetTimestamp","lastRebaselineTimestamp","mint"])||!base58Bytes(identity.walletPubkey,32)||!base58Bytes(identity.identityPda,32)||!base58Bytes(identity.mint,32)||!integer(identity.creationTimestamp,1)||!integer(identity.lastVerificationTimestamp,identity.creationTimestamp)||!integer(identity.verificationCount,0,4294967295)||!integer(identity.trustScore,0,1e4)||!commitment(identity.currentCommitment)||!integer(identity.projectionVersion,0,2)||!integer(identity.lastResetTimestamp)||!integer(identity.lastRebaselineTimestamp)||!record(transaction)||!exactKeys(transaction,["signature","slot","blockTime","commitment","kind"])||!base58Bytes(transaction.signature,64)||!integer(transaction.slot)||!integer(transaction.blockTime,identity.creationTimestamp-BLOCK_TIME_TOLERANCE_SECONDS)||!commitment(transaction.commitment)||!["mint","update","rebaseline"].includes(String(transaction.kind))?!1:isPolicyAttestation(value.attestation)}function evaluatePolicy(request,observation,nowSeconds){let requirements=normalizePolicyRequest(request);if(!integer(nowSeconds,1)||nowSeconds>Number.MAX_SAFE_INTEGER-31536e3)throw new PolicyValidationError("invalid_evidence");let base={policyId:requirements.id,policyVersion:1,requirements,evaluatedAt:nowSeconds,expiresAt:nowSeconds,evidenceTimestamp:null,evaluatedAgeSeconds:null};if(record(observation)&&observation.status==="unavailable")return{...base,decision:"unavailable",reason:"state_unavailable",evidence:null};if(!record(observation)||observation.status!=="available"||!isPolicyEvidence(observation.evidence))return{...base,decision:"deny",reason:"invalid_evidence",evidence:null};let evidence=observation.evidence,{identity,transaction,attestation}=evidence,deny=reason=>({...base,decision:"deny",reason,evidence}),earliestClock=transaction.blockTime-BLOCK_TIME_TOLERANCE_SECONDS,latestClock=transaction.blockTime+BLOCK_TIME_TOLERANCE_SECONDS,freshMint=transaction.kind==="mint"&&identity.verificationCount===0&&identity.trustScore===0&&identity.creationTimestamp===identity.lastVerificationTimestamp&&identity.lastVerificationTimestamp>=earliestClock&&identity.lastVerificationTimestamp<=latestClock&&identity.lastResetTimestamp===0&&identity.lastRebaselineTimestamp===0;return identity.verificationCount===0&&!freshMint||identity.currentCommitment!==transaction.commitment||identity.lastResetTimestamp>=earliestClock||identity.lastResetTimestamp>identity.lastVerificationTimestamp||identity.lastRebaselineTimestamp>identity.lastVerificationTimestamp||identity.lastRebaselineTimestamp>(transaction.kind==="rebaseline"?latestClock:earliestClock)||identity.lastVerificationTimestamp>nowSeconds||transaction.blockTime>nowSeconds||evidence.readContextSlot<transaction.slot||attestation.status==="invalid"||attestation.status==="present"&&(attestation.readContextSlot<transaction.slot||attestation.expiresAt!==null&&attestation.expiresAt<=nowSeconds)?deny("invalid_evidence"):(base.evidenceTimestamp=Math.min(identity.lastVerificationTimestamp,transaction.blockTime),base.evaluatedAgeSeconds=nowSeconds-base.evidenceTimestamp,base.expiresAt=Math.min(base.evidenceTimestamp+requirements.maxVerificationAgeSeconds,nowSeconds+requirements.maxEvaluationAgeSeconds),requirements.requireAttestation&&attestation.status==="present"&&attestation.expiresAt!==null&&(base.expiresAt=Math.min(base.expiresAt,attestation.expiresAt)),identity.trustScore<requirements.minTrustScore?deny("score_below_minimum"):nowSeconds>=base.expiresAt?deny("verification_stale"):requirements.requireAttestation&&attestation.status==="missing"?deny("attestation_required"):requirements.requireAttestation&&attestation.status==="unavailable"?{...base,decision:"unavailable",reason:"state_unavailable",evidence}:{...base,decision:"allow",reason:"accepted",evidence})}function policyResultToWire(result){let e=result.evidence;return{policy_id:result.policyId,policy_version:1,decision:result.decision,reason:result.reason,requirements:result.requirements,evaluated_at:result.evaluatedAt,expires_at:result.expiresAt,evidence_timestamp:result.evidenceTimestamp,evaluated_age_seconds:result.evaluatedAgeSeconds,wallet_pubkey:e?.identity.walletPubkey??null,identity_pda:e?.identity.identityPda??null,verified_transaction:e?{signature:e.transaction.signature,slot:e.transaction.slot,block_time:e.transaction.blockTime,commitment:e.transaction.commitment,kind:e.transaction.kind}:null,verification_timestamp:e?.identity.lastVerificationTimestamp??null,trust_score:e?.identity.trustScore??null,anchor_created_at:e?.identity.creationTimestamp??null,verification_count:e?.identity.verificationCount??null,current_commitment:e?.identity.currentCommitment??null,projection_version:e?.identity.projectionVersion??null,last_reset_timestamp:e?.identity.lastResetTimestamp??null,last_rebaseline_timestamp:e?.identity.lastRebaselineTimestamp??null,mint:e?.identity.mint??null,uniqueness_status:e?.uniquenessStatus??null,assurance_tier:e?.assuranceTier??null,cluster:e?.cluster??null,genesis_hash:e?.genesisHash??null,program_ids:e?.programIds??null,read_context_slot:e?.readContextSlot??null,attestation:e?e.attestation.status==="present"?{status:"present",address:e.attestation.address,read_context_slot:e.attestation.readContextSlot,expires_at:e.attestation.expiresAt}:e.attestation:null}}function parsePolicyWireResult(input){if(!record(input)||!integer(input.evaluated_at,1))return null;try{let requirements=normalizePolicyRequest(input.requirements),observation;if(input.wallet_pubkey===null)observation=input.decision==="unavailable"?{status:"unavailable",reason:"state_unavailable"}:{status:"invalid",reason:"invalid_evidence"};else{let tx=input.verified_transaction,sas=input.attestation;if(!record(tx)||!record(sas))return null;let evidence={cluster:input.cluster,genesisHash:input.genesis_hash,programIds:input.program_ids,assuranceTier:input.assurance_tier,uniquenessStatus:input.uniqueness_status,readContextSlot:input.read_context_slot,identity:{walletPubkey:input.wallet_pubkey,identityPda:input.identity_pda,creationTimestamp:input.anchor_created_at,lastVerificationTimestamp:input.verification_timestamp,verificationCount:input.verification_count,trustScore:input.trust_score,currentCommitment:input.current_commitment,projectionVersion:input.projection_version,lastResetTimestamp:input.last_reset_timestamp,lastRebaselineTimestamp:input.last_rebaseline_timestamp,mint:input.mint},transaction:{signature:tx.signature,slot:tx.slot,blockTime:tx.block_time,commitment:tx.commitment,kind:tx.kind},attestation:sas.status==="present"?{status:"present",address:sas.address,readContextSlot:sas.read_context_slot,expiresAt:sas.expires_at}:{status:sas.status}};if(!isPolicyEvidence(evidence))return null;observation={status:"available",evidence}}let result=evaluatePolicy(requirements,observation,input.evaluated_at);return canonicalEqual(input,policyResultToWire(result))?result:null}catch{return null}}function canonicalEqual(left,right){return left===right?!0:!record(left)||!record(right)?!1:exactKeys(left,Object.keys(right))&&Object.keys(right).every(key=>canonicalEqual(left[key],right[key]))}function isPolicyReason(value){return typeof value=="string"&&["accepted","score_below_minimum","verification_stale","attestation_required","unsupported_policy","unsupported_assurance","unsupported_uniqueness","invalid_evidence","state_unavailable"].includes(value)}function validatePolicyVerifiedPayload(payload,requestedPolicy,nowSeconds){if(!record(payload))return{ok:!1,reason:"invalid_evidence"};if(!Object.prototype.hasOwnProperty.call(payload,"policy"))return{ok:!1,reason:"unsupported_policy"};let result=parsePolicyWireResult(payload.policy);if(!result||!canonicalEqual(result.requirements,normalizePolicyRequest(requestedPolicy)))return{ok:!1,reason:"invalid_evidence"};if(result.decision!=="allow")return{ok:!1,reason:result.reason};if(!integer(nowSeconds,1)||result.evaluatedAt>nowSeconds||nowSeconds>=result.expiresAt)return{ok:!1,reason:"verification_stale"};let current=evaluatePolicy(requestedPolicy,{status:"available",evidence:result.evidence},nowSeconds);if(current.decision!=="allow")return{ok:!1,reason:current.reason};let e=result.evidence,address=e.attestation.status==="present"?e.attestation.address:null;return payload.wallet_pubkey!==e.identity.walletPubkey||payload.trust_score!==e.identity.trustScore||payload.cluster!==e.cluster||payload.tx_sig!==e.transaction.signature||payload.attestation_pda!==address?{ok:!1,reason:"invalid_evidence"}:{ok:!0,result}}var MAX_TIMESTAMP_DRIFT_MS=90*1e3,ERROR_REASONS=new Set(["wallet_rejected","validation_failed","network_error","user_canceled","origin_invalid","popup_blocked","timeout","unknown"]),HEARTBEAT_STATUSES=new Set(["wallet_connecting","capturing","proving","submitting","attesting"]),ENTROS_MESSAGE_TYPES=new Set(["entros/verified","entros/error","entros/heartbeat"]);function isEntrosMessage(data){if(typeof data!="object"||data===null)return!1;let msg=data;return msg.source==="entros"&&msg.version===1&&typeof msg.type=="string"&&ENTROS_MESSAGE_TYPES.has(msg.type)&&typeof msg.request_id=="string"&&msg.request_id.length>0&&typeof msg.timestamp=="number"&&Number.isFinite(msg.timestamp)&&"payload"in msg}function isFreshMessage(msg,now=Date.now()){return Math.abs(now-msg.timestamp)<MAX_TIMESTAMP_DRIFT_MS}function isErrorPayload(payload){if(typeof payload!="object"||payload===null)return!1;let p=payload;return typeof p.reason=="string"&&ERROR_REASONS.has(p.reason)&&(p.policy_reason===void 0||isPolicyReason(p.policy_reason)&&p.policy_reason!=="accepted")}function isHeartbeatPayload(payload){if(typeof payload!="object"||payload===null)return!1;let p=payload;return typeof p.status=="string"&&HEARTBEAT_STATUSES.has(p.status)}var VALID_INTEGRATOR_KEY=/^[a-z0-9_-]{1,64}$/;function isOrigin(value){try{let url=new URL(value);return(url.protocol==="https:"||url.protocol==="http:")&&url.origin===value}catch{return!1}}function buildPopupUrl(opts){if(opts.cluster!=="devnet")throw new Error("Unsupported cluster: @entros/verify currently supports devnet only");if(!VALID_INTEGRATOR_KEY.test(opts.integratorKey))throw new Error(`Invalid integratorKey: must match /^[a-z0-9_-]{1,64}$/ (got "${opts.integratorKey}")`);if(!isOrigin(opts.parentOrigin))throw new Error(`Invalid parentOrigin: must be a fully-qualified origin (got "${opts.parentOrigin}")`);if(opts.minTrustScore!==void 0&&(!Number.isInteger(opts.minTrustScore)||opts.minTrustScore<0||opts.minTrustScore>1e4))throw new Error(`Invalid minTrustScore: must be an integer in [0, 10000] (got ${String(opts.minTrustScore)})`);let policy=normalizePolicyRequest(opts.policy,opts.minTrustScore),url=new URL("/embed/verify-popup",opts.baseOrigin);return url.searchParams.set("integrator",opts.integratorKey),url.searchParams.set("parent_origin",opts.parentOrigin),url.searchParams.set("cluster",opts.cluster),url.searchParams.set("request_id",opts.requestId),url.searchParams.set("policy_version","1"),url.searchParams.set("policy",encodePolicyRequest(policy)),opts.minTrustScore!==void 0&&url.searchParams.set("min_trust_score",String(opts.minTrustScore)),url.toString()}function generateRequestId(){if(typeof crypto>"u")throw new Error("crypto is unavailable in this environment; @entros/verify requires a secure context");if(typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto.getRandomValues!="function")throw new Error("crypto.getRandomValues is unavailable; @entros/verify requires a secure context");let bytes=new Uint8Array(16);crypto.getRandomValues(bytes),bytes[6]=(bytes[6]??0)&15|64,bytes[8]=(bytes[8]??0)&63|128;let hex=Array.from(bytes,b=>b.toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}var DEFAULT_TIMEOUT_MS=540*1e3,POPUP_CLOSED_POLL_MS=500,POPUP_CLOSED_GRACE_MS=1500,POPUP_OWNED_FALLBACK_CLOSE_MS=3e4;function openVerifyPopup(opts){if(typeof window>"u")throw new Error("openVerifyPopup must be called in a browser context");let requestId=generateRequestId(),requestedPolicy=normalizePolicyRequest(opts.policy,opts.minTrustScore),parentOrigin=window.location.origin,url=buildPopupUrl({baseOrigin:opts.baseOrigin,integratorKey:opts.integratorKey,parentOrigin,cluster:opts.cluster,requestId,minTrustScore:opts.minTrustScore,policy:requestedPolicy}),left=Math.max(0,Math.floor((window.screen.availWidth-opts.popupWidth)/2)),top=Math.max(0,Math.floor((window.screen.availHeight-opts.popupHeight)/2)),features=[`width=${opts.popupWidth}`,`height=${opts.popupHeight}`,`left=${left}`,`top=${top}`,"menubar=no","toolbar=no","location=yes","status=no","resizable=yes","scrollbars=yes"].join(","),popupName=`entros_verify_${requestId}`,rawPopup=window.open(url,popupName,features);if(!rawPopup||rawPopup.closed)return null;let popup=rawPopup,expectedPopupOrigin=new URL(opts.baseOrigin).origin,settled=!1,pollTimerId=null,timeoutTimerId=null,popupClosedAtMs=null;function clearListenersAndTimers(){window.removeEventListener("message",onMessage),pollTimerId!==null&&(clearInterval(pollTimerId),pollTimerId=null),timeoutTimerId!==null&&(clearTimeout(timeoutTimerId),timeoutTimerId=null)}function forceClosePopup(){if(popup&&!popup.closed)try{popup.close()}catch{}}function settleVerified(result){settled||(settled=!0,clearListenersAndTimers(),setTimeout(forceClosePopup,POPUP_OWNED_FALLBACK_CLOSE_MS),opts.onVerified(result))}function settleError(reason,forceImmediateClose=!1,policyReason){settled||(settled=!0,clearListenersAndTimers(),forceImmediateClose?forceClosePopup():setTimeout(forceClosePopup,POPUP_OWNED_FALLBACK_CLOSE_MS),opts.onError(policyReason===void 0?{reason}:{reason,policyReason}))}function onMessage(event){if(!settled&&event.origin===expectedPopupOrigin&&event.source===popup&&isEntrosMessage(event.data)&&event.data.request_id===requestId&&isFreshMessage(event.data))switch(event.data.type){case"entros/verified":{let validated=validatePolicyVerifiedPayload(event.data.payload,requestedPolicy,Math.floor(Date.now()/1e3));if(!validated.ok){settleError(validated.reason==="state_unavailable"?"network_error":"validation_failed",!1,validated.reason);break}let evidence=validated.result.evidence;settleVerified({walletPubkey:evidence.identity.walletPubkey,attestationPda:evidence.attestation.status==="present"?evidence.attestation.address:null,txSig:evidence.transaction.signature,trustScore:evidence.identity.trustScore,cluster:evidence.cluster,policy:validated.result});break}case"entros/error":{isErrorPayload(event.data.payload)&&settleError(event.data.payload.reason,!1,event.data.payload.policy_reason);break}case"entros/heartbeat":{isHeartbeatPayload(event.data.payload)&&opts.onProgress&&opts.onProgress({status:event.data.payload.status});break}}}function onPoll(){if(!settled)if(popup.closed){if(popupClosedAtMs===null){popupClosedAtMs=Date.now();return}Date.now()-popupClosedAtMs>=POPUP_CLOSED_GRACE_MS&&settleError("user_canceled",!0)}else popupClosedAtMs=null}function onTimeout(){settleError("timeout",!0)}return window.addEventListener("message",onMessage),pollTimerId=setInterval(onPoll,POPUP_CLOSED_POLL_MS),timeoutTimerId=setTimeout(onTimeout,opts.timeoutMs??DEFAULT_TIMEOUT_MS),{cancel:()=>settleError("user_canceled",!0)}}var import_jsx_runtime=require("react/jsx-runtime"),DEFAULT_BASE_ORIGIN="https://entros.io",DEFAULT_POPUP_WIDTH=480,DEFAULT_POPUP_HEIGHT=800,SETTLE_RESET_MS=1500;function EntrosVerify(props){let[state,setState]=(0,import_react.useState)({kind:"idle"}),handleRef=(0,import_react.useRef)(null),resetTimerRef=(0,import_react.useRef)(null),onVerifiedRef=(0,import_react.useRef)(props.onVerified),onErrorRef=(0,import_react.useRef)(props.onError),onProgressRef=(0,import_react.useRef)(props.onProgress);(0,import_react.useEffect)(()=>{onVerifiedRef.current=props.onVerified,onErrorRef.current=props.onError,onProgressRef.current=props.onProgress}),(0,import_react.useEffect)(()=>()=>{handleRef.current&&(handleRef.current.cancel(),handleRef.current=null),resetTimerRef.current!==null&&(clearTimeout(resetTimerRef.current),resetTimerRef.current=null)},[]);let scheduleReset=(0,import_react.useCallback)(()=>{resetTimerRef.current!==null&&clearTimeout(resetTimerRef.current),resetTimerRef.current=setTimeout(()=>{resetTimerRef.current=null,setState({kind:"idle"})},SETTLE_RESET_MS)},[]),trigger=(0,import_react.useCallback)(()=>{resetTimerRef.current!==null&&(clearTimeout(resetTimerRef.current),resetTimerRef.current=null),setState({kind:"opening"});let policy;try{policy=normalizePolicyRequest(props.policy,props.minTrustScore)}catch(error){let policyReason=error instanceof PolicyValidationError?error.reason:"unsupported_policy";setState({kind:"error",reason:"validation_failed"}),onErrorRef.current?.({reason:"validation_failed",policyReason}),scheduleReset();return}let handle;try{handle=openVerifyPopup({baseOrigin:props.baseOrigin??DEFAULT_BASE_ORIGIN,integratorKey:props.integratorKey,cluster:props.cluster??"devnet",minTrustScore:props.minTrustScore,policy,popupWidth:props.popupWidth??DEFAULT_POPUP_WIDTH,popupHeight:props.popupHeight??DEFAULT_POPUP_HEIGHT,timeoutMs:props.timeoutMs,onVerified:result=>{handleRef.current=null,setState({kind:"done"}),onVerifiedRef.current(result),scheduleReset()},onError:error=>{handleRef.current=null,setState({kind:"error",reason:error.reason}),onErrorRef.current?.(error),scheduleReset()},onProgress:progress=>{onProgressRef.current?.(progress)}})}catch{setState({kind:"error",reason:"validation_failed"}),onErrorRef.current?.({reason:"validation_failed"}),scheduleReset();return}if(handle===null){setState({kind:"blocked"}),onErrorRef.current?.({reason:"popup_blocked"});return}handleRef.current=handle,setState({kind:"waiting"})},[props.baseOrigin,props.cluster,props.integratorKey,props.minTrustScore,props.policy,props.popupHeight,props.popupWidth,props.timeoutMs,scheduleReset]),isWaiting=state.kind==="opening"||state.kind==="waiting",showFallback=state.kind==="blocked"&&(props.popupBlockedFallback??!0);return(0,import_jsx_runtime.jsxs)("div",{className:"entros-verify-container","data-state":state.kind,children:[(0,import_jsx_runtime.jsx)("button",{type:"button",onClick:trigger,disabled:isWaiting,className:props.className,style:props.style,children:isWaiting?"Verifying\u2026":props.children??"Verify with Entros"}),showFallback&&(0,import_jsx_runtime.jsxs)("div",{role:"alert",className:"entros-verify-blocked",children:[(0,import_jsx_runtime.jsx)("span",{children:"Popup blocked. "}),(0,import_jsx_runtime.jsx)("button",{type:"button",onClick:trigger,className:props.className,children:"Click here to open verification"})]})]})}var ALPHABET="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function base58Encode(bytes){let number=0n;for(let byte of bytes)number=number<<8n|BigInt(byte);let text="";for(;number>0n;)text=ALPHABET[Number(number%58n)]+text,number/=58n;let zeros=0;for(;zeros<bytes.length&&bytes[zeros]===0;)zeros++;return"1".repeat(zeros)+text}function base58Decode(text){if(text.length===0)return null;let number=0n;for(let character of text){let digit=ALPHABET.indexOf(character);if(digit<0)return null;number=number*58n+BigInt(digit)}let body=[];for(;number>0n;)body.unshift(Number(number&0xffn)),number>>=8n;let zeros=0;for(;zeros<text.length&&text[zeros]==="1";)zeros++;return Uint8Array.from([...new Array(zeros).fill(0),...body])}function canonicalKeyBytes(text){if(text.length<32||text.length>44)return null;let bytes=base58Decode(text);return!bytes||bytes.length!==32||base58Encode(bytes)!==text?null:bytes}function readClock(nowSeconds){let value=typeof nowSeconds=="function"?nowSeconds():nowSeconds;if(typeof value!="number"||!Number.isSafeInteger(value)||value<1||value>Number.MAX_SAFE_INTEGER-31536e3)throw new PolicyValidationError("invalid_evidence");return value}function needsCapture(reason,policy=null){return{status:"needs_capture",policy,reason}}async function evaluateWarmPolicyReuse(input){let normalized=normalizePolicyRequest(input.policy,input.minTrustScore),requireLegacy=input.requireLegacyAttestation===!0&&input.policy===void 0,effectivePolicy=requireLegacy?{...normalized,requireAttestation:!0}:normalized;if(typeof input.nowSeconds!="function"&&readClock(input.nowSeconds),typeof input.walletPubkey!="string"||canonicalKeyBytes(input.walletPubkey)===null)return needsCapture("invalid_evidence");let observation,expectedSignature;if(input.observation!==void 0)observation=input.observation;else if(typeof input.readEvidence=="function"){if(typeof input.findVerification=="function"){let lookup;try{lookup=await input.findVerification({walletPubkey:input.walletPubkey})}catch{return needsCapture("state_unavailable")}if(lookup===null)return needsCapture("evidence_not_found");if(typeof lookup=="string"){if(lookup.length===0)return needsCapture("evidence_not_found");expectedSignature=lookup}else if(lookup.status==="found"){if(typeof lookup.signature!="string"||lookup.signature.length===0)return needsCapture("invalid_evidence");expectedSignature=lookup.signature}else return lookup.status==="none"?needsCapture("evidence_not_found"):lookup.status==="unavailable"?needsCapture("state_unavailable"):needsCapture("invalid_evidence")}try{observation=await input.readEvidence(expectedSignature===void 0?{walletPubkey:input.walletPubkey}:{walletPubkey:input.walletPubkey,transactionSignature:expectedSignature})}catch{return needsCapture("state_unavailable")}}else return needsCapture("evidence_not_found");if(observation===null)return needsCapture("evidence_not_found");let evaluatedNow=readClock(input.nowSeconds),policy=evaluatePolicy(effectivePolicy,observation,evaluatedNow);return policy.evidence!==null&&policy.evidence.identity.walletPubkey!==input.walletPubkey||expectedSignature!==void 0&&policy.evidence!==null&&policy.evidence.transaction.signature!==expectedSignature?needsCapture("invalid_evidence"):policy.decision!=="allow"?needsCapture(policy.reason,policy):requireLegacy&&policy.evidence.attestation.status!=="present"?needsCapture("attestation_required"):{status:"reused",policy,evidence:policy.evidence}}0&&(module.exports={EntrosVerify,evaluateWarmPolicyReuse});
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{useCallback,useEffect,useRef,useState}from"react";var POLICY_NETWORK=Object.freeze({genesisHash:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG",programIds:Object.freeze({anchor:"GZYwTp2ozeuRA5Gof9vs4ya961aANcJBdUzB7LN6q4b2",verifier:"4F97jNoxQzT2qRbkWpW3ztC3Nz2TtKj3rnKG8ExgnrfV",registry:"6VBs3zr9KrfFPGd6j7aGBPQWwZa5tajVfA7HN6MMV9VW",sas:"22zoJMtdu4tQc2PzL74ZUT7FrwgB1Udec8DdW4yw4BdG",credential:"AMBtabCgRFwGLjoZ21Z2LhSKJ6c47NckxUkMogJ3Lpuw",schema:"5LNc7syFW7USPLveVLcNcjjY1xqS7QTXVjHZ7CQCbAMQ"})}),PolicyValidationError=class extends Error{constructor(reason){super(`Invalid verification policy: ${reason}`);this.reason=reason;this.name="PolicyValidationError"}};function record(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function exactKeys(value,keys){return Object.keys(value).length===keys.length&&keys.every(key=>Object.prototype.hasOwnProperty.call(value,key))}var BLOCK_TIME_TOLERANCE_SECONDS=2;function integer(value,minimum=0,maximum=Number.MAX_SAFE_INTEGER){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=minimum&&value<=maximum}var REQUEST_KEYS=["id","version","minTrustScore","maxVerificationAgeSeconds","maxEvaluationAgeSeconds","requiredAssurance","uniquenessRequirement","requireAttestation","cluster"];function normalizePolicyRequest(input,legacyMinTrustScore){if(legacyMinTrustScore!==void 0&&!integer(legacyMinTrustScore,0,1e4))throw new PolicyValidationError("unsupported_policy");let value=input===void 0?{id:"entros-verify-default",version:1,minTrustScore:legacyMinTrustScore??0,maxVerificationAgeSeconds:86400,requiredAssurance:"browser_unattested",uniquenessRequirement:"allow_unmeasured",cluster:"devnet"}:input;if(!record(value)||Object.keys(value).some(key=>!REQUEST_KEYS.includes(key)))throw new PolicyValidationError("unsupported_policy");if(value.requiredAssurance!=="browser_unattested")throw new PolicyValidationError("unsupported_assurance");if(value.uniquenessRequirement!=="allow_unmeasured")throw new PolicyValidationError("unsupported_uniqueness");if(typeof value.id!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(value.id)||value.version!==1||!integer(value.minTrustScore,0,1e4)||!integer(value.maxVerificationAgeSeconds,1,31536e3)||!integer(value.maxEvaluationAgeSeconds===void 0?90:value.maxEvaluationAgeSeconds,1,90)||value.requireAttestation!==void 0&&typeof value.requireAttestation!="boolean"||value.cluster!=="devnet"||legacyMinTrustScore!==void 0&&value.minTrustScore!==legacyMinTrustScore)throw new PolicyValidationError("unsupported_policy");return{id:value.id,version:1,minTrustScore:value.minTrustScore,maxVerificationAgeSeconds:value.maxVerificationAgeSeconds,maxEvaluationAgeSeconds:value.maxEvaluationAgeSeconds??90,requiredAssurance:"browser_unattested",uniquenessRequirement:"allow_unmeasured",requireAttestation:value.requireAttestation===!0,cluster:"devnet"}}function encodePolicyRequest(request){return JSON.stringify(normalizePolicyRequest(request))}var BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function base58Bytes(value,expected){if(typeof value!="string"||value.length<1||value.length>expected*2)return!1;let number=0n;for(let character of value){let digit=BASE58.indexOf(character);if(digit<0)return!1;number=number*58n+BigInt(digit)}let bytes=0;for(;number>0n;)bytes++,number>>=8n;let zeros=0;for(;value[zeros]==="1";)zeros++;return bytes+zeros===expected}function commitment(value){return typeof value=="string"&&/^[0-9a-f]{64}$/.test(value)&&!/^0+$/.test(value)}function isPolicyAttestation(value){return record(value)?value.status==="present"?exactKeys(value,["status","address","readContextSlot","expiresAt"])&&base58Bytes(value.address,32)&&integer(value.readContextSlot)&&(value.expiresAt===null||integer(value.expiresAt,1)):exactKeys(value,["status"])&&["missing","invalid","unavailable"].includes(String(value.status)):!1}function isPolicyEvidence(value){if(!record(value)||!exactKeys(value,["cluster","genesisHash","programIds","assuranceTier","uniquenessStatus","readContextSlot","identity","transaction","attestation"])||value.cluster!=="devnet"||value.genesisHash!==POLICY_NETWORK.genesisHash||value.assuranceTier!=="browser_unattested"||value.uniquenessStatus!=="unmeasured"||!integer(value.readContextSlot))return!1;let programs=value.programIds;if(!record(programs)||!exactKeys(programs,Object.keys(POLICY_NETWORK.programIds))||Object.entries(POLICY_NETWORK.programIds).some(([key,id])=>programs[key]!==id))return!1;let identity=value.identity,transaction=value.transaction;return!record(identity)||!exactKeys(identity,["walletPubkey","identityPda","creationTimestamp","lastVerificationTimestamp","verificationCount","trustScore","currentCommitment","projectionVersion","lastResetTimestamp","lastRebaselineTimestamp","mint"])||!base58Bytes(identity.walletPubkey,32)||!base58Bytes(identity.identityPda,32)||!base58Bytes(identity.mint,32)||!integer(identity.creationTimestamp,1)||!integer(identity.lastVerificationTimestamp,identity.creationTimestamp)||!integer(identity.verificationCount,0,4294967295)||!integer(identity.trustScore,0,1e4)||!commitment(identity.currentCommitment)||!integer(identity.projectionVersion,0,2)||!integer(identity.lastResetTimestamp)||!integer(identity.lastRebaselineTimestamp)||!record(transaction)||!exactKeys(transaction,["signature","slot","blockTime","commitment","kind"])||!base58Bytes(transaction.signature,64)||!integer(transaction.slot)||!integer(transaction.blockTime,identity.creationTimestamp-BLOCK_TIME_TOLERANCE_SECONDS)||!commitment(transaction.commitment)||!["mint","update","rebaseline"].includes(String(transaction.kind))?!1:isPolicyAttestation(value.attestation)}function evaluatePolicy(request,observation,nowSeconds){let requirements=normalizePolicyRequest(request);if(!integer(nowSeconds,1)||nowSeconds>Number.MAX_SAFE_INTEGER-31536e3)throw new PolicyValidationError("invalid_evidence");let base={policyId:requirements.id,policyVersion:1,requirements,evaluatedAt:nowSeconds,expiresAt:nowSeconds,evidenceTimestamp:null,evaluatedAgeSeconds:null};if(record(observation)&&observation.status==="unavailable")return{...base,decision:"unavailable",reason:"state_unavailable",evidence:null};if(!record(observation)||observation.status!=="available"||!isPolicyEvidence(observation.evidence))return{...base,decision:"deny",reason:"invalid_evidence",evidence:null};let evidence=observation.evidence,{identity,transaction,attestation}=evidence,deny=reason=>({...base,decision:"deny",reason,evidence}),earliestClock=transaction.blockTime-BLOCK_TIME_TOLERANCE_SECONDS,latestClock=transaction.blockTime+BLOCK_TIME_TOLERANCE_SECONDS,freshMint=transaction.kind==="mint"&&identity.verificationCount===0&&identity.trustScore===0&&identity.creationTimestamp===identity.lastVerificationTimestamp&&identity.lastVerificationTimestamp>=earliestClock&&identity.lastVerificationTimestamp<=latestClock&&identity.lastResetTimestamp===0&&identity.lastRebaselineTimestamp===0;return identity.verificationCount===0&&!freshMint||identity.currentCommitment!==transaction.commitment||identity.lastResetTimestamp>=earliestClock||identity.lastResetTimestamp>identity.lastVerificationTimestamp||identity.lastRebaselineTimestamp>identity.lastVerificationTimestamp||identity.lastRebaselineTimestamp>(transaction.kind==="rebaseline"?latestClock:earliestClock)||identity.lastVerificationTimestamp>nowSeconds||transaction.blockTime>nowSeconds||evidence.readContextSlot<transaction.slot||attestation.status==="invalid"||attestation.status==="present"&&(attestation.readContextSlot<transaction.slot||attestation.expiresAt!==null&&attestation.expiresAt<=nowSeconds)?deny("invalid_evidence"):(base.evidenceTimestamp=Math.min(identity.lastVerificationTimestamp,transaction.blockTime),base.evaluatedAgeSeconds=nowSeconds-base.evidenceTimestamp,base.expiresAt=Math.min(base.evidenceTimestamp+requirements.maxVerificationAgeSeconds,nowSeconds+requirements.maxEvaluationAgeSeconds),requirements.requireAttestation&&attestation.status==="present"&&attestation.expiresAt!==null&&(base.expiresAt=Math.min(base.expiresAt,attestation.expiresAt)),identity.trustScore<requirements.minTrustScore?deny("score_below_minimum"):nowSeconds>=base.expiresAt?deny("verification_stale"):requirements.requireAttestation&&attestation.status==="missing"?deny("attestation_required"):requirements.requireAttestation&&attestation.status==="unavailable"?{...base,decision:"unavailable",reason:"state_unavailable",evidence}:{...base,decision:"allow",reason:"accepted",evidence})}function policyResultToWire(result){let e=result.evidence;return{policy_id:result.policyId,policy_version:1,decision:result.decision,reason:result.reason,requirements:result.requirements,evaluated_at:result.evaluatedAt,expires_at:result.expiresAt,evidence_timestamp:result.evidenceTimestamp,evaluated_age_seconds:result.evaluatedAgeSeconds,wallet_pubkey:e?.identity.walletPubkey??null,identity_pda:e?.identity.identityPda??null,verified_transaction:e?{signature:e.transaction.signature,slot:e.transaction.slot,block_time:e.transaction.blockTime,commitment:e.transaction.commitment,kind:e.transaction.kind}:null,verification_timestamp:e?.identity.lastVerificationTimestamp??null,trust_score:e?.identity.trustScore??null,anchor_created_at:e?.identity.creationTimestamp??null,verification_count:e?.identity.verificationCount??null,current_commitment:e?.identity.currentCommitment??null,projection_version:e?.identity.projectionVersion??null,last_reset_timestamp:e?.identity.lastResetTimestamp??null,last_rebaseline_timestamp:e?.identity.lastRebaselineTimestamp??null,mint:e?.identity.mint??null,uniqueness_status:e?.uniquenessStatus??null,assurance_tier:e?.assuranceTier??null,cluster:e?.cluster??null,genesis_hash:e?.genesisHash??null,program_ids:e?.programIds??null,read_context_slot:e?.readContextSlot??null,attestation:e?e.attestation.status==="present"?{status:"present",address:e.attestation.address,read_context_slot:e.attestation.readContextSlot,expires_at:e.attestation.expiresAt}:e.attestation:null}}function parsePolicyWireResult(input){if(!record(input)||!integer(input.evaluated_at,1))return null;try{let requirements=normalizePolicyRequest(input.requirements),observation;if(input.wallet_pubkey===null)observation=input.decision==="unavailable"?{status:"unavailable",reason:"state_unavailable"}:{status:"invalid",reason:"invalid_evidence"};else{let tx=input.verified_transaction,sas=input.attestation;if(!record(tx)||!record(sas))return null;let evidence={cluster:input.cluster,genesisHash:input.genesis_hash,programIds:input.program_ids,assuranceTier:input.assurance_tier,uniquenessStatus:input.uniqueness_status,readContextSlot:input.read_context_slot,identity:{walletPubkey:input.wallet_pubkey,identityPda:input.identity_pda,creationTimestamp:input.anchor_created_at,lastVerificationTimestamp:input.verification_timestamp,verificationCount:input.verification_count,trustScore:input.trust_score,currentCommitment:input.current_commitment,projectionVersion:input.projection_version,lastResetTimestamp:input.last_reset_timestamp,lastRebaselineTimestamp:input.last_rebaseline_timestamp,mint:input.mint},transaction:{signature:tx.signature,slot:tx.slot,blockTime:tx.block_time,commitment:tx.commitment,kind:tx.kind},attestation:sas.status==="present"?{status:"present",address:sas.address,readContextSlot:sas.read_context_slot,expiresAt:sas.expires_at}:{status:sas.status}};if(!isPolicyEvidence(evidence))return null;observation={status:"available",evidence}}let result=evaluatePolicy(requirements,observation,input.evaluated_at);return canonicalEqual(input,policyResultToWire(result))?result:null}catch{return null}}function canonicalEqual(left,right){return left===right?!0:!record(left)||!record(right)?!1:exactKeys(left,Object.keys(right))&&Object.keys(right).every(key=>canonicalEqual(left[key],right[key]))}function isPolicyReason(value){return typeof value=="string"&&["accepted","score_below_minimum","verification_stale","attestation_required","unsupported_policy","unsupported_assurance","unsupported_uniqueness","invalid_evidence","state_unavailable"].includes(value)}function validatePolicyVerifiedPayload(payload,requestedPolicy,nowSeconds){if(!record(payload))return{ok:!1,reason:"invalid_evidence"};if(!Object.prototype.hasOwnProperty.call(payload,"policy"))return{ok:!1,reason:"unsupported_policy"};let result=parsePolicyWireResult(payload.policy);if(!result||!canonicalEqual(result.requirements,normalizePolicyRequest(requestedPolicy)))return{ok:!1,reason:"invalid_evidence"};if(result.decision!=="allow")return{ok:!1,reason:result.reason};if(!integer(nowSeconds,1)||result.evaluatedAt>nowSeconds||nowSeconds>=result.expiresAt)return{ok:!1,reason:"verification_stale"};let current=evaluatePolicy(requestedPolicy,{status:"available",evidence:result.evidence},nowSeconds);if(current.decision!=="allow")return{ok:!1,reason:current.reason};let e=result.evidence,address=e.attestation.status==="present"?e.attestation.address:null;return payload.wallet_pubkey!==e.identity.walletPubkey||payload.trust_score!==e.identity.trustScore||payload.cluster!==e.cluster||payload.tx_sig!==e.transaction.signature||payload.attestation_pda!==address?{ok:!1,reason:"invalid_evidence"}:{ok:!0,result}}var MAX_TIMESTAMP_DRIFT_MS=90*1e3,ERROR_REASONS=new Set(["wallet_rejected","validation_failed","network_error","user_canceled","origin_invalid","popup_blocked","timeout","unknown"]),HEARTBEAT_STATUSES=new Set(["wallet_connecting","capturing","proving","submitting","attesting"]),ENTROS_MESSAGE_TYPES=new Set(["entros/verified","entros/error","entros/heartbeat"]);function isEntrosMessage(data){if(typeof data!="object"||data===null)return!1;let msg=data;return msg.source==="entros"&&msg.version===1&&typeof msg.type=="string"&&ENTROS_MESSAGE_TYPES.has(msg.type)&&typeof msg.request_id=="string"&&msg.request_id.length>0&&typeof msg.timestamp=="number"&&Number.isFinite(msg.timestamp)&&"payload"in msg}function isFreshMessage(msg,now=Date.now()){return Math.abs(now-msg.timestamp)<MAX_TIMESTAMP_DRIFT_MS}function isErrorPayload(payload){if(typeof payload!="object"||payload===null)return!1;let p=payload;return typeof p.reason=="string"&&ERROR_REASONS.has(p.reason)&&(p.policy_reason===void 0||isPolicyReason(p.policy_reason)&&p.policy_reason!=="accepted")}function isHeartbeatPayload(payload){if(typeof payload!="object"||payload===null)return!1;let p=payload;return typeof p.status=="string"&&HEARTBEAT_STATUSES.has(p.status)}var VALID_INTEGRATOR_KEY=/^[a-z0-9_-]{1,64}$/,ORIGIN_PATTERN=/^https?:\/\/[^/]+$/;function buildPopupUrl(opts){if(opts.cluster!=="devnet")throw new Error("Unsupported cluster: @entros/verify currently supports devnet only");if(!VALID_INTEGRATOR_KEY.test(opts.integratorKey))throw new Error(`Invalid integratorKey: must match /^[a-z0-9_-]{1,64}$/ (got "${opts.integratorKey}")`);if(!ORIGIN_PATTERN.test(opts.parentOrigin))throw new Error(`Invalid parentOrigin: must be a fully-qualified origin (got "${opts.parentOrigin}")`);if(opts.minTrustScore!==void 0&&(!Number.isInteger(opts.minTrustScore)||opts.minTrustScore<0||opts.minTrustScore>1e4))throw new Error(`Invalid minTrustScore: must be an integer in [0, 10000] (got ${String(opts.minTrustScore)})`);let policy=normalizePolicyRequest(opts.policy,opts.minTrustScore),url=new URL("/embed/verify-popup",opts.baseOrigin);return url.searchParams.set("integrator",opts.integratorKey),url.searchParams.set("parent_origin",opts.parentOrigin),url.searchParams.set("cluster",opts.cluster),url.searchParams.set("request_id",opts.requestId),url.searchParams.set("policy_version","1"),url.searchParams.set("policy",encodePolicyRequest(policy)),opts.minTrustScore!==void 0&&url.searchParams.set("min_trust_score",String(opts.minTrustScore)),url.toString()}function generateRequestId(){if(typeof crypto>"u")throw new Error("crypto is unavailable in this environment; @entros/verify requires a secure context");if(typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto.getRandomValues!="function")throw new Error("crypto.getRandomValues is unavailable; @entros/verify requires a secure context");let bytes=new Uint8Array(16);crypto.getRandomValues(bytes),bytes[6]=(bytes[6]??0)&15|64,bytes[8]=(bytes[8]??0)&63|128;let hex=Array.from(bytes,b=>b.toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}var DEFAULT_TIMEOUT_MS=540*1e3,POPUP_CLOSED_POLL_MS=500,POPUP_CLOSED_GRACE_MS=1500,POPUP_OWNED_FALLBACK_CLOSE_MS=3e4;function openVerifyPopup(opts){if(typeof window>"u")throw new Error("openVerifyPopup must be called in a browser context");let requestId=generateRequestId(),requestedPolicy=normalizePolicyRequest(opts.policy,opts.minTrustScore),parentOrigin=window.location.origin,url=buildPopupUrl({baseOrigin:opts.baseOrigin,integratorKey:opts.integratorKey,parentOrigin,cluster:opts.cluster,requestId,minTrustScore:opts.minTrustScore,policy:requestedPolicy}),left=Math.max(0,Math.floor((window.screen.availWidth-opts.popupWidth)/2)),top=Math.max(0,Math.floor((window.screen.availHeight-opts.popupHeight)/2)),features=[`width=${opts.popupWidth}`,`height=${opts.popupHeight}`,`left=${left}`,`top=${top}`,"menubar=no","toolbar=no","location=yes","status=no","resizable=yes","scrollbars=yes"].join(","),popupName=`entros_verify_${requestId}`,rawPopup=window.open(url,popupName,features);if(!rawPopup||rawPopup.closed)return null;let popup=rawPopup,expectedPopupOrigin=new URL(opts.baseOrigin).origin,settled=!1,pollTimerId=null,timeoutTimerId=null,popupClosedAtMs=null;function clearListenersAndTimers(){window.removeEventListener("message",onMessage),pollTimerId!==null&&(clearInterval(pollTimerId),pollTimerId=null),timeoutTimerId!==null&&(clearTimeout(timeoutTimerId),timeoutTimerId=null)}function forceClosePopup(){if(popup&&!popup.closed)try{popup.close()}catch{}}function settleVerified(result){settled||(settled=!0,clearListenersAndTimers(),setTimeout(forceClosePopup,POPUP_OWNED_FALLBACK_CLOSE_MS),opts.onVerified(result))}function settleError(reason,forceImmediateClose=!1,policyReason){settled||(settled=!0,clearListenersAndTimers(),forceImmediateClose?forceClosePopup():setTimeout(forceClosePopup,POPUP_OWNED_FALLBACK_CLOSE_MS),opts.onError(policyReason===void 0?{reason}:{reason,policyReason}))}function onMessage(event){if(!settled&&event.origin===expectedPopupOrigin&&event.source===popup&&isEntrosMessage(event.data)&&event.data.request_id===requestId&&isFreshMessage(event.data))switch(event.data.type){case"entros/verified":{let validated=validatePolicyVerifiedPayload(event.data.payload,requestedPolicy,Math.floor(Date.now()/1e3));if(!validated.ok){settleError(validated.reason==="state_unavailable"?"network_error":"validation_failed",!1,validated.reason);break}let evidence=validated.result.evidence;settleVerified({walletPubkey:evidence.identity.walletPubkey,attestationPda:evidence.attestation.status==="present"?evidence.attestation.address:null,txSig:evidence.transaction.signature,trustScore:evidence.identity.trustScore,cluster:evidence.cluster,policy:validated.result});break}case"entros/error":{isErrorPayload(event.data.payload)&&settleError(event.data.payload.reason,!1,event.data.payload.policy_reason);break}case"entros/heartbeat":{isHeartbeatPayload(event.data.payload)&&opts.onProgress&&opts.onProgress({status:event.data.payload.status});break}}}function onPoll(){if(!settled)if(popup.closed){if(popupClosedAtMs===null){popupClosedAtMs=Date.now();return}Date.now()-popupClosedAtMs>=POPUP_CLOSED_GRACE_MS&&settleError("user_canceled",!0)}else popupClosedAtMs=null}function onTimeout(){settleError("timeout",!0)}return window.addEventListener("message",onMessage),pollTimerId=setInterval(onPoll,POPUP_CLOSED_POLL_MS),timeoutTimerId=setTimeout(onTimeout,opts.timeoutMs??DEFAULT_TIMEOUT_MS),{cancel:()=>settleError("user_canceled",!0)}}import{jsx,jsxs}from"react/jsx-runtime";var DEFAULT_BASE_ORIGIN="https://entros.io",DEFAULT_POPUP_WIDTH=480,DEFAULT_POPUP_HEIGHT=800,SETTLE_RESET_MS=1500;function EntrosVerify(props){let[state,setState]=useState({kind:"idle"}),handleRef=useRef(null),resetTimerRef=useRef(null),onVerifiedRef=useRef(props.onVerified),onErrorRef=useRef(props.onError),onProgressRef=useRef(props.onProgress);useEffect(()=>{onVerifiedRef.current=props.onVerified,onErrorRef.current=props.onError,onProgressRef.current=props.onProgress}),useEffect(()=>()=>{handleRef.current&&(handleRef.current.cancel(),handleRef.current=null),resetTimerRef.current!==null&&(clearTimeout(resetTimerRef.current),resetTimerRef.current=null)},[]);let scheduleReset=useCallback(()=>{resetTimerRef.current!==null&&clearTimeout(resetTimerRef.current),resetTimerRef.current=setTimeout(()=>{resetTimerRef.current=null,setState({kind:"idle"})},SETTLE_RESET_MS)},[]),trigger=useCallback(()=>{resetTimerRef.current!==null&&(clearTimeout(resetTimerRef.current),resetTimerRef.current=null),setState({kind:"opening"});let policy;try{policy=normalizePolicyRequest(props.policy,props.minTrustScore)}catch(error){let policyReason=error instanceof PolicyValidationError?error.reason:"unsupported_policy";setState({kind:"error",reason:"validation_failed"}),onErrorRef.current?.({reason:"validation_failed",policyReason}),scheduleReset();return}let handle=openVerifyPopup({baseOrigin:props.baseOrigin??DEFAULT_BASE_ORIGIN,integratorKey:props.integratorKey,cluster:props.cluster??"devnet",minTrustScore:props.minTrustScore,policy,popupWidth:props.popupWidth??DEFAULT_POPUP_WIDTH,popupHeight:props.popupHeight??DEFAULT_POPUP_HEIGHT,timeoutMs:props.timeoutMs,onVerified:result=>{handleRef.current=null,setState({kind:"done"}),onVerifiedRef.current(result),scheduleReset()},onError:error=>{handleRef.current=null,setState({kind:"error",reason:error.reason}),onErrorRef.current?.(error),scheduleReset()},onProgress:progress=>{onProgressRef.current?.(progress)}});if(handle===null){setState({kind:"blocked"}),onErrorRef.current?.({reason:"popup_blocked"});return}handleRef.current=handle,setState({kind:"waiting"})},[props.baseOrigin,props.cluster,props.integratorKey,props.minTrustScore,props.policy,props.popupHeight,props.popupWidth,props.timeoutMs,scheduleReset]),isWaiting=state.kind==="opening"||state.kind==="waiting",showFallback=state.kind==="blocked"&&(props.popupBlockedFallback??!0);return jsxs("div",{className:"entros-verify-container","data-state":state.kind,children:[jsx("button",{type:"button",onClick:trigger,disabled:isWaiting,className:props.className,style:props.style,children:isWaiting?"Verifying\u2026":props.children??"Verify with Entros"}),showFallback&&jsxs("div",{role:"alert",className:"entros-verify-blocked",children:[jsx("span",{children:"Popup blocked. "}),jsx("button",{type:"button",onClick:trigger,className:props.className,children:"Click here to open verification"})]})]})}export{EntrosVerify};
|
|
2
|
+
import{useCallback,useEffect,useRef,useState}from"react";var POLICY_NETWORK=Object.freeze({genesisHash:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG",programIds:Object.freeze({anchor:"GZYwTp2ozeuRA5Gof9vs4ya961aANcJBdUzB7LN6q4b2",verifier:"4F97jNoxQzT2qRbkWpW3ztC3Nz2TtKj3rnKG8ExgnrfV",registry:"6VBs3zr9KrfFPGd6j7aGBPQWwZa5tajVfA7HN6MMV9VW",sas:"22zoJMtdu4tQc2PzL74ZUT7FrwgB1Udec8DdW4yw4BdG",credential:"AMBtabCgRFwGLjoZ21Z2LhSKJ6c47NckxUkMogJ3Lpuw",schema:"5LNc7syFW7USPLveVLcNcjjY1xqS7QTXVjHZ7CQCbAMQ"})}),PolicyValidationError=class extends Error{constructor(reason){super(`Invalid verification policy: ${reason}`);this.reason=reason;this.name="PolicyValidationError"}};function record(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function exactKeys(value,keys){return Object.keys(value).length===keys.length&&keys.every(key=>Object.prototype.hasOwnProperty.call(value,key))}var BLOCK_TIME_TOLERANCE_SECONDS=2;function integer(value,minimum=0,maximum=Number.MAX_SAFE_INTEGER){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=minimum&&value<=maximum}var REQUEST_KEYS=["id","version","minTrustScore","maxVerificationAgeSeconds","maxEvaluationAgeSeconds","requiredAssurance","uniquenessRequirement","requireAttestation","cluster"];function normalizePolicyRequest(input,legacyMinTrustScore){if(legacyMinTrustScore!==void 0&&!integer(legacyMinTrustScore,0,1e4))throw new PolicyValidationError("unsupported_policy");let value=input===void 0?{id:"entros-verify-default",version:1,minTrustScore:legacyMinTrustScore??0,maxVerificationAgeSeconds:86400,requiredAssurance:"browser_unattested",uniquenessRequirement:"allow_unmeasured",cluster:"devnet"}:input;if(!record(value)||Object.keys(value).some(key=>!REQUEST_KEYS.includes(key)))throw new PolicyValidationError("unsupported_policy");if(value.requiredAssurance!=="browser_unattested")throw new PolicyValidationError("unsupported_assurance");if(value.uniquenessRequirement!=="allow_unmeasured")throw new PolicyValidationError("unsupported_uniqueness");if(typeof value.id!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(value.id)||value.version!==1||!integer(value.minTrustScore,0,1e4)||!integer(value.maxVerificationAgeSeconds,1,31536e3)||!integer(value.maxEvaluationAgeSeconds===void 0?90:value.maxEvaluationAgeSeconds,1,90)||value.requireAttestation!==void 0&&typeof value.requireAttestation!="boolean"||value.cluster!=="devnet"||legacyMinTrustScore!==void 0&&value.minTrustScore!==legacyMinTrustScore)throw new PolicyValidationError("unsupported_policy");return{id:value.id,version:1,minTrustScore:value.minTrustScore,maxVerificationAgeSeconds:value.maxVerificationAgeSeconds,maxEvaluationAgeSeconds:value.maxEvaluationAgeSeconds??90,requiredAssurance:"browser_unattested",uniquenessRequirement:"allow_unmeasured",requireAttestation:value.requireAttestation===!0,cluster:"devnet"}}function encodePolicyRequest(request){return JSON.stringify(normalizePolicyRequest(request))}var BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function base58Bytes(value,expected){if(typeof value!="string"||value.length<1||value.length>expected*2)return!1;let number=0n;for(let character of value){let digit=BASE58.indexOf(character);if(digit<0)return!1;number=number*58n+BigInt(digit)}let bytes=0;for(;number>0n;)bytes++,number>>=8n;let zeros=0;for(;value[zeros]==="1";)zeros++;return bytes+zeros===expected}function commitment(value){return typeof value=="string"&&/^[0-9a-f]{64}$/.test(value)&&!/^0+$/.test(value)}function isPolicyAttestation(value){return record(value)?value.status==="present"?exactKeys(value,["status","address","readContextSlot","expiresAt"])&&base58Bytes(value.address,32)&&integer(value.readContextSlot)&&(value.expiresAt===null||integer(value.expiresAt,1)):exactKeys(value,["status"])&&["missing","invalid","unavailable"].includes(String(value.status)):!1}function isPolicyEvidence(value){if(!record(value)||!exactKeys(value,["cluster","genesisHash","programIds","assuranceTier","uniquenessStatus","readContextSlot","identity","transaction","attestation"])||value.cluster!=="devnet"||value.genesisHash!==POLICY_NETWORK.genesisHash||value.assuranceTier!=="browser_unattested"||value.uniquenessStatus!=="unmeasured"||!integer(value.readContextSlot))return!1;let programs=value.programIds;if(!record(programs)||!exactKeys(programs,Object.keys(POLICY_NETWORK.programIds))||Object.entries(POLICY_NETWORK.programIds).some(([key,id])=>programs[key]!==id))return!1;let identity=value.identity,transaction=value.transaction;return!record(identity)||!exactKeys(identity,["walletPubkey","identityPda","creationTimestamp","lastVerificationTimestamp","verificationCount","trustScore","currentCommitment","projectionVersion","lastResetTimestamp","lastRebaselineTimestamp","mint"])||!base58Bytes(identity.walletPubkey,32)||!base58Bytes(identity.identityPda,32)||!base58Bytes(identity.mint,32)||!integer(identity.creationTimestamp,1)||!integer(identity.lastVerificationTimestamp,identity.creationTimestamp)||!integer(identity.verificationCount,0,4294967295)||!integer(identity.trustScore,0,1e4)||!commitment(identity.currentCommitment)||!integer(identity.projectionVersion,0,2)||!integer(identity.lastResetTimestamp)||!integer(identity.lastRebaselineTimestamp)||!record(transaction)||!exactKeys(transaction,["signature","slot","blockTime","commitment","kind"])||!base58Bytes(transaction.signature,64)||!integer(transaction.slot)||!integer(transaction.blockTime,identity.creationTimestamp-BLOCK_TIME_TOLERANCE_SECONDS)||!commitment(transaction.commitment)||!["mint","update","rebaseline"].includes(String(transaction.kind))?!1:isPolicyAttestation(value.attestation)}function evaluatePolicy(request,observation,nowSeconds){let requirements=normalizePolicyRequest(request);if(!integer(nowSeconds,1)||nowSeconds>Number.MAX_SAFE_INTEGER-31536e3)throw new PolicyValidationError("invalid_evidence");let base={policyId:requirements.id,policyVersion:1,requirements,evaluatedAt:nowSeconds,expiresAt:nowSeconds,evidenceTimestamp:null,evaluatedAgeSeconds:null};if(record(observation)&&observation.status==="unavailable")return{...base,decision:"unavailable",reason:"state_unavailable",evidence:null};if(!record(observation)||observation.status!=="available"||!isPolicyEvidence(observation.evidence))return{...base,decision:"deny",reason:"invalid_evidence",evidence:null};let evidence=observation.evidence,{identity,transaction,attestation}=evidence,deny=reason=>({...base,decision:"deny",reason,evidence}),earliestClock=transaction.blockTime-BLOCK_TIME_TOLERANCE_SECONDS,latestClock=transaction.blockTime+BLOCK_TIME_TOLERANCE_SECONDS,freshMint=transaction.kind==="mint"&&identity.verificationCount===0&&identity.trustScore===0&&identity.creationTimestamp===identity.lastVerificationTimestamp&&identity.lastVerificationTimestamp>=earliestClock&&identity.lastVerificationTimestamp<=latestClock&&identity.lastResetTimestamp===0&&identity.lastRebaselineTimestamp===0;return identity.verificationCount===0&&!freshMint||identity.currentCommitment!==transaction.commitment||identity.lastResetTimestamp>=earliestClock||identity.lastResetTimestamp>identity.lastVerificationTimestamp||identity.lastRebaselineTimestamp>identity.lastVerificationTimestamp||identity.lastRebaselineTimestamp>(transaction.kind==="rebaseline"?latestClock:earliestClock)||identity.lastVerificationTimestamp>nowSeconds||transaction.blockTime>nowSeconds||evidence.readContextSlot<transaction.slot||attestation.status==="invalid"||attestation.status==="present"&&(attestation.readContextSlot<transaction.slot||attestation.expiresAt!==null&&attestation.expiresAt<=nowSeconds)?deny("invalid_evidence"):(base.evidenceTimestamp=Math.min(identity.lastVerificationTimestamp,transaction.blockTime),base.evaluatedAgeSeconds=nowSeconds-base.evidenceTimestamp,base.expiresAt=Math.min(base.evidenceTimestamp+requirements.maxVerificationAgeSeconds,nowSeconds+requirements.maxEvaluationAgeSeconds),requirements.requireAttestation&&attestation.status==="present"&&attestation.expiresAt!==null&&(base.expiresAt=Math.min(base.expiresAt,attestation.expiresAt)),identity.trustScore<requirements.minTrustScore?deny("score_below_minimum"):nowSeconds>=base.expiresAt?deny("verification_stale"):requirements.requireAttestation&&attestation.status==="missing"?deny("attestation_required"):requirements.requireAttestation&&attestation.status==="unavailable"?{...base,decision:"unavailable",reason:"state_unavailable",evidence}:{...base,decision:"allow",reason:"accepted",evidence})}function policyResultToWire(result){let e=result.evidence;return{policy_id:result.policyId,policy_version:1,decision:result.decision,reason:result.reason,requirements:result.requirements,evaluated_at:result.evaluatedAt,expires_at:result.expiresAt,evidence_timestamp:result.evidenceTimestamp,evaluated_age_seconds:result.evaluatedAgeSeconds,wallet_pubkey:e?.identity.walletPubkey??null,identity_pda:e?.identity.identityPda??null,verified_transaction:e?{signature:e.transaction.signature,slot:e.transaction.slot,block_time:e.transaction.blockTime,commitment:e.transaction.commitment,kind:e.transaction.kind}:null,verification_timestamp:e?.identity.lastVerificationTimestamp??null,trust_score:e?.identity.trustScore??null,anchor_created_at:e?.identity.creationTimestamp??null,verification_count:e?.identity.verificationCount??null,current_commitment:e?.identity.currentCommitment??null,projection_version:e?.identity.projectionVersion??null,last_reset_timestamp:e?.identity.lastResetTimestamp??null,last_rebaseline_timestamp:e?.identity.lastRebaselineTimestamp??null,mint:e?.identity.mint??null,uniqueness_status:e?.uniquenessStatus??null,assurance_tier:e?.assuranceTier??null,cluster:e?.cluster??null,genesis_hash:e?.genesisHash??null,program_ids:e?.programIds??null,read_context_slot:e?.readContextSlot??null,attestation:e?e.attestation.status==="present"?{status:"present",address:e.attestation.address,read_context_slot:e.attestation.readContextSlot,expires_at:e.attestation.expiresAt}:e.attestation:null}}function parsePolicyWireResult(input){if(!record(input)||!integer(input.evaluated_at,1))return null;try{let requirements=normalizePolicyRequest(input.requirements),observation;if(input.wallet_pubkey===null)observation=input.decision==="unavailable"?{status:"unavailable",reason:"state_unavailable"}:{status:"invalid",reason:"invalid_evidence"};else{let tx=input.verified_transaction,sas=input.attestation;if(!record(tx)||!record(sas))return null;let evidence={cluster:input.cluster,genesisHash:input.genesis_hash,programIds:input.program_ids,assuranceTier:input.assurance_tier,uniquenessStatus:input.uniqueness_status,readContextSlot:input.read_context_slot,identity:{walletPubkey:input.wallet_pubkey,identityPda:input.identity_pda,creationTimestamp:input.anchor_created_at,lastVerificationTimestamp:input.verification_timestamp,verificationCount:input.verification_count,trustScore:input.trust_score,currentCommitment:input.current_commitment,projectionVersion:input.projection_version,lastResetTimestamp:input.last_reset_timestamp,lastRebaselineTimestamp:input.last_rebaseline_timestamp,mint:input.mint},transaction:{signature:tx.signature,slot:tx.slot,blockTime:tx.block_time,commitment:tx.commitment,kind:tx.kind},attestation:sas.status==="present"?{status:"present",address:sas.address,readContextSlot:sas.read_context_slot,expiresAt:sas.expires_at}:{status:sas.status}};if(!isPolicyEvidence(evidence))return null;observation={status:"available",evidence}}let result=evaluatePolicy(requirements,observation,input.evaluated_at);return canonicalEqual(input,policyResultToWire(result))?result:null}catch{return null}}function canonicalEqual(left,right){return left===right?!0:!record(left)||!record(right)?!1:exactKeys(left,Object.keys(right))&&Object.keys(right).every(key=>canonicalEqual(left[key],right[key]))}function isPolicyReason(value){return typeof value=="string"&&["accepted","score_below_minimum","verification_stale","attestation_required","unsupported_policy","unsupported_assurance","unsupported_uniqueness","invalid_evidence","state_unavailable"].includes(value)}function validatePolicyVerifiedPayload(payload,requestedPolicy,nowSeconds){if(!record(payload))return{ok:!1,reason:"invalid_evidence"};if(!Object.prototype.hasOwnProperty.call(payload,"policy"))return{ok:!1,reason:"unsupported_policy"};let result=parsePolicyWireResult(payload.policy);if(!result||!canonicalEqual(result.requirements,normalizePolicyRequest(requestedPolicy)))return{ok:!1,reason:"invalid_evidence"};if(result.decision!=="allow")return{ok:!1,reason:result.reason};if(!integer(nowSeconds,1)||result.evaluatedAt>nowSeconds||nowSeconds>=result.expiresAt)return{ok:!1,reason:"verification_stale"};let current=evaluatePolicy(requestedPolicy,{status:"available",evidence:result.evidence},nowSeconds);if(current.decision!=="allow")return{ok:!1,reason:current.reason};let e=result.evidence,address=e.attestation.status==="present"?e.attestation.address:null;return payload.wallet_pubkey!==e.identity.walletPubkey||payload.trust_score!==e.identity.trustScore||payload.cluster!==e.cluster||payload.tx_sig!==e.transaction.signature||payload.attestation_pda!==address?{ok:!1,reason:"invalid_evidence"}:{ok:!0,result}}var MAX_TIMESTAMP_DRIFT_MS=90*1e3,ERROR_REASONS=new Set(["wallet_rejected","validation_failed","network_error","user_canceled","origin_invalid","popup_blocked","timeout","unknown"]),HEARTBEAT_STATUSES=new Set(["wallet_connecting","capturing","proving","submitting","attesting"]),ENTROS_MESSAGE_TYPES=new Set(["entros/verified","entros/error","entros/heartbeat"]);function isEntrosMessage(data){if(typeof data!="object"||data===null)return!1;let msg=data;return msg.source==="entros"&&msg.version===1&&typeof msg.type=="string"&&ENTROS_MESSAGE_TYPES.has(msg.type)&&typeof msg.request_id=="string"&&msg.request_id.length>0&&typeof msg.timestamp=="number"&&Number.isFinite(msg.timestamp)&&"payload"in msg}function isFreshMessage(msg,now=Date.now()){return Math.abs(now-msg.timestamp)<MAX_TIMESTAMP_DRIFT_MS}function isErrorPayload(payload){if(typeof payload!="object"||payload===null)return!1;let p=payload;return typeof p.reason=="string"&&ERROR_REASONS.has(p.reason)&&(p.policy_reason===void 0||isPolicyReason(p.policy_reason)&&p.policy_reason!=="accepted")}function isHeartbeatPayload(payload){if(typeof payload!="object"||payload===null)return!1;let p=payload;return typeof p.status=="string"&&HEARTBEAT_STATUSES.has(p.status)}var VALID_INTEGRATOR_KEY=/^[a-z0-9_-]{1,64}$/;function isOrigin(value){try{let url=new URL(value);return(url.protocol==="https:"||url.protocol==="http:")&&url.origin===value}catch{return!1}}function buildPopupUrl(opts){if(opts.cluster!=="devnet")throw new Error("Unsupported cluster: @entros/verify currently supports devnet only");if(!VALID_INTEGRATOR_KEY.test(opts.integratorKey))throw new Error(`Invalid integratorKey: must match /^[a-z0-9_-]{1,64}$/ (got "${opts.integratorKey}")`);if(!isOrigin(opts.parentOrigin))throw new Error(`Invalid parentOrigin: must be a fully-qualified origin (got "${opts.parentOrigin}")`);if(opts.minTrustScore!==void 0&&(!Number.isInteger(opts.minTrustScore)||opts.minTrustScore<0||opts.minTrustScore>1e4))throw new Error(`Invalid minTrustScore: must be an integer in [0, 10000] (got ${String(opts.minTrustScore)})`);let policy=normalizePolicyRequest(opts.policy,opts.minTrustScore),url=new URL("/embed/verify-popup",opts.baseOrigin);return url.searchParams.set("integrator",opts.integratorKey),url.searchParams.set("parent_origin",opts.parentOrigin),url.searchParams.set("cluster",opts.cluster),url.searchParams.set("request_id",opts.requestId),url.searchParams.set("policy_version","1"),url.searchParams.set("policy",encodePolicyRequest(policy)),opts.minTrustScore!==void 0&&url.searchParams.set("min_trust_score",String(opts.minTrustScore)),url.toString()}function generateRequestId(){if(typeof crypto>"u")throw new Error("crypto is unavailable in this environment; @entros/verify requires a secure context");if(typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto.getRandomValues!="function")throw new Error("crypto.getRandomValues is unavailable; @entros/verify requires a secure context");let bytes=new Uint8Array(16);crypto.getRandomValues(bytes),bytes[6]=(bytes[6]??0)&15|64,bytes[8]=(bytes[8]??0)&63|128;let hex=Array.from(bytes,b=>b.toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}var DEFAULT_TIMEOUT_MS=540*1e3,POPUP_CLOSED_POLL_MS=500,POPUP_CLOSED_GRACE_MS=1500,POPUP_OWNED_FALLBACK_CLOSE_MS=3e4;function openVerifyPopup(opts){if(typeof window>"u")throw new Error("openVerifyPopup must be called in a browser context");let requestId=generateRequestId(),requestedPolicy=normalizePolicyRequest(opts.policy,opts.minTrustScore),parentOrigin=window.location.origin,url=buildPopupUrl({baseOrigin:opts.baseOrigin,integratorKey:opts.integratorKey,parentOrigin,cluster:opts.cluster,requestId,minTrustScore:opts.minTrustScore,policy:requestedPolicy}),left=Math.max(0,Math.floor((window.screen.availWidth-opts.popupWidth)/2)),top=Math.max(0,Math.floor((window.screen.availHeight-opts.popupHeight)/2)),features=[`width=${opts.popupWidth}`,`height=${opts.popupHeight}`,`left=${left}`,`top=${top}`,"menubar=no","toolbar=no","location=yes","status=no","resizable=yes","scrollbars=yes"].join(","),popupName=`entros_verify_${requestId}`,rawPopup=window.open(url,popupName,features);if(!rawPopup||rawPopup.closed)return null;let popup=rawPopup,expectedPopupOrigin=new URL(opts.baseOrigin).origin,settled=!1,pollTimerId=null,timeoutTimerId=null,popupClosedAtMs=null;function clearListenersAndTimers(){window.removeEventListener("message",onMessage),pollTimerId!==null&&(clearInterval(pollTimerId),pollTimerId=null),timeoutTimerId!==null&&(clearTimeout(timeoutTimerId),timeoutTimerId=null)}function forceClosePopup(){if(popup&&!popup.closed)try{popup.close()}catch{}}function settleVerified(result){settled||(settled=!0,clearListenersAndTimers(),setTimeout(forceClosePopup,POPUP_OWNED_FALLBACK_CLOSE_MS),opts.onVerified(result))}function settleError(reason,forceImmediateClose=!1,policyReason){settled||(settled=!0,clearListenersAndTimers(),forceImmediateClose?forceClosePopup():setTimeout(forceClosePopup,POPUP_OWNED_FALLBACK_CLOSE_MS),opts.onError(policyReason===void 0?{reason}:{reason,policyReason}))}function onMessage(event){if(!settled&&event.origin===expectedPopupOrigin&&event.source===popup&&isEntrosMessage(event.data)&&event.data.request_id===requestId&&isFreshMessage(event.data))switch(event.data.type){case"entros/verified":{let validated=validatePolicyVerifiedPayload(event.data.payload,requestedPolicy,Math.floor(Date.now()/1e3));if(!validated.ok){settleError(validated.reason==="state_unavailable"?"network_error":"validation_failed",!1,validated.reason);break}let evidence=validated.result.evidence;settleVerified({walletPubkey:evidence.identity.walletPubkey,attestationPda:evidence.attestation.status==="present"?evidence.attestation.address:null,txSig:evidence.transaction.signature,trustScore:evidence.identity.trustScore,cluster:evidence.cluster,policy:validated.result});break}case"entros/error":{isErrorPayload(event.data.payload)&&settleError(event.data.payload.reason,!1,event.data.payload.policy_reason);break}case"entros/heartbeat":{isHeartbeatPayload(event.data.payload)&&opts.onProgress&&opts.onProgress({status:event.data.payload.status});break}}}function onPoll(){if(!settled)if(popup.closed){if(popupClosedAtMs===null){popupClosedAtMs=Date.now();return}Date.now()-popupClosedAtMs>=POPUP_CLOSED_GRACE_MS&&settleError("user_canceled",!0)}else popupClosedAtMs=null}function onTimeout(){settleError("timeout",!0)}return window.addEventListener("message",onMessage),pollTimerId=setInterval(onPoll,POPUP_CLOSED_POLL_MS),timeoutTimerId=setTimeout(onTimeout,opts.timeoutMs??DEFAULT_TIMEOUT_MS),{cancel:()=>settleError("user_canceled",!0)}}import{jsx,jsxs}from"react/jsx-runtime";var DEFAULT_BASE_ORIGIN="https://entros.io",DEFAULT_POPUP_WIDTH=480,DEFAULT_POPUP_HEIGHT=800,SETTLE_RESET_MS=1500;function EntrosVerify(props){let[state,setState]=useState({kind:"idle"}),handleRef=useRef(null),resetTimerRef=useRef(null),onVerifiedRef=useRef(props.onVerified),onErrorRef=useRef(props.onError),onProgressRef=useRef(props.onProgress);useEffect(()=>{onVerifiedRef.current=props.onVerified,onErrorRef.current=props.onError,onProgressRef.current=props.onProgress}),useEffect(()=>()=>{handleRef.current&&(handleRef.current.cancel(),handleRef.current=null),resetTimerRef.current!==null&&(clearTimeout(resetTimerRef.current),resetTimerRef.current=null)},[]);let scheduleReset=useCallback(()=>{resetTimerRef.current!==null&&clearTimeout(resetTimerRef.current),resetTimerRef.current=setTimeout(()=>{resetTimerRef.current=null,setState({kind:"idle"})},SETTLE_RESET_MS)},[]),trigger=useCallback(()=>{resetTimerRef.current!==null&&(clearTimeout(resetTimerRef.current),resetTimerRef.current=null),setState({kind:"opening"});let policy;try{policy=normalizePolicyRequest(props.policy,props.minTrustScore)}catch(error){let policyReason=error instanceof PolicyValidationError?error.reason:"unsupported_policy";setState({kind:"error",reason:"validation_failed"}),onErrorRef.current?.({reason:"validation_failed",policyReason}),scheduleReset();return}let handle;try{handle=openVerifyPopup({baseOrigin:props.baseOrigin??DEFAULT_BASE_ORIGIN,integratorKey:props.integratorKey,cluster:props.cluster??"devnet",minTrustScore:props.minTrustScore,policy,popupWidth:props.popupWidth??DEFAULT_POPUP_WIDTH,popupHeight:props.popupHeight??DEFAULT_POPUP_HEIGHT,timeoutMs:props.timeoutMs,onVerified:result=>{handleRef.current=null,setState({kind:"done"}),onVerifiedRef.current(result),scheduleReset()},onError:error=>{handleRef.current=null,setState({kind:"error",reason:error.reason}),onErrorRef.current?.(error),scheduleReset()},onProgress:progress=>{onProgressRef.current?.(progress)}})}catch{setState({kind:"error",reason:"validation_failed"}),onErrorRef.current?.({reason:"validation_failed"}),scheduleReset();return}if(handle===null){setState({kind:"blocked"}),onErrorRef.current?.({reason:"popup_blocked"});return}handleRef.current=handle,setState({kind:"waiting"})},[props.baseOrigin,props.cluster,props.integratorKey,props.minTrustScore,props.policy,props.popupHeight,props.popupWidth,props.timeoutMs,scheduleReset]),isWaiting=state.kind==="opening"||state.kind==="waiting",showFallback=state.kind==="blocked"&&(props.popupBlockedFallback??!0);return jsxs("div",{className:"entros-verify-container","data-state":state.kind,children:[jsx("button",{type:"button",onClick:trigger,disabled:isWaiting,className:props.className,style:props.style,children:isWaiting?"Verifying\u2026":props.children??"Verify with Entros"}),showFallback&&jsxs("div",{role:"alert",className:"entros-verify-blocked",children:[jsx("span",{children:"Popup blocked. "}),jsx("button",{type:"button",onClick:trigger,className:props.className,children:"Click here to open verification"})]})]})}var ALPHABET="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function base58Encode(bytes){let number=0n;for(let byte of bytes)number=number<<8n|BigInt(byte);let text="";for(;number>0n;)text=ALPHABET[Number(number%58n)]+text,number/=58n;let zeros=0;for(;zeros<bytes.length&&bytes[zeros]===0;)zeros++;return"1".repeat(zeros)+text}function base58Decode(text){if(text.length===0)return null;let number=0n;for(let character of text){let digit=ALPHABET.indexOf(character);if(digit<0)return null;number=number*58n+BigInt(digit)}let body=[];for(;number>0n;)body.unshift(Number(number&0xffn)),number>>=8n;let zeros=0;for(;zeros<text.length&&text[zeros]==="1";)zeros++;return Uint8Array.from([...new Array(zeros).fill(0),...body])}function canonicalKeyBytes(text){if(text.length<32||text.length>44)return null;let bytes=base58Decode(text);return!bytes||bytes.length!==32||base58Encode(bytes)!==text?null:bytes}function readClock(nowSeconds){let value=typeof nowSeconds=="function"?nowSeconds():nowSeconds;if(typeof value!="number"||!Number.isSafeInteger(value)||value<1||value>Number.MAX_SAFE_INTEGER-31536e3)throw new PolicyValidationError("invalid_evidence");return value}function needsCapture(reason,policy=null){return{status:"needs_capture",policy,reason}}async function evaluateWarmPolicyReuse(input){let normalized=normalizePolicyRequest(input.policy,input.minTrustScore),requireLegacy=input.requireLegacyAttestation===!0&&input.policy===void 0,effectivePolicy=requireLegacy?{...normalized,requireAttestation:!0}:normalized;if(typeof input.nowSeconds!="function"&&readClock(input.nowSeconds),typeof input.walletPubkey!="string"||canonicalKeyBytes(input.walletPubkey)===null)return needsCapture("invalid_evidence");let observation,expectedSignature;if(input.observation!==void 0)observation=input.observation;else if(typeof input.readEvidence=="function"){if(typeof input.findVerification=="function"){let lookup;try{lookup=await input.findVerification({walletPubkey:input.walletPubkey})}catch{return needsCapture("state_unavailable")}if(lookup===null)return needsCapture("evidence_not_found");if(typeof lookup=="string"){if(lookup.length===0)return needsCapture("evidence_not_found");expectedSignature=lookup}else if(lookup.status==="found"){if(typeof lookup.signature!="string"||lookup.signature.length===0)return needsCapture("invalid_evidence");expectedSignature=lookup.signature}else return lookup.status==="none"?needsCapture("evidence_not_found"):lookup.status==="unavailable"?needsCapture("state_unavailable"):needsCapture("invalid_evidence")}try{observation=await input.readEvidence(expectedSignature===void 0?{walletPubkey:input.walletPubkey}:{walletPubkey:input.walletPubkey,transactionSignature:expectedSignature})}catch{return needsCapture("state_unavailable")}}else return needsCapture("evidence_not_found");if(observation===null)return needsCapture("evidence_not_found");let evaluatedNow=readClock(input.nowSeconds),policy=evaluatePolicy(effectivePolicy,observation,evaluatedNow);return policy.evidence!==null&&policy.evidence.identity.walletPubkey!==input.walletPubkey||expectedSignature!==void 0&&policy.evidence!==null&&policy.evidence.transaction.signature!==expectedSignature?needsCapture("invalid_evidence"):policy.decision!=="allow"?needsCapture(policy.reason,policy):requireLegacy&&policy.evidence.attestation.status!=="present"?needsCapture("attestation_required"):{status:"reused",policy,evidence:policy.evidence}}export{EntrosVerify,evaluateWarmPolicyReuse};
|