@zkp2p/zkp2p-attestation 3.1.0 → 4.0.0-rc.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.0.0-rc.1 - 2026-10-16
4
+
5
+ - BREAKING: payment attestations are signed for UnifiedPaymentVerifierV4. Extension word 0, the signed `uint256` dispute window in seconds, follows UPV3's 448-byte payload, so `encodedPaymentDetails` is 480 bytes. `dataHash` covers every byte.
6
+ - Add `DISPUTE_WINDOW_POLICY`, `getDefaultDisputeWindow`, `getDefaultDisputeWindowForHash` and the `DisputeWindowPaymentMethod` type. They give the default dispute window in seconds by payment-method name or contract hash: Venmo and PayPal 1209600, every other supported method 0. Unknown names and hashes throw.
7
+ - Remove the unreleased `IntentConditionsV1` type and the `conditions` field on `verifyBuyerTeePayment` params; payment attestations carry only extension word 0 (480 bytes).
8
+
9
+ ## 4.0.0-rc.0
10
+
11
+ - Add X Money seller credential uploads and receipt-gated `register_xmoney` seller identity types. Mailbox credentials support Google OAuth, Microsoft OAuth, and iCloud Mail; standalone X Money identity requests remain unavailable.
12
+
13
+ - BREAKING: Monobank buyer TEE now uses entrepreneur business portal `gatewayState`/`browserId` credentials and `CLIENT_ID`/`TRANSACTION_ID` params. Retire the buyer Open API token shape; enforce settled UAH transfers and a service-owned 14-day timestamp buffer.
14
+
15
+ - Add typed X Money Buyer TEE requests with encrypted captured `url` and headers, and no public params. Replay the captured GraphQL operation ID and derive the transaction ID from the URL instead of accepting duplicate input.
16
+
17
+ - BREAKING: remove the retired HDFC Gmail buyer proof types and action. Amazon
18
+ Pay is the supported UPI buyer and seller verification path.
19
+
3
20
  ## 3.1.0
4
21
 
5
22
  - Remove the retired preproduction hostname and PCR8 from bundled trust pins.
package/README.md CHANGED
@@ -86,15 +86,17 @@ const encryptedUpload = await nitro.createEncryptedSellerCredentialUpload({
86
86
  });
87
87
  ```
88
88
 
89
+ Venmo Gmail OAuth uploads use the same encryption helper with numeric Venmo account id as `payeeId` and `sessionMaterial: { credentialSource: "google_oauth", authorizationCode, redirectUri, oauthClient? }`. The service binds a DKIM-verified receipt recipient to that account through Venmo's public profile API. The optional partner app secret and refresh token remain inside the encrypted seller bundle. Existing Venmo session-cookie uploads remain an independently supported credential type.
90
+
89
91
  PayPal Gmail OAuth seller uploads use the same app-selection model. Pass the seller PayPal email as `payeeId` and use `sessionMaterial: { credentialSource: "google_oauth", authorizationCode, redirectUri }`; the service validates Gmail access against paypal.com DKIM-signed payment receipts. To onboard through a partner-owned Google OAuth app, include `oauthClient: { clientId, clientSecret }` inside the encrypted `sessionMaterial`. The PayPal partner client secret is handled as seller credential material: it rides only in the compact JWE upload plaintext, is sealed with the Gmail refresh token in the KMS-envelope seller credential bundle, and is reused only to refresh that seller's Gmail access token.
90
92
 
91
93
  Buyer TEE requests use the same attested upload key and compact JWE envelope. The typed helper encrypts the captured
92
94
  session material, posts `{ encryptedSessionMaterial, params, chainId, intent }` to
93
95
  `POST /buyer/verify/:platform/:actionType`, unwraps the service envelope, and returns a typed `AttestationOutput`.
94
- The service does not enforce capture-age or one-use replay limits for buyer TEE session material; verification depends
95
- on the upstream session still being active. A leaked encrypted JWE is therefore valid for the upstream session
96
- lifetime — treat any accidental disclosure as equivalent to leaking the underlying upstream credential (cookies, PAT,
97
- etc.) and rotate the upstream session.
96
+ The service does not enforce capture-age or one-use replay limits for reusable
97
+ buyer TEE session material; verification depends on the upstream session still
98
+ being active. Treat any accidental JWE disclosure as equivalent to leaking its
99
+ underlying private evidence.
98
100
 
99
101
  ```ts
