@entros/verify 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -3,6 +3,371 @@
3
3
  // src/EntrosVerify.tsx
4
4
  import { useCallback, useEffect, useRef, useState } from "react";
5
5
 
6
+ // src/policy.ts
7
+ var POLICY_NETWORK = Object.freeze({
8
+ genesisHash: "EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG",
9
+ programIds: Object.freeze({
10
+ anchor: "GZYwTp2ozeuRA5Gof9vs4ya961aANcJBdUzB7LN6q4b2",
11
+ verifier: "4F97jNoxQzT2qRbkWpW3ztC3Nz2TtKj3rnKG8ExgnrfV",
12
+ registry: "6VBs3zr9KrfFPGd6j7aGBPQWwZa5tajVfA7HN6MMV9VW",
13
+ sas: "22zoJMtdu4tQc2PzL74ZUT7FrwgB1Udec8DdW4yw4BdG",
14
+ credential: "AMBtabCgRFwGLjoZ21Z2LhSKJ6c47NckxUkMogJ3Lpuw",
15
+ schema: "5LNc7syFW7USPLveVLcNcjjY1xqS7QTXVjHZ7CQCbAMQ"
16
+ })
17
+ });
18
+ var PolicyValidationError = class extends Error {
19
+ constructor(reason) {
20
+ super(`Invalid verification policy: ${reason}`);
21
+ this.reason = reason;
22
+ this.name = "PolicyValidationError";
23
+ }
24
+ };
25
+ function record(value) {
26
+ return typeof value === "object" && value !== null && !Array.isArray(value);
27
+ }
28
+ function exactKeys(value, keys) {
29
+ return Object.keys(value).length === keys.length && keys.every((key) => Object.prototype.hasOwnProperty.call(value, key));
30
+ }
31
+ function integer(value, minimum = 0, maximum = Number.MAX_SAFE_INTEGER) {
32
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= minimum && value <= maximum;
33
+ }
34
+ var REQUEST_KEYS = [
35
+ "id",
36
+ "version",
37
+ "minTrustScore",
38
+ "maxVerificationAgeSeconds",
39
+ "maxEvaluationAgeSeconds",
40
+ "requiredAssurance",
41
+ "uniquenessRequirement",
42
+ "requireAttestation",
43
+ "cluster"
44
+ ];
45
+ function normalizePolicyRequest(input, legacyMinTrustScore) {
46
+ if (legacyMinTrustScore !== void 0 && !integer(legacyMinTrustScore, 0, 1e4)) {
47
+ throw new PolicyValidationError("unsupported_policy");
48
+ }
49
+ const value = input === void 0 ? {
50
+ id: "entros-verify-default",
51
+ version: 1,
52
+ minTrustScore: legacyMinTrustScore ?? 0,
53
+ maxVerificationAgeSeconds: 86400,
54
+ requiredAssurance: "browser_unattested",
55
+ uniquenessRequirement: "allow_unmeasured",
56
+ cluster: "devnet"
57
+ } : input;
58
+ if (!record(value) || Object.keys(value).some(
59
+ (key) => !REQUEST_KEYS.includes(key)
60
+ )) {
61
+ throw new PolicyValidationError("unsupported_policy");
62
+ }
63
+ if (value.requiredAssurance !== "browser_unattested")
64
+ throw new PolicyValidationError("unsupported_assurance");
65
+ if (value.uniquenessRequirement !== "allow_unmeasured")
66
+ throw new PolicyValidationError("unsupported_uniqueness");
67
+ 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(
68
+ value.maxEvaluationAgeSeconds === void 0 ? 90 : value.maxEvaluationAgeSeconds,
69
+ 1,
70
+ 90
71
+ ) || value.requireAttestation !== void 0 && typeof value.requireAttestation !== "boolean" || value.cluster !== "devnet" || legacyMinTrustScore !== void 0 && value.minTrustScore !== legacyMinTrustScore) {
72
+ throw new PolicyValidationError("unsupported_policy");
73
+ }
74
+ return {
75
+ id: value.id,
76
+ version: 1,
77
+ minTrustScore: value.minTrustScore,
78
+ maxVerificationAgeSeconds: value.maxVerificationAgeSeconds,
79
+ maxEvaluationAgeSeconds: value.maxEvaluationAgeSeconds ?? 90,
80
+ requiredAssurance: "browser_unattested",
81
+ uniquenessRequirement: "allow_unmeasured",
82
+ requireAttestation: value.requireAttestation === true,
83
+ cluster: "devnet"
84
+ };
85
+ }
86
+ function encodePolicyRequest(request) {
87
+ return JSON.stringify(normalizePolicyRequest(request));
88
+ }
89
+ var BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
90
+ function base58Bytes(value, expected) {
91
+ if (typeof value !== "string" || value.length < 1 || value.length > expected * 2)
92
+ return false;
93
+ let number = 0n;
94
+ for (const character of value) {
95
+ const digit = BASE58.indexOf(character);
96
+ if (digit < 0) return false;
97
+ number = number * 58n + BigInt(digit);
98
+ }
99
+ let bytes = 0;
100
+ while (number > 0n) {
101
+ bytes++;
102
+ number >>= 8n;
103
+ }
104
+ let zeros = 0;
105
+ while (value[zeros] === "1") zeros++;
106
+ return bytes + zeros === expected;
107
+ }
108
+ function commitment(value) {
109
+ return typeof value === "string" && /^[0-9a-f]{64}$/.test(value) && !/^0+$/.test(value);
110
+ }
111
+ function isPolicyAttestation(value) {
112
+ if (!record(value)) return false;
113
+ if (value.status === "present") {
114
+ return exactKeys(value, ["status", "address", "readContextSlot", "expiresAt"]) && base58Bytes(value.address, 32) && integer(value.readContextSlot) && (value.expiresAt === null || integer(value.expiresAt, 1));
115
+ }
116
+ return exactKeys(value, ["status"]) && ["missing", "invalid", "unavailable"].includes(String(value.status));
117
+ }
118
+ function isPolicyEvidence(value) {
119
+ if (!record(value) || !exactKeys(value, [
120
+ "cluster",
121
+ "genesisHash",
122
+ "programIds",
123
+ "assuranceTier",
124
+ "uniquenessStatus",
125
+ "readContextSlot",
126
+ "identity",
127
+ "transaction",
128
+ "attestation"
129
+ ]))
130
+ return false;
131
+ if (value.cluster !== "devnet" || value.genesisHash !== POLICY_NETWORK.genesisHash || value.assuranceTier !== "browser_unattested" || value.uniquenessStatus !== "unmeasured" || !integer(value.readContextSlot))
132
+ return false;
133
+ const programs = value.programIds;
134
+ if (!record(programs) || !exactKeys(programs, Object.keys(POLICY_NETWORK.programIds)) || Object.entries(POLICY_NETWORK.programIds).some(
135
+ ([key, id]) => programs[key] !== id
136
+ ))
137
+ return false;
138
+ const identity = value.identity;
139
+ const transaction = value.transaction;
140
+ if (!record(identity) || !exactKeys(identity, [
141
+ "walletPubkey",
142
+ "identityPda",
143
+ "creationTimestamp",
144
+ "lastVerificationTimestamp",
145
+ "verificationCount",
146
+ "trustScore",
147
+ "currentCommitment",
148
+ "projectionVersion",
149
+ "lastResetTimestamp",
150
+ "lastRebaselineTimestamp",
151
+ "mint"
152
+ ]) || !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))
153
+ return false;
154
+ if (!record(transaction) || !exactKeys(transaction, [
155
+ "signature",
156
+ "slot",
157
+ "blockTime",
158
+ "commitment",
159
+ "kind"
160
+ ]) || !base58Bytes(transaction.signature, 64) || !integer(transaction.slot) || !integer(transaction.blockTime, identity.creationTimestamp) || !commitment(transaction.commitment) || !["mint", "update", "rebaseline"].includes(String(transaction.kind)))
161
+ return false;
162
+ return isPolicyAttestation(value.attestation);
163
+ }
164
+ function evaluatePolicy(request, observation, nowSeconds) {
165
+ const requirements = normalizePolicyRequest(request);
166
+ if (!integer(nowSeconds, 1) || nowSeconds > Number.MAX_SAFE_INTEGER - 31536e3)
167
+ throw new PolicyValidationError("invalid_evidence");
168
+ const base = {
169
+ policyId: requirements.id,
170
+ policyVersion: 1,
171
+ requirements,
172
+ evaluatedAt: nowSeconds,
173
+ expiresAt: nowSeconds,
174
+ evidenceTimestamp: null,
175
+ evaluatedAgeSeconds: null
176
+ };
177
+ if (record(observation) && observation.status === "unavailable")
178
+ return {
179
+ ...base,
180
+ decision: "unavailable",
181
+ reason: "state_unavailable",
182
+ evidence: null
183
+ };
184
+ if (!record(observation) || observation.status !== "available" || !isPolicyEvidence(observation.evidence)) {
185
+ return {
186
+ ...base,
187
+ decision: "deny",
188
+ reason: "invalid_evidence",
189
+ evidence: null
190
+ };
191
+ }
192
+ const evidence = observation.evidence;
193
+ const { identity, transaction, attestation } = evidence;
194
+ const deny = (reason) => ({ ...base, decision: "deny", reason, evidence });
195
+ const freshMint = transaction.kind === "mint" && identity.verificationCount === 0 && identity.trustScore === 0 && identity.creationTimestamp === transaction.blockTime && identity.lastVerificationTimestamp === transaction.blockTime && identity.lastResetTimestamp === 0 && identity.lastRebaselineTimestamp === 0;
196
+ if (identity.verificationCount === 0 && !freshMint || identity.currentCommitment !== transaction.commitment || identity.lastResetTimestamp >= transaction.blockTime || identity.lastResetTimestamp > identity.lastVerificationTimestamp || identity.lastRebaselineTimestamp > identity.lastVerificationTimestamp || identity.lastRebaselineTimestamp > transaction.blockTime || 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)) {
197
+ return deny("invalid_evidence");
198
+ }
199
+ base.evidenceTimestamp = Math.min(
200
+ identity.lastVerificationTimestamp,
201
+ transaction.blockTime
202
+ );
203
+ base.evaluatedAgeSeconds = nowSeconds - base.evidenceTimestamp;
204
+ base.expiresAt = Math.min(
205
+ base.evidenceTimestamp + requirements.maxVerificationAgeSeconds,
206
+ nowSeconds + requirements.maxEvaluationAgeSeconds
207
+ );
208
+ if (requirements.requireAttestation && attestation.status === "present" && attestation.expiresAt !== null)
209
+ base.expiresAt = Math.min(base.expiresAt, attestation.expiresAt);
210
+ if (identity.trustScore < requirements.minTrustScore)
211
+ return deny("score_below_minimum");
212
+ if (nowSeconds >= base.expiresAt) return deny("verification_stale");
213
+ if (requirements.requireAttestation && attestation.status === "missing")
214
+ return deny("attestation_required");
215
+ if (requirements.requireAttestation && attestation.status === "unavailable")
216
+ return {
217
+ ...base,
218
+ decision: "unavailable",
219
+ reason: "state_unavailable",
220
+ evidence
221
+ };
222
+ return { ...base, decision: "allow", reason: "accepted", evidence };
223
+ }
224
+ function policyResultToWire(result) {
225
+ const e = result.evidence;
226
+ return {
227
+ policy_id: result.policyId,
228
+ policy_version: 1,
229
+ decision: result.decision,
230
+ reason: result.reason,
231
+ requirements: result.requirements,
232
+ evaluated_at: result.evaluatedAt,
233
+ expires_at: result.expiresAt,
234
+ evidence_timestamp: result.evidenceTimestamp,
235
+ evaluated_age_seconds: result.evaluatedAgeSeconds,
236
+ wallet_pubkey: e?.identity.walletPubkey ?? null,
237
+ identity_pda: e?.identity.identityPda ?? null,
238
+ verified_transaction: e ? {
239
+ signature: e.transaction.signature,
240
+ slot: e.transaction.slot,
241
+ block_time: e.transaction.blockTime,
242
+ commitment: e.transaction.commitment,
243
+ kind: e.transaction.kind
244
+ } : null,
245
+ verification_timestamp: e?.identity.lastVerificationTimestamp ?? null,
246
+ trust_score: e?.identity.trustScore ?? null,
247
+ anchor_created_at: e?.identity.creationTimestamp ?? null,
248
+ verification_count: e?.identity.verificationCount ?? null,
249
+ current_commitment: e?.identity.currentCommitment ?? null,
250
+ projection_version: e?.identity.projectionVersion ?? null,
251
+ last_reset_timestamp: e?.identity.lastResetTimestamp ?? null,
252
+ last_rebaseline_timestamp: e?.identity.lastRebaselineTimestamp ?? null,
253
+ mint: e?.identity.mint ?? null,
254
+ uniqueness_status: e?.uniquenessStatus ?? null,
255
+ assurance_tier: e?.assuranceTier ?? null,
256
+ cluster: e?.cluster ?? null,
257
+ genesis_hash: e?.genesisHash ?? null,
258
+ program_ids: e?.programIds ?? null,
259
+ read_context_slot: e?.readContextSlot ?? null,
260
+ attestation: e ? e.attestation.status === "present" ? {
261
+ status: "present",
262
+ address: e.attestation.address,
263
+ read_context_slot: e.attestation.readContextSlot,
264
+ expires_at: e.attestation.expiresAt
265
+ } : e.attestation : null
266
+ };
267
+ }
268
+ function parsePolicyWireResult(input) {
269
+ if (!record(input) || !integer(input.evaluated_at, 1)) return null;
270
+ try {
271
+ const requirements = normalizePolicyRequest(input.requirements);
272
+ let observation;
273
+ if (input.wallet_pubkey === null) {
274
+ observation = input.decision === "unavailable" ? { status: "unavailable", reason: "state_unavailable" } : { status: "invalid", reason: "invalid_evidence" };
275
+ } else {
276
+ const tx = input.verified_transaction;
277
+ const sas = input.attestation;
278
+ if (!record(tx) || !record(sas)) return null;
279
+ const evidence = {
280
+ cluster: input.cluster,
281
+ genesisHash: input.genesis_hash,
282
+ programIds: input.program_ids,
283
+ assuranceTier: input.assurance_tier,
284
+ uniquenessStatus: input.uniqueness_status,
285
+ readContextSlot: input.read_context_slot,
286
+ identity: {
287
+ walletPubkey: input.wallet_pubkey,
288
+ identityPda: input.identity_pda,
289
+ creationTimestamp: input.anchor_created_at,
290
+ lastVerificationTimestamp: input.verification_timestamp,
291
+ verificationCount: input.verification_count,
292
+ trustScore: input.trust_score,
293
+ currentCommitment: input.current_commitment,
294
+ projectionVersion: input.projection_version,
295
+ lastResetTimestamp: input.last_reset_timestamp,
296
+ lastRebaselineTimestamp: input.last_rebaseline_timestamp,
297
+ mint: input.mint
298
+ },
299
+ transaction: {
300
+ signature: tx.signature,
301
+ slot: tx.slot,
302
+ blockTime: tx.block_time,
303
+ commitment: tx.commitment,
304
+ kind: tx.kind
305
+ },
306
+ attestation: sas.status === "present" ? {
307
+ status: "present",
308
+ address: sas.address,
309
+ readContextSlot: sas.read_context_slot,
310
+ expiresAt: sas.expires_at
311
+ } : { status: sas.status }
312
+ };
313
+ if (!isPolicyEvidence(evidence)) return null;
314
+ observation = { status: "available", evidence };
315
+ }
316
+ const result = evaluatePolicy(
317
+ requirements,
318
+ observation,
319
+ input.evaluated_at
320
+ );
321
+ return canonicalEqual(input, policyResultToWire(result)) ? result : null;
322
+ } catch {
323
+ return null;
324
+ }
325
+ }
326
+ function canonicalEqual(left, right) {
327
+ if (left === right) return true;
328
+ if (!record(left) || !record(right)) return false;
329
+ return exactKeys(left, Object.keys(right)) && Object.keys(right).every((key) => canonicalEqual(left[key], right[key]));
330
+ }
331
+ function isPolicyReason(value) {
332
+ return typeof value === "string" && [
333
+ "accepted",
334
+ "score_below_minimum",
335
+ "verification_stale",
336
+ "attestation_required",
337
+ "unsupported_policy",
338
+ "unsupported_assurance",
339
+ "unsupported_uniqueness",
340
+ "invalid_evidence",
341
+ "state_unavailable"
342
+ ].includes(value);
343
+ }
344
+ function validatePolicyVerifiedPayload(payload, requestedPolicy, nowSeconds) {
345
+ if (!record(payload)) return { ok: false, reason: "invalid_evidence" };
346
+ if (!Object.prototype.hasOwnProperty.call(payload, "policy"))
347
+ return { ok: false, reason: "unsupported_policy" };
348
+ const result = parsePolicyWireResult(payload.policy);
349
+ if (!result || !canonicalEqual(
350
+ result.requirements,
351
+ normalizePolicyRequest(requestedPolicy)
352
+ ))
353
+ return { ok: false, reason: "invalid_evidence" };
354
+ if (result.decision !== "allow") return { ok: false, reason: result.reason };
355
+ if (!integer(nowSeconds, 1) || result.evaluatedAt > nowSeconds || nowSeconds >= result.expiresAt)
356
+ return { ok: false, reason: "verification_stale" };
357
+ const current = evaluatePolicy(
358
+ requestedPolicy,
359
+ { status: "available", evidence: result.evidence },
360
+ nowSeconds
361
+ );
362
+ if (current.decision !== "allow")
363
+ return { ok: false, reason: current.reason };
364
+ const e = result.evidence;
365
+ const address = e.attestation.status === "present" ? e.attestation.address : null;
366
+ if (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)
367
+ return { ok: false, reason: "invalid_evidence" };
368
+ return { ok: true, result };
369
+ }
370
+
6
371
  // src/messaging.ts
