@oma3/omatrust 0.1.0-alpha.0 → 0.1.0-alpha.10

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.
Files changed (36) hide show
  1. package/README.md +72 -7
  2. package/dist/identity/index.cjs +2 -3
  3. package/dist/identity/index.cjs.map +1 -1
  4. package/dist/identity/index.js +3 -4
  5. package/dist/identity/index.js.map +1 -1
  6. package/dist/index-B9KW02US.d.cts +119 -0
  7. package/dist/index-DXrwBex9.d.ts +119 -0
  8. package/dist/index.cjs +657 -93
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +2 -1
  11. package/dist/index.d.ts +2 -1
  12. package/dist/index.js +658 -94
  13. package/dist/index.js.map +1 -1
  14. package/dist/reputation/index.browser.cjs +2133 -0
  15. package/dist/reputation/index.browser.cjs.map +1 -0
  16. package/dist/reputation/index.browser.d.cts +14 -0
  17. package/dist/reputation/index.browser.d.ts +14 -0
  18. package/dist/reputation/index.browser.js +2071 -0
  19. package/dist/reputation/index.browser.js.map +1 -0
  20. package/dist/reputation/index.cjs +676 -92
  21. package/dist/reputation/index.cjs.map +1 -1
  22. package/dist/reputation/index.d.cts +2 -1
  23. package/dist/reputation/index.d.ts +2 -1
  24. package/dist/reputation/index.js +670 -94
  25. package/dist/reputation/index.js.map +1 -1
  26. package/dist/subject-ownership-CXvzEjpH.d.cts +434 -0
  27. package/dist/subject-ownership-CXvzEjpH.d.ts +434 -0
  28. package/dist/widgets/index.cjs +195 -0
  29. package/dist/widgets/index.cjs.map +1 -0
  30. package/dist/widgets/index.d.cts +134 -0
  31. package/dist/widgets/index.d.ts +134 -0
  32. package/dist/widgets/index.js +185 -0
  33. package/dist/widgets/index.js.map +1 -0
  34. package/package.json +33 -6
  35. package/dist/index-ChbJxwOA.d.cts +0 -415
  36. package/dist/index-ChbJxwOA.d.ts +0 -415
