@entros/verify 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,793 +1,2 @@
1
1
  "use client";
2
- "use strict";
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
-
21
- // src/index.ts
22
- var index_exports = {};
23
- __export(index_exports, {
24
- EntrosVerify: () => EntrosVerify
25
- });
26
- module.exports = __toCommonJS(index_exports);
27
-
28
- // src/EntrosVerify.tsx
29
- var import_react = require("react");
30
-
31
- // src/policy.ts
32
- var POLICY_NETWORK = Object.freeze({
33
- genesisHash: "EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG",
34
- programIds: Object.freeze({
35
- anchor: "GZYwTp2ozeuRA5Gof9vs4ya961aANcJBdUzB7LN6q4b2",
36
- verifier: "4F97jNoxQzT2qRbkWpW3ztC3Nz2TtKj3rnKG8ExgnrfV",
37
- registry: "6VBs3zr9KrfFPGd6j7aGBPQWwZa5tajVfA7HN6MMV9VW",
38
- sas: "22zoJMtdu4tQc2PzL74ZUT7FrwgB1Udec8DdW4yw4BdG",
39
- credential: "AMBtabCgRFwGLjoZ21Z2LhSKJ6c47NckxUkMogJ3Lpuw",
40
- schema: "5LNc7syFW7USPLveVLcNcjjY1xqS7QTXVjHZ7CQCbAMQ"
41
- })
42
- });
43
- var PolicyValidationError = class extends Error {
44
- constructor(reason) {
45
- super(`Invalid verification policy: ${reason}`);
46
- this.reason = reason;
47
- this.name = "PolicyValidationError";
48
- }
49
- };
50
- function record(value) {
51
- return typeof value === "object" && value !== null && !Array.isArray(value);
52
- }
53
- function exactKeys(value, keys) {
54
- return Object.keys(value).length === keys.length && keys.every((key) => Object.prototype.hasOwnProperty.call(value, key));
55
- }
56
- function integer(value, minimum = 0, maximum = Number.MAX_SAFE_INTEGER) {
57
- return typeof value === "number" && Number.isSafeInteger(value) && value >= minimum && value <= maximum;
58
- }
59
- var REQUEST_KEYS = [
60
- "id",
61
- "version",
62
- "minTrustScore",
63
- "maxVerificationAgeSeconds",
64
- "maxEvaluationAgeSeconds",
65
- "requiredAssurance",
66
- "uniquenessRequirement",
67
- "requireAttestation",
68
- "cluster"
69
- ];
70
- function normalizePolicyRequest(input, legacyMinTrustScore) {
71
- if (legacyMinTrustScore !== void 0 && !integer(legacyMinTrustScore, 0, 1e4)) {
72
- throw new PolicyValidationError("unsupported_policy");
73
- }
74
- const value = input === void 0 ? {
75
- id: "entros-verify-default",
76
- version: 1,
77
- minTrustScore: legacyMinTrustScore ?? 0,
78
- maxVerificationAgeSeconds: 86400,
79
- requiredAssurance: "browser_unattested",
80
- uniquenessRequirement: "allow_unmeasured",
81
- cluster: "devnet"
82
- } : input;
83
- if (!record(value) || Object.keys(value).some(
84
- (key) => !REQUEST_KEYS.includes(key)
85
- )) {
86
- throw new PolicyValidationError("unsupported_policy");
87
- }
88
- if (value.requiredAssurance !== "browser_unattested")
89
- throw new PolicyValidationError("unsupported_assurance");
90
- if (value.uniquenessRequirement !== "allow_unmeasured")
91
- throw new PolicyValidationError("unsupported_uniqueness");
92
- 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(
93
- value.maxEvaluationAgeSeconds === void 0 ? 90 : value.maxEvaluationAgeSeconds,
94
- 1,
95
- 90
96
- ) || value.requireAttestation !== void 0 && typeof value.requireAttestation !== "boolean" || value.cluster !== "devnet" || legacyMinTrustScore !== void 0 && value.minTrustScore !== legacyMinTrustScore) {
97
- throw new PolicyValidationError("unsupported_policy");
98
- }
99
- return {
100
- id: value.id,
101
- version: 1,
102
- minTrustScore: value.minTrustScore,
103
- maxVerificationAgeSeconds: value.maxVerificationAgeSeconds,
104
- maxEvaluationAgeSeconds: value.maxEvaluationAgeSeconds ?? 90,
105
- requiredAssurance: "browser_unattested",
106
- uniquenessRequirement: "allow_unmeasured",
107
- requireAttestation: value.requireAttestation === true,
108
- cluster: "devnet"
109
- };
110
- }
111
- function encodePolicyRequest(request) {
112
- return JSON.stringify(normalizePolicyRequest(request));
113
- }
114
- var BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
115
- function base58Bytes(value, expected) {
116
- if (typeof value !== "string" || value.length < 1 || value.length > expected * 2)
117
- return false;
118
- let number = 0n;
119
- for (const character of value) {
120
- const digit = BASE58.indexOf(character);
121
- if (digit < 0) return false;
122
- number = number * 58n + BigInt(digit);
123
- }
124
- let bytes = 0;
125
- while (number > 0n) {
126
- bytes++;
127
- number >>= 8n;
128
- }
129
- let zeros = 0;
130
- while (value[zeros] === "1") zeros++;
131
- return bytes + zeros === expected;
132
- }
133
- function commitment(value) {
134
- return typeof value === "string" && /^[0-9a-f]{64}$/.test(value) && !/^0+$/.test(value);
135
- }
136
- function isPolicyAttestation(value) {
137
- if (!record(value)) return false;
138
- if (value.status === "present") {
139
- return exactKeys(value, ["status", "address", "readContextSlot", "expiresAt"]) && base58Bytes(value.address, 32) && integer(value.readContextSlot) && (value.expiresAt === null || integer(value.expiresAt, 1));
140
- }
141
- return exactKeys(value, ["status"]) && ["missing", "invalid", "unavailable"].includes(String(value.status));
142
- }
143
- function isPolicyEvidence(value) {
144
- if (!record(value) || !exactKeys(value, [
145
- "cluster",
146
- "genesisHash",
147
- "programIds",
148
- "assuranceTier",
149
- "uniquenessStatus",
150
- "readContextSlot",
151
- "identity",
152
- "transaction",
153
- "attestation"
154
- ]))
155
- return false;
156
- if (value.cluster !== "devnet" || value.genesisHash !== POLICY_NETWORK.genesisHash || value.assuranceTier !== "browser_unattested" || value.uniquenessStatus !== "unmeasured" || !integer(value.readContextSlot))
157
- return false;
158
- const programs = value.programIds;
159
- if (!record(programs) || !exactKeys(programs, Object.keys(POLICY_NETWORK.programIds)) || Object.entries(POLICY_NETWORK.programIds).some(
160
- ([key, id]) => programs[key] !== id
161
- ))
162
- return false;
163
- const identity = value.identity;
164
- const transaction = value.transaction;
165
- if (!record(identity) || !exactKeys(identity, [
166
- "walletPubkey",
167
- "identityPda",
168
- "creationTimestamp",
169
- "lastVerificationTimestamp",
170
- "verificationCount",
171
- "trustScore",
172
- "currentCommitment",
173
- "projectionVersion",
174
- "lastResetTimestamp",
175
- "lastRebaselineTimestamp",
176
- "mint"
177
- ]) || !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))
178
- return false;
179
- if (!record(transaction) || !exactKeys(transaction, [
180
- "signature",
181
- "slot",
182
- "blockTime",
183
- "commitment",
184
- "kind"
185
- ]) || !base58Bytes(transaction.signature, 64) || !integer(transaction.slot) || !integer(transaction.blockTime, identity.creationTimestamp) || !commitment(transaction.commitment) || !["mint", "update", "rebaseline"].includes(String(transaction.kind)))
186
- return false;
187
- return isPolicyAttestation(value.attestation);
188
- }
189
- function evaluatePolicy(request, observation, nowSeconds) {
190
- const requirements = normalizePolicyRequest(request);
191
- if (!integer(nowSeconds, 1) || nowSeconds > Number.MAX_SAFE_INTEGER - 31536e3)
192
- throw new PolicyValidationError("invalid_evidence");
193
- const base = {
194
- policyId: requirements.id,
195
- policyVersion: 1,
196
- requirements,
197
- evaluatedAt: nowSeconds,
198
- expiresAt: nowSeconds,
199
- evidenceTimestamp: null,
200
- evaluatedAgeSeconds: null
201
- };
202
- if (record(observation) && observation.status === "unavailable")
203
- return {
204
- ...base,
205
- decision: "unavailable",
206
- reason: "state_unavailable",
207
- evidence: null
208
- };
209
- if (!record(observation) || observation.status !== "available" || !isPolicyEvidence(observation.evidence)) {
210
- return {
211
- ...base,
212
- decision: "deny",
213
- reason: "invalid_evidence",
214
- evidence: null
215
- };
216
- }
217
- const evidence = observation.evidence;
218
- const { identity, transaction, attestation } = evidence;
219
- const deny = (reason) => ({ ...base, decision: "deny", reason, evidence });
220
- 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;
221
- 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)) {
222
- return deny("invalid_evidence");
223
- }
224
- base.evidenceTimestamp = Math.min(
225
- identity.lastVerificationTimestamp,
226
- transaction.blockTime
227
- );
228
- base.evaluatedAgeSeconds = nowSeconds - base.evidenceTimestamp;
229
- base.expiresAt = Math.min(
230
- base.evidenceTimestamp + requirements.maxVerificationAgeSeconds,
231
- nowSeconds + requirements.maxEvaluationAgeSeconds
232
- );
233
- if (requirements.requireAttestation && attestation.status === "present" && attestation.expiresAt !== null)
234
- base.expiresAt = Math.min(base.expiresAt, attestation.expiresAt);
235
- if (identity.trustScore < requirements.minTrustScore)
236
- return deny("score_below_minimum");
237
- if (nowSeconds >= base.expiresAt) return deny("verification_stale");
238
- if (requirements.requireAttestation && attestation.status === "missing")
239
- return deny("attestation_required");
240
- if (requirements.requireAttestation && attestation.status === "unavailable")
241
- return {
242
- ...base,
243
- decision: "unavailable",
244
- reason: "state_unavailable",
245
- evidence
246
- };
247
- return { ...base, decision: "allow", reason: "accepted", evidence };
248
- }
249
- function policyResultToWire(result) {
250
- const e = result.evidence;
251
- return {
252
- policy_id: result.policyId,
253
- policy_version: 1,
254
- decision: result.decision,
255
- reason: result.reason,
256
- requirements: result.requirements,
257
- evaluated_at: result.evaluatedAt,
258
- expires_at: result.expiresAt,
259
- evidence_timestamp: result.evidenceTimestamp,
260
- evaluated_age_seconds: result.evaluatedAgeSeconds,
261
- wallet_pubkey: e?.identity.walletPubkey ?? null,
262
- identity_pda: e?.identity.identityPda ?? null,
263
- verified_transaction: e ? {
264
- signature: e.transaction.signature,
265
- slot: e.transaction.slot,
266
- block_time: e.transaction.blockTime,
267
- commitment: e.transaction.commitment,
268
- kind: e.transaction.kind
269
- } : null,
270
- verification_timestamp: e?.identity.lastVerificationTimestamp ?? null,
271
- trust_score: e?.identity.trustScore ?? null,
272
- anchor_created_at: e?.identity.creationTimestamp ?? null,
273
- verification_count: e?.identity.verificationCount ?? null,
274
- current_commitment: e?.identity.currentCommitment ?? null,
275
- projection_version: e?.identity.projectionVersion ?? null,
276
- last_reset_timestamp: e?.identity.lastResetTimestamp ?? null,
277
- last_rebaseline_timestamp: e?.identity.lastRebaselineTimestamp ?? null,
278
- mint: e?.identity.mint ?? null,
279
- uniqueness_status: e?.uniquenessStatus ?? null,
280
- assurance_tier: e?.assuranceTier ?? null,
281
- cluster: e?.cluster ?? null,
282
- genesis_hash: e?.genesisHash ?? null,
283
- program_ids: e?.programIds ?? null,
284
- read_context_slot: e?.readContextSlot ?? null,
285
- attestation: e ? e.attestation.status === "present" ? {
286
- status: "present",
287
- address: e.attestation.address,
288
- read_context_slot: e.attestation.readContextSlot,
289
- expires_at: e.attestation.expiresAt
290
- } : e.attestation : null
291
- };
292
- }
293
- function parsePolicyWireResult(input) {
294
- if (!record(input) || !integer(input.evaluated_at, 1)) return null;
295
- try {
296
- const requirements = normalizePolicyRequest(input.requirements);
297
- let observation;
298
- if (input.wallet_pubkey === null) {
299
- observation = input.decision === "unavailable" ? { status: "unavailable", reason: "state_unavailable" } : { status: "invalid", reason: "invalid_evidence" };
300
- } else {
301
- const tx = input.verified_transaction;
302
- const sas = input.attestation;
303
- if (!record(tx) || !record(sas)) return null;
304
- const evidence = {
305
- cluster: input.cluster,
306
- genesisHash: input.genesis_hash,
307
- programIds: input.program_ids,
308
- assuranceTier: input.assurance_tier,
309
- uniquenessStatus: input.uniqueness_status,
310
- readContextSlot: input.read_context_slot,
311
- identity: {
312
- walletPubkey: input.wallet_pubkey,
313
- identityPda: input.identity_pda,
314
- creationTimestamp: input.anchor_created_at,
315
- lastVerificationTimestamp: input.verification_timestamp,
316
- verificationCount: input.verification_count,
317
- trustScore: input.trust_score,
318
- currentCommitment: input.current_commitment,
319
- projectionVersion: input.projection_version,
320
- lastResetTimestamp: input.last_reset_timestamp,
321
- lastRebaselineTimestamp: input.last_rebaseline_timestamp,
322
- mint: input.mint
323
- },
324
- transaction: {
325
- signature: tx.signature,
326
- slot: tx.slot,
327
- blockTime: tx.block_time,
328
- commitment: tx.commitment,
329
- kind: tx.kind
330
- },
331
- attestation: sas.status === "present" ? {
332
- status: "present",
333
- address: sas.address,
334
- readContextSlot: sas.read_context_slot,
335
- expiresAt: sas.expires_at
336
- } : { status: sas.status }
337
- };
338
- if (!isPolicyEvidence(evidence)) return null;
339
- observation = { status: "available", evidence };
340
- }
341
- const result = evaluatePolicy(
342
- requirements,
343
- observation,
344
- input.evaluated_at
345
- );
346
- return canonicalEqual(input, policyResultToWire(result)) ? result : null;
347
- } catch {
348
- return null;
349
- }
350
- }
351
- function canonicalEqual(left, right) {
352
- if (left === right) return true;
353
- if (!record(left) || !record(right)) return false;
354
- return exactKeys(left, Object.keys(right)) && Object.keys(right).every((key) => canonicalEqual(left[key], right[key]));
355
- }
356
- function isPolicyReason(value) {
357
- return typeof value === "string" && [
358
- "accepted",
359
- "score_below_minimum",
360
- "verification_stale",
361
- "attestation_required",
362
- "unsupported_policy",
363
- "unsupported_assurance",
364
- "unsupported_uniqueness",
365
- "invalid_evidence",
366
- "state_unavailable"
367
- ].includes(value);
368
- }
369
- function validatePolicyVerifiedPayload(payload, requestedPolicy, nowSeconds) {
370
- if (!record(payload)) return { ok: false, reason: "invalid_evidence" };
371
- if (!Object.prototype.hasOwnProperty.call(payload, "policy"))
372
- return { ok: false, reason: "unsupported_policy" };
373
- const result = parsePolicyWireResult(payload.policy);
374
- if (!result || !canonicalEqual(
375
- result.requirements,
376
- normalizePolicyRequest(requestedPolicy)
377
- ))
378
- return { ok: false, reason: "invalid_evidence" };
379
- if (result.decision !== "allow") return { ok: false, reason: result.reason };
380
- if (!integer(nowSeconds, 1) || result.evaluatedAt > nowSeconds || nowSeconds >= result.expiresAt)
381
- return { ok: false, reason: "verification_stale" };
382
- const current = evaluatePolicy(
383
- requestedPolicy,
384
- { status: "available", evidence: result.evidence },
385
- nowSeconds
386
- );
387
- if (current.decision !== "allow")
388
- return { ok: false, reason: current.reason };
389
- const e = result.evidence;
390
- const address = e.attestation.status === "present" ? e.attestation.address : null;
391
- 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)
392
- return { ok: false, reason: "invalid_evidence" };
393
- return { ok: true, result };
394
- }
395
-
396
- // src/messaging.ts
397
- var MAX_TIMESTAMP_DRIFT_MS = 90 * 1e3;
398
- var ERROR_REASONS = /* @__PURE__ */ new Set([
399
- "wallet_rejected",
400
- "validation_failed",
401
- "network_error",
402
- "user_canceled",
403
- "origin_invalid",
404
- "popup_blocked",
405
- "timeout",
406
- "unknown"
407
- ]);
408
- var HEARTBEAT_STATUSES = /* @__PURE__ */ new Set([
409
- "wallet_connecting",
410
- "capturing",
411
- "proving",
412
- "submitting",
413
- "attesting"
414
- ]);
415
- var ENTROS_MESSAGE_TYPES = /* @__PURE__ */ new Set([
416
- "entros/verified",
417
- "entros/error",
418
- "entros/heartbeat"
419
- ]);
420
- function isEntrosMessage(data) {
421
- if (typeof data !== "object" || data === null) return false;
422
- const msg = data;
423
- 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;
424
- }
425
- function isFreshMessage(msg, now = Date.now()) {
426
- return Math.abs(now - msg.timestamp) < MAX_TIMESTAMP_DRIFT_MS;
427
- }
428
- function isErrorPayload(payload) {
429
- if (typeof payload !== "object" || payload === null) return false;
430
- const p = payload;
431
- return typeof p.reason === "string" && ERROR_REASONS.has(p.reason) && (p.policy_reason === void 0 || isPolicyReason(p.policy_reason) && p.policy_reason !== "accepted");
432
- }
433
- function isHeartbeatPayload(payload) {
434
- if (typeof payload !== "object" || payload === null) return false;
435
- const p = payload;
436
- return typeof p.status === "string" && HEARTBEAT_STATUSES.has(p.status);
437
- }
438
-
439
- // src/url.ts
440
- var VALID_INTEGRATOR_KEY = /^[a-z0-9_-]{1,64}$/;
441
- var ORIGIN_PATTERN = /^https?:\/\/[^/]+$/;
442
- function buildPopupUrl(opts) {
443
- if (opts.cluster !== "devnet") {
444
- throw new Error(
445
- "Unsupported cluster: @entros/verify currently supports devnet only"
446
- );
447
- }
448
- if (!VALID_INTEGRATOR_KEY.test(opts.integratorKey)) {
449
- throw new Error(
450
- `Invalid integratorKey: must match /^[a-z0-9_-]{1,64}$/ (got "${opts.integratorKey}")`
451
- );
452
- }
453
- if (!ORIGIN_PATTERN.test(opts.parentOrigin)) {
454
- throw new Error(
455
- `Invalid parentOrigin: must be a fully-qualified origin (got "${opts.parentOrigin}")`
456
- );
457
- }
458
- if (opts.minTrustScore !== void 0) {
459
- if (!Number.isInteger(opts.minTrustScore) || opts.minTrustScore < 0 || opts.minTrustScore > 1e4) {
460
- throw new Error(
461
- `Invalid minTrustScore: must be an integer in [0, 10000] (got ${String(opts.minTrustScore)})`
462
- );
463
- }
464
- }
465
- const policy = normalizePolicyRequest(opts.policy, opts.minTrustScore);
466
- const url = new URL("/embed/verify-popup", opts.baseOrigin);
467
- url.searchParams.set("integrator", opts.integratorKey);
468
- url.searchParams.set("parent_origin", opts.parentOrigin);
469
- url.searchParams.set("cluster", opts.cluster);
470
- url.searchParams.set("request_id", opts.requestId);
471
- url.searchParams.set("policy_version", "1");
472
- url.searchParams.set("policy", encodePolicyRequest(policy));
473
- if (opts.minTrustScore !== void 0) {
474
- url.searchParams.set("min_trust_score", String(opts.minTrustScore));
475
- }
476
- return url.toString();
477
- }
478
- function generateRequestId() {
479
- if (typeof crypto === "undefined") {
480
- throw new Error(
481
- "crypto is unavailable in this environment; @entros/verify requires a secure context"
482
- );
483
- }
484
- if (typeof crypto.randomUUID === "function") {
485
- return crypto.randomUUID();
486
- }
487
- if (typeof crypto.getRandomValues !== "function") {
488
- throw new Error(
489
- "crypto.getRandomValues is unavailable; @entros/verify requires a secure context"
490
- );
491
- }
492
- const bytes = new Uint8Array(16);
493
- crypto.getRandomValues(bytes);
494
- bytes[6] = (bytes[6] ?? 0) & 15 | 64;
495
- bytes[8] = (bytes[8] ?? 0) & 63 | 128;
496
- const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0"));
497
- 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("");
498
- }
499
-
500
- // src/popup-manager.ts
501
- var DEFAULT_TIMEOUT_MS = 9 * 60 * 1e3;
502
- var POPUP_CLOSED_POLL_MS = 500;
503
- var POPUP_CLOSED_GRACE_MS = 1500;
504
- var POPUP_OWNED_FALLBACK_CLOSE_MS = 3e4;
505
- function openVerifyPopup(opts) {
506
- if (typeof window === "undefined") {
507
- throw new Error("openVerifyPopup must be called in a browser context");
508
- }
509
- const requestId = generateRequestId();
510
- const requestedPolicy = normalizePolicyRequest(
511
- opts.policy,
512
- opts.minTrustScore
513
- );
514
- const parentOrigin = window.location.origin;
515
- const url = buildPopupUrl({
516
- baseOrigin: opts.baseOrigin,
517
- integratorKey: opts.integratorKey,
518
- parentOrigin,
519
- cluster: opts.cluster,
520
- requestId,
521
- minTrustScore: opts.minTrustScore,
522
- policy: requestedPolicy
523
- });
524
- const left = Math.max(
525
- 0,
526
- Math.floor((window.screen.availWidth - opts.popupWidth) / 2)
527
- );
528
- const top = Math.max(
529
- 0,
530
- Math.floor((window.screen.availHeight - opts.popupHeight) / 2)
531
- );
532
- const features = [
533
- `width=${opts.popupWidth}`,
534
- `height=${opts.popupHeight}`,
535
- `left=${left}`,
536
- `top=${top}`,
537
- "menubar=no",
538
- "toolbar=no",
539
- // location=yes lets the user verify entros.io in the URL bar.
540
- "location=yes",
541
- "status=no",
542
- "resizable=yes",
543
- "scrollbars=yes"
544
- ].join(",");
545
- const popupName = `entros_verify_${requestId}`;
546
- const rawPopup = window.open(url, popupName, features);
547
- if (!rawPopup || rawPopup.closed) {
548
- return null;
549
- }
550
- const popup = rawPopup;
551
- const expectedPopupOrigin = new URL(opts.baseOrigin).origin;
552
- let settled = false;
553
- let pollTimerId = null;
554
- let timeoutTimerId = null;
555
- let popupClosedAtMs = null;
556
- function clearListenersAndTimers() {
557
- window.removeEventListener("message", onMessage);
558
- if (pollTimerId !== null) {
559
- clearInterval(pollTimerId);
560
- pollTimerId = null;
561
- }
562
- if (timeoutTimerId !== null) {
563
- clearTimeout(timeoutTimerId);
564
- timeoutTimerId = null;
565
- }
566
- }
567
- function forceClosePopup() {
568
- if (popup && !popup.closed) {
569
- try {
570
- popup.close();
571
- } catch {
572
- }
573
- }
574
- }
575
- function settleVerified(result) {
576
- if (settled) return;
577
- settled = true;
578
- clearListenersAndTimers();
579
- setTimeout(forceClosePopup, POPUP_OWNED_FALLBACK_CLOSE_MS);
580
- opts.onVerified(result);
581
- }
582
- function settleError(reason, forceImmediateClose = false, policyReason) {
583
- if (settled) return;
584
- settled = true;
585
- clearListenersAndTimers();
586
- if (forceImmediateClose) {
587
- forceClosePopup();
588
- } else {
589
- setTimeout(forceClosePopup, POPUP_OWNED_FALLBACK_CLOSE_MS);
590
- }
591
- opts.onError(
592
- policyReason === void 0 ? { reason } : { reason, policyReason }
593
- );
594
- }
595
- function onMessage(event) {
596
- if (settled) return;
597
- if (event.origin !== expectedPopupOrigin) return;
598
- if (event.source !== popup) return;
599
- if (!isEntrosMessage(event.data)) return;
600
- if (event.data.request_id !== requestId) return;
601
- if (!isFreshMessage(event.data)) return;
602
- switch (event.data.type) {
603
- case "entros/verified": {
604
- const validated = validatePolicyVerifiedPayload(
605
- event.data.payload,
606
- requestedPolicy,
607
- Math.floor(Date.now() / 1e3)
608
- );
609
- if (!validated.ok) {
610
- settleError(
611
- validated.reason === "state_unavailable" ? "network_error" : "validation_failed",
612
- false,
613
- validated.reason
614
- );
615
- break;
616
- }
617
- const evidence = validated.result.evidence;
618
- settleVerified({
619
- walletPubkey: evidence.identity.walletPubkey,
620
- attestationPda: evidence.attestation.status === "present" ? evidence.attestation.address : null,
621
- txSig: evidence.transaction.signature,
622
- trustScore: evidence.identity.trustScore,
623
- cluster: evidence.cluster,
624
- policy: validated.result
625
- });
626
- break;
627
- }
628
- case "entros/error": {
629
- if (isErrorPayload(event.data.payload)) {
630
- settleError(
631
- event.data.payload.reason,
632
- false,
633
- event.data.payload.policy_reason
634
- );
635
- }
636
- break;
637
- }
638
- case "entros/heartbeat": {
639
- if (isHeartbeatPayload(event.data.payload) && opts.onProgress) {
640
- opts.onProgress({ status: event.data.payload.status });
641
- }
642
- break;
643
- }
644
- }
645
- }
646
- function onPoll() {
647
- if (settled) return;
648
- if (popup.closed) {
649
- if (popupClosedAtMs === null) {
650
- popupClosedAtMs = Date.now();
651
- return;
652
- }
653
- if (Date.now() - popupClosedAtMs >= POPUP_CLOSED_GRACE_MS) {
654
- settleError("user_canceled", true);
655
- }
656
- } else {
657
- popupClosedAtMs = null;
658
- }
659
- }
660
- function onTimeout() {
661
- settleError("timeout", true);
662
- }
663
- window.addEventListener("message", onMessage);
664
- pollTimerId = setInterval(onPoll, POPUP_CLOSED_POLL_MS);
665
- timeoutTimerId = setTimeout(onTimeout, opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);
666
- return {
667
- cancel: () => settleError("user_canceled", true)
668
- };
669
- }
670
-
671
- // src/EntrosVerify.tsx
672
- var import_jsx_runtime = require("react/jsx-runtime");
673
- var DEFAULT_BASE_ORIGIN = "https://entros.io";
674
- var DEFAULT_POPUP_WIDTH = 480;
675
- var DEFAULT_POPUP_HEIGHT = 720;
676
- var SETTLE_RESET_MS = 1500;
677
- function EntrosVerify(props) {
678
- const [state, setState] = (0, import_react.useState)({ kind: "idle" });
679
- const handleRef = (0, import_react.useRef)(null);
680
- const resetTimerRef = (0, import_react.useRef)(null);
681
- const onVerifiedRef = (0, import_react.useRef)(props.onVerified);
682
- const onErrorRef = (0, import_react.useRef)(props.onError);
683
- const onProgressRef = (0, import_react.useRef)(props.onProgress);
684
- (0, import_react.useEffect)(() => {
685
- onVerifiedRef.current = props.onVerified;
686
- onErrorRef.current = props.onError;
687
- onProgressRef.current = props.onProgress;
688
- });
689
- (0, import_react.useEffect)(() => {
690
- return () => {
691
- if (handleRef.current) {
692
- handleRef.current.cancel();
693
- handleRef.current = null;
694
- }
695
- if (resetTimerRef.current !== null) {
696
- clearTimeout(resetTimerRef.current);
697
- resetTimerRef.current = null;
698
- }
699
- };
700
- }, []);
701
- const scheduleReset = (0, import_react.useCallback)(() => {
702
- if (resetTimerRef.current !== null) {
703
- clearTimeout(resetTimerRef.current);
704
- }
705
- resetTimerRef.current = setTimeout(() => {
706
- resetTimerRef.current = null;
707
- setState({ kind: "idle" });
708
- }, SETTLE_RESET_MS);
709
- }, []);
710
- const trigger = (0, import_react.useCallback)(() => {
711
- if (resetTimerRef.current !== null) {
712
- clearTimeout(resetTimerRef.current);
713
- resetTimerRef.current = null;
714
- }
715
- setState({ kind: "opening" });
716
- let policy;
717
- try {
718
- policy = normalizePolicyRequest(props.policy, props.minTrustScore);
719
- } catch (error) {
720
- const policyReason = error instanceof PolicyValidationError ? error.reason : "unsupported_policy";
721
- setState({ kind: "error", reason: "validation_failed" });
722
- onErrorRef.current?.({ reason: "validation_failed", policyReason });
723
- scheduleReset();
724
- return;
725
- }
726
- const handle = openVerifyPopup({
727
- baseOrigin: props.baseOrigin ?? DEFAULT_BASE_ORIGIN,
728
- integratorKey: props.integratorKey,
729
- cluster: props.cluster ?? "devnet",
730
- minTrustScore: props.minTrustScore,
731
- policy,
732
- popupWidth: props.popupWidth ?? DEFAULT_POPUP_WIDTH,
733
- popupHeight: props.popupHeight ?? DEFAULT_POPUP_HEIGHT,
734
- timeoutMs: props.timeoutMs,
735
- onVerified: (result) => {
736
- handleRef.current = null;
737
- setState({ kind: "done" });
738
- onVerifiedRef.current(result);
739
- scheduleReset();
740
- },
741
- onError: (error) => {
742
- handleRef.current = null;
743
- setState({ kind: "error", reason: error.reason });
744
- onErrorRef.current?.(error);
745
- scheduleReset();
746
- },
747
- onProgress: (progress) => {
748
- onProgressRef.current?.(progress);
749
- }
750
- });
751
- if (handle === null) {
752
- setState({ kind: "blocked" });
753
- onErrorRef.current?.({ reason: "popup_blocked" });
754
- return;
755
- }
756
- handleRef.current = handle;
757
- setState({ kind: "waiting" });
758
- }, [
759
- props.baseOrigin,
760
- props.cluster,
761
- props.integratorKey,
762
- props.minTrustScore,
763
- props.policy,
764
- props.popupHeight,
765
- props.popupWidth,
766
- props.timeoutMs,
767
- scheduleReset
768
- ]);
769
- const isWaiting = state.kind === "opening" || state.kind === "waiting";
770
- const showFallback = state.kind === "blocked" && (props.popupBlockedFallback ?? true);
771
- return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "entros-verify-container", "data-state": state.kind, children: [
772
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
773
- "button",
774
- {
775
- type: "button",
776
- onClick: trigger,
777
- disabled: isWaiting,
778
- className: props.className,
779
- style: props.style,
780
- children: isWaiting ? "Verifying\u2026" : props.children ?? "Verify with Entros"
781
- }
782
- ),
783
- showFallback && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { role: "alert", className: "entros-verify-blocked", children: [
784
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "Popup blocked. " }),
785
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", onClick: trigger, className: props.className, children: "Click here to open verification" })
786
- ] })
787
- ] });
788
- }
789
- // Annotate the CommonJS export names for ESM import in node:
790
- 0 && (module.exports = {
791
- EntrosVerify
792
- });
793
- //# sourceMappingURL=index.js.map
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))}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)||!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}),freshMint=transaction.kind==="mint"&&identity.verificationCount===0&&identity.trustScore===0&&identity.creationTimestamp===transaction.blockTime&&identity.lastVerificationTimestamp===transaction.blockTime&&identity.lastResetTimestamp===0&&identity.lastRebaselineTimestamp===0;return 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)?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});