100
102
  const attestation = await nitro.verifyBuyerTeePayment({
@@ -153,11 +155,41 @@ Buyer TEE platform matrix:
153
155
  | `zelle` | `transfer_zelle_chase` | `Cookie`, `x-jpmc-channel`, `x-jpmc-csrf-token`, `Referer`, `Origin` | `index` |
154
156
  | `zelle` | `transfer_zelle_citi` | `Cookie` | `index` |
155
157
  | `paypal` | `transfer_paypal` | `Cookie` | `PAYMENT_ID` |
158
+ | `monobank` | `transfer_monobank` | `gatewayState`, `browserId` | `CLIENT_ID`, `TRANSACTION_ID` |
156
159
  | `alipay` | `transfer_alipay` | `Cookie` | `TRADE_NO` |
160
+ | `upi` | `transfer_upi_amazonpay` | `Cookie`, `User-Agent`, `body` | `TRANSACTION_URL` |
161
+ | `xmoney` | `transfer_xmoney` | `url`, `Cookie` and other captured session headers | `{}` |
162
+
163
+ Monobank buyer verification uses the entrepreneur business portal session. Capture
164
+ `localStorage.gateway` as `gatewayState`, and encode the raw P-256 public key from
165
+ `localStorage.browserId.publicKey` as unpadded base64url `browserId`. Encrypt both
166
+ inside the normal buyer JWE. `CLIENT_ID` selects the business profile and
167
+ `TRANSACTION_ID` selects its payment detail. The attestor constructs and encrypts
168
+ the bank request itself; caller-supplied payment JSON or encrypted request bodies
169
+ are rejected. It accepts settled outgoing UAH transfers (bank currency code 980),
170
+ hashes the recipient IBAN and bank payment ID, and signs a service-owned 14-day
171
+ buffer. The previous buyer Open API token shape is no longer accepted.
172
+
173
+ X Money replays the captured `url`, including X's current GraphQL operation ID,
174
+ just as Chime replays its captured `body`. Both stay inside encrypted session
175
+ material. The attestor owns endpoint and operation validation; X Money remains
176
+ GET-only on `https://x.com`, derives the transaction ID from the captured URL,
177
+ and requires the response ID to match. Ship the X Money extension capture and attestor changes
178
+ together; captures without `url` are rejected. Chime's contract is unchanged.
157
179
 
158
180
  Zelle buyer verification uses only `platform: "zelle"` with bank-specific action types. Every Zelle action attests
159
181
  `intent.paymentMethod = hashUtf8("zelle")`; direct bank-specific platforms are unsupported.
160
182
 
183
+ Amazon Pay uses `platform: "upi"` and `actionType: "transfer_upi_amazonpay"`.
184
+ Capture the `getTransactionHistory` GraphQL request after signing into Amazon
185
+ Pay and applying a transaction-history filter. Send its headers and exact request
186
+ body as encrypted session material, with only the selected history row's
187
+ `transactionDetailPageURL` as `params.TRANSACTION_URL`. The service rebuilds the
188
+ history query, confirms the selected outgoing payment, and fetches its receipt;
189
+ receipt URL labels alone do not establish payment direction. Both UPI actions use
190
+ the same `upi:<UPI reference>` payment-id preimage. Amazon session cookies remain
191
+ subject to server-side expiry or revocation; the package does not refresh them.
192
+
161
193
  Per-platform session-material types require these headers using the canonical names shown above while still allowing
162
194
  additional captured headers. Captured request bodies are session material because they can contain sensitive data and
163
195
  are encrypted before being sent to the service.
@@ -370,3 +402,42 @@ yarn verify --service https://attestation-service-staging.zkp2p.xyz
370
402
  ```
371
403
 
372
404
  Optional EIP-712 signer cross-check remains available through `--verify-signature`.
405
+
406
+ ## Dispute windows (UPV4)
407
+
408
+ ```ts
409
+ import { DISPUTE_WINDOW_POLICY, getDefaultDisputeWindow, getDefaultDisputeWindowForHash } from "@zkp2p/zkp2p-attestation";
410
+
411
+ getDefaultDisputeWindow("venmo"); // 1209600 seconds (14 days)
412
+ getDefaultDisputeWindow("upi"); // 0 seconds
413
+ getDefaultDisputeWindow("n26"); // 0 seconds
414
+ getDefaultDisputeWindowForHash(paymentMethodHash); // Same default for the contract's method hash
415
+ ```
416
+
417
+ The typed, immutable table uses payment-method names (`venmo`, `paypal`, `zelle`,
418
+ `upi`, etc.), not platform IDs or hashes. Venmo and PayPal default to 1209600
419
+ seconds; every other supported method defaults to zero. The table covers the
420
+ contracts catalogue on Base and Base staging, plus N26. Unknown names and hashes
421
+ reject; the hash helper accepts case-insensitive hexadecimal hashes.
422
+ A default above zero means the payment **may require stake or hold the payout**.
423
+ Quote-time protection applies when the default is positive, the deposit token is
424
+ USDC, the deposit+method whitelist is off, and the taker is not a registered
425
+ relayer whose deposit has not opted out of relayer bypass:
426
+ `defaultWindow > 0 && isUSDC && !whitelistEnabled && !(takerIsRegisteredRelayer && !relayerBypassOptedOut)`.
427
+ The indexer projects `relayerBypassOptedOut` per deposit as a boolean, default
428
+ `false`. Only the depositor can opt out per deposit (escrow + depositId, not per
429
+ method) through `DisputeProtectionPolicyV2.setDepositOptOutForRelayerBypass`.
430
+ Registered relayer takers on deposits that have not opted out pay now without a
431
+ policy record or event. Whitelist and relayer exemptions are on-chain decisions;
432
+ they do not change attestation signing. The attestor may sign a shorter window
433
+ for a specific payment: a complete, balance-funded Venmo buyer TEE proof signs
434
+ zero. SAR and fake payments use the rail default. The service's
435
+ `DISPUTE_WINDOWS_DISABLED=true` switch signs zero for every payment; the exported
436
+ policy continues to describe the rail defaults.
437
+
438
+ Every UPV4 payment includes extension word 0, `uint256 disputeWindow` in seconds,
439
+ after the unchanged 448-byte payment/snapshot base. Payloads are always 480 bytes. Zero means
440
+ pay now; it is not a balance-funding flag. `/attestation` advertises
441
+ `disputeWindowPolicy` (decimal-string seconds by payment-method name) and
442
+ `disputeWindowsDisabled` alongside its existing metadata. This policy metadata is
443
+ informational; the payment's signed payload binds its actual window.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var ue=Object.defineProperty;var At=Object.getOwnPropertyDescriptor;var Tt=Object.getOwnPropertyNames;var St=Object.prototype.hasOwnProperty;var Et=(e,t)=>{for(var r in t)ue(e,r,{get:t[r],enumerable:!0})},gt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Tt(t))!St.call(e,o)&&o!==r&&ue(e,o,{get:()=>t[o],enumerable:!(n=At(t,o))||n.enumerable});return e};var It=e=>gt(ue({},"__esModule",{value:!0}),e);var Ir={};Et(Ir,{AWS_NITRO_ROOT_FINGERPRINT_SHA256_HEX:()=>W,AWS_NITRO_ROOT_PEM:()=>J,NitroAttestationError:()=>R,createEncryptedBuyerTeeSessionMaterial:()=>M,createEncryptedDisputeSessionMaterial:()=>v,createEncryptedIdentitySessionMaterial:()=>H,createEncryptedSellerCredentialUpload:()=>F,createNitroAttestationClient:()=>rt,encryptBuyerTeeSessionMaterial:()=>w,encryptDisputeSessionMaterial:()=>V,encryptIdentitySessionMaterial:()=>B,encryptSellerCredentialUpload:()=>L,fetchAndVerifyAttestation:()=>K,getDisputeVerifierDomainSeparator:()=>ie,getUnifiedPaymentVerifierDomainSeparator:()=>ne,hashUtf8:()=>y,requestIdentityAttestation:()=>Z,uploadSellerCredential:()=>ee,verifyBuyerTeePayment:()=>te,verifyBuyerTeePaymentAttestation:()=>dt,verifyDispute:()=>re,verifyDisputeAttestation:()=>pt,verifyIdentityAttestation:()=>ft,verifySellerCredentialBundle:()=>yt});module.exports=It(Ir);var R=class extends Error{code;cause;details;constructor(t,r,n={}){super(r),this.name="NitroAttestationError",this.code=t,this.cause=n.cause,this.details=n.details}};function s(e,t,r){throw new R(e,t,r)}async function S(e,t,r){try{return await e}catch(n){s(t,r,{cause:n})}}function j(e){return e!==void 0?(typeof e!="function"&&s("CRYPTO_UNAVAILABLE","fetch is unavailable; pass a fetch implementation"),e):(typeof globalThis.fetch!="function"&&s("CRYPTO_UNAVAILABLE","fetch is unavailable; pass a fetch implementation"),globalThis.fetch.bind(globalThis))}function Pt(e){let t=e??globalThis.crypto?.subtle;return t||s("CRYPTO_UNAVAILABLE","SubtleCrypto is unavailable; pass params.subtle"),t}function ht(e){if(e)return e;let t=globalThis.crypto;return typeof t?.getRandomValues!="function"&&s("CRYPTO_UNAVAILABLE","crypto.getRandomValues is unavailable; pass params.getRandomValues"),r=>t.getRandomValues(r)}function T(e){return{subtle:Pt(e.subtle),getRandomValues:ht(e.getRandomValues)}}function Pe(e,t){return typeof t!="function"&&s("CRYPTO_UNAVAILABLE","crypto.getRandomValues is unavailable; pass params.getRandomValues"),{subtle:e,getRandomValues:t,randomUUID:()=>xt(t)}}function xt(e){let t=e(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;let r=Array.from(t,n=>n.toString(16).padStart(2,"0"));return`${r.slice(0,4).join("")}-${r.slice(4,6).join("")}-${r.slice(6,8).join("")}-${r.slice(8,10).join("")}-${r.slice(10).join("")}`}var G="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",z=Ct(G);function Ct(e){let t={};for(let r=0;r<e.length;r+=1)t[e[r]]=r;return t}function E(e){let t="";for(let r of e)t+=r.toString(16).padStart(2,"0");return t}function P(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e);let t=[];for(let r=0;r<e.length;r+=1){let n=e.codePointAt(r);n>65535&&(r+=1),n<=127?t.push(n):n<=2047?t.push(192|n>>6,128|n&63):n<=65535?t.push(224|n>>12,128|n>>6&63,128|n&63):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return new Uint8Array(t)}function U(e){if(typeof TextDecoder<"u")return new TextDecoder().decode(e);let t="";for(let r=0;r<e.length;r+=1){let n=e[r];n<128?t+=String.fromCodePoint(n):(n&224)===192?t+=String.fromCodePoint((n&31)<<6|e[++r]&63):(n&240)===224?t+=String.fromCodePoint((n&15)<<12|(e[++r]&63)<<6|e[++r]&63):t+=String.fromCodePoint((n&7)<<18|(e[++r]&63)<<12|(e[++r]&63)<<6|e[++r]&63)}return t}function bt(e){let t="";for(let r=0;r<e.length;r+=3){let n=e[r],o=e[r+1]??0,a=e[r+2]??0,i=n<<16|o<<8|a;t+=G[i>>18&63],t+=G[i>>12&63],t+=r+1<e.length?G[i>>6&63]:"=",t+=r+2<e.length?G[i&63]:"="}return t}function he(e){return Dt(e,!1)}function O(e){return bt(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function Dt(e,t){let r=e.replace(/\s+/g,""),n=t?r.replaceAll("-","+").replaceAll("_","/"):r;if(n.length%4===1)throw new Error("Invalid base64 length");let o=n+"=".repeat((4-n.length%4)%4),a=[];for(let i=0;i<o.length;i+=4){let u=o.slice(i,i+4),l=u.endsWith("==")?2:u.endsWith("=")?1:0,c=X(u[0],z),f=X(u[1],z),A=u[2]==="="?0:X(u[2],z),ce=u[3]==="="?0:X(u[3],z),_=c<<18|f<<12|A<<6|ce;a.push(_>>16&255),l<2&&a.push(_>>8&255),l<1&&a.push(_&255)}return new Uint8Array(a)}function X(e,t){let r=t[e];if(r===void 0)throw new Error(`Invalid base64 character: ${e}`);return r}function h(e){let t=e.reduce((o,a)=>o+a.length,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function g(e){return new Uint8Array(e).buffer}function xe(e){let t={sessionMaterial:e.sessionMaterial,...e.callerAddress!==void 0?{callerAddress:e.callerAddress}:{},boundPubKeySha256:e.key.publicKeySha256Hex,issuedAtMs:e.issuedAtMs,jweId:e.jweId};return e.platform==="wise"||e.platform==="monobank"?t:{payeeId:e.payeeId,...t}}function Ce(e){return{platform:e.platform,actionType:e.actionType,sessionMaterial:e.sessionMaterial,boundPubKeySha256:e.key.publicKeySha256Hex}}function be(e){return JSON.stringify(e)}var Rt={alg:"RSA-OAEP-256",enc:"A256GCM"},Nt=/^[A-Za-z0-9_-]{16,128}$/;async function De(e){let t=e.request.issuedAtMs??e.now(),r=e.request.jweId??Ut(e.getRandomValues);return _t(r),Ue({key:e.request.key,plaintext:xe({...e.request,issuedAtMs:t,jweId:r}),subtle:e.subtle,getRandomValues:e.getRandomValues,failureContext:"seller credential upload"})}async function Re(e){return de({...e,failureContext:"buyer TEE session material"})}async function Ne(e){return de({...e,failureContext:"identity session material"})}async function _e(e){return de({...e,failureContext:"dispute session material"})}async function de(e){return Ue({key:e.request.key,plaintext:Ce(e.request),subtle:e.subtle,getRandomValues:e.getRandomValues,failureContext:e.failureContext})}async function Ue(e){let t=P(be(e.plaintext)),r=e.getRandomValues(new Uint8Array(32)),n=await S(e.subtle.importKey("spki",g(e.key.publicKeyDer),{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]),"CRYPTO_UNAVAILABLE","Failed to import attested enclave-upload RSA public key"),o=new Uint8Array(await S(e.subtle.encrypt({name:"RSA-OAEP"},n,g(r)),"CRYPTO_UNAVAILABLE","Failed to RSA-OAEP encrypt the content encryption key")),a=e.getRandomValues(new Uint8Array(12)),i=O(P(JSON.stringify(Rt))),u=P(i),l=await S(e.subtle.importKey("raw",g(r),{name:"AES-GCM",length:256},!1,["encrypt"]),"CRYPTO_UNAVAILABLE","Failed to import generated AES-GCM content encryption key"),c=new Uint8Array(await S(e.subtle.encrypt({name:"AES-GCM",iv:g(a),additionalData:g(u),tagLength:128},l,g(t)),"CRYPTO_UNAVAILABLE",`Failed to AES-GCM encrypt ${e.failureContext}`)),f=c.slice(0,c.length-16),A=c.slice(c.length-16);return[i,O(o),O(a),O(f),O(A)].join(".")}function _t(e){Nt.test(e)||s("INVALID_PARAMETER","jweId must be 16-128 URL-safe characters")}function Ut(e){let t=e(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;let r=Array.from(t,n=>n.toString(16).padStart(2,"0"));return`${r.slice(0,4).join("")}-${r.slice(4,6).join("")}-${r.slice(6,8).join("")}-${r.slice(8,10).join("")}-${r.slice(10).join("")}`}async function w(e){let t=T(e);return Re({request:e,subtle:t.subtle,getRandomValues:t.getRandomValues})}var Oe=require("@peculiar/x509");var J=`-----BEGIN CERTIFICATE-----
1
+ "use strict";var de=Object.defineProperty;var gt=Object.getOwnPropertyDescriptor;var It=Object.getOwnPropertyNames;var Pt=Object.prototype.hasOwnProperty;var ht=(e,t)=>{for(var r in t)de(e,r,{get:t[r],enumerable:!0})},xt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of It(t))!Pt.call(e,o)&&o!==r&&de(e,o,{get:()=>t[o],enumerable:!(n=gt(t,o))||n.enumerable});return e};var Ct=e=>xt(de({},"__esModule",{value:!0}),e);var br={};ht(br,{AWS_NITRO_ROOT_FINGERPRINT_SHA256_HEX:()=>G,AWS_NITRO_ROOT_PEM:()=>Q,DISPUTE_WINDOW_POLICY:()=>j,NitroAttestationError:()=>R,createEncryptedBuyerTeeSessionMaterial:()=>M,createEncryptedDisputeSessionMaterial:()=>V,createEncryptedIdentitySessionMaterial:()=>H,createEncryptedSellerCredentialUpload:()=>F,createNitroAttestationClient:()=>nt,encryptBuyerTeeSessionMaterial:()=>w,encryptDisputeSessionMaterial:()=>v,encryptIdentitySessionMaterial:()=>B,encryptSellerCredentialUpload:()=>L,fetchAndVerifyAttestation:()=>K,getDefaultDisputeWindow:()=>ot,getDefaultDisputeWindowForHash:()=>st,getDisputeVerifierDomainSeparator:()=>oe,getUnifiedPaymentVerifierDomainSeparator:()=>ie,hashUtf8:()=>y,requestIdentityAttestation:()=>ee,uploadSellerCredential:()=>te,verifyBuyerTeePayment:()=>re,verifyBuyerTeePaymentAttestation:()=>yt,verifyDispute:()=>ne,verifyDisputeAttestation:()=>At,verifyIdentityAttestation:()=>Tt,verifySellerCredentialBundle:()=>St});module.exports=Ct(br);var R=class extends Error{code;cause;details;constructor(t,r,n={}){super(r),this.name="NitroAttestationError",this.code=t,this.cause=n.cause,this.details=n.details}};function s(e,t,r){throw new R(e,t,r)}async function S(e,t,r){try{return await e}catch(n){s(t,r,{cause:n})}}function z(e){return e!==void 0?(typeof e!="function"&&s("CRYPTO_UNAVAILABLE","fetch is unavailable; pass a fetch implementation"),e):(typeof globalThis.fetch!="function"&&s("CRYPTO_UNAVAILABLE","fetch is unavailable; pass a fetch implementation"),globalThis.fetch.bind(globalThis))}function bt(e){let t=e??globalThis.crypto?.subtle;return t||s("CRYPTO_UNAVAILABLE","SubtleCrypto is unavailable; pass params.subtle"),t}function Dt(e){if(e)return e;let t=globalThis.crypto;return typeof t?.getRandomValues!="function"&&s("CRYPTO_UNAVAILABLE","crypto.getRandomValues is unavailable; pass params.getRandomValues"),r=>t.getRandomValues(r)}function T(e){return{subtle:bt(e.subtle),getRandomValues:Dt(e.getRandomValues)}}function he(e,t){return typeof t!="function"&&s("CRYPTO_UNAVAILABLE","crypto.getRandomValues is unavailable; pass params.getRandomValues"),{subtle:e,getRandomValues:t,randomUUID:()=>Rt(t)}}function Rt(e){let t=e(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;let r=Array.from(t,n=>n.toString(16).padStart(2,"0"));return`${r.slice(0,4).join("")}-${r.slice(4,6).join("")}-${r.slice(6,8).join("")}-${r.slice(8,10).join("")}-${r.slice(10).join("")}`}var W="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",X=Nt(W);function Nt(e){let t={};for(let r=0;r<e.length;r+=1)t[e[r]]=r;return t}function E(e){let t="";for(let r of e)t+=r.toString(16).padStart(2,"0");return t}function P(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e);let t=[];for(let r=0;r<e.length;r+=1){let n=e.codePointAt(r);n>65535&&(r+=1),n<=127?t.push(n):n<=2047?t.push(192|n>>6,128|n&63):n<=65535?t.push(224|n>>12,128|n>>6&63,128|n&63):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return new Uint8Array(t)}function U(e){if(typeof TextDecoder<"u")return new TextDecoder().decode(e);let t="";for(let r=0;r<e.length;r+=1){let n=e[r];n<128?t+=String.fromCodePoint(n):(n&224)===192?t+=String.fromCodePoint((n&31)<<6|e[++r]&63):(n&240)===224?t+=String.fromCodePoint((n&15)<<12|(e[++r]&63)<<6|e[++r]&63):t+=String.fromCodePoint((n&7)<<18|(e[++r]&63)<<12|(e[++r]&63)<<6|e[++r]&63)}return t}function _t(e){let t="";for(let r=0;r<e.length;r+=3){let n=e[r],o=e[r+1]??0,a=e[r+2]??0,i=n<<16|o<<8|a;t+=W[i>>18&63],t+=W[i>>12&63],t+=r+1<e.length?W[i>>6&63]:"=",t+=r+2<e.length?W[i&63]:"="}return t}function xe(e){return Ut(e,!1)}function O(e){return _t(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function Ut(e,t){let r=e.replace(/\s+/g,""),n=t?r.replaceAll("-","+").replaceAll("_","/"):r;if(n.length%4===1)throw new Error("Invalid base64 length");let o=n+"=".repeat((4-n.length%4)%4),a=[];for(let i=0;i<o.length;i+=4){let u=o.slice(i,i+4),l=u.endsWith("==")?2:u.endsWith("=")?1:0,c=J(u[0],X),f=J(u[1],X),A=u[2]==="="?0:J(u[2],X),ue=u[3]==="="?0:J(u[3],X),_=c<<18|f<<12|A<<6|ue;a.push(_>>16&255),l<2&&a.push(_>>8&255),l<1&&a.push(_&255)}return new Uint8Array(a)}function J(e,t){let r=t[e];if(r===void 0)throw new Error(`Invalid base64 character: ${e}`);return r}function h(e){let t=e.reduce((o,a)=>o+a.length,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function g(e){return new Uint8Array(e).buffer}function Ce(e){let t={sessionMaterial:e.sessionMaterial,...e.callerAddress!==void 0?{callerAddress:e.callerAddress}:{},boundPubKeySha256:e.key.publicKeySha256Hex,issuedAtMs:e.issuedAtMs,jweId:e.jweId};return e.platform==="wise"||e.platform==="monobank"||e.platform==="upi"?t:{payeeId:e.payeeId,...t}}function be(e){return{platform:e.platform,actionType:e.actionType,sessionMaterial:e.sessionMaterial,boundPubKeySha256:e.key.publicKeySha256Hex}}function De(e){return JSON.stringify(e)}var Ot={alg:"RSA-OAEP-256",enc:"A256GCM"},wt=/^[A-Za-z0-9_-]{16,128}$/;async function Re(e){let t=e.request.issuedAtMs??e.now(),r=e.request.jweId??vt(e.getRandomValues);return Mt(r),Oe({key:e.request.key,plaintext:Ce({...e.request,issuedAtMs:t,jweId:r}),subtle:e.subtle,getRandomValues:e.getRandomValues,failureContext:"seller credential upload"})}async function Ne(e){return le({...e,failureContext:"buyer TEE session material"})}async function _e(e){return le({...e,failureContext:"identity session material"})}async function Ue(e){return le({...e,failureContext:"dispute session material"})}async function le(e){return Oe({key:e.request.key,plaintext:be(e.request),subtle:e.subtle,getRandomValues:e.getRandomValues,failureContext:e.failureContext})}async function Oe(e){let t=P(De(e.plaintext)),r=e.getRandomValues(new Uint8Array(32)),n=await S(e.subtle.importKey("spki",g(e.key.publicKeyDer),{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]),"CRYPTO_UNAVAILABLE","Failed to import attested enclave-upload RSA public key"),o=new Uint8Array(await S(e.subtle.encrypt({name:"RSA-OAEP"},n,g(r)),"CRYPTO_UNAVAILABLE","Failed to RSA-OAEP encrypt the content encryption key")),a=e.getRandomValues(new Uint8Array(12)),i=O(P(JSON.stringify(Ot))),u=P(i),l=await S(e.subtle.importKey("raw",g(r),{name:"AES-GCM",length:256},!1,["encrypt"]),"CRYPTO_UNAVAILABLE","Failed to import generated AES-GCM content encryption key"),c=new Uint8Array(await S(e.subtle.encrypt({name:"AES-GCM",iv:g(a),additionalData:g(u),tagLength:128},l,g(t)),"CRYPTO_UNAVAILABLE",`Failed to AES-GCM encrypt ${e.failureContext}`)),f=c.slice(0,c.length-16),A=c.slice(c.length-16);return[i,O(o),O(a),O(f),O(A)].join(".")}function Mt(e){wt.test(e)||s("INVALID_PARAMETER","jweId must be 16-128 URL-safe characters")}function vt(e){let t=e(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;let r=Array.from(t,n=>n.toString(16).padStart(2,"0"));return`${r.slice(0,4).join("")}-${r.slice(4,6).join("")}-${r.slice(6,8).join("")}-${r.slice(8,10).join("")}-${r.slice(10).join("")}`}async function w(e){let t=T(e);return Ne({request:e,subtle:t.subtle,getRandomValues:t.getRandomValues})}var we=require("@peculiar/x509");var Q=`-----BEGIN CERTIFICATE-----
2
2
  MIICETCCAZagAwIBAgIRAPkxdWgbkK/hHUbMtOTn+FYwCgYIKoZIzj0EAwMwSTEL
3
3
  MAkGA1UEBhMCVVMxDzANBgNVBAoMBkFtYXpvbjEMMAoGA1UECwwDQVdTMRswGQYD
4
4
  VQQDDBJhd3Mubml0cm8tZW5jbGF2ZXMwHhcNMTkxMDI4MTMyODA1WhcNNDkxMDI4
@@ -12,5 +12,5 @@ MQCjfy+Rocm9Xue4YnwWmNJVA44fA0P5W2OpYow9OYCVRaEevL8uO1XYru5xtMPW
12
12
  rfMCMQCi85sWBbJwKKXdS6BptQFuZbT73o/gBh1qUxl/nNr12UO8Yfwr6wPLb+6N
13
13
  IwLz3/Y=
14
14
  -----END CERTIFICATE-----
15
- `,W="641a0321a3e244efe456463195d606317ed7cdcc3c1756e09893f3c68f79bb5b";var Ot=10080*60*1e3;async function we(e){let t=Pe(e.subtle,e.getRandomValues),r=le(e.rootPem??J,"AWS Nitro root certificate"),n=await pe(r,e.subtle);n!==W&&s("AWS_ROOT_FINGERPRINT_MISMATCH","Bundled AWS Nitro root certificate fingerprint mismatch",{details:{expected:W,actual:n}});let o=le(e.leafCertificateDer,"attestation leaf certificate"),a=e.cabundleDer.map((f,A)=>le(f,`cabundle[${A}]`)),i=[r,...a,o];for(let f of i)Mt(f,e.nowMs),Vt(f,e.nowMs,e.onWarning);let u=await pe(o,e.subtle),l=[];for(let f of a){let A=await pe(f,e.subtle);A!==u&&A!==n&&l.push(f)}let c=[[o,...l.slice().reverse(),r],[o,...l,r]];for(let f of c)if(await wt(f,t)){let A=await S(o.publicKey.export({name:"ECDSA",namedCurve:"P-384"},["verify"],t),"CERT_CHAIN_INVALID","Failed to export attestation leaf public key");return{leafCertificate:o,leafPublicKey:A}}s("CERT_CHAIN_INVALID","Attestation certificate chain does not verify to the pinned AWS Nitro root")}async function wt(e,t){for(let r=0;r<e.length-1;r+=1){let n=e[r],o=e[r+1];if(!await n.verify({publicKey:o.publicKey,signatureOnly:!0},t))return!1}return e.length>0&&await e[e.length-1].isSelfSigned(t)}function le(e,t){try{return new Oe.X509Certificate(e)}catch(r){s("CERT_CHAIN_INVALID",`Could not parse ${t}`,{cause:r})}}async function pe(e,t){return E(new Uint8Array(await t.digest("SHA-256",e.rawData)))}function Mt(e,t){(t<e.notBefore.getTime()||t>e.notAfter.getTime())&&s("CERT_NOT_TIME_VALID","Certificate is outside its validity window",{details:{subject:e.subject,notBefore:e.notBefore.toISOString(),notAfter:e.notAfter.toISOString()}})}function Vt(e,t,r){e.notAfter.getTime()<t+Ot&&r?.({code:"CERT_VALIDITY_NEAR_EXPIRY",message:"Certificate in Nitro attestation chain expires within 7 days",details:{subject:e.subject,notAfter:e.notAfter.toISOString()}})}function $(e){let t=new fe(e),r=t.readValue();if(!t.done())throw new Error("Trailing CBOR bytes");return r}function Q(e){if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new Error("CBOR number must be a safe integer");return e>=0?x(0,e):x(1,-1-e)}if(typeof e=="bigint")return e>=0n?x(0,e):x(1,-1n-e);if(typeof e=="string"){let t=P(e);return h([x(3,t.length),t])}if(e instanceof Uint8Array)return h([x(2,e.length),e]);if(Array.isArray(e))return h([x(4,e.length),...e.map(Q)]);if(e instanceof Map)return h([x(5,e.size),...Array.from(e.entries()).flatMap(([t,r])=>[Q(t),Q(r)])]);if(typeof e=="boolean")return new Uint8Array([e?245:244]);if(e===null)return new Uint8Array([246]);throw new Error("Unsupported CBOR value")}function Me(e,t){return Q(["Signature1",e,new Uint8Array,t])}function x(e,t){let r=BigInt(t);return r<24n?new Uint8Array([e<<5|Number(r)]):r<=0xffn?new Uint8Array([e<<5|24,Number(r)]):r<=0xffffn?new Uint8Array([e<<5|25,Number(r>>8n&0xffn),Number(r&0xffn)]):r<=0xffffffffn?new Uint8Array([e<<5|26,Number(r>>24n&0xffn),Number(r>>16n&0xffn),Number(r>>8n&0xffn),Number(r&0xffn)]):new Uint8Array([e<<5|27,Number(r>>56n&0xffn),Number(r>>48n&0xffn),Number(r>>40n&0xffn),Number(r>>32n&0xffn),Number(r>>24n&0xffn),Number(r>>16n&0xffn),Number(r>>8n&0xffn),Number(r&0xffn)])}var fe=class{constructor(t){this.bytes=t}bytes;offset=0;done(){return this.offset===this.bytes.length}readValue(){let t=this.readByte(),r=t>>5,n=t&31;if(n===31)return this.readIndefiniteValue(r);if(r===0)return this.readLength(n);if(r===1){let o=this.readLength(n);return typeof o=="bigint"?-1n-o:-1-o}if(r===2){let o=this.lengthAsNumber(this.readLength(n));return this.readBytes(o)}if(r===3){let o=this.lengthAsNumber(this.readLength(n));return U(this.readBytes(o))}if(r===4){let o=this.lengthAsNumber(this.readLength(n)),a=[];for(let i=0;i<o;i+=1)a.push(this.readValue());return a}if(r===5){let o=this.lengthAsNumber(this.readLength(n)),a=new Map;for(let i=0;i<o;i+=1)a.set(this.readValue(),this.readValue());return a}if(r===6)return this.readLength(n),this.readValue();if(r===7){if(n===20)return!1;if(n===21)return!0;if(n===22)return null}throw new Error(`Unsupported CBOR major/additional type: ${r}/${n}`)}readIndefiniteValue(t){if(t===2){let r=[];for(;!this.consumeBreak();){let n=this.readValue();if(!(n instanceof Uint8Array))throw new Error("Indefinite CBOR byte string chunk must be a byte string");r.push(n)}return h(r)}if(t===3){let r="";for(;!this.consumeBreak();){let n=this.readValue();if(typeof n!="string")throw new Error("Indefinite CBOR text string chunk must be a text string");r+=n}return r}if(t===4){let r=[];for(;!this.consumeBreak();)r.push(this.readValue());return r}if(t===5){let r=new Map;for(;!this.consumeBreak();){let n=this.readValue();if(this.peekBreak())throw new Error("Indefinite CBOR map ended after a key");r.set(n,this.readValue())}return r}throw new Error(`Indefinite CBOR major type ${t} is not supported`)}readLength(t){if(t<24)return t;if(t===24)return this.readByte();if(t===25)return this.readByte()<<8|this.readByte();if(t===26)return this.readByte()*16777216+(this.readByte()<<16)+(this.readByte()<<8)+this.readByte()>>>0;if(t===27){let r=0n;for(let n=0;n<8;n+=1)r=r<<8n|BigInt(this.readByte());return r<=BigInt(Number.MAX_SAFE_INTEGER)?Number(r):r}throw new Error("Indefinite CBOR lengths are not supported")}readByte(){if(this.offset>=this.bytes.length)throw new Error("Unexpected end of CBOR input");return this.bytes[this.offset++]}peekBreak(){return this.offset<this.bytes.length&&this.bytes[this.offset]===255}consumeBreak(){return this.peekBreak()?(this.offset+=1,!0):!1}readBytes(t){if(this.offset+t>this.bytes.length)throw new Error("Unexpected end of CBOR byte string");let r=this.bytes.slice(this.offset,this.offset+t);return this.offset+=t,r}lengthAsNumber(t){if(typeof t=="bigint")throw new Error("CBOR length exceeds JavaScript safe integer range");return t}};function Ve(e){let t=e[0]===210?e.slice(1):e,r;try{r=$(t)}catch(u){s("COSE_STRUCTURE_INVALID","Attestation document is not a valid COSE_Sign1 CBOR value",{cause:u})}(!Array.isArray(r)||r.length!==4)&&s("COSE_STRUCTURE_INVALID","COSE_Sign1 must be [protected, unprotected, payload, signature]");let[n,o,a,i]=r;return(!(n instanceof Uint8Array)||!(o instanceof Map)||!(a instanceof Uint8Array)||!(i instanceof Uint8Array))&&s("COSE_STRUCTURE_INVALID","COSE_Sign1 fields have invalid CBOR types"),vt(n),i.length!==96&&s("COSE_SIGNATURE_INVALID_SIZE",`Expected a 96-byte ES384 signature, got ${i.length} bytes`),{protectedHeadersBytes:n,payloadBytes:a,signature:i}}async function ve(e){let t=Me(e.protectedHeadersBytes,e.payloadBytes);await S(e.subtle.verify({name:"ECDSA",hash:"SHA-384"},e.leafPublicKey,e.signature,t),"COSE_SIGNATURE_VERIFY_FAILED","COSE_Sign1 signature verification failed")||s("COSE_SIGNATURE_VERIFY_FAILED","COSE_Sign1 signature does not verify with the attestation leaf certificate")}function vt(e){let t;try{t=$(e)}catch(r){s("COSE_STRUCTURE_INVALID","COSE protected headers are not a valid CBOR map",{cause:r})}t instanceof Map||s("COSE_STRUCTURE_INVALID","COSE protected headers must be a CBOR map"),t.get(1)!==-35&&s("COSE_ALG_UNSUPPORTED","COSE protected header alg must be -35 (ES384)")}var ye=96;function C(e,t){let r=e.replace(/^0x/i,"").toLowerCase();return(r.length!==ye||!/^[0-9a-f]+$/.test(r))&&s("TRUST_PIN_REQUIRED",`${t} must be ${ye} lowercase hex characters`),r}function Be(e,t){let r=C(e,t);return e!==r&&s("ATTESTATION_RESPONSE_INVALID",`${t} must be ${ye} lowercase hex characters`),r}var He=256*1024,Bt=3,Ht=150,Lt=/^0x[0-9a-fA-F]{40}$/;function Ft(e,t){let r=new URL(e),n=r.pathname.replace(/\/+$/,"");return r.pathname=n.endsWith("/attestation")?n:`${n}/attestation`,r.search="",r.searchParams.set("nonce",t),r}async function Ye(e){let t=Ft(e.attestationServiceUrl,e.nonceHex),r=await Wt(t.toString(),e.fetch,e.timeoutMs),n=await Yt(r);r.ok||s("ATTESTATION_FETCH_FAILED",`GET /attestation failed with HTTP ${r.status}`,{details:{status:r.status,body:n.slice(0,400)}});let o;try{o=JSON.parse(n)}catch(a){s("ATTESTATION_RESPONSE_INVALID","GET /attestation returned non-JSON response",{cause:a})}return kt(o)}function kt(e){(!ke(e)||e.success!==!0||!ke(e.responseObject))&&s("ATTESTATION_RESPONSE_INVALID","Expected { success: true, responseObject: {...} }");let t=e.responseObject;(typeof t.attestationDocument!="string"||typeof t.nonce!="string")&&s("ATTESTATION_RESPONSE_INVALID","Attestation response is missing attestationDocument or nonce");let r;try{r=he(t.attestationDocument)}catch(n){s("ATTESTATION_RESPONSE_INVALID","attestationDocument is not valid base64",{cause:n})}return r.length===0&&s("ATTESTATION_RESPONSE_INVALID","attestationDocument decoded to empty bytes"),{attestationDocument:r,nonce:t.nonce.toLowerCase(),advertised:{chainId:typeof t.chainId=="number"?t.chainId:void 0,verifyingContract:Fe(t.verifyingContract,"verifyingContract"),expectedSigner:Fe(t.expectedSigner,"expectedSigner"),expectedPcr8:Gt(t.expectedPcr8,"expectedPcr8")}}}async function Yt(e){if(!e.body){let o=await e.text();return Le(P(o).length),o}let t=e.body.getReader(),r=[],n=0;for(;;){let{done:o,value:a}=await t.read();if(o)break;a&&(n+=a.length,Le(n),r.push(a))}return U(h(r))}function Le(e){e>He&&s("ATTESTATION_RESPONSE_INVALID","GET /attestation response exceeded maximum size",{details:{maxBytes:He,actualBytes:e}})}function Fe(e,t){if(e!==void 0)return(typeof e!="string"||!Lt.test(e))&&s("ATTESTATION_RESPONSE_INVALID",`${t} must be a 0x-prefixed 20-byte hex address`),e.toLowerCase()}function Gt(e,t){if(e!==void 0){typeof e!="string"&&s("ATTESTATION_RESPONSE_INVALID",`${t} must be a 96-character lowercase hex string`);try{return Be(e,t)}catch(r){s("ATTESTATION_RESPONSE_INVALID",`${t} must be a 96-character lowercase hex string`,{cause:r})}}}async function Wt(e,t,r){let n=1;for(;;)try{return await $t(e,t,r)}catch(o){if(!qt(o)||n>=Bt)throw o;await Kt(Ht*n),n+=1}}async function $t(e,t,r){let n=typeof AbortController<"u"?new AbortController:void 0,o,a=new Promise((i,u)=>{o=setTimeout(()=>{n?.abort(),u(new Error("timeout"))},r)});try{let i=await Promise.race([t(e,{headers:{accept:"application/json"},signal:n?.signal}),a]);return o!==void 0&&clearTimeout(o),i}catch(i){o!==void 0&&clearTimeout(o),i instanceof Error&&(i.name==="AbortError"||i.message==="timeout")&&s("TIMEOUT",`GET /attestation timed out after ${r}ms`,{cause:i}),s("ATTESTATION_FETCH_FAILED","GET /attestation failed at the network layer",{cause:i,details:{layer:"network"}})}}function qt(e){return e instanceof R&&e.code==="ATTESTATION_FETCH_FAILED"&&e.details?.layer==="network"}function Kt(e){return new Promise(t=>setTimeout(t,e))}function ke(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var jt=32;function Ge(e){return E(e(new Uint8Array(jt)))}function We(e,t){e.toLowerCase()!==t&&s("ATTESTATION_NONCE_MISMATCH","Attestation service echoed a different nonce",{details:{expectedNonce:t,echoedNonce:e}})}function qe(e){let t;try{t=$(e)}catch(a){s("PAYLOAD_FIELD_MISSING","Attestation payload is not a valid CBOR map",{cause:a})}let r=$e(t,"payload"),n=$e(r.get("pcrs"),"pcrs"),o=q(r.get("user_data"),"user_data");return{timestampMs:zt(r.get("timestamp")),nonceHex:U(o),pcr0Hex:me(n,0),pcr1Hex:me(n,1),pcr2Hex:me(n,2),pcr8Hex:E(q(n.get(8),"pcrs[8]")),certificateDer:q(r.get("certificate"),"certificate"),cabundleDer:Xt(r.get("cabundle"),"cabundle").map((a,i)=>q(a,`cabundle[${i}]`)),publicKeyDer:q(r.get("public_key"),"public_key")}}function me(e,t){let r=e.get(t);return r instanceof Uint8Array?E(r):""}function zt(e){if(typeof e=="number"&&Number.isSafeInteger(e)&&e>=0)return e;s("PAYLOAD_FIELD_MISSING","Attestation payload timestamp must be an unsigned safe integer")}function $e(e,t){if(e instanceof Map)return e;s("PAYLOAD_FIELD_MISSING",`Attestation payload field ${t} must be a CBOR map`)}function q(e,t){if(e instanceof Uint8Array)return e;s("PAYLOAD_FIELD_MISSING",`Attestation payload field ${t} must be a byte string`)}function Xt(e,t){if(Array.isArray(e))return e;s("PAYLOAD_FIELD_MISSING",`Attestation payload field ${t} must be an array`)}var Jt="https://attestation-service-staging.zkp2p.xyz",Qt="https://attestation-service.zkp2p.xyz",Ke="5636e3bd96f847cf12cfd9de7faa8cad0e6fa00962ce16ba185f8e5ea57105abb3cc9cc34f1e1e4de3444ceabcca7485",je="41a4ae0b9b96752cab5addb7d22689b3070e564e29f90a54316fa33fa38ea51387a6e887ea4f5a4b0cc34f69cea3f40e",ze={"attestation-service-staging.zkp2p.xyz":C(Ke,"bundled staging PCR8"),"attestation-service.zkp2p.xyz":C(je,"bundled production PCR8")},Xe={staging:{attestationServiceUrl:Jt,expectedPcr8Hex:Ke},production:{attestationServiceUrl:Qt,expectedPcr8Hex:je}};function Je(e){let{trust:t,advertisedExpectedPcr8:r,onWarning:n}=e,o=e.hostname.toLowerCase();if(t?.expectedPcr8Hex)return C(t.expectedPcr8Hex,"trust.expectedPcr8Hex");let a=t?.expectedPcr8ByHost,i=a?Zt(a,o):void 0;if(i)return C(i,`trust.expectedPcr8ByHost[${o}]`);let u=ze[o];if(u)return u;if(t?.strictPin===!0&&s("TRUST_PIN_REQUIRED",`No trusted PCR8 pin is configured for ${o}`),r){let l=C(r,"service-advertised expectedPcr8");return n?.({code:"TRUST_PIN_NOT_PROVIDED",message:`No caller or bundled PCR8 pin was available for ${o}; falling back to service-advertised expectedPcr8`,details:{hostname:o,expectedPcr8:l}}),l}s("TRUST_PIN_REQUIRED",`No trusted or service-advertised PCR8 pin is available for ${o}`)}function Zt(e,t){for(let[r,n]of Object.entries(e))if(r.toLowerCase()===t)return n}var er=300*1e3;async function b(e){return(await K(e)).attestedSellerUploadKey}async function K(e){let t=j(e.fetch),r=T(e),n=e.now??Date.now,o=Ge(r.getRandomValues),a=await Ye({attestationServiceUrl:e.attestationServiceUrl,nonceHex:o,fetch:t,timeoutMs:e.timeoutMs??1e4});We(a.nonce,o);let{protectedHeadersBytes:i,payloadBytes:u,signature:l}=Ve(a.attestationDocument),c=qe(u);c.nonceHex!==o&&s("NONCE_BINDING_FAILED","Attestation payload user_data did not match the request nonce",{details:{expectedNonce:o,payloadNonce:c.nonceHex}});let f=e.trust?.freshnessWindowMs??er,A=n();Math.abs(A-c.timestampMs)>f&&s("FRESHNESS_CHECK_FAILED",`Attestation timestamp skew exceeds ${f}ms`,{details:{timestampMs:c.timestampMs,nowMs:A,freshnessWindowMs:f}});let ce=new URL(e.attestationServiceUrl).hostname,_=Je({trust:e.trust,hostname:ce,advertisedExpectedPcr8:a.advertised.expectedPcr8,onWarning:e.onWarning});c.pcr8Hex!==_&&s("PCR8_PIN_MISMATCH","Attestation PCR8 does not match the trusted pin",{details:{expectedPcr8:_,actualPcr8:c.pcr8Hex}});let{leafPublicKey:mt}=await we({leafCertificateDer:c.certificateDer,cabundleDer:c.cabundleDer,rootPem:e.trust?.awsNitroRootPem,nowMs:A,subtle:r.subtle,getRandomValues:r.getRandomValues,onWarning:e.onWarning});return await ve({protectedHeadersBytes:i,payloadBytes:u,signature:l,leafPublicKey:mt,subtle:r.subtle}),{attestedSellerUploadKey:{publicKeyDer:c.publicKeyDer,publicKeySha256Hex:E(new Uint8Array(await r.subtle.digest("SHA-256",g(c.publicKeyDer))))},payload:{timestampMs:c.timestampMs,pcr0Hex:c.pcr0Hex,pcr1Hex:c.pcr1Hex,pcr2Hex:c.pcr2Hex,pcr8Hex:c.pcr8Hex,nonceHex:c.nonceHex,advertised:a.advertised}}}async function M(e){return w({...e,key:await b(e)})}async function V(e){let t=T(e);return _e({request:e,subtle:t.subtle,getRandomValues:t.getRandomValues})}async function v(e){return V({key:await b(e),platform:e.platform,actionType:e.actionType,sessionMaterial:e.sessionMaterial,subtle:e.subtle,getRandomValues:e.getRandomValues})}async function B(e){let t=T(e);return Ne({request:e,subtle:t.subtle,getRandomValues:t.getRandomValues})}async function H(e){return B({key:await b(e),platform:e.platform,actionType:e.actionType,sessionMaterial:e.sessionMaterial,subtle:e.subtle,getRandomValues:e.getRandomValues})}async function L(e){let t=T(e);return De({request:e,subtle:t.subtle,getRandomValues:t.getRandomValues,now:e.now??Date.now})}async function F(e){return L({...e,key:await b(e)})}var Qe=require("ethers");function Ze(e){try{return(0,Qe.getAddress)(e)}catch(t){s("INVALID_PARAMETER","callerAddress must be a valid Ethereum address",{cause:t})}}var tr=400;async function D(e){let t=j(e.fetch),r=e.timeoutMs??1e4,n=new AbortController,o,a=new Promise((c,f)=>{o=setTimeout(()=>{n.abort(),f(new Error("timeout"))},r)}),i,u;try{i=await Promise.race([t(or(e.attestationServiceUrl,e.path),{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:n.signal}),a]),u=await Promise.race([i.text(),a])}catch(c){n.signal.aborted&&s("TIMEOUT",`${e.failureContext} timed out after ${r}ms`,{cause:c}),s("ATTESTATION_FETCH_FAILED",`${e.failureContext} failed at the network layer`,{cause:c})}finally{clearTimeout(o)}if(!i.ok){let c=rr(u);c?.success===!1&&et(e.failureContext,i.status,c),s("ATTESTATION_FETCH_FAILED",`${e.failureContext} failed with HTTP ${i.status}`,{details:{status:i.status,body:u.slice(0,400)}})}let l;try{l=JSON.parse(u)}catch(c){s("ATTESTATION_RESPONSE_INVALID",`${e.failureContext} returned a non-JSON ServiceResponse`,{cause:c})}return l.success!==!0&&(l.success===!1&&et(e.failureContext,i.status,l),s("ATTESTATION_RESPONSE_INVALID",`${e.failureContext} returned an unsuccessful ServiceResponse`)),nr(l.responseObject)||s("ATTESTATION_RESPONSE_INVALID",`${e.failureContext} returned a ServiceResponse without responseObject`,{details:{status:i.status,envelopeSnippet:ir(l)}}),l.responseObject}function rr(e){try{return JSON.parse(e)}catch{return}}function et(e,t,r){let n={status:t,statusCode:r.statusCode,message:r.message,responseObject:r.responseObject};s("SERVICE_RESPONSE_ERROR",`${e} returned an unsuccessful ServiceResponse`,{details:n})}function nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ir(e){return JSON.stringify(e).slice(0,tr)}function or(e,t){let r=new URL(e);return r.pathname=`${r.pathname.replace(/\/+$/u,"")}${t}`,r.search="",r.toString()}async function Z(e){let t=Ze(e.callerAddress),r=await H({attestationServiceUrl:e.attestationServiceUrl,trust:e.trust,fetch:e.fetch,subtle:e.subtle,getRandomValues:e.getRandomValues,now:e.now,onWarning:e.onWarning,timeoutMs:e.timeoutMs,platform:e.platform,actionType:e.actionType,sessionMaterial:e.sessionMaterial});return D({attestationServiceUrl:e.attestationServiceUrl,path:"/identity",fetch:e.fetch,failureContext:"POST /identity",timeoutMs:e.timeoutMs,body:{platform:e.platform,actionType:e.actionType,callerAddress:t,encryptedSessionMaterial:r,params:e.params}})}async function ee(e){let t=await F(e);return D({attestationServiceUrl:e.attestationServiceUrl,path:`/seller/credentials/${encodeURIComponent(e.platform)}`,fetch:e.fetch,failureContext:"POST /seller/credentials",timeoutMs:e.timeoutMs,body:{encryptedUpload:t}})}async function te(e){let t=await M(e);return D({attestationServiceUrl:e.attestationServiceUrl,path:`/buyer/verify/${encodeURIComponent(e.platform)}/${encodeURIComponent(e.actionType)}`,fetch:e.fetch,failureContext:"POST /buyer/verify",timeoutMs:e.timeoutMs,body:{encryptedSessionMaterial:t,params:e.params,chainId:e.chainId,intent:e.intent}})}async function re(e){let t=await v(e);return D({attestationServiceUrl:e.attestationServiceUrl,path:`/dispute/verify/${encodeURIComponent(e.platform)}/${encodeURIComponent(e.actionType)}`,fetch:e.fetch,failureContext:"POST /dispute/verify",timeoutMs:e.timeoutMs,body:{encryptedSessionMaterial:t,params:e.params,chainId:e.chainId,intentHash:e.intentHash}})}function rt(e){let t=Xe[e.environment],r=e.attestationServiceUrl??t.attestationServiceUrl,n=tt({strictPin:!0},e.trust),o=i=>({...i,attestationServiceUrl:i.attestationServiceUrl??r,trust:tt(n,i.trust),fetch:i.fetch??e.fetch,subtle:i.subtle??e.subtle,getRandomValues:i.getRandomValues??e.getRandomValues,now:i.now??e.now,onWarning:i.onWarning??e.onWarning,timeoutMs:i.timeoutMs??e.timeoutMs}),a=i=>({...i,subtle:i.subtle??e.subtle,getRandomValues:i.getRandomValues??e.getRandomValues});return{createEncryptedBuyerTeeSessionMaterial:i=>M(o(i)),createEncryptedIdentitySessionMaterial:i=>H(o(i)),createEncryptedDisputeSessionMaterial:i=>v(o(i)),createEncryptedSellerCredentialUpload:i=>F(o(i)),requestIdentityAttestation:i=>Z(o(i)),uploadSellerCredential:i=>ee(o(i)),verifyBuyerTeePayment:i=>{let u=o(i);return te(u)},verifyDispute:i=>re(o(i)),fetchAndVerifyAttestation:(i={})=>K(o(i)),encryptBuyerTeeSessionMaterial:i=>w(a(i)),encryptIdentitySessionMaterial:i=>B(a(i)),encryptDisputeSessionMaterial:i=>V(a(i)),encryptSellerCredentialUpload:i=>L({...a(i),now:i.now??e.now})}}function tt(e,t){return t?{...e,...t,expectedPcr8ByHost:{...e.expectedPcr8ByHost,...t.expectedPcr8ByHost}}:e}var p=require("ethers");var sr={name:"UnifiedPaymentVerifier",version:"1"},Te={PaymentAttestation:[{name:"intentHash",type:"bytes32"},{name:"releaseAmount",type:"uint256"},{name:"dataHash",type:"bytes32"}]},ar="PaymentAttestation(bytes32 intentHash,uint256 releaseAmount,bytes32 dataHash)",nt=y(ar),cr={name:"ZKP2P DisputeVerifier",version:"1"},Se={DisputeAttestation:[{name:"intentHash",type:"bytes32"},{name:"dataHash",type:"bytes32"}]},ur="DisputeAttestation(bytes32 intentHash,bytes32 dataHash)",it=y(ur),Ee={name:"ZKP2PIdentityVerifier",version:"1"},ge={IdentityAttestation:[{name:"method",type:"bytes32"},{name:"actionType",type:"bytes32"},{name:"callerAddress",type:"address"},{name:"payeeIdHash",type:"bytes32"},{name:"dataHash",type:"bytes32"},{name:"issuedAt",type:"uint256"},{name:"validUntil",type:"uint256"}]},dr="IdentityAttestation(bytes32 method,bytes32 actionType,address callerAddress,bytes32 payeeIdHash,bytes32 dataHash,uint256 issuedAt,uint256 validUntil)",ot=y(dr),st=p.TypedDataEncoder.hashDomain(Ee).toLowerCase(),at={name:"ZKP2P Seller Credential Bundle",version:"1"},ct={SellerCredentialBundle:[{name:"platform",type:"string"},{name:"payeeIdHash",type:"bytes32"},{name:"encryptedBlobHash",type:"bytes32"},{name:"encryptedDataKeyHash",type:"bytes32"},{name:"nonceHash",type:"bytes32"},{name:"credentialType",type:"string"},{name:"credentialValidatedAt",type:"string"},{name:"credentialExpiresAt",type:"string"}]};function lr(e){return{...sr,chainId:e.chainId,verifyingContract:(0,p.getAddress)(e.verifyingContract)}}function ne(e){return p.TypedDataEncoder.hashDomain(lr(e)).toLowerCase()}function pr(e){return{...cr,chainId:e.chainId,verifyingContract:(0,p.getAddress)(e.verifyingContract)}}function ie(e){return p.TypedDataEncoder.hashDomain(pr(e)).toLowerCase()}function y(e){return(0,p.keccak256)((0,p.toUtf8Bytes)(e)).toLowerCase()}function oe(e){return(0,p.keccak256)(e).toLowerCase()}function se(e){try{let t=p.TypedDataEncoder.from(e.types).hash(e.value),r=(0,p.keccak256)((0,p.concat)(["0x1901",e.domainSeparator,t]));return N((0,p.recoverAddress)(r,e.signature))}catch(t){s("ATTESTATION_SIGNATURE_INVALID","Unable to recover signer from attestation signature",{cause:t})}}function ae(e){try{return N((0,p.verifyTypedData)(e.domain,e.types,e.value,e.signature))}catch(t){s("ATTESTATION_SIGNATURE_INVALID","Unable to verify attestation signature",{cause:t})}}function Ie(e,t){let r=N(e),n=new Set(t.map(o=>N(o)));return n.has(r)||s("SIGNER_NOT_TRUSTED","Recovered signer is not in trustedSigners",{details:{recoveredSigner:r,trustedSigners:Array.from(n)}}),r}function k(e){let t=Ie(e.recoveredSigner,e.trustedSigners),r=N(e.payloadSigner);return r!==t&&s("ATTESTATION_SIGNATURE_INVALID","Payload signer does not match the recovered signer",{details:{payloadSigner:r,recoveredSigner:t}}),t}function d(e,t,r){e.toLowerCase()!==t.toLowerCase()&&s("ATTESTATION_BINDING_MISMATCH",`${r} did not match expected value`,{details:{actual:e,expected:t}})}function ut(e,t,r){let n,o;try{n=N(e),o=N(t)}catch(a){s("INVALID_PARAMETER",`${r} must be a valid Ethereum address`,{cause:a})}n!==o&&s("ATTESTATION_BINDING_MISMATCH",`${r} did not match expected value`,{details:{actual:e,expected:t}})}function m(e,t,r){e!==t&&s("ATTESTATION_BINDING_MISMATCH",`${r} did not match expected value`,{details:{actual:e,expected:t}})}function Y(e,t){JSON.stringify(e)!==JSON.stringify(t)&&s("ATTESTATION_BINDING_MISMATCH","typedDataSpec.types did not match the expected EIP-712 types")}function I(e,t){return typeof e!="string"&&s("INVALID_PARAMETER",`${t} is required`),e}function N(e){return(0,p.getAddress)(e).toLowerCase()}function dt(e,t){m(e.platform,t.expectedPlatform,"platform"),m(e.actionType,t.expectedActionType,"actionType"),m(e.typedDataSpec.primaryType,"PaymentAttestation","typedDataSpec.primaryType"),Y(e.typedDataSpec.types,Te),d(e.typeHash,nt,"typeHash"),d(e.domainSeparator,ne(t.expectedDomain),"domainSeparator"),d(oe(e.encodedPaymentDetails),e.typedDataValue.dataHash,"encodedPaymentDetails"),d(e.typedDataValue.intentHash,I(t.expectedIntentHash,"expectedIntentHash"),"typedDataValue.intentHash");let r=se({domainSeparator:e.domainSeparator,types:Te,value:{...e.typedDataValue},signature:e.signature});return k({payloadSigner:e.signer,recoveredSigner:r,trustedSigners:t.trustedSigners}),e}var lt=require("ethers");var fr="tuple(bytes32 paymentMethod,bytes32 originalPaymentId,bytes32 disputeId,uint256 paymentAmount,bytes32 paymentCurrency)";function pt(e,t){m(e.platform,t.expectedPlatform,"platform"),m(e.actionType,t.expectedActionType,"actionType"),m(e.typedDataSpec.primaryType,"DisputeAttestation","typedDataSpec.primaryType"),Y(e.typedDataSpec.types,Se),d(e.typeHash,it,"typeHash"),d(e.domainSeparator,ie(t.expectedDomain),"domainSeparator"),d(e.typedDataValue.intentHash,I(t.expectedIntentHash,"expectedIntentHash"),"typedDataValue.intentHash"),d(oe(e.encodedDisputeDetails),e.typedDataValue.dataHash,"encodedDisputeDetails"),d(e.disputeDetails.paymentMethod,y(e.platform),"paymentMethod"),yr(e);let r=se({domainSeparator:e.domainSeparator,types:Se,value:{...e.typedDataValue},signature:e.signature});return k({payloadSigner:e.signer,recoveredSigner:r,trustedSigners:t.trustedSigners}),e}function yr(e){let t;try{let r=e.disputeDetails;t=lt.AbiCoder.defaultAbiCoder().encode([fr],[[r.paymentMethod,r.originalPaymentId,r.disputeId,r.paymentAmount,r.paymentCurrency]])}catch(r){s("ATTESTATION_RESPONSE_INVALID","disputeDetails could not be ABI encoded",{cause:r})}d(e.encodedDisputeDetails,t,"disputeDetails")}var mr=["platform","actionType","payeeId","username","metadata"];function ft(e,t){m(e.platform,t.expectedPlatform,"platform"),m(e.actionType,t.expectedActionType,"actionType"),m(e.identity.platform,e.platform,"identity.platform"),m(e.identity.actionType,e.actionType,"identity.actionType"),m(e.typedDataSpec.primaryType,"IdentityAttestation","typedDataSpec.primaryType"),Y(e.typedDataSpec.types,ge),d(e.domainSeparator,st,"domainSeparator"),d(e.typeHash,ot,"typeHash"),d(e.identity.method,y(e.identity.platform),"identity.method"),d(e.identity.payeeIdHash,y(e.identity.payeeId),"identity.payeeIdHash"),d(e.typedDataValue.method,e.identity.method,"typedDataValue.method"),d(e.typedDataValue.actionType,y(e.identity.actionType),"typedDataValue.actionType"),ut(e.typedDataValue.callerAddress,I(t.expectedCallerAddress,"expectedCallerAddress"),"typedDataValue.callerAddress"),d(e.typedDataValue.payeeIdHash,e.identity.payeeIdHash,"typedDataValue.payeeIdHash"),d(e.typedDataValue.payeeIdHash,I(t.expectedPayeeIdHash,"expectedPayeeIdHash"),"typedDataValue.payeeIdHash"),d(e.typedDataValue.dataHash,Ar(e.identity),"typedDataValue.dataHash"),Sr(e.typedDataValue.validUntil,t.now??Date.now);let r=ae({domain:Ee,types:ge,value:{...e.typedDataValue},signature:e.signature});return k({payloadSigner:e.signer,recoveredSigner:r,trustedSigners:t.trustedSigners}),e.identity}function Ar(e){let t={platform:e.platform,actionType:e.actionType,payeeId:e.payeeId,username:e.username,metadata:Tr(e.metadata)},r=JSON.stringify(Object.fromEntries(mr.map(n=>[n,t[n]])));return y(r)}function Tr(e){return Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)))}function Sr(e,t){let r=t();BigInt(r)>BigInt(e)&&s("ATTESTATION_EXPIRED","Identity attestation validUntil is in the past",{details:{validUntil:e,nowMs:r}})}function yt(e,t){m(e.platform,t.expectedPlatform,"platform"),d(e.payeeIdHash,I(t.expectedPayeeIdHash,"expectedPayeeIdHash"),"payeeIdHash"),gr(e.credentialExpiresAt,t.now??Date.now);let r=ae({domain:at,types:ct,value:Er(e),signature:e.bundleSignature});return Ie(r,t.trustedSigners),e}function Er(e){return{platform:e.platform,payeeIdHash:e.payeeIdHash,encryptedBlobHash:y(e.encryptedBlob),encryptedDataKeyHash:y(e.encryptedDataKey),nonceHash:y(e.nonce),credentialType:e.credentialType,credentialValidatedAt:e.credentialValidatedAt,credentialExpiresAt:e.credentialExpiresAt??""}}function gr(e,t){let r=t();e!==null&&BigInt(r)>BigInt(e)&&s("ATTESTATION_EXPIRED","Seller credential bundle credentialExpiresAt is in the past",{details:{credentialExpiresAt:e,nowMs:r}})}0&&(module.exports={AWS_NITRO_ROOT_FINGERPRINT_SHA256_HEX,AWS_NITRO_ROOT_PEM,NitroAttestationError,createEncryptedBuyerTeeSessionMaterial,createEncryptedDisputeSessionMaterial,createEncryptedIdentitySessionMaterial,createEncryptedSellerCredentialUpload,createNitroAttestationClient,encryptBuyerTeeSessionMaterial,encryptDisputeSessionMaterial,encryptIdentitySessionMaterial,encryptSellerCredentialUpload,fetchAndVerifyAttestation,getDisputeVerifierDomainSeparator,getUnifiedPaymentVerifierDomainSeparator,hashUtf8,requestIdentityAttestation,uploadSellerCredential,verifyBuyerTeePayment,verifyBuyerTeePaymentAttestation,verifyDispute,verifyDisputeAttestation,verifyIdentityAttestation,verifySellerCredentialBundle});
15
+ `,G="641a0321a3e244efe456463195d606317ed7cdcc3c1756e09893f3c68f79bb5b";var Vt=10080*60*1e3;async function Me(e){let t=he(e.subtle,e.getRandomValues),r=pe(e.rootPem??Q,"AWS Nitro root certificate"),n=await fe(r,e.subtle);n!==G&&s("AWS_ROOT_FINGERPRINT_MISMATCH","Bundled AWS Nitro root certificate fingerprint mismatch",{details:{expected:G,actual:n}});let o=pe(e.leafCertificateDer,"attestation leaf certificate"),a=e.cabundleDer.map((f,A)=>pe(f,`cabundle[${A}]`)),i=[r,...a,o];for(let f of i)Ht(f,e.nowMs),Lt(f,e.nowMs,e.onWarning);let u=await fe(o,e.subtle),l=[];for(let f of a){let A=await fe(f,e.subtle);A!==u&&A!==n&&l.push(f)}let c=[[o,...l.slice().reverse(),r],[o,...l,r]];for(let f of c)if(await Bt(f,t)){let A=await S(o.publicKey.export({name:"ECDSA",namedCurve:"P-384"},["verify"],t),"CERT_CHAIN_INVALID","Failed to export attestation leaf public key");return{leafCertificate:o,leafPublicKey:A}}s("CERT_CHAIN_INVALID","Attestation certificate chain does not verify to the pinned AWS Nitro root")}async function Bt(e,t){for(let r=0;r<e.length-1;r+=1){let n=e[r],o=e[r+1];if(!await n.verify({publicKey:o.publicKey,signatureOnly:!0},t))return!1}return e.length>0&&await e[e.length-1].isSelfSigned(t)}function pe(e,t){try{return new we.X509Certificate(e)}catch(r){s("CERT_CHAIN_INVALID",`Could not parse ${t}`,{cause:r})}}async function fe(e,t){return E(new Uint8Array(await t.digest("SHA-256",e.rawData)))}function Ht(e,t){(t<e.notBefore.getTime()||t>e.notAfter.getTime())&&s("CERT_NOT_TIME_VALID","Certificate is outside its validity window",{details:{subject:e.subject,notBefore:e.notBefore.toISOString(),notAfter:e.notAfter.toISOString()}})}function Lt(e,t,r){e.notAfter.getTime()<t+Vt&&r?.({code:"CERT_VALIDITY_NEAR_EXPIRY",message:"Certificate in Nitro attestation chain expires within 7 days",details:{subject:e.subject,notAfter:e.notAfter.toISOString()}})}function $(e){let t=new ye(e),r=t.readValue();if(!t.done())throw new Error("Trailing CBOR bytes");return r}function Z(e){if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new Error("CBOR number must be a safe integer");return e>=0?x(0,e):x(1,-1-e)}if(typeof e=="bigint")return e>=0n?x(0,e):x(1,-1n-e);if(typeof e=="string"){let t=P(e);return h([x(3,t.length),t])}if(e instanceof Uint8Array)return h([x(2,e.length),e]);if(Array.isArray(e))return h([x(4,e.length),...e.map(Z)]);if(e instanceof Map)return h([x(5,e.size),...Array.from(e.entries()).flatMap(([t,r])=>[Z(t),Z(r)])]);if(typeof e=="boolean")return new Uint8Array([e?245:244]);if(e===null)return new Uint8Array([246]);throw new Error("Unsupported CBOR value")}function ve(e,t){return Z(["Signature1",e,new Uint8Array,t])}function x(e,t){let r=BigInt(t);return r<24n?new Uint8Array([e<<5|Number(r)]):r<=0xffn?new Uint8Array([e<<5|24,Number(r)]):r<=0xffffn?new Uint8Array([e<<5|25,Number(r>>8n&0xffn),Number(r&0xffn)]):r<=0xffffffffn?new Uint8Array([e<<5|26,Number(r>>24n&0xffn),Number(r>>16n&0xffn),Number(r>>8n&0xffn),Number(r&0xffn)]):new Uint8Array([e<<5|27,Number(r>>56n&0xffn),Number(r>>48n&0xffn),Number(r>>40n&0xffn),Number(r>>32n&0xffn),Number(r>>24n&0xffn),Number(r>>16n&0xffn),Number(r>>8n&0xffn),Number(r&0xffn)])}var ye=class{constructor(t){this.bytes=t}bytes;offset=0;done(){return this.offset===this.bytes.length}readValue(){let t=this.readByte(),r=t>>5,n=t&31;if(n===31)return this.readIndefiniteValue(r);if(r===0)return this.readLength(n);if(r===1){let o=this.readLength(n);return typeof o=="bigint"?-1n-o:-1-o}if(r===2){let o=this.lengthAsNumber(this.readLength(n));return this.readBytes(o)}if(r===3){let o=this.lengthAsNumber(this.readLength(n));return U(this.readBytes(o))}if(r===4){let o=this.lengthAsNumber(this.readLength(n)),a=[];for(let i=0;i<o;i+=1)a.push(this.readValue());return a}if(r===5){let o=this.lengthAsNumber(this.readLength(n)),a=new Map;for(let i=0;i<o;i+=1)a.set(this.readValue(),this.readValue());return a}if(r===6)return this.readLength(n),this.readValue();if(r===7){if(n===20)return!1;if(n===21)return!0;if(n===22)return null}throw new Error(`Unsupported CBOR major/additional type: ${r}/${n}`)}readIndefiniteValue(t){if(t===2){let r=[];for(;!this.consumeBreak();){let n=this.readValue();if(!(n instanceof Uint8Array))throw new Error("Indefinite CBOR byte string chunk must be a byte string");r.push(n)}return h(r)}if(t===3){let r="";for(;!this.consumeBreak();){let n=this.readValue();if(typeof n!="string")throw new Error("Indefinite CBOR text string chunk must be a text string");r+=n}return r}if(t===4){let r=[];for(;!this.consumeBreak();)r.push(this.readValue());return r}if(t===5){let r=new Map;for(;!this.consumeBreak();){let n=this.readValue();if(this.peekBreak())throw new Error("Indefinite CBOR map ended after a key");r.set(n,this.readValue())}return r}throw new Error(`Indefinite CBOR major type ${t} is not supported`)}readLength(t){if(t<24)return t;if(t===24)return this.readByte();if(t===25)return this.readByte()<<8|this.readByte();if(t===26)return this.readByte()*16777216+(this.readByte()<<16)+(this.readByte()<<8)+this.readByte()>>>0;if(t===27){let r=0n;for(let n=0;n<8;n+=1)r=r<<8n|BigInt(this.readByte());return r<=BigInt(Number.MAX_SAFE_INTEGER)?Number(r):r}throw new Error("Indefinite CBOR lengths are not supported")}readByte(){if(this.offset>=this.bytes.length)throw new Error("Unexpected end of CBOR input");return this.bytes[this.offset++]}peekBreak(){return this.offset<this.bytes.length&&this.bytes[this.offset]===255}consumeBreak(){return this.peekBreak()?(this.offset+=1,!0):!1}readBytes(t){if(this.offset+t>this.bytes.length)throw new Error("Unexpected end of CBOR byte string");let r=this.bytes.slice(this.offset,this.offset+t);return this.offset+=t,r}lengthAsNumber(t){if(typeof t=="bigint")throw new Error("CBOR length exceeds JavaScript safe integer range");return t}};function Ve(e){let t=e[0]===210?e.slice(1):e,r;try{r=$(t)}catch(u){s("COSE_STRUCTURE_INVALID","Attestation document is not a valid COSE_Sign1 CBOR value",{cause:u})}(!Array.isArray(r)||r.length!==4)&&s("COSE_STRUCTURE_INVALID","COSE_Sign1 must be [protected, unprotected, payload, signature]");let[n,o,a,i]=r;return(!(n instanceof Uint8Array)||!(o instanceof Map)||!(a instanceof Uint8Array)||!(i instanceof Uint8Array))&&s("COSE_STRUCTURE_INVALID","COSE_Sign1 fields have invalid CBOR types"),Ft(n),i.length!==96&&s("COSE_SIGNATURE_INVALID_SIZE",`Expected a 96-byte ES384 signature, got ${i.length} bytes`),{protectedHeadersBytes:n,payloadBytes:a,signature:i}}async function Be(e){let t=ve(e.protectedHeadersBytes,e.payloadBytes);await S(e.subtle.verify({name:"ECDSA",hash:"SHA-384"},e.leafPublicKey,e.signature,t),"COSE_SIGNATURE_VERIFY_FAILED","COSE_Sign1 signature verification failed")||s("COSE_SIGNATURE_VERIFY_FAILED","COSE_Sign1 signature does not verify with the attestation leaf certificate")}function Ft(e){let t;try{t=$(e)}catch(r){s("COSE_STRUCTURE_INVALID","COSE protected headers are not a valid CBOR map",{cause:r})}t instanceof Map||s("COSE_STRUCTURE_INVALID","COSE protected headers must be a CBOR map"),t.get(1)!==-35&&s("COSE_ALG_UNSUPPORTED","COSE protected header alg must be -35 (ES384)")}var me=96;function C(e,t){let r=e.replace(/^0x/i,"").toLowerCase();return(r.length!==me||!/^[0-9a-f]+$/.test(r))&&s("TRUST_PIN_REQUIRED",`${t} must be ${me} lowercase hex characters`),r}function He(e,t){let r=C(e,t);return e!==r&&s("ATTESTATION_RESPONSE_INVALID",`${t} must be ${me} lowercase hex characters`),r}var Le=256*1024,kt=3,Yt=150,Wt=/^0x[0-9a-fA-F]{40}$/;function Gt(e,t){let r=new URL(e),n=r.pathname.replace(/\/+$/,"");return r.pathname=n.endsWith("/attestation")?n:`${n}/attestation`,r.search="",r.searchParams.set("nonce",t),r}async function We(e){let t=Gt(e.attestationServiceUrl,e.nonceHex),r=await jt(t.toString(),e.fetch,e.timeoutMs),n=await qt(r);r.ok||s("ATTESTATION_FETCH_FAILED",`GET /attestation failed with HTTP ${r.status}`,{details:{status:r.status,body:n.slice(0,400)}});let o;try{o=JSON.parse(n)}catch(a){s("ATTESTATION_RESPONSE_INVALID","GET /attestation returned non-JSON response",{cause:a})}return $t(o)}function $t(e){(!Ye(e)||e.success!==!0||!Ye(e.responseObject))&&s("ATTESTATION_RESPONSE_INVALID","Expected { success: true, responseObject: {...} }");let t=e.responseObject;(typeof t.attestationDocument!="string"||typeof t.nonce!="string")&&s("ATTESTATION_RESPONSE_INVALID","Attestation response is missing attestationDocument or nonce");let r;try{r=xe(t.attestationDocument)}catch(n){s("ATTESTATION_RESPONSE_INVALID","attestationDocument is not valid base64",{cause:n})}return r.length===0&&s("ATTESTATION_RESPONSE_INVALID","attestationDocument decoded to empty bytes"),{attestationDocument:r,nonce:t.nonce.toLowerCase(),advertised:{chainId:typeof t.chainId=="number"?t.chainId:void 0,verifyingContract:ke(t.verifyingContract,"verifyingContract"),expectedSigner:ke(t.expectedSigner,"expectedSigner"),expectedPcr8:Kt(t.expectedPcr8,"expectedPcr8")}}}async function qt(e){if(!e.body){let o=await e.text();return Fe(P(o).length),o}let t=e.body.getReader(),r=[],n=0;for(;;){let{done:o,value:a}=await t.read();if(o)break;a&&(n+=a.length,Fe(n),r.push(a))}return U(h(r))}function Fe(e){e>Le&&s("ATTESTATION_RESPONSE_INVALID","GET /attestation response exceeded maximum size",{details:{maxBytes:Le,actualBytes:e}})}function ke(e,t){if(e!==void 0)return(typeof e!="string"||!Wt.test(e))&&s("ATTESTATION_RESPONSE_INVALID",`${t} must be a 0x-prefixed 20-byte hex address`),e.toLowerCase()}function Kt(e,t){if(e!==void 0){typeof e!="string"&&s("ATTESTATION_RESPONSE_INVALID",`${t} must be a 96-character lowercase hex string`);try{return He(e,t)}catch(r){s("ATTESTATION_RESPONSE_INVALID",`${t} must be a 96-character lowercase hex string`,{cause:r})}}}async function jt(e,t,r){let n=1;for(;;)try{return await zt(e,t,r)}catch(o){if(!Xt(o)||n>=kt)throw o;await Jt(Yt*n),n+=1}}async function zt(e,t,r){let n=typeof AbortController<"u"?new AbortController:void 0,o,a=new Promise((i,u)=>{o=setTimeout(()=>{n?.abort(),u(new Error("timeout"))},r)});try{let i=await Promise.race([t(e,{headers:{accept:"application/json"},signal:n?.signal}),a]);return o!==void 0&&clearTimeout(o),i}catch(i){o!==void 0&&clearTimeout(o),i instanceof Error&&(i.name==="AbortError"||i.message==="timeout")&&s("TIMEOUT",`GET /attestation timed out after ${r}ms`,{cause:i}),s("ATTESTATION_FETCH_FAILED","GET /attestation failed at the network layer",{cause:i,details:{layer:"network"}})}}function Xt(e){return e instanceof R&&e.code==="ATTESTATION_FETCH_FAILED"&&e.details?.layer==="network"}function Jt(e){return new Promise(t=>setTimeout(t,e))}function Ye(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Qt=32;function Ge(e){return E(e(new Uint8Array(Qt)))}function $e(e,t){e.toLowerCase()!==t&&s("ATTESTATION_NONCE_MISMATCH","Attestation service echoed a different nonce",{details:{expectedNonce:t,echoedNonce:e}})}function Ke(e){let t;try{t=$(e)}catch(a){s("PAYLOAD_FIELD_MISSING","Attestation payload is not a valid CBOR map",{cause:a})}let r=qe(t,"payload"),n=qe(r.get("pcrs"),"pcrs"),o=q(r.get("user_data"),"user_data");return{timestampMs:Zt(r.get("timestamp")),nonceHex:U(o),pcr0Hex:Ae(n,0),pcr1Hex:Ae(n,1),pcr2Hex:Ae(n,2),pcr8Hex:E(q(n.get(8),"pcrs[8]")),certificateDer:q(r.get("certificate"),"certificate"),cabundleDer:er(r.get("cabundle"),"cabundle").map((a,i)=>q(a,`cabundle[${i}]`)),publicKeyDer:q(r.get("public_key"),"public_key")}}function Ae(e,t){let r=e.get(t);return r instanceof Uint8Array?E(r):""}function Zt(e){if(typeof e=="number"&&Number.isSafeInteger(e)&&e>=0)return e;s("PAYLOAD_FIELD_MISSING","Attestation payload timestamp must be an unsigned safe integer")}function qe(e,t){if(e instanceof Map)return e;s("PAYLOAD_FIELD_MISSING",`Attestation payload field ${t} must be a CBOR map`)}function q(e,t){if(e instanceof Uint8Array)return e;s("PAYLOAD_FIELD_MISSING",`Attestation payload field ${t} must be a byte string`)}function er(e,t){if(Array.isArray(e))return e;s("PAYLOAD_FIELD_MISSING",`Attestation payload field ${t} must be an array`)}var tr="https://attestation-service-staging.zkp2p.xyz",rr="https://attestation-service.zkp2p.xyz",je="5636e3bd96f847cf12cfd9de7faa8cad0e6fa00962ce16ba185f8e5ea57105abb3cc9cc34f1e1e4de3444ceabcca7485",ze="41a4ae0b9b96752cab5addb7d22689b3070e564e29f90a54316fa33fa38ea51387a6e887ea4f5a4b0cc34f69cea3f40e",Xe={"attestation-service-staging.zkp2p.xyz":C(je,"bundled staging PCR8"),"attestation-service.zkp2p.xyz":C(ze,"bundled production PCR8")},Je={staging:{attestationServiceUrl:tr,expectedPcr8Hex:je},production:{attestationServiceUrl:rr,expectedPcr8Hex:ze}};function Qe(e){let{trust:t,advertisedExpectedPcr8:r,onWarning:n}=e,o=e.hostname.toLowerCase();if(t?.expectedPcr8Hex)return C(t.expectedPcr8Hex,"trust.expectedPcr8Hex");let a=t?.expectedPcr8ByHost,i=a?nr(a,o):void 0;if(i)return C(i,`trust.expectedPcr8ByHost[${o}]`);let u=Xe[o];if(u)return u;if(t?.strictPin===!0&&s("TRUST_PIN_REQUIRED",`No trusted PCR8 pin is configured for ${o}`),r){let l=C(r,"service-advertised expectedPcr8");return n?.({code:"TRUST_PIN_NOT_PROVIDED",message:`No caller or bundled PCR8 pin was available for ${o}; falling back to service-advertised expectedPcr8`,details:{hostname:o,expectedPcr8:l}}),l}s("TRUST_PIN_REQUIRED",`No trusted or service-advertised PCR8 pin is available for ${o}`)}function nr(e,t){for(let[r,n]of Object.entries(e))if(r.toLowerCase()===t)return n}var ir=300*1e3;async function b(e){return(await K(e)).attestedSellerUploadKey}async function K(e){let t=z(e.fetch),r=T(e),n=e.now??Date.now,o=Ge(r.getRandomValues),a=await We({attestationServiceUrl:e.attestationServiceUrl,nonceHex:o,fetch:t,timeoutMs:e.timeoutMs??1e4});$e(a.nonce,o);let{protectedHeadersBytes:i,payloadBytes:u,signature:l}=Ve(a.attestationDocument),c=Ke(u);c.nonceHex!==o&&s("NONCE_BINDING_FAILED","Attestation payload user_data did not match the request nonce",{details:{expectedNonce:o,payloadNonce:c.nonceHex}});let f=e.trust?.freshnessWindowMs??ir,A=n();Math.abs(A-c.timestampMs)>f&&s("FRESHNESS_CHECK_FAILED",`Attestation timestamp skew exceeds ${f}ms`,{details:{timestampMs:c.timestampMs,nowMs:A,freshnessWindowMs:f}});let ue=new URL(e.attestationServiceUrl).hostname,_=Qe({trust:e.trust,hostname:ue,advertisedExpectedPcr8:a.advertised.expectedPcr8,onWarning:e.onWarning});c.pcr8Hex!==_&&s("PCR8_PIN_MISMATCH","Attestation PCR8 does not match the trusted pin",{details:{expectedPcr8:_,actualPcr8:c.pcr8Hex}});let{leafPublicKey:Et}=await Me({leafCertificateDer:c.certificateDer,cabundleDer:c.cabundleDer,rootPem:e.trust?.awsNitroRootPem,nowMs:A,subtle:r.subtle,getRandomValues:r.getRandomValues,onWarning:e.onWarning});return await Be({protectedHeadersBytes:i,payloadBytes:u,signature:l,leafPublicKey:Et,subtle:r.subtle}),{attestedSellerUploadKey:{publicKeyDer:c.publicKeyDer,publicKeySha256Hex:E(new Uint8Array(await r.subtle.digest("SHA-256",g(c.publicKeyDer))))},payload:{timestampMs:c.timestampMs,pcr0Hex:c.pcr0Hex,pcr1Hex:c.pcr1Hex,pcr2Hex:c.pcr2Hex,pcr8Hex:c.pcr8Hex,nonceHex:c.nonceHex,advertised:a.advertised}}}async function M(e){return w({...e,key:await b(e)})}async function v(e){let t=T(e);return Ue({request:e,subtle:t.subtle,getRandomValues:t.getRandomValues})}async function V(e){return v({key:await b(e),platform:e.platform,actionType:e.actionType,sessionMaterial:e.sessionMaterial,subtle:e.subtle,getRandomValues:e.getRandomValues})}async function B(e){let t=T(e);return _e({request:e,subtle:t.subtle,getRandomValues:t.getRandomValues})}async function H(e){return B({key:await b(e),platform:e.platform,actionType:e.actionType,sessionMaterial:e.sessionMaterial,subtle:e.subtle,getRandomValues:e.getRandomValues})}async function L(e){let t=T(e);return Re({request:e,subtle:t.subtle,getRandomValues:t.getRandomValues,now:e.now??Date.now})}async function F(e){return L({...e,key:await b(e)})}var Ze=require("ethers");function et(e){try{return(0,Ze.getAddress)(e)}catch(t){s("INVALID_PARAMETER","callerAddress must be a valid Ethereum address",{cause:t})}}var or=400;async function D(e){let t=z(e.fetch),r=e.timeoutMs??1e4,n=new AbortController,o,a=new Promise((c,f)=>{o=setTimeout(()=>{n.abort(),f(new Error("timeout"))},r)}),i,u;try{i=await Promise.race([t(ur(e.attestationServiceUrl,e.path),{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:n.signal}),a]),u=await Promise.race([i.text(),a])}catch(c){n.signal.aborted&&s("TIMEOUT",`${e.failureContext} timed out after ${r}ms`,{cause:c}),s("ATTESTATION_FETCH_FAILED",`${e.failureContext} failed at the network layer`,{cause:c})}finally{clearTimeout(o)}if(!i.ok){let c=sr(u);c?.success===!1&&tt(e.failureContext,i.status,c),s("ATTESTATION_FETCH_FAILED",`${e.failureContext} failed with HTTP ${i.status}`,{details:{status:i.status,body:u.slice(0,400)}})}let l;try{l=JSON.parse(u)}catch(c){s("ATTESTATION_RESPONSE_INVALID",`${e.failureContext} returned a non-JSON ServiceResponse`,{cause:c})}return l.success!==!0&&(l.success===!1&&tt(e.failureContext,i.status,l),s("ATTESTATION_RESPONSE_INVALID",`${e.failureContext} returned an unsuccessful ServiceResponse`)),ar(l.responseObject)||s("ATTESTATION_RESPONSE_INVALID",`${e.failureContext} returned a ServiceResponse without responseObject`,{details:{status:i.status,envelopeSnippet:cr(l)}}),l.responseObject}function sr(e){try{return JSON.parse(e)}catch{return}}function tt(e,t,r){let n={status:t,statusCode:r.statusCode,message:r.message,responseObject:r.responseObject};s("SERVICE_RESPONSE_ERROR",`${e} returned an unsuccessful ServiceResponse`,{details:n})}function ar(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cr(e){return JSON.stringify(e).slice(0,or)}function ur(e,t){let r=new URL(e);return r.pathname=`${r.pathname.replace(/\/+$/u,"")}${t}`,r.search="",r.toString()}async function ee(e){let t=et(e.callerAddress),r=await H({attestationServiceUrl:e.attestationServiceUrl,trust:e.trust,fetch:e.fetch,subtle:e.subtle,getRandomValues:e.getRandomValues,now:e.now,onWarning:e.onWarning,timeoutMs:e.timeoutMs,platform:e.platform,actionType:e.actionType,sessionMaterial:e.sessionMaterial});return D({attestationServiceUrl:e.attestationServiceUrl,path:"/identity",fetch:e.fetch,failureContext:"POST /identity",timeoutMs:e.timeoutMs,body:{platform:e.platform,actionType:e.actionType,callerAddress:t,encryptedSessionMaterial:r,params:e.params}})}async function te(e){let t=await F(e);return D({attestationServiceUrl:e.attestationServiceUrl,path:`/seller/credentials/${encodeURIComponent(e.platform)}`,fetch:e.fetch,failureContext:"POST /seller/credentials",timeoutMs:e.timeoutMs,body:{encryptedUpload:t}})}async function re(e){let t=await M(e);return D({attestationServiceUrl:e.attestationServiceUrl,path:`/buyer/verify/${encodeURIComponent(e.platform)}/${encodeURIComponent(e.actionType)}`,fetch:e.fetch,failureContext:"POST /buyer/verify",timeoutMs:e.timeoutMs,body:{encryptedSessionMaterial:t,params:e.params,chainId:e.chainId,intent:e.intent}})}async function ne(e){let t=await V(e);return D({attestationServiceUrl:e.attestationServiceUrl,path:`/dispute/verify/${encodeURIComponent(e.platform)}/${encodeURIComponent(e.actionType)}`,fetch:e.fetch,failureContext:"POST /dispute/verify",timeoutMs:e.timeoutMs,body:{encryptedSessionMaterial:t,params:e.params,chainId:e.chainId,intentHash:e.intentHash}})}function nt(e){let t=Je[e.environment],r=e.attestationServiceUrl??t.attestationServiceUrl,n=rt({strictPin:!0},e.trust),o=i=>({...i,attestationServiceUrl:i.attestationServiceUrl??r,trust:rt(n,i.trust),fetch:i.fetch??e.fetch,subtle:i.subtle??e.subtle,getRandomValues:i.getRandomValues??e.getRandomValues,now:i.now??e.now,onWarning:i.onWarning??e.onWarning,timeoutMs:i.timeoutMs??e.timeoutMs}),a=i=>({...i,subtle:i.subtle??e.subtle,getRandomValues:i.getRandomValues??e.getRandomValues});return{createEncryptedBuyerTeeSessionMaterial:i=>M(o(i)),createEncryptedIdentitySessionMaterial:i=>H(o(i)),createEncryptedDisputeSessionMaterial:i=>V(o(i)),createEncryptedSellerCredentialUpload:i=>F(o(i)),requestIdentityAttestation:i=>ee(o(i)),uploadSellerCredential:i=>te(o(i)),verifyBuyerTeePayment:i=>{let u=o(i);return re(u)},verifyDispute:i=>ne(o(i)),fetchAndVerifyAttestation:(i={})=>K(o(i)),encryptBuyerTeeSessionMaterial:i=>w(a(i)),encryptIdentitySessionMaterial:i=>B(a(i)),encryptDisputeSessionMaterial:i=>v(a(i)),encryptSellerCredentialUpload:i=>L({...a(i),now:i.now??e.now})}}function rt(e,t){return t?{...e,...t,expectedPcr8ByHost:{...e.expectedPcr8ByHost,...t.expectedPcr8ByHost}}:e}var it=require("ethers"),j=Object.freeze({venmo:1209600,paypal:1209600,cashapp:0,monzo:0,wise:0,revolut:0,chime:0,zelle:0,monobank:0,alipay:0,upi:0,xmoney:0,mercadopago:0,mercury:0,n26:0});function ot(e){if(!Object.hasOwn(j,e))throw new Error(`Unknown dispute-window payment method: ${e}`);return j[e]}var dr=new Map(Object.entries(j).map(([e,t])=>[(0,it.id)(e),t]));function st(e){let t=dr.get(e.toLowerCase());if(t===void 0)throw new Error(`Unknown dispute-window payment method hash: ${e}`);return t}var p=require("ethers");var lr={name:"UnifiedPaymentVerifier",version:"1"},Se={PaymentAttestation:[{name:"intentHash",type:"bytes32"},{name:"releaseAmount",type:"uint256"},{name:"dataHash",type:"bytes32"}]},pr="PaymentAttestation(bytes32 intentHash,uint256 releaseAmount,bytes32 dataHash)",at=y(pr),fr={name:"ZKP2P DisputeVerifier",version:"1"},Ee={DisputeAttestation:[{name:"intentHash",type:"bytes32"},{name:"dataHash",type:"bytes32"}]},yr="DisputeAttestation(bytes32 intentHash,bytes32 dataHash)",ct=y(yr),ge={name:"ZKP2PIdentityVerifier",version:"1"},Ie={IdentityAttestation:[{name:"method",type:"bytes32"},{name:"actionType",type:"bytes32"},{name:"callerAddress",type:"address"},{name:"payeeIdHash",type:"bytes32"},{name:"dataHash",type:"bytes32"},{name:"issuedAt",type:"uint256"},{name:"validUntil",type:"uint256"}]},mr="IdentityAttestation(bytes32 method,bytes32 actionType,address callerAddress,bytes32 payeeIdHash,bytes32 dataHash,uint256 issuedAt,uint256 validUntil)",ut=y(mr),dt=p.TypedDataEncoder.hashDomain(ge).toLowerCase(),lt={name:"ZKP2P Seller Credential Bundle",version:"1"},pt={SellerCredentialBundle:[{name:"platform",type:"string"},{name:"payeeIdHash",type:"bytes32"},{name:"encryptedBlobHash",type:"bytes32"},{name:"encryptedDataKeyHash",type:"bytes32"},{name:"nonceHash",type:"bytes32"},{name:"credentialType",type:"string"},{name:"credentialValidatedAt",type:"string"},{name:"credentialExpiresAt",type:"string"}]};function Ar(e){return{...lr,chainId:e.chainId,verifyingContract:(0,p.getAddress)(e.verifyingContract)}}function ie(e){return p.TypedDataEncoder.hashDomain(Ar(e)).toLowerCase()}function Tr(e){return{...fr,chainId:e.chainId,verifyingContract:(0,p.getAddress)(e.verifyingContract)}}function oe(e){return p.TypedDataEncoder.hashDomain(Tr(e)).toLowerCase()}function y(e){return(0,p.keccak256)((0,p.toUtf8Bytes)(e)).toLowerCase()}function se(e){return(0,p.keccak256)(e).toLowerCase()}function ae(e){try{let t=p.TypedDataEncoder.from(e.types).hash(e.value),r=(0,p.keccak256)((0,p.concat)(["0x1901",e.domainSeparator,t]));return N((0,p.recoverAddress)(r,e.signature))}catch(t){s("ATTESTATION_SIGNATURE_INVALID","Unable to recover signer from attestation signature",{cause:t})}}function ce(e){try{return N((0,p.verifyTypedData)(e.domain,e.types,e.value,e.signature))}catch(t){s("ATTESTATION_SIGNATURE_INVALID","Unable to verify attestation signature",{cause:t})}}function Pe(e,t){let r=N(e),n=new Set(t.map(o=>N(o)));return n.has(r)||s("SIGNER_NOT_TRUSTED","Recovered signer is not in trustedSigners",{details:{recoveredSigner:r,trustedSigners:Array.from(n)}}),r}function k(e){let t=Pe(e.recoveredSigner,e.trustedSigners),r=N(e.payloadSigner);return r!==t&&s("ATTESTATION_SIGNATURE_INVALID","Payload signer does not match the recovered signer",{details:{payloadSigner:r,recoveredSigner:t}}),t}function d(e,t,r){e.toLowerCase()!==t.toLowerCase()&&s("ATTESTATION_BINDING_MISMATCH",`${r} did not match expected value`,{details:{actual:e,expected:t}})}function ft(e,t,r){let n,o;try{n=N(e),o=N(t)}catch(a){s("INVALID_PARAMETER",`${r} must be a valid Ethereum address`,{cause:a})}n!==o&&s("ATTESTATION_BINDING_MISMATCH",`${r} did not match expected value`,{details:{actual:e,expected:t}})}function m(e,t,r){e!==t&&s("ATTESTATION_BINDING_MISMATCH",`${r} did not match expected value`,{details:{actual:e,expected:t}})}function Y(e,t){JSON.stringify(e)!==JSON.stringify(t)&&s("ATTESTATION_BINDING_MISMATCH","typedDataSpec.types did not match the expected EIP-712 types")}function I(e,t){return typeof e!="string"&&s("INVALID_PARAMETER",`${t} is required`),e}function N(e){return(0,p.getAddress)(e).toLowerCase()}function yt(e,t){m(e.platform,t.expectedPlatform,"platform"),m(e.actionType,t.expectedActionType,"actionType"),m(e.typedDataSpec.primaryType,"PaymentAttestation","typedDataSpec.primaryType"),Y(e.typedDataSpec.types,Se),d(e.typeHash,at,"typeHash"),d(e.domainSeparator,ie(t.expectedDomain),"domainSeparator"),d(se(e.encodedPaymentDetails),e.typedDataValue.dataHash,"encodedPaymentDetails"),d(e.typedDataValue.intentHash,I(t.expectedIntentHash,"expectedIntentHash"),"typedDataValue.intentHash");let r=ae({domainSeparator:e.domainSeparator,types:Se,value:{...e.typedDataValue},signature:e.signature});return k({payloadSigner:e.signer,recoveredSigner:r,trustedSigners:t.trustedSigners}),e}var mt=require("ethers");var Sr="tuple(bytes32 paymentMethod,bytes32 originalPaymentId,bytes32 disputeId,uint256 paymentAmount,bytes32 paymentCurrency)";function At(e,t){m(e.platform,t.expectedPlatform,"platform"),m(e.actionType,t.expectedActionType,"actionType"),m(e.typedDataSpec.primaryType,"DisputeAttestation","typedDataSpec.primaryType"),Y(e.typedDataSpec.types,Ee),d(e.typeHash,ct,"typeHash"),d(e.domainSeparator,oe(t.expectedDomain),"domainSeparator"),d(e.typedDataValue.intentHash,I(t.expectedIntentHash,"expectedIntentHash"),"typedDataValue.intentHash"),d(se(e.encodedDisputeDetails),e.typedDataValue.dataHash,"encodedDisputeDetails"),d(e.disputeDetails.paymentMethod,y(e.platform),"paymentMethod"),Er(e);let r=ae({domainSeparator:e.domainSeparator,types:Ee,value:{...e.typedDataValue},signature:e.signature});return k({payloadSigner:e.signer,recoveredSigner:r,trustedSigners:t.trustedSigners}),e}function Er(e){let t;try{let r=e.disputeDetails;t=mt.AbiCoder.defaultAbiCoder().encode([Sr],[[r.paymentMethod,r.originalPaymentId,r.disputeId,r.paymentAmount,r.paymentCurrency]])}catch(r){s("ATTESTATION_RESPONSE_INVALID","disputeDetails could not be ABI encoded",{cause:r})}d(e.encodedDisputeDetails,t,"disputeDetails")}var gr=["platform","actionType","payeeId","username","metadata"];function Tt(e,t){m(e.platform,t.expectedPlatform,"platform"),m(e.actionType,t.expectedActionType,"actionType"),m(e.identity.platform,e.platform,"identity.platform"),m(e.identity.actionType,e.actionType,"identity.actionType"),m(e.typedDataSpec.primaryType,"IdentityAttestation","typedDataSpec.primaryType"),Y(e.typedDataSpec.types,Ie),d(e.domainSeparator,dt,"domainSeparator"),d(e.typeHash,ut,"typeHash"),d(e.identity.method,y(e.identity.platform),"identity.method"),d(e.identity.payeeIdHash,y(e.identity.payeeId),"identity.payeeIdHash"),d(e.typedDataValue.method,e.identity.method,"typedDataValue.method"),d(e.typedDataValue.actionType,y(e.identity.actionType),"typedDataValue.actionType"),ft(e.typedDataValue.callerAddress,I(t.expectedCallerAddress,"expectedCallerAddress"),"typedDataValue.callerAddress"),d(e.typedDataValue.payeeIdHash,e.identity.payeeIdHash,"typedDataValue.payeeIdHash"),d(e.typedDataValue.payeeIdHash,I(t.expectedPayeeIdHash,"expectedPayeeIdHash"),"typedDataValue.payeeIdHash"),d(e.typedDataValue.dataHash,Ir(e.identity),"typedDataValue.dataHash"),hr(e.typedDataValue.validUntil,t.now??Date.now);let r=ce({domain:ge,types:Ie,value:{...e.typedDataValue},signature:e.signature});return k({payloadSigner:e.signer,recoveredSigner:r,trustedSigners:t.trustedSigners}),e.identity}function Ir(e){let t={platform:e.platform,actionType:e.actionType,payeeId:e.payeeId,username:e.username,metadata:Pr(e.metadata)},r=JSON.stringify(Object.fromEntries(gr.map(n=>[n,t[n]])));return y(r)}function Pr(e){return Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)))}function hr(e,t){let r=t();BigInt(r)>BigInt(e)&&s("ATTESTATION_EXPIRED","Identity attestation validUntil is in the past",{details:{validUntil:e,nowMs:r}})}function St(e,t){m(e.platform,t.expectedPlatform,"platform"),d(e.payeeIdHash,I(t.expectedPayeeIdHash,"expectedPayeeIdHash"),"payeeIdHash"),Cr(e.credentialExpiresAt,t.now??Date.now);let r=ce({domain:lt,types:pt,value:xr(e),signature:e.bundleSignature});return Pe(r,t.trustedSigners),e}function xr(e){return{platform:e.platform,payeeIdHash:e.payeeIdHash,encryptedBlobHash:y(e.encryptedBlob),encryptedDataKeyHash:y(e.encryptedDataKey),nonceHash:y(e.nonce),credentialType:e.credentialType,credentialValidatedAt:e.credentialValidatedAt,credentialExpiresAt:e.credentialExpiresAt??""}}function Cr(e,t){let r=t();e!==null&&BigInt(r)>BigInt(e)&&s("ATTESTATION_EXPIRED","Seller credential bundle credentialExpiresAt is in the past",{details:{credentialExpiresAt:e,nowMs:r}})}0&&(module.exports={AWS_NITRO_ROOT_FINGERPRINT_SHA256_HEX,AWS_NITRO_ROOT_PEM,DISPUTE_WINDOW_POLICY,NitroAttestationError,createEncryptedBuyerTeeSessionMaterial,createEncryptedDisputeSessionMaterial,createEncryptedIdentitySessionMaterial,createEncryptedSellerCredentialUpload,createNitroAttestationClient,encryptBuyerTeeSessionMaterial,encryptDisputeSessionMaterial,encryptIdentitySessionMaterial,encryptSellerCredentialUpload,fetchAndVerifyAttestation,getDefaultDisputeWindow,getDefaultDisputeWindowForHash,getDisputeVerifierDomainSeparator,getUnifiedPaymentVerifierDomainSeparator,hashUtf8,requestIdentityAttestation,uploadSellerCredential,verifyBuyerTeePayment,verifyBuyerTeePaymentAttestation,verifyDispute,verifyDisputeAttestation,verifyIdentityAttestation,verifySellerCredentialBundle});
16
16
  //# sourceMappingURL=index.cjs.map