@@ -0,0 +1,434 @@
1
+ type Hex = `0x${string}`;
2
+ type Did = string;
3
+ type ProofType = "pop-jws" | "pop-eip712" | "x402-receipt" | "evidence-pointer" | "tx-encoded-value" | "tx-interaction" | "x402-offer";
4
+ type ProofPurpose = "shared-control" | "commercial-tx";
5
+ type SchemaField = {
6
+ name: string;
7
+ type: string;
8
+ value?: unknown;
9
+ };
10
+ type AttestationValidationError = {
11
+ schemaFieldName: string;
12
+ expectedType: string;
13
+ providedType: string;
14
+ providedValue: unknown;
15
+ };
16
+ type AttestationQueryResult = {
17
+ uid: Hex;
18
+ schema: Hex;
19
+ attester: Hex;
20
+ recipient: Hex;
21
+ txHash?: Hex;
22
+ revocable: boolean;
23
+ revocationTime: bigint;
24
+ expirationTime: bigint;
25
+ time: bigint;
26
+ refUID: Hex;
27
+ data: Record<string, unknown>;
28
+ raw?: Hex;
29
+ };
30
+ type ProofWrapper = {
31
+ proofType: ProofType;
32
+ proofObject: unknown;
33
+ proofPurpose?: ProofPurpose;
34
+ version?: number;
35
+ issuedAt?: number;
36
+ expiresAt?: number;
37
+ };
38
+ type TxEncodedValueProof = ProofWrapper & {
39
+ proofType: "tx-encoded-value";
40
+ proofPurpose: ProofPurpose;
41
+ proofObject: {
42
+ chainId: string;
43
+ txHash: Hex;
44
+ };
45
+ };
46
+ type TxInteractionProof = ProofWrapper & {
47
+ proofType: "tx-interaction";
48
+ proofPurpose: "commercial-tx";
49
+ proofObject: {
50
+ chainId: string;
51
+ txHash: Hex;
52
+ };
53
+ };
54
+ type PopEip712Proof = ProofWrapper & {
55
+ proofType: "pop-eip712";
56
+ proofObject: {
57
+ domain: {
58
+ name: string;
59
+ version: string;
60
+ chainId: number;
61
+ verifyingContract?: Hex;
62
+ };
63
+ message: {
64
+ signer: string;
65
+ authorizedEntity: string;
66
+ signingPurpose: string;
67
+ creationTimestamp: number;
68
+ expirationTimestamp: number;
69
+ randomValue: Hex;
70
+ statement: string;
71
+ };
72
+ signature: Hex;
73
+ };
74
+ };
75
+ type PopJwsProof = ProofWrapper & {
76
+ proofType: "pop-jws";
77
+ proofObject: string;
78
+ };
79
+ type X402ReceiptProof = ProofWrapper & {
80
+ proofType: "x402-receipt";
81
+ proofPurpose: "commercial-tx";
82
+ proofObject: Record<string, unknown>;
83
+ };
84
+ type X402OfferProof = ProofWrapper & {
85
+ proofType: "x402-offer";
86
+ proofPurpose: "commercial-tx";
87
+ proofObject: Record<string, unknown>;
88
+ };
89
+ type EvidencePointerProof = ProofWrapper & {
90
+ proofType: "evidence-pointer";
91
+ proofPurpose: "shared-control";
92
+ proofObject: {
93
+ url: string;
94
+ };
95
+ };
96
+ type ChainConstants = {
97
+ base: bigint;
98
+ range: bigint;
99
+ decimals: number;
100
+ nativeSymbol: string;
101
+ };
102
+ type SubmitAttestationParams = {
103
+ signer: unknown;
104
+ chainId: number;
105
+ easContractAddress: Hex;
106
+ schemaUid: Hex;
107
+ schema: SchemaField[] | string;
108
+ data: Record<string, unknown>;
109
+ revocable?: boolean;
110
+ expirationTime?: bigint | number;
111
+ refUid?: Hex;
112
+ value?: bigint | number;
113
+ };
114
+ type SubmitAttestationResult = {
115
+ uid: Hex;
116
+ txHash: Hex;
117
+ receipt?: unknown;
118
+ };
119
+ type RevokeAttestationParams = {
120
+ signer: unknown;
121
+ easContractAddress: Hex;
122
+ schemaUid: Hex;
123
+ uid: Hex;
124
+ value?: bigint | number;
125
+ };
126
+ type RevokeAttestationResult = {
127
+ txHash: Hex;
128
+ receipt?: unknown;
129
+ };
130
+ type PrepareDelegatedAttestationParams = {
131
+ chainId: number;
132
+ easContractAddress: Hex;
133
+ schemaUid: Hex;
134
+ schema: SchemaField[] | string;
135
+ data: Record<string, unknown>;
136
+ attester: Hex;
137
+ nonce: bigint | number;
138
+ revocable?: boolean;
139
+ expirationTime?: bigint | number;
140
+ refUid?: Hex;
141
+ value?: bigint | number;
142
+ deadline?: bigint | number;
143
+ };
144
+ type PrepareDelegatedAttestationResult = {
145
+ delegatedRequest: Record<string, unknown>;
146
+ typedData: {
147
+ domain: Record<string, unknown>;
148
+ types: Record<string, unknown>;
149
+ message: Record<string, unknown>;
150
+ };
151
+ };
152
+ type BuildDelegatedTypedDataFromEncodedParams = {
153
+ chainId: number;
154
+ easContractAddress: Hex;
155
+ schemaUid: Hex;
156
+ encodedData: Hex;
157
+ recipient: Hex;
158
+ attester: Hex;
159
+ nonce: bigint | number;
160
+ revocable?: boolean;
161
+ expirationTime?: bigint | number;
162
+ refUid?: Hex;
163
+ value?: bigint | number;
164
+ deadline?: bigint | number;
165
+ };
166
+ type SubmitDelegatedAttestationParams = {
167
+ relayUrl: string;
168
+ prepared: PrepareDelegatedAttestationResult;
169
+ signature: Hex | string;
170
+ attester?: Hex;
171
+ };
172
+ type SubmitDelegatedAttestationResult = {
173
+ uid: Hex;
174
+ txHash?: Hex;
175
+ status: "submitted" | "confirmed";
176
+ };
177
+ type GetAttestationParams = {
178
+ uid: Hex;
179
+ provider: unknown;
180
+ easContractAddress: Hex;
181
+ schema?: SchemaField[] | string;
182
+ };
183
+ type ListAttestationsParams = {
184
+ did: Did;
185
+ provider: unknown;
186
+ easContractAddress: Hex;
187
+ schemas?: Hex[];
188
+ limit?: number;
189
+ fromBlock?: number;
190
+ toBlock?: number;
191
+ };
192
+ type GetAttestationsByAttesterParams = {
193
+ attester: Hex;
194
+ provider: unknown;
195
+ easContractAddress: Hex;
196
+ schemas?: Hex[];
197
+ limit?: number;
198
+ fromBlock?: number;
199
+ toBlock?: number;
200
+ };
201
+ type VerifyAttestationParams = {
202
+ attestation: AttestationQueryResult;
203
+ provider?: unknown;
204
+ checks?: ProofType[];
205
+ context?: Record<string, unknown>;
206
+ };
207
+ type VerifyAttestationResult = {
208
+ valid: boolean;
209
+ checks: Record<string, boolean>;
210
+ reasons: string[];
211
+ };
212
+ type CallControllerWitnessParams = {
213
+ gatewayUrl: string;
214
+ attestationUid: Hex;
215
+ chainId: number;
216
+ easContract: Hex;
217
+ schemaUid: Hex;
218
+ subject: Did;
219
+ controller: Did;
220
+ timeoutMs?: number;
221
+ };
222
+ type CallControllerWitnessResult = {
223
+ ok: boolean;
224
+ method: "dns-txt" | "did-json";
225
+ details?: unknown;
226
+ };
227
+ type VerifyProofParams = {
228
+ proof: ProofWrapper;
229
+ provider?: unknown;
230
+ expectedSubject?: Did;
231
+ expectedController?: Did;
232
+ };
233
+ type VerifyProofResult = {
234
+ valid: boolean;
235
+ proofType: ProofType;
236
+ reason?: string;
237
+ };
238
+
239
+ declare function submitAttestation(params: SubmitAttestationParams): Promise<SubmitAttestationResult>;
240
+
241
+ declare function revokeAttestation(params: RevokeAttestationParams): Promise<RevokeAttestationResult>;
242
+
243
+ declare function buildDelegatedAttestationTypedData(params: PrepareDelegatedAttestationParams): {
244
+ domain: Record<string, unknown>;
245
+ types: Record<string, unknown>;
246
+ message: Record<string, unknown>;
247
+ };
248
+ declare function buildDelegatedTypedDataFromEncoded(params: BuildDelegatedTypedDataFromEncodedParams): {
249
+ domain: Record<string, unknown>;
250
+ types: Record<string, unknown>;
251
+ message: Record<string, unknown>;
252
+ };
253
+ declare function splitSignature(signature: Hex | string): {
254
+ v: number;
255
+ r: Hex;
256
+ s: Hex;
257
+ };
258
+ declare function prepareDelegatedAttestation(params: PrepareDelegatedAttestationParams): Promise<PrepareDelegatedAttestationResult>;
259
+ declare function submitDelegatedAttestation(params: SubmitDelegatedAttestationParams): Promise<SubmitDelegatedAttestationResult>;
260
+
261
+ declare function getAttestation(params: GetAttestationParams): Promise<AttestationQueryResult>;
262
+ declare function getAttestationsForDid(params: ListAttestationsParams): Promise<AttestationQueryResult[]>;
263
+ declare function getAttestationsByAttester(params: GetAttestationsByAttesterParams): Promise<AttestationQueryResult[]>;
264
+ declare function listAttestations(params: ListAttestationsParams): Promise<AttestationQueryResult[]>;
265
+ type GetLatestAttestationsParams = {
266
+ provider: unknown;
267
+ easContractAddress: Hex;
268
+ schemas?: Hex[];
269
+ limit?: number;
270
+ fromBlock?: number;
271
+ };
272
+ declare function getLatestAttestations(params: GetLatestAttestationsParams): Promise<AttestationQueryResult[]>;
273
+ declare function deduplicateReviews(attestations: AttestationQueryResult[]): AttestationQueryResult[];
274
+ declare function calculateAverageUserReviewRating(attestations: AttestationQueryResult[]): number;
275
+ declare function getMajorVersion(version: string): number;
276
+
277
+ declare function verifyProof(params: VerifyProofParams): Promise<VerifyProofResult>;
278
+ declare function verifyAttestation(params: VerifyAttestationParams): Promise<VerifyAttestationResult>;
279
+
280
+ declare function normalizeSchema(schema: SchemaField[] | string): SchemaField[];
281
+ declare function schemaToString(schema: SchemaField[] | string): string;
282
+ declare function encodeAttestationData(schema: SchemaField[] | string, data: Record<string, unknown>): Hex;
283
+ declare function validateAttestationData(schema: SchemaField[] | string, data: Record<string, unknown>): AttestationValidationError[];
284
+ declare function decodeAttestationData(schema: SchemaField[] | string, encodedData: Hex): Record<string, unknown>;
285
+ declare function extractExpirationTime(data: Record<string, unknown>): bigint | number | undefined;
286
+
287
+ declare function verifySchemaExists(schemaRegistry: unknown, schemaUid: Hex): Promise<boolean>;
288
+ declare function getSchemaDetails(schemaRegistry: unknown, schemaUid: Hex): Promise<{
289
+ uid: Hex;
290
+ schema: string;
291
+ resolver: Hex;
292
+ revocable: boolean;
293
+ }>;
294
+ declare function formatSchemaUid(schemaUid: string): Hex;
295
+
296
+ declare function callControllerWitness(params: CallControllerWitnessParams): Promise<CallControllerWitnessResult>;
297
+
298
+ declare function getSupportedChainIds(): number[];
299
+ declare function isChainSupported(chainId: number): boolean;
300
+ declare function getChainConstants(chainId: number, purpose: ProofPurpose): ChainConstants;
301
+ declare function constructSeed(subjectDidHash: Hex, counterpartyDidHash: Hex, purpose: ProofPurpose): Uint8Array;
302
+ declare function hashSeed(seedBytes: Uint8Array, chainId: number): Hex;
303
+ declare function calculateTransferAmount(subject: string, counterparty: string, chainId: number, purpose: ProofPurpose): bigint;
304
+ declare function calculateTransferAmountFromAddresses(subjectAddress: string, counterpartyAddress: string, chainId: number, purpose: ProofPurpose): bigint;
305
+ declare function createTxEncodedValueProof(chainId: number, txHash: Hex, purpose: ProofPurpose): TxEncodedValueProof;
306
+ declare function formatTransferAmount(amount: bigint | number, chainId: number): string;
307
+ declare function getExplorerTxUrl(chainId: number, txHash: Hex): string;
308
+ declare function getExplorerAddressUrl(chainId: number, address: string): string;
309
+
310
+ declare function createTxInteractionProof(chainId: number, txHash: Hex): TxInteractionProof;
311
+
312
+ type CreatePopEip712ProofParams = {
313
+ signer: string;
314
+ authorizedEntity: string;
315
+ signingPurpose: ProofPurpose;
316
+ chainId: number;
317
+ creationTimestamp?: number;
318
+ expirationTimestamp?: number;
319
+ randomValue?: Hex;
320
+ statement?: string;
321
+ };
322
+ declare function createPopEip712Proof(params: CreatePopEip712ProofParams, signFn: (typedData: Record<string, unknown>) => Promise<Hex>): Promise<PopEip712Proof>;
323
+
324
+ type CreatePopJwsProofParams = {
325
+ issuer: Did;
326
+ audience: Did;
327
+ purpose: ProofPurpose;
328
+ issuedAt?: number;
329
+ expiresAt?: number;
330
+ nonce?: string;
331
+ };
332
+ declare function createPopJwsProof(params: CreatePopJwsProofParams, signFn: (payload: Record<string, unknown>, header: Record<string, unknown>) => Promise<string>): Promise<PopJwsProof>;
333
+
334
+ declare function createX402ReceiptProof(receipt: Record<string, unknown>): X402ReceiptProof;
335
+ declare function createX402OfferProof(offer: Record<string, unknown>): X402OfferProof;
336
+
337
+ declare function createEvidencePointerProof(url: string): EvidencePointerProof;
338
+
339
+ declare function parseDnsTxtRecord(record: string): {
340
+ version?: string;
341
+ controller?: Did;
342
+ [key: string]: string | undefined;
343
+ };
344
+ declare function buildDnsTxtRecord(controllerDid: Did): string;
345
+
346
+ declare function fetchDidDocument(domain: string): Promise<Record<string, unknown>>;
347
+ interface VerifyDidJsonControllerDidOptions {
348
+ fetchDidDocument?: (domain: string) => Promise<Record<string, unknown>>;
349
+ }
350
+ declare function extractAddressesFromDidDocument(didDocument: Record<string, unknown>): string[];
351
+ declare function verifyDidDocumentControllerDid(didDocument: Record<string, unknown>, expectedControllerDid: Did): {
352
+ valid: boolean;
353
+ reason?: string;
354
+ };
355
+ declare function verifyDidJsonControllerDid(domain: string, expectedControllerDid: Did, options?: VerifyDidJsonControllerDidOptions): Promise<{
356
+ valid: boolean;
357
+ reason?: string;
358
+ }>;
359
+
360
+ declare function buildEip712Domain(name: string, version: string, chainId: number, verifyingContract: Hex): {
361
+ name: string;
362
+ version: string;
363
+ chainId: number;
364
+ verifyingContract: Hex;
365
+ };
366
+ declare function getOmaTrustProofEip712Types(): {
367
+ primaryType: string;
368
+ types: Record<string, Array<{
369
+ name: string;
370
+ type: string;
371
+ }>>;
372
+ };
373
+ declare function verifyEip712Signature(typedData: {
374
+ domain: Record<string, unknown>;
375
+ types: Record<string, unknown>;
376
+ message: Record<string, unknown>;
377
+ }, signature: Hex | string): {
378
+ valid: boolean;
379
+ signer?: string;
380
+ };
381
+
382
+ interface VerifyDnsTxtControllerDidOptions {
383
+ resolveTxt?: (host: string) => Promise<string[][]>;
384
+ recordPrefix?: string;
385
+ }
386
+
387
+ type SubjectOwnershipVerificationMethod = "dns" | "did-document" | "wallet" | "contract" | "minting-wallet" | "transfer";
388
+ interface SubjectOwnershipVerificationResult {
389
+ valid: boolean;
390
+ method?: SubjectOwnershipVerificationMethod;
391
+ reason?: string;
392
+ details?: string;
393
+ subjectDid: Did;
394
+ connectedWalletDid: Did;
395
+ controllingWalletDid?: Did;
396
+ }
397
+ interface EvmOwnershipProvider {
398
+ call(transaction: {
399
+ to: string;
400
+ data: string;
401
+ }): Promise<string>;
402
+ getCode(address: string): Promise<string>;
403
+ getStorage(address: string, slot: string): Promise<string>;
404
+ getTransaction(hash: string): Promise<{
405
+ from?: string | null;
406
+ to?: string | null;
407
+ value?: bigint | string | number | null;
408
+ blockNumber?: number | null;
409
+ } | null>;
410
+ getTransactionReceipt(hash: string): Promise<{
411
+ blockNumber: number;
412
+ } | null>;
413
+ getBlockNumber(): Promise<number>;
414
+ getBlock(blockNumber: number): Promise<{
415
+ timestamp: number;
416
+ } | null>;
417
+ }
418
+ interface VerifyDidWebOwnershipParams extends VerifyDnsTxtControllerDidOptions {
419
+ subjectDid: Did;
420
+ connectedWalletDid: Did;
421
+ fetchDidDocument?: (domain: string) => Promise<Record<string, unknown>>;
422
+ }
423
+ interface VerifyDidPkhOwnershipParams {
424
+ subjectDid: Did;
425
+ connectedWalletDid: Did;
426
+ provider: EvmOwnershipProvider;
427
+ txHash?: Hex | string;
428
+ }
429
+ type VerifySubjectOwnershipParams = VerifyDidWebOwnershipParams | (VerifyDidPkhOwnershipParams & VerifyDnsTxtControllerDidOptions);
430
+ declare function verifyDidWebOwnership(params: VerifyDidWebOwnershipParams): Promise<SubjectOwnershipVerificationResult>;
431
+ declare function verifyDidPkhOwnership(params: VerifyDidPkhOwnershipParams): Promise<SubjectOwnershipVerificationResult>;
432
+ declare function verifySubjectOwnership(params: VerifySubjectOwnershipParams): Promise<SubjectOwnershipVerificationResult>;
433
+
434
+ export { createEvidencePointerProof as $, type AttestationQueryResult as A, type BuildDelegatedTypedDataFromEncodedParams as B, type CallControllerWitnessParams as C, type Did as D, type EvidencePointerProof as E, type VerifyProofParams as F, type GetAttestationParams as G, type Hex as H, type VerifyProofResult as I, type VerifySubjectOwnershipParams as J, type X402ReceiptProof as K, type ListAttestationsParams as L, buildDelegatedAttestationTypedData as M, buildDelegatedTypedDataFromEncoded as N, buildDnsTxtRecord as O, type PopEip712Proof as P, buildEip712Domain as Q, type RevokeAttestationParams as R, type SchemaField as S, type TxEncodedValueProof as T, calculateAverageUserReviewRating as U, type VerifyAttestationParams as V, calculateTransferAmount as W, type X402OfferProof as X, calculateTransferAmountFromAddresses as Y, callControllerWitness as Z, constructSeed as _, type AttestationValidationError as a, createPopEip712Proof as a0, createPopJwsProof as a1, createTxEncodedValueProof as a2, createTxInteractionProof as a3, createX402OfferProof as a4, createX402ReceiptProof as a5, decodeAttestationData as a6, deduplicateReviews as a7, encodeAttestationData as a8, extractAddressesFromDidDocument as a9, validateAttestationData as aA, verifyAttestation as aB, verifyDidDocumentControllerDid as aC, verifyDidJsonControllerDid as aD, verifyDidPkhOwnership as aE, verifyDidWebOwnership as aF, verifyEip712Signature as aG, verifyProof as aH, verifySchemaExists as aI, verifySubjectOwnership as aJ, extractExpirationTime as aa, fetchDidDocument as ab, formatSchemaUid as ac, formatTransferAmount as ad, getAttestation as ae, getAttestationsByAttester as af, getAttestationsForDid as ag, getChainConstants as ah, getExplorerAddressUrl as ai, getExplorerTxUrl as aj, getLatestAttestations as ak, getMajorVersion as al, getOmaTrustProofEip712Types as am, getSchemaDetails as an, getSupportedChainIds as ao, hashSeed as ap, isChainSupported as aq, listAttestations as ar, normalizeSchema as as, parseDnsTxtRecord as at, prepareDelegatedAttestation as au, revokeAttestation as av, schemaToString as aw, splitSignature as ax, submitAttestation as ay, submitDelegatedAttestation as az, type CallControllerWitnessResult as b, type ChainConstants as c, type CreatePopEip712ProofParams as d, type CreatePopJwsProofParams as e, type EvmOwnershipProvider as f, type GetAttestationsByAttesterParams as g, type GetLatestAttestationsParams as h, type PopJwsProof as i, type PrepareDelegatedAttestationParams as j, type PrepareDelegatedAttestationResult as k, type ProofPurpose as l, type ProofType as m, type ProofWrapper as n, type RevokeAttestationResult as o, type SubjectOwnershipVerificationMethod as p, type SubjectOwnershipVerificationResult as q, type SubmitAttestationParams as r, type SubmitAttestationResult as s, type SubmitDelegatedAttestationParams as t, type SubmitDelegatedAttestationResult as u, type TxInteractionProof as v, type VerifyAttestationResult as w, type VerifyDidJsonControllerDidOptions as x, type VerifyDidPkhOwnershipParams as y, type VerifyDidWebOwnershipParams as z };
@@ -0,0 +1,195 @@
1
+ 'use strict';
2
+
3
+ // src/widgets/protocol.ts
4
+ var OMATRUST_READY = "omatrust:ready";
5
+ var OMATRUST_HOST_READY = "omatrust:hostReady";
6
+ var OMATRUST_SIGN_TYPED_DATA = "omatrust:signTypedData";
7
+ var OMATRUST_SIGNATURE = "omatrust:signature";
8
+ var OMATRUST_SIGNATURE_ERROR = "omatrust:signatureError";
9
+
10
+ // src/widgets/trust-policy.ts
11
+ var DEFAULT_TRUST_POLICY_URL = "https://api.omatrust.org/v1/trust-policy";
12
+ var TRUST_POLICY_URL = DEFAULT_TRUST_POLICY_URL;
13
+ var cachedPolicy = null;
14
+ var cacheTimestamp = 0;
15
+ var CACHE_TTL_MS = 5 * 60 * 1e3;
16
+ async function fetchTrustPolicy(url) {
17
+ const now = Date.now();
18
+ if (cachedPolicy && now - cacheTimestamp < CACHE_TTL_MS) {
19
+ return cachedPolicy;
20
+ }
21
+ const res = await fetch(url ?? TRUST_POLICY_URL);
22
+ if (!res.ok) {
23
+ throw new Error(`Failed to fetch trust policy: ${res.status} ${res.statusText}`);
24
+ }
25
+ const policy = await res.json();
26
+ if (!policy.version || !policy.chains || typeof policy.chains !== "object") {
27
+ throw new Error("Invalid trust policy format");
28
+ }
29
+ cachedPolicy = policy;
30
+ cacheTimestamp = now;
31
+ return policy;
32
+ }
33
+ function extractAllowlists(policy) {
34
+ const contracts = [];
35
+ const schemas = [];
36
+ for (const chain of Object.values(policy.chains)) {
37
+ if (chain.easContract) contracts.push(chain.easContract);
38
+ if (chain.schemas) schemas.push(...chain.schemas);
39
+ }
40
+ return {
41
+ allowedContracts: [...new Set(contracts)],
42
+ allowedSchemas: [...new Set(schemas)]
43
+ };
44
+ }
45
+
46
+ // src/widgets/bridge.ts
47
+ function getTrustedBaseDomain() {
48
+ try {
49
+ const hostname = new URL(TRUST_POLICY_URL).hostname;
50
+ const parts = hostname.split(".");
51
+ return parts.length >= 2 ? parts.slice(-2).join(".") : hostname;
52
+ } catch {
53
+ return "omatrust.org";
54
+ }
55
+ }
56
+ function isOriginTrusted(messageOrigin, baseDomain, policyOrigins, devOverride) {
57
+ if (devOverride && messageOrigin === devOverride) return true;
58
+ try {
59
+ const hostname = new URL(messageOrigin).hostname;
60
+ if (hostname === baseDomain || hostname.endsWith(`.${baseDomain}`)) return true;
61
+ } catch {
62
+ }
63
+ if (policyOrigins.includes(messageOrigin)) return true;
64
+ return false;
65
+ }
66
+ var HEX_ADDRESS_RE = /^0x[a-fA-F0-9]{40}$/;
67
+ var BYTES32_RE = /^0x[a-fA-F0-9]{64}$/;
68
+ function validateEasSigningRequest(data, allowedSchemas, allowedContracts) {
69
+ const { id, domain, types, message } = data;
70
+ if (!id || typeof id !== "string") {
71
+ return { valid: false, reason: "Missing or invalid request id" };
72
+ }
73
+ if (!domain || typeof domain !== "object") {
74
+ return { valid: false, reason: "Missing domain object" };
75
+ }
76
+ const d = domain;
77
+ if (d.name !== "EAS") {
78
+ return { valid: false, reason: `Unexpected domain name: "${d.name}" (expected "EAS")` };
79
+ }
80
+ if (d.version !== "1.4.0") {
81
+ return { valid: false, reason: `Unexpected domain version: "${d.version}" (expected "1.4.0")` };
82
+ }
83
+ const chainId = Number(d.chainId);
84
+ if (!Number.isInteger(chainId) || chainId <= 0) {
85
+ return { valid: false, reason: `Invalid domain chainId: ${d.chainId}` };
86
+ }
87
+ if (typeof d.verifyingContract !== "string" || !HEX_ADDRESS_RE.test(d.verifyingContract)) {
88
+ return { valid: false, reason: `Invalid verifyingContract: ${d.verifyingContract}` };
89
+ }
90
+ const contractLower = d.verifyingContract.toLowerCase();
91
+ if (!allowedContracts.some((c) => c.toLowerCase() === contractLower)) {
92
+ return { valid: false, reason: `Contract ${d.verifyingContract} is not in the OMA3 trust policy` };
93
+ }
94
+ if (!types || typeof types !== "object") {
95
+ return { valid: false, reason: "Missing types object" };
96
+ }
97
+ if (!message || typeof message !== "object") {
98
+ return { valid: false, reason: "Missing message object" };
99
+ }
100
+ const m = message;
101
+ if (typeof m.schema !== "string" || !BYTES32_RE.test(m.schema)) {
102
+ return { valid: false, reason: `Invalid schema UID: ${m.schema}` };
103
+ }
104
+ const schemaLower = m.schema.toLowerCase();
105
+ if (!allowedSchemas.some((s) => s.toLowerCase() === schemaLower)) {
106
+ return { valid: false, reason: `Schema ${m.schema} is not in the OMA3 trust policy` };
107
+ }
108
+ if (typeof m.attester !== "string" || !HEX_ADDRESS_RE.test(m.attester)) {
109
+ return { valid: false, reason: `Invalid attester address: ${m.attester}` };
110
+ }
111
+ const deadline = Number(m.deadline);
112
+ if (!Number.isFinite(deadline) || deadline <= 0) {
113
+ return { valid: false, reason: `Invalid deadline: ${m.deadline}` };
114
+ }
115
+ const now = Math.floor(Date.now() / 1e3);
116
+ if (deadline <= now) {
117
+ return { valid: false, reason: `Deadline has passed: ${deadline} <= ${now}` };
118
+ }
119
+ return { valid: true };
120
+ }
121
+ async function createSigningBridge(options) {
122
+ const { iframeId, signTypedData, devOriginOverride } = options;
123
+ const policy = await fetchTrustPolicy();
124
+ const { allowedContracts, allowedSchemas } = extractAllowlists(policy);
125
+ if (allowedContracts.length === 0 || allowedSchemas.length === 0) {
126
+ throw new Error("Trust policy contains no allowed contracts or schemas");
127
+ }
128
+ const baseDomain = getTrustedBaseDomain();
129
+ const policyOrigins = policy.widgetOrigins ?? [];
130
+ async function handleMessage(event) {
131
+ const data = event.data;
132
+ if (!data || typeof data !== "object" || typeof data.type !== "string") return;
133
+ if (!String(data.type).startsWith("omatrust:")) return;
134
+ if (!isOriginTrusted(event.origin, baseDomain, policyOrigins, devOriginOverride)) {
135
+ return;
136
+ }
137
+ const iframe = document.getElementById(iframeId);
138
+ if (!iframe) return;
139
+ if (event.source !== iframe.contentWindow) {
140
+ return;
141
+ }
142
+ const source = event.source;
143
+ const replyOrigin = devOriginOverride ?? (() => {
144
+ try {
145
+ return new URL(iframe.src).origin;
146
+ } catch {
147
+ return "*";
148
+ }
149
+ })();
150
+ function reply(msg) {
151
+ source.postMessage(msg, replyOrigin);
152
+ }
153
+ if (data.type === OMATRUST_READY) {
154
+ reply({ type: OMATRUST_HOST_READY });
155
+ return;
156
+ }
157
+ if (data.type === OMATRUST_SIGN_TYPED_DATA) {
158
+ const { id, domain, types, message } = data;
159
+ const validation = validateEasSigningRequest(data, allowedSchemas, allowedContracts);
160
+ if (!validation.valid) {
161
+ reply({
162
+ type: OMATRUST_SIGNATURE_ERROR,
163
+ id: id ?? "unknown",
164
+ error: `Signing request rejected: ${validation.reason}`
165
+ });
166
+ return;
167
+ }
168
+ try {
169
+ const signature = await signTypedData(domain, types, message);
170
+ reply({ type: OMATRUST_SIGNATURE, id, signature });
171
+ } catch (err) {
172
+ const error = err instanceof Error ? err.message : "Signing failed";
173
+ reply({ type: OMATRUST_SIGNATURE_ERROR, id, error });
174
+ }
175
+ }
176
+ }
177
+ window.addEventListener("message", handleMessage);
178
+ return {
179
+ destroy() {
180
+ window.removeEventListener("message", handleMessage);
181
+ }
182
+ };
183
+ }
184
+
185
+ exports.OMATRUST_HOST_READY = OMATRUST_HOST_READY;
186
+ exports.OMATRUST_READY = OMATRUST_READY;
187
+ exports.OMATRUST_SIGNATURE = OMATRUST_SIGNATURE;
188
+ exports.OMATRUST_SIGNATURE_ERROR = OMATRUST_SIGNATURE_ERROR;
189
+ exports.OMATRUST_SIGN_TYPED_DATA = OMATRUST_SIGN_TYPED_DATA;
190
+ exports.TRUST_POLICY_URL = TRUST_POLICY_URL;
191
+ exports.createSigningBridge = createSigningBridge;
192
+ exports.extractAllowlists = extractAllowlists;
193
+ exports.fetchTrustPolicy = fetchTrustPolicy;
194
+ //# sourceMappingURL=index.cjs.map
195
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/widgets/protocol.ts","../../src/widgets/trust-policy.ts","../../src/widgets/bridge.ts"],"names":[],"mappings":";;;AAaO,IAAM,cAAA,GAAiB;AACvB,IAAM,mBAAA,GAAsB;AAC5B,IAAM,wBAAA,GAA2B;AACjC,IAAM,kBAAA,GAAqB;AAC3B,IAAM,wBAAA,GAA2B;;;ACVxC,IAAM,wBAAA,GAA2B,0CAAA;AAE1B,IAAM,gBAAA,GAAmB;AAehC,IAAI,YAAA,GAAmC,IAAA;AACvC,IAAI,cAAA,GAAiB,CAAA;AACrB,IAAM,YAAA,GAAe,IAAI,EAAA,GAAK,GAAA;AAQ9B,eAAsB,iBAAiB,GAAA,EAAoC;AACzE,EAAA,MAAM,GAAA,GAAM,KAA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A,EAAM,wBAAA;AAAA,UACN,IAAI,EAAA,IAAM,SAAA;AAAA,UACV,KAAA,EAAO,CAAA,0BAAA,EAA6B,UAAA,CAAW,MAAM,CAAA;AAAA,SACtD,CAAA;AACD,QAAA;AAAA,MACF;AAEA,MAAA,IAAI;AACF,QAAA,MAAM,SAAA,GAAY,MAAM,aAAA,CAAc,MAAA,EAAQ,OAAO,OAAO,CAAA;AAC5D,QAAA,KAAA,CAAM,EAAE,IAAA,EAAM,kBAAA,EAAoB,EAAA,EAAI,WAAW,CAAA;AAAA,MACnD,SAAS,GAAA,EAAK;AACZ,QAAA,MAAM,KAAA,GAAQ,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,gBAAA;AACnD,QAAA,KAAA,CAAM,EAAE,IAAA,EAAM,wBAAA,EAA0B,EAAA,EAAI,OAAO,CAAA;AAAA,MACrD;AAAA,IACF;AAAA,EACF;AAEA,EAAA,MAAA,CAAO,gBAAA,CAAiB,WAAW,aAAa,CAAA;AAEhD,EAAA,OAAO;AAAA,IACL,OAAA,GAAU;AACR,MAAA,MAAA,CAAO,mBAAA,CAAoB,WAAW,aAAa,CAAA;AAAA,IACrD;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * postMessage protocol constants and types for the OMATrust widget bridge.\n *\n * Widget (iframe) → Host:\n * omatrust:ready — widget loaded, requesting handshake\n * omatrust:signTypedData — widget requests EIP-712 signature\n *\n * Host → Widget (iframe):\n * omatrust:hostReady — host acknowledges the widget\n * omatrust:signature — host returns a signature\n * omatrust:signatureError — host reports a signing failure\n */\n\nexport const OMATRUST_READY = \"omatrust:ready\" as const;\nexport const OMATRUST_HOST_READY = \"omatrust:hostReady\" as const;\nexport const OMATRUST_SIGN_TYPED_DATA = \"omatrust:signTypedData\" as const;\nexport const OMATRUST_SIGNATURE = \"omatrust:signature\" as const;\nexport const OMATRUST_SIGNATURE_ERROR = \"omatrust:signatureError\" as const;\n\nexport type OmaTrustReadyMessage = {\n type: typeof OMATRUST_READY;\n};\n\nexport type OmaTrustHostReadyMessage = {\n type: typeof OMATRUST_HOST_READY;\n};\n\nexport type OmaTrustSignTypedDataMessage = {\n type: typeof OMATRUST_SIGN_TYPED_DATA;\n id: string;\n domain: Record<string, unknown>;\n types: Record<string, unknown>;\n message: Record<string, unknown>;\n};\n\nexport type OmaTrustSignatureMessage = {\n type: typeof OMATRUST_SIGNATURE;\n id: string;\n signature: string;\n};\n\nexport type OmaTrustSignatureErrorMessage = {\n type: typeof OMATRUST_SIGNATURE_ERROR;\n id: string;\n error: string;\n};\n\nexport type OmaTrustMessage =\n | OmaTrustReadyMessage\n | OmaTrustHostReadyMessage\n | OmaTrustSignTypedDataMessage\n | OmaTrustSignatureMessage\n | OmaTrustSignatureErrorMessage;\n","/**\n * Trust policy: fetches the OMA3 allowlist of EAS contracts and schemas.\n *\n * The bridge uses this to validate signing requests automatically.\n * Developers don't need to maintain their own allowlists.\n */\n\nconst DEFAULT_TRUST_POLICY_URL = \"https://api.omatrust.org/v1/trust-policy\";\n\nexport const TRUST_POLICY_URL = DEFAULT_TRUST_POLICY_URL;\n\nexport type ChainPolicy = {\n name: string;\n easContract: string;\n schemas: string[];\n};\n\nexport type TrustPolicy = {\n version: number;\n updatedAt: string;\n widgetOrigins?: string[];\n chains: Record<string, ChainPolicy>;\n};\n\nlet cachedPolicy: TrustPolicy | null = null;\nlet cacheTimestamp = 0;\nconst CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes\n\n/**\n * Fetch the trust policy from the OMA3 API gateway.\n * Caches the result for 5 minutes.\n *\n * @param url Override the trust policy URL (for testing or custom deployments)\n */\nexport async function fetchTrustPolicy(url?: string): Promise<TrustPolicy> {\n const now = Date.now();\n if (cachedPolicy && now - cacheTimestamp < CACHE_TTL_MS) {\n return cachedPolicy;\n }\n\n const res = await fetch(url ?? TRUST_POLICY_URL);\n if (!res.ok) {\n throw new Error(`Failed to fetch trust policy: ${res.status} ${res.statusText}`);\n }\n\n const policy: TrustPolicy = await res.json();\n\n if (!policy.version || !policy.chains || typeof policy.chains !== \"object\") {\n throw new Error(\"Invalid trust policy format\");\n }\n\n cachedPolicy = policy;\n cacheTimestamp = now;\n return policy;\n}\n\n/**\n * Extract the allowed contracts and schemas from a trust policy.\n * Returns all contracts and schemas across all chains.\n */\nexport function extractAllowlists(policy: TrustPolicy): {\n allowedContracts: string[];\n allowedSchemas: string[];\n} {\n const contracts: string[] = [];\n const schemas: string[] = [];\n\n for (const chain of Object.values(policy.chains)) {\n if (chain.easContract) contracts.push(chain.easContract);\n if (chain.schemas) schemas.push(...chain.schemas);\n }\n\n return {\n allowedContracts: [...new Set(contracts)],\n allowedSchemas: [...new Set(schemas)],\n };\n}\n","/**\n * Host-side signing bridge for OMATrust widget iframes.\n *\n * Handles the postMessage protocol between a host page and an embedded\n * OMATrust widget. Validates incoming EAS signing requests against the\n * OMA3 trust policy before forwarding to the host's wallet.\n *\n * The bridge resolves the iframe element lazily by ID when messages arrive,\n * avoiding React ref timing issues with conditionally rendered iframes.\n *\n * Usage:\n * import { createSigningBridge } from \"@oma3/omatrust/widgets\";\n *\n * const bridge = await createSigningBridge({\n * iframeId: \"omatrust-widget\",\n * signTypedData: async (domain, types, message) => {\n * return await signer.signTypedData(domain, types, message);\n * },\n * });\n *\n * bridge.destroy();\n */\n\nimport {\n OMATRUST_READY,\n OMATRUST_HOST_READY,\n OMATRUST_SIGN_TYPED_DATA,\n OMATRUST_SIGNATURE,\n OMATRUST_SIGNATURE_ERROR,\n} from \"./protocol\";\nimport { fetchTrustPolicy, extractAllowlists, TRUST_POLICY_URL } from \"./trust-policy\";\n\nexport type SigningBridgeOptions = {\n /**\n * The ID of the iframe element containing the widget.\n * The bridge looks up the element by ID when messages arrive,\n * so the iframe doesn't need to exist when the bridge is created.\n */\n iframeId: string;\n\n /**\n * Callback to sign EIP-712 typed data using the host's wallet.\n * Must return the hex-encoded signature string.\n */\n signTypedData: (\n domain: Record<string, unknown>,\n types: Record<string, unknown>,\n message: Record<string, unknown>\n ) => Promise<string>;\n\n /**\n * Override the allowed widget origin for local development.\n * In production, the origin is derived from the trust policy domain\n * (*.omatrust.org) plus any widgetOrigins in the policy.\n * Only set this for local dev (e.g., \"http://localhost:3000\").\n */\n devOriginOverride?: string;\n};\n\nexport type SigningBridge = {\n /** Remove all event listeners and stop the bridge. */\n destroy: () => void;\n};\n\n// ---------------------------------------------------------------------------\n// Origin resolution\n// ---------------------------------------------------------------------------\n\nfunction getTrustedBaseDomain(): string {\n try {\n const hostname = new URL(TRUST_POLICY_URL).hostname;\n const parts = hostname.split(\".\");\n return parts.length >= 2 ? parts.slice(-2).join(\".\") : hostname;\n } catch {\n return \"omatrust.org\";\n }\n}\n\nfunction isOriginTrusted(\n messageOrigin: string,\n baseDomain: string,\n policyOrigins: string[],\n devOverride?: string\n): boolean {\n if (devOverride && messageOrigin === devOverride) return true;\n\n try {\n const hostname = new URL(messageOrigin).hostname;\n if (hostname === baseDomain || hostname.endsWith(`.${baseDomain}`)) return true;\n } catch {\n // Invalid origin\n }\n\n if (policyOrigins.includes(messageOrigin)) return true;\n\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// EAS request validation\n// ---------------------------------------------------------------------------\n\nconst HEX_ADDRESS_RE = /^0x[a-fA-F0-9]{40}$/;\nconst BYTES32_RE = /^0x[a-fA-F0-9]{64}$/;\n\ntype ValidationResult =\n | { valid: true }\n | { valid: false; reason: string };\n\nfunction validateEasSigningRequest(\n data: Record<string, unknown>,\n allowedSchemas: string[],\n allowedContracts: string[]\n): ValidationResult {\n const { id, domain, types, message } = data;\n\n if (!id || typeof id !== \"string\") {\n return { valid: false, reason: \"Missing or invalid request id\" };\n }\n if (!domain || typeof domain !== \"object\") {\n return { valid: false, reason: \"Missing domain object\" };\n }\n\n const d = domain as Record<string, unknown>;\n\n if (d.name !== \"EAS\") {\n return { valid: false, reason: `Unexpected domain name: \"${d.name}\" (expected \"EAS\")` };\n }\n if (d.version !== \"1.4.0\") {\n return { valid: false, reason: `Unexpected domain version: \"${d.version}\" (expected \"1.4.0\")` };\n }\n const chainId = Number(d.chainId);\n if (!Number.isInteger(chainId) || chainId <= 0) {\n return { valid: false, reason: `Invalid domain chainId: ${d.chainId}` };\n }\n if (typeof d.verifyingContract !== \"string\" || !HEX_ADDRESS_RE.test(d.verifyingContract)) {\n return { valid: false, reason: `Invalid verifyingContract: ${d.verifyingContract}` };\n }\n\n const contractLower = (d.verifyingContract as string).toLowerCase();\n if (!allowedContracts.some(c => c.toLowerCase() === contractLower)) {\n return { valid: false, reason: `Contract ${d.verifyingContract} is not in the OMA3 trust policy` };\n }\n\n if (!types || typeof types !== \"object\") {\n return { valid: false, reason: \"Missing types object\" };\n }\n if (!message || typeof message !== \"object\") {\n return { valid: false, reason: \"Missing message object\" };\n }\n\n const m = message as Record<string, unknown>;\n\n if (typeof m.schema !== \"string\" || !BYTES32_RE.test(m.schema)) {\n return { valid: false, reason: `Invalid schema UID: ${m.schema}` };\n }\n\n const schemaLower = m.schema.toLowerCase();\n if (!allowedSchemas.some(s => s.toLowerCase() === schemaLower)) {\n return { valid: false, reason: `Schema ${m.schema} is not in the OMA3 trust policy` };\n }\n\n if (typeof m.attester !== \"string\" || !HEX_ADDRESS_RE.test(m.attester)) {\n return { valid: false, reason: `Invalid attester address: ${m.attester}` };\n }\n\n const deadline = Number(m.deadline);\n if (!Number.isFinite(deadline) || deadline <= 0) {\n return { valid: false, reason: `Invalid deadline: ${m.deadline}` };\n }\n const now = Math.floor(Date.now() / 1000);\n if (deadline <= now) {\n return { valid: false, reason: `Deadline has passed: ${deadline} <= ${now}` };\n }\n\n return { valid: true };\n}\n\n// ---------------------------------------------------------------------------\n// Bridge implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Create a signing bridge between the host page and an OMATrust widget iframe.\n *\n * The bridge resolves the iframe element by ID when messages arrive, not at\n * creation time. This avoids React ref timing issues — the bridge can be\n * created before the iframe is in the DOM.\n *\n * Fetches the OMA3 trust policy on creation. Fails closed if unavailable.\n */\nexport async function createSigningBridge(options: SigningBridgeOptions): Promise<SigningBridge> {\n const { iframeId, signTypedData, devOriginOverride } = options;\n\n // Fetch the trust policy — fail closed if unavailable\n const policy = await fetchTrustPolicy();\n const { allowedContracts, allowedSchemas } = extractAllowlists(policy);\n\n if (allowedContracts.length === 0 || allowedSchemas.length === 0) {\n throw new Error(\"Trust policy contains no allowed contracts or schemas\");\n }\n\n const baseDomain = getTrustedBaseDomain();\n const policyOrigins = policy.widgetOrigins ?? [];\n\n async function handleMessage(event: MessageEvent) {\n const data = event.data;\n if (!data || typeof data !== \"object\" || typeof data.type !== \"string\") return;\n if (!String(data.type).startsWith(\"omatrust:\")) return;\n\n // Origin check\n if (!isOriginTrusted(event.origin, baseDomain, policyOrigins, devOriginOverride)) {\n return;\n }\n\n // Resolve the iframe element lazily by ID.\n // This works even if the iframe was mounted after the bridge was created.\n const iframe = document.getElementById(iframeId) as HTMLIFrameElement | null;\n if (!iframe) return;\n\n // Source check — must come from this specific iframe\n if (event.source !== iframe.contentWindow) {\n return;\n }\n\n const source = event.source as WindowProxy;\n\n // Determine reply origin from the iframe's current src\n const replyOrigin = devOriginOverride ?? (() => {\n try { return new URL(iframe.src).origin; }\n catch { return \"*\"; }\n })();\n\n function reply(msg: Record<string, unknown>) {\n source.postMessage(msg, replyOrigin);\n }\n\n // Handshake\n if (data.type === OMATRUST_READY) {\n reply({ type: OMATRUST_HOST_READY });\n return;\n }\n\n // Signing request\n if (data.type === OMATRUST_SIGN_TYPED_DATA) {\n const { id, domain, types, message } = data;\n\n const validation = validateEasSigningRequest(data, allowedSchemas, allowedContracts);\n if (!validation.valid) {\n reply({\n type: OMATRUST_SIGNATURE_ERROR,\n id: id ?? \"unknown\",\n error: `Signing request rejected: ${validation.reason}`,\n });\n return;\n }\n\n try {\n const signature = await signTypedData(domain, types, message);\n reply({ type: OMATRUST_SIGNATURE, id, signature });\n } catch (err) {\n const error = err instanceof Error ? err.message : \"Signing failed\";\n reply({ type: OMATRUST_SIGNATURE_ERROR, id, error });\n }\n }\n }\n\n window.addEventListener(\"message\", handleMessage);\n\n return {\n destroy() {\n window.removeEventListener(\"message\", handleMessage);\n },\n };\n}\n"]}