7
372
  var MAX_TIMESTAMP_DRIFT_MS = 90 * 1e3;
8
373
  var ERROR_REASONS = /* @__PURE__ */ new Set([
@@ -27,7 +392,6 @@ var ENTROS_MESSAGE_TYPES = /* @__PURE__ */ new Set([
27
392
  "entros/error",
28
393
  "entros/heartbeat"
29
394
  ]);
30
- var CLUSTERS = /* @__PURE__ */ new Set(["devnet"]);
31
395
  function isEntrosMessage(data) {
32
396
  if (typeof data !== "object" || data === null) return false;
33
397
  const msg = data;
@@ -36,15 +400,10 @@ function isEntrosMessage(data) {
36
400
  function isFreshMessage(msg, now = Date.now()) {
37
401
  return Math.abs(now - msg.timestamp) < MAX_TIMESTAMP_DRIFT_MS;
38
402
  }
39
- function isVerifiedPayload(payload) {
40
- if (typeof payload !== "object" || payload === null) return false;
41
- const p = payload;
42
- return typeof p.wallet_pubkey === "string" && p.wallet_pubkey.length > 0 && typeof p.attestation_pda === "string" && p.attestation_pda.length > 0 && typeof p.tx_sig === "string" && p.tx_sig.length > 0 && typeof p.trust_score === "number" && Number.isFinite(p.trust_score) && p.trust_score >= 0 && typeof p.cluster === "string" && CLUSTERS.has(p.cluster);
43
- }
44
403
  function isErrorPayload(payload) {
45
404
  if (typeof payload !== "object" || payload === null) return false;
46
405
  const p = payload;
47
- return typeof p.reason === "string" && ERROR_REASONS.has(p.reason);
406
+ return typeof p.reason === "string" && ERROR_REASONS.has(p.reason) && (p.policy_reason === void 0 || isPolicyReason(p.policy_reason) && p.policy_reason !== "accepted");
48
407
  }
49
408
  function isHeartbeatPayload(payload) {
50
409
  if (typeof payload !== "object" || payload === null) return false;
@@ -57,7 +416,9 @@ var VALID_INTEGRATOR_KEY = /^[a-z0-9_-]{1,64}$/;
57
416
  var ORIGIN_PATTERN = /^https?:\/\/[^/]+$/;
58
417
  function buildPopupUrl(opts) {
59
418
  if (opts.cluster !== "devnet") {
60
- throw new Error("Unsupported cluster: @entros/verify currently supports devnet only");
419
+ throw new Error(
420
+ "Unsupported cluster: @entros/verify currently supports devnet only"
421
+ );
61
422
  }
62
423
  if (!VALID_INTEGRATOR_KEY.test(opts.integratorKey)) {
63
424
  throw new Error(
@@ -76,11 +437,14 @@ function buildPopupUrl(opts) {
76
437
  );
77
438
  }
78
439
  }
440
+ const policy = normalizePolicyRequest(opts.policy, opts.minTrustScore);
79
441
  const url = new URL("/embed/verify-popup", opts.baseOrigin);
80
442
  url.searchParams.set("integrator", opts.integratorKey);
81
443
  url.searchParams.set("parent_origin", opts.parentOrigin);
82
444
  url.searchParams.set("cluster", opts.cluster);
83
445
  url.searchParams.set("request_id", opts.requestId);
446
+ url.searchParams.set("policy_version", "1");
447
+ url.searchParams.set("policy", encodePolicyRequest(policy));
84
448
  if (opts.minTrustScore !== void 0) {
85
449
  url.searchParams.set("min_trust_score", String(opts.minTrustScore));
86
450
  }
@@ -118,6 +482,10 @@ function openVerifyPopup(opts) {
118
482
  throw new Error("openVerifyPopup must be called in a browser context");
119
483
  }
120
484
  const requestId = generateRequestId();
485
+ const requestedPolicy = normalizePolicyRequest(
486
+ opts.policy,
487
+ opts.minTrustScore
488
+ );
121
489
  const parentOrigin = window.location.origin;
122
490
  const url = buildPopupUrl({
123
491
  baseOrigin: opts.baseOrigin,
@@ -125,7 +493,8 @@ function openVerifyPopup(opts) {
125
493
  parentOrigin,
126
494
  cluster: opts.cluster,
127
495
  requestId,
128
- minTrustScore: opts.minTrustScore
496
+ minTrustScore: opts.minTrustScore,
497
+ policy: requestedPolicy
129
498
  });
130
499
  const left = Math.max(
131
500
  0,
@@ -185,7 +554,7 @@ function openVerifyPopup(opts) {
185
554
  setTimeout(forceClosePopup, POPUP_OWNED_FALLBACK_CLOSE_MS);
186
555
  opts.onVerified(result);
187
556
  }
188
- function settleError(reason, forceImmediateClose = false) {
557
+ function settleError(reason, forceImmediateClose = false, policyReason) {
189
558
  if (settled) return;
190
559
  settled = true;
191
560
  clearListenersAndTimers();
@@ -194,7 +563,9 @@ function openVerifyPopup(opts) {
194
563
  } else {
195
564
  setTimeout(forceClosePopup, POPUP_OWNED_FALLBACK_CLOSE_MS);
196
565
  }
197
- opts.onError({ reason });
566
+ opts.onError(
567
+ policyReason === void 0 ? { reason } : { reason, policyReason }
568
+ );
198
569
  }
199
570
  function onMessage(event) {
200
571
  if (settled) return;
@@ -205,20 +576,37 @@ function openVerifyPopup(opts) {
205
576
  if (!isFreshMessage(event.data)) return;
206
577
  switch (event.data.type) {
207
578
  case "entros/verified": {
208
- if (isVerifiedPayload(event.data.payload)) {
209
- settleVerified({
210
- walletPubkey: event.data.payload.wallet_pubkey,
211
- attestationPda: event.data.payload.attestation_pda,
212
- txSig: event.data.payload.tx_sig,
213
- trustScore: event.data.payload.trust_score,
214
- cluster: event.data.payload.cluster
215
- });
579
+ const validated = validatePolicyVerifiedPayload(
580
+ event.data.payload,
581
+ requestedPolicy,
582
+ Math.floor(Date.now() / 1e3)
583
+ );
584
+ if (!validated.ok) {
585
+ settleError(
586
+ validated.reason === "state_unavailable" ? "network_error" : "validation_failed",
587
+ false,
588
+ validated.reason
589
+ );
590
+ break;
216
591
  }
592
+ const evidence = validated.result.evidence;
593
+ settleVerified({
594
+ walletPubkey: evidence.identity.walletPubkey,
595
+ attestationPda: evidence.attestation.status === "present" ? evidence.attestation.address : null,
596
+ txSig: evidence.transaction.signature,
597
+ trustScore: evidence.identity.trustScore,
598
+ cluster: evidence.cluster,
599
+ policy: validated.result
600
+ });
217
601
  break;
218
602
  }
219
603
  case "entros/error": {
220
604
  if (isErrorPayload(event.data.payload)) {
221
- settleError(event.data.payload.reason);
605
+ settleError(
606
+ event.data.payload.reason,
607
+ false,
608
+ event.data.payload.policy_reason
609
+ );
222
610
  }
223
611
  break;
224
612
  }
@@ -300,11 +688,22 @@ function EntrosVerify(props) {
300
688
  resetTimerRef.current = null;
301
689
  }
302
690
  setState({ kind: "opening" });
691
+ let policy;
692
+ try {
693
+ policy = normalizePolicyRequest(props.policy, props.minTrustScore);
694
+ } catch (error) {
695
+ const policyReason = error instanceof PolicyValidationError ? error.reason : "unsupported_policy";
696
+ setState({ kind: "error", reason: "validation_failed" });
697
+ onErrorRef.current?.({ reason: "validation_failed", policyReason });
698
+ scheduleReset();
699
+ return;
700
+ }
303
701
  const handle = openVerifyPopup({
304
702
  baseOrigin: props.baseOrigin ?? DEFAULT_BASE_ORIGIN,
305
703
  integratorKey: props.integratorKey,
306
704
  cluster: props.cluster ?? "devnet",
307
705
  minTrustScore: props.minTrustScore,
706
+ policy,
308
707
  popupWidth: props.popupWidth ?? DEFAULT_POPUP_WIDTH,
309
708
  popupHeight: props.popupHeight ?? DEFAULT_POPUP_HEIGHT,
310
709
  timeoutMs: props.timeoutMs,
@@ -336,6 +735,7 @@ function EntrosVerify(props) {
336
735
  props.cluster,
337
736
  props.integratorKey,
338
737
  props.minTrustScore,
738
+ props.policy,
339
739
  props.popupHeight,
340
740
  props.popupWidth,
341
741
  props.timeoutMs,