vesant-sdk 1.6.6 → 1.7.0-dev.117915b

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 (86) hide show
  1. package/README.md +14 -4
  2. package/dist/client-B0qhE2kr.d.mts +436 -0
  3. package/dist/{client-ePzhQKp9.d.mts → client-BolQlL5e.d.mts} +1 -1
  4. package/dist/{client-ePzhQKp9.d.ts → client-BolQlL5e.d.ts} +1 -1
  5. package/dist/{client-BlCxjbY2.d.mts → client-DF7hlMEz.d.ts} +18 -3
  6. package/dist/{client-C_A7QLcB.d.ts → client-DrjgZoH_.d.mts} +18 -3
  7. package/dist/client-DtH2RLuy.d.ts +436 -0
  8. package/dist/compliance/index.d.mts +25 -429
  9. package/dist/compliance/index.d.ts +25 -429
  10. package/dist/compliance/index.js +186 -105
  11. package/dist/compliance/index.js.map +1 -1
  12. package/dist/compliance/index.mjs +186 -106
  13. package/dist/compliance/index.mjs.map +1 -1
  14. package/dist/decisions/index.d.mts +2 -2
  15. package/dist/decisions/index.d.ts +2 -2
  16. package/dist/decisions/index.js +1 -1
  17. package/dist/decisions/index.js.map +1 -1
  18. package/dist/decisions/index.mjs +1 -1
  19. package/dist/decisions/index.mjs.map +1 -1
  20. package/dist/geolocation/index.d.mts +4 -4
  21. package/dist/geolocation/index.d.ts +4 -4
  22. package/dist/geolocation/index.js +7 -24
  23. package/dist/geolocation/index.js.map +1 -1
  24. package/dist/geolocation/index.mjs +7 -24
  25. package/dist/geolocation/index.mjs.map +1 -1
  26. package/dist/index.d.mts +12 -70
  27. package/dist/index.d.ts +12 -70
  28. package/dist/index.js +305 -299
  29. package/dist/index.js.map +1 -1
  30. package/dist/index.mjs +304 -298
  31. package/dist/index.mjs.map +1 -1
  32. package/dist/kyc/core.d.mts +4 -4
  33. package/dist/kyc/core.d.ts +4 -4
  34. package/dist/kyc/core.js +86 -27
  35. package/dist/kyc/core.js.map +1 -1
  36. package/dist/kyc/core.mjs +86 -28
  37. package/dist/kyc/core.mjs.map +1 -1
  38. package/dist/kyc/index.d.mts +309 -50
  39. package/dist/kyc/index.d.ts +309 -50
  40. package/dist/kyc/index.js +86 -27
  41. package/dist/kyc/index.js.map +1 -1
  42. package/dist/kyc/index.mjs +86 -28
  43. package/dist/kyc/index.mjs.map +1 -1
  44. package/dist/react.d.mts +48 -9
  45. package/dist/react.d.ts +48 -9
  46. package/dist/react.js +930 -276
  47. package/dist/react.js.map +1 -1
  48. package/dist/react.mjs +929 -275
  49. package/dist/react.mjs.map +1 -1
  50. package/dist/risk-profile/index.d.mts +4 -4
  51. package/dist/risk-profile/index.d.ts +4 -4
  52. package/dist/risk-profile/index.js +1 -1
  53. package/dist/risk-profile/index.js.map +1 -1
  54. package/dist/risk-profile/index.mjs +1 -1
  55. package/dist/risk-profile/index.mjs.map +1 -1
  56. package/dist/scores/index.d.mts +2 -2
  57. package/dist/scores/index.d.ts +2 -2
  58. package/dist/scores/index.js +1 -1
  59. package/dist/scores/index.js.map +1 -1
  60. package/dist/scores/index.mjs +1 -1
  61. package/dist/scores/index.mjs.map +1 -1
  62. package/dist/tax/index.d.mts +23 -41
  63. package/dist/tax/index.d.ts +23 -41
  64. package/dist/tax/index.js +5 -37
  65. package/dist/tax/index.js.map +1 -1
  66. package/dist/tax/index.mjs +5 -37
  67. package/dist/tax/index.mjs.map +1 -1
  68. package/dist/{types-1RzYeSal.d.mts → types-BOFaMQxI.d.mts} +2 -2
  69. package/dist/{types-B4Ezqo7V.d.mts → types-CBQRNL-l.d.mts} +14 -1
  70. package/dist/{types-B4Ezqo7V.d.ts → types-CBQRNL-l.d.ts} +14 -1
  71. package/dist/{types-X5Md_dD_.d.ts → types-UGyDl1fd.d.ts} +2 -2
  72. package/dist/webhooks/index.d.mts +189 -2
  73. package/dist/webhooks/index.d.ts +189 -2
  74. package/dist/webhooks/index.js +49 -7
  75. package/dist/webhooks/index.js.map +1 -1
  76. package/dist/webhooks/index.mjs +49 -7
  77. package/dist/webhooks/index.mjs.map +1 -1
  78. package/package.json +16 -13
  79. package/dist/fraud/index.d.mts +0 -80
  80. package/dist/fraud/index.d.ts +0 -80
  81. package/dist/fraud/index.js +0 -606
  82. package/dist/fraud/index.js.map +0 -1
  83. package/dist/fraud/index.mjs +0 -604
  84. package/dist/fraud/index.mjs.map +0 -1
  85. package/dist/index-B04H4xfJ.d.mts +0 -320
  86. package/dist/index-CItMPmLL.d.ts +0 -320
package/dist/index.js CHANGED
@@ -242,7 +242,7 @@ var noopLogger = {
242
242
  };
243
243
 
244
244
  // src/core/version.ts
245
- var SDK_VERSION = "1.6.6";
245
+ var SDK_VERSION = "1.7.0";
246
246
 
247
247
  // src/shared/browser-utils.ts
248
248
  function generateUUID() {
@@ -652,8 +652,9 @@ async function computeHmacSha256(message, secret) {
652
652
  const { createHmac } = await import('crypto');
653
653
  return createHmac("sha256", secret).update(message).digest("hex");
654
654
  } catch {
655
- throw new Error(
656
- "No crypto implementation available. Requires Web Crypto API or Node.js crypto module."
655
+ throw new VesantError(
656
+ "No crypto implementation available. Requires Web Crypto API or Node.js crypto module.",
657
+ "CRYPTO_UNAVAILABLE"
657
658
  );
658
659
  }
659
660
  }
@@ -787,7 +788,7 @@ function encodePayload(payload) {
787
788
  } else if (typeof Buffer !== "undefined") {
788
789
  return Buffer.from(json, "utf-8").toString("base64");
789
790
  }
790
- throw new Error("No base64 encoding method available");
791
+ throw new VesantError("No base64 encoding method available", "BASE64_UNAVAILABLE");
791
792
  }
792
793
  async function generateCipherText(options, config) {
793
794
  const warnings = [];
@@ -812,8 +813,9 @@ async function generateCipherText(options, config) {
812
813
  if (location) {
813
814
  locationData = location;
814
815
  } else if (gpsRequiredByConfig) {
815
- throw new Error(
816
- `GPS location is required for ${options.reason} by tenant configuration, but GPS was not available or permission was denied`
816
+ throw new VesantError(
817
+ `GPS location is required for ${options.reason} by tenant configuration, but GPS was not available or permission was denied`,
818
+ "GPS_REQUIRED"
817
819
  );
818
820
  } else {
819
821
  warnings.push("GPS location not available or permission denied");
@@ -932,10 +934,9 @@ var GeolocationClient = class extends BaseClient {
932
934
  if (!request.ip_address?.trim()) {
933
935
  throw new ValidationError("ip_address is required and must be a non-empty string", ["ip_address"]);
934
936
  }
935
- const enrichedRequest = request.device_fingerprint ? request : { ...request, device_fingerprint: collectDeviceFingerprint() };
936
937
  return this.requestWithRetry("/api/v1/geo/verify", {
937
938
  method: "POST",
938
- body: JSON.stringify(enrichedRequest)
939
+ body: JSON.stringify(request)
939
940
  }, void 0, void 0, requestOptions);
940
941
  }
941
942
  /**
@@ -1160,6 +1161,7 @@ var GeolocationClient = class extends BaseClient {
1160
1161
  risk_level: risk.level ?? "low",
1161
1162
  risk_score: risk.score ?? 0,
1162
1163
  risk_reasons: risk.is_blocked && risk.block_reasons ? risk.block_reasons : risk.factors ?? [],
1164
+ risk_reasons_structured: risk.block_reasons_structured ?? [],
1163
1165
  jurisdiction: cipherTextResult.jurisdiction,
1164
1166
  geofence_evaluation: cipherTextResult.geofence_evaluation,
1165
1167
  record_id: cipherTextResult.record_id ?? "",
@@ -1339,24 +1341,6 @@ var GeolocationClient = class extends BaseClient {
1339
1341
  // Utility Methods (inherited from BaseClient: healthCheck, updateConfig, getConfig, buildQueryString)
1340
1342
  // ============================================================================
1341
1343
  };
1342
- function collectDeviceFingerprint() {
1343
- const deviceId = generateDeviceId();
1344
- const browserInfo = getBrowserInfo();
1345
- const userAgent = typeof navigator !== "undefined" ? navigator.userAgent : "server";
1346
- const platform = typeof navigator !== "undefined" ? navigator.platform || "unknown" : "server";
1347
- return {
1348
- device_id: deviceId,
1349
- user_agent: userAgent,
1350
- platform,
1351
- browser: browserInfo.browser,
1352
- browser_version: browserInfo.browser_version,
1353
- os: browserInfo.os,
1354
- os_version: browserInfo.os_version,
1355
- screen_resolution: typeof screen !== "undefined" ? `${screen.width}x${screen.height}` : void 0,
1356
- language: typeof navigator !== "undefined" ? navigator.language : void 0,
1357
- timezone: Intl?.DateTimeFormat?.()?.resolvedOptions?.()?.timeZone
1358
- };
1359
- }
1360
1344
 
1361
1345
  // src/risk-profile/client.ts
1362
1346
  var RiskProfileClient = class extends BaseClient {
@@ -1473,6 +1457,81 @@ var RiskProfileClient = class extends BaseClient {
1473
1457
  }
1474
1458
  };
1475
1459
 
1460
+ // src/compliance/block-reasons.ts
1461
+ var sdkReasons = {
1462
+ // Jurisdiction
1463
+ jurisdictionBlocked: (country, countryISO) => ({
1464
+ code: "JURISDICTION_BLOCKED",
1465
+ message: "Access from a blocked jurisdiction",
1466
+ metadata: { country, country_iso: countryISO }
1467
+ }),
1468
+ jurisdictionNonCompliant: () => ({
1469
+ code: "JURISDICTION_NON_COMPLIANT",
1470
+ message: "Location does not meet compliance requirements"
1471
+ }),
1472
+ jurisdictionRegistrationDenied: () => ({
1473
+ code: "JURISDICTION_REGISTRATION_DENIED",
1474
+ message: "Registration is not permitted in this jurisdiction"
1475
+ }),
1476
+ jurisdictionRestricted: () => ({
1477
+ code: "JURISDICTION_RESTRICTED",
1478
+ message: "Access from a restricted jurisdiction"
1479
+ }),
1480
+ // Risk
1481
+ riskCriticalLevel: () => ({
1482
+ code: "RISK_CRITICAL_LEVEL",
1483
+ message: "Risk assessment reached critical threshold"
1484
+ }),
1485
+ accountSuspended: () => ({
1486
+ code: "RISK_ACCOUNT_SUSPENDED",
1487
+ message: "Customer account is suspended"
1488
+ }),
1489
+ sanctionsMatch: () => ({
1490
+ code: "RISK_SANCTIONS_MATCH",
1491
+ message: "Customer profile matched against sanctions list"
1492
+ }),
1493
+ riskHighLocation: () => ({
1494
+ code: "RISK_HIGH_LOCATION",
1495
+ message: "High-risk geographic location"
1496
+ }),
1497
+ riskHighCustomer: () => ({
1498
+ code: "RISK_HIGH_CUSTOMER",
1499
+ message: "Customer flagged as high risk"
1500
+ }),
1501
+ // Device
1502
+ ciphertextInvalid: () => ({
1503
+ code: "DEVICE_CIPHERTEXT_INVALID",
1504
+ message: "Device verification payload failed validation"
1505
+ }),
1506
+ gpsIPMismatch: () => ({
1507
+ code: "DEVICE_GPS_IP_MISMATCH",
1508
+ message: "GPS location does not match IP-derived location"
1509
+ }),
1510
+ gpsRequired: () => ({
1511
+ code: "DEVICE_GPS_REQUIRED",
1512
+ message: "GPS verification is required but was not provided"
1513
+ }),
1514
+ // Transaction
1515
+ transactionHighAmount: (amount, currency, threshold) => ({
1516
+ code: "TRANSACTION_HIGH_AMOUNT",
1517
+ message: "Transaction amount exceeds high-value threshold",
1518
+ metadata: { amount, currency, threshold }
1519
+ }),
1520
+ transactionElevatedAmount: (amount, currency, threshold) => ({
1521
+ code: "TRANSACTION_ELEVATED_AMOUNT",
1522
+ message: "Transaction amount exceeds elevated-value threshold",
1523
+ metadata: { amount, currency, threshold }
1524
+ }),
1525
+ transactionJurisdictionLimit: () => ({
1526
+ code: "TRANSACTION_JURISDICTION_LIMIT",
1527
+ message: "Transaction amount exceeds jurisdiction limit"
1528
+ }),
1529
+ anonymizationDetected: () => ({
1530
+ code: "NETWORK_ANONYMIZER_DETECTED",
1531
+ message: "Anonymization tool detected"
1532
+ })
1533
+ };
1534
+
1476
1535
  // src/compliance/types.ts
1477
1536
  var DEFAULT_CURRENCY_RATES = {
1478
1537
  USD: 1,
@@ -1619,10 +1678,10 @@ var ComplianceClient = class {
1619
1678
  device_fingerprint: request.deviceFingerprint
1620
1679
  }, requestOptions);
1621
1680
  }
1622
- const blockReasons = this.evaluateRegistrationBlock(geoVerification, cipherTextResult);
1623
- if (blockReasons.length > 0) {
1681
+ const structuredBlockReasons = this.evaluateRegistrationBlock(geoVerification, cipherTextResult);
1682
+ if (structuredBlockReasons.length > 0) {
1624
1683
  if (this.config.debug) {
1625
- this.logger.debug("Registration blocked at geo stage", { blockReasons });
1684
+ this.logger.debug("Registration blocked at geo stage", { blockReasons: structuredBlockReasons });
1626
1685
  }
1627
1686
  return {
1628
1687
  allowed: false,
@@ -1630,9 +1689,7 @@ var ComplianceClient = class {
1630
1689
  profile: null,
1631
1690
  requiresKYC: false,
1632
1691
  requiresEDD: false,
1633
- blockReasons,
1634
- processingTime: Date.now() - startTime,
1635
- cipherTextValidation: cipherTextResult
1692
+ ...this.buildReasonTail(structuredBlockReasons, startTime, cipherTextResult)
1636
1693
  };
1637
1694
  }
1638
1695
  const profile = await this.riskClient.createProfile({
@@ -1666,14 +1723,12 @@ var ComplianceClient = class {
1666
1723
  profile,
1667
1724
  requiresKYC,
1668
1725
  requiresEDD,
1669
- blockReasons: [],
1670
- processingTime: Date.now() - startTime,
1671
- cipherTextValidation: cipherTextResult
1726
+ ...this.buildReasonTail([], startTime, cipherTextResult)
1672
1727
  };
1673
1728
  } catch (error) {
1674
1729
  if (this.config.debug) {
1675
1730
  this.logger.error("Registration verification failed", {
1676
- code: error instanceof Error ? error.code : void 0,
1731
+ code: error instanceof VesantError ? error.code : void 0,
1677
1732
  message: error instanceof Error ? error.message : "Unknown error"
1678
1733
  });
1679
1734
  }
@@ -1702,52 +1757,59 @@ var ComplianceClient = class {
1702
1757
  evaluateRegistrationBlock(geoVerification, cipherTextResult) {
1703
1758
  const blockReasons = [];
1704
1759
  if (geoVerification.is_blocked) {
1705
- blockReasons.push(...geoVerification.risk_reasons ?? []);
1760
+ blockReasons.push(...geoVerification.risk_reasons_structured ?? []);
1706
1761
  }
1707
1762
  if (!geoVerification.is_compliant) {
1708
- if (!blockReasons.includes("non_compliant_jurisdiction")) {
1709
- blockReasons.push("non_compliant_jurisdiction");
1763
+ if (!blockReasons.some((r) => r.code === "JURISDICTION_NON_COMPLIANT")) {
1764
+ blockReasons.push(sdkReasons.jurisdictionNonCompliant());
1710
1765
  }
1711
1766
  }
1712
1767
  const jurisdiction = geoVerification.jurisdiction;
1713
1768
  if (jurisdiction) {
1714
1769
  if (jurisdiction.allow_registration === false) {
1715
- blockReasons.push("registration_not_allowed_in_jurisdiction");
1770
+ blockReasons.push(sdkReasons.jurisdictionRegistrationDenied());
1716
1771
  }
1717
1772
  if (jurisdiction.status === "blocked" || jurisdiction.status === "sanctioned") {
1718
- if (!blockReasons.includes("blocked_jurisdiction")) {
1719
- blockReasons.push("blocked_jurisdiction");
1773
+ if (!blockReasons.some((r) => r.code === "JURISDICTION_BLOCKED")) {
1774
+ blockReasons.push(sdkReasons.jurisdictionBlocked(jurisdiction.country_name ?? "", jurisdiction.country_iso ?? ""));
1720
1775
  }
1721
1776
  }
1722
1777
  if (jurisdiction.status === "restricted" && jurisdiction.allow_registration === false) {
1723
- if (!blockReasons.includes("restricted_jurisdiction_no_registration")) {
1724
- blockReasons.push("restricted_jurisdiction_no_registration");
1778
+ if (!blockReasons.some((r) => r.code === "JURISDICTION_RESTRICTED")) {
1779
+ blockReasons.push(sdkReasons.jurisdictionRestricted());
1725
1780
  }
1726
1781
  }
1727
1782
  }
1728
1783
  if (geoVerification.geofence_evaluation?.blocked) {
1729
- blockReasons.push(...geoVerification.geofence_evaluation.reasons ?? []);
1784
+ blockReasons.push(
1785
+ ...(geoVerification.geofence_evaluation.reasons ?? []).map((m) => ({
1786
+ code: "JURISDICTION_GEOFENCE_VIOLATION",
1787
+ message: m
1788
+ }))
1789
+ );
1730
1790
  }
1731
1791
  if (geoVerification.risk_level === "critical") {
1732
- if (!blockReasons.includes("critical_risk_level")) {
1733
- blockReasons.push("critical_risk_level");
1792
+ if (!blockReasons.some((r) => r.code === "RISK_CRITICAL_LEVEL")) {
1793
+ blockReasons.push(sdkReasons.riskCriticalLevel());
1734
1794
  }
1735
1795
  }
1736
1796
  if (cipherTextResult) {
1737
1797
  if (!cipherTextResult.valid) {
1738
- blockReasons.push("ciphertext_validation_failed");
1798
+ blockReasons.push(sdkReasons.ciphertextInvalid());
1739
1799
  }
1740
1800
  if (cipherTextResult.risk?.is_blocked) {
1741
- blockReasons.push(...cipherTextResult.risk.block_reasons || []);
1742
- }
1743
- if (cipherTextResult.risk?.location_mismatch) {
1744
- blockReasons.push("gps_ip_location_mismatch");
1801
+ blockReasons.push(...cipherTextResult.risk.block_reasons_structured ?? []);
1745
1802
  }
1746
1803
  }
1747
1804
  if (geoVerification.gps_required && !cipherTextResult) {
1748
- blockReasons.push("gps_verification_required");
1805
+ blockReasons.push(sdkReasons.gpsRequired());
1749
1806
  }
1750
- return [...new Set(blockReasons)];
1807
+ const seen = /* @__PURE__ */ new Set();
1808
+ return blockReasons.filter((r) => {
1809
+ if (seen.has(r.code)) return false;
1810
+ seen.add(r.code);
1811
+ return true;
1812
+ });
1751
1813
  }
1752
1814
  /**
1753
1815
  * Validate registration request has all required fields
@@ -1918,9 +1980,7 @@ var ComplianceClient = class {
1918
1980
  geolocation: geoVerification,
1919
1981
  profile: null,
1920
1982
  requiresStepUp: false,
1921
- blockReasons: loginBlockReasons,
1922
- processingTime: Date.now() - startTime,
1923
- cipherTextValidation: cipherTextResult
1983
+ ...this.buildReasonTail(loginBlockReasons, startTime, cipherTextResult)
1924
1984
  };
1925
1985
  }
1926
1986
  let profile;
@@ -1940,14 +2000,13 @@ var ComplianceClient = class {
1940
2000
  profile = await this.createProfileFromGeo(request.customerId, geoVerification);
1941
2001
  }
1942
2002
  const requiresStepUp = geoVerification.risk_level === "high" || geoVerification.risk_level === "critical" || cipherTextResult?.risk?.location_mismatch === true;
2003
+ const loginFinalStructured = isBlocked || profile.customer_status === "suspended" ? this.getBlockReasons(geoVerification, profile, cipherTextResult) : [];
1943
2004
  return {
1944
2005
  allowed: !isBlocked && profile.customer_status !== "suspended",
1945
2006
  geolocation: geoVerification,
1946
2007
  profile,
1947
2008
  requiresStepUp,
1948
- blockReasons: isBlocked || profile.customer_status === "suspended" ? this.getBlockReasons(geoVerification, profile, cipherTextResult) : [],
1949
- processingTime: Date.now() - startTime,
1950
- cipherTextValidation: cipherTextResult
2009
+ ...this.buildReasonTail(loginFinalStructured, startTime, cipherTextResult)
1951
2010
  };
1952
2011
  } catch (error) {
1953
2012
  throw new ComplianceError("Login verification failed", error instanceof Error ? error.message : void 0);
@@ -2029,20 +2088,19 @@ var ComplianceClient = class {
2029
2088
  }
2030
2089
  const geoBlocked = !geoVerification.is_compliant || geoVerification.is_blocked || !!cipherTextResult?.risk?.is_blocked || cipherTextResult?.valid === false || geoVerification.gps_required && !cipherTextResult;
2031
2090
  if (geoBlocked && !profileResult) {
2091
+ const earlyStructured = this.getTransactionBlockReasons(
2092
+ geoVerification,
2093
+ { score: 0, level: "low", factors: [], allowed: false, requiresManualReview: false },
2094
+ true,
2095
+ cipherTextResult
2096
+ );
2032
2097
  return {
2033
2098
  allowed: false,
2034
2099
  geolocation: geoVerification,
2035
2100
  profile: null,
2036
2101
  transactionRisk: { score: 0, level: "low", factors: [], allowed: false, requiresManualReview: false },
2037
2102
  requiresApproval: false,
2038
- blockReasons: this.getTransactionBlockReasons(
2039
- geoVerification,
2040
- { score: 0, level: "low", factors: [], allowed: false, requiresManualReview: false },
2041
- true,
2042
- cipherTextResult
2043
- ),
2044
- processingTime: Date.now() - startTime,
2045
- cipherTextValidation: cipherTextResult
2103
+ ...this.buildReasonTail(earlyStructured, startTime, cipherTextResult)
2046
2104
  };
2047
2105
  }
2048
2106
  if (!profileResult) {
@@ -2062,20 +2120,19 @@ var ComplianceClient = class {
2062
2120
  geoVerification.jurisdiction
2063
2121
  );
2064
2122
  const isAllowed = !geoBlocked && jurisdictionAllowed && transactionRisk.allowed && profile.customer_status !== "suspended";
2123
+ const txStructured = this.getTransactionBlockReasons(
2124
+ geoVerification,
2125
+ transactionRisk,
2126
+ jurisdictionAllowed,
2127
+ cipherTextResult
2128
+ );
2065
2129
  return {
2066
2130
  allowed: isAllowed,
2067
2131
  geolocation: geoVerification,
2068
2132
  profile,
2069
2133
  transactionRisk,
2070
2134
  requiresApproval: transactionRisk.requiresManualReview,
2071
- blockReasons: this.getTransactionBlockReasons(
2072
- geoVerification,
2073
- transactionRisk,
2074
- jurisdictionAllowed,
2075
- cipherTextResult
2076
- ),
2077
- processingTime: Date.now() - startTime,
2078
- cipherTextValidation: cipherTextResult
2135
+ ...this.buildReasonTail(txStructured, startTime, cipherTextResult)
2079
2136
  };
2080
2137
  } catch (error) {
2081
2138
  throw new ComplianceError("Transaction verification failed", error instanceof Error ? error.message : void 0);
@@ -2128,30 +2185,42 @@ var ComplianceClient = class {
2128
2185
  }
2129
2186
  }
2130
2187
  const cipherTextBlocked = cipherTextResult ? !cipherTextResult.valid || cipherTextResult.risk?.is_blocked === true : false;
2131
- const blockReasons = [...geoVerification.risk_reasons ?? []];
2188
+ const structuredEventReasons = [...geoVerification.risk_reasons_structured ?? []];
2132
2189
  if (cipherTextResult) {
2133
2190
  if (!cipherTextResult.valid) {
2134
- blockReasons.push("ciphertext_validation_failed");
2191
+ structuredEventReasons.push(sdkReasons.ciphertextInvalid());
2135
2192
  }
2136
2193
  if (cipherTextResult.risk?.is_blocked) {
2137
- blockReasons.push(...cipherTextResult.risk.block_reasons || []);
2194
+ structuredEventReasons.push(...cipherTextResult.risk.block_reasons_structured ?? []);
2138
2195
  }
2139
2196
  }
2140
2197
  const gpsBlocked = geoVerification.gps_required && !cipherTextResult;
2141
2198
  if (gpsBlocked) {
2142
- blockReasons.push("gps_verification_required");
2199
+ structuredEventReasons.push(sdkReasons.gpsRequired());
2143
2200
  }
2201
+ const seen = /* @__PURE__ */ new Set();
2202
+ const dedupedStructured = structuredEventReasons.filter((r) => {
2203
+ if (seen.has(r.code)) return false;
2204
+ seen.add(r.code);
2205
+ return true;
2206
+ });
2144
2207
  return {
2145
2208
  allowed: geoVerification.is_compliant && !geoVerification.is_blocked && !cipherTextBlocked && !gpsBlocked,
2146
2209
  geolocation: geoVerification,
2147
- blockReasons: [...new Set(blockReasons)],
2148
- processingTime: Date.now() - startTime,
2149
- cipherTextValidation: cipherTextResult
2210
+ ...this.buildReasonTail(dedupedStructured, startTime, cipherTextResult)
2150
2211
  };
2151
2212
  }
2152
2213
  // ============================================================================
2153
2214
  // Helper Methods
2154
2215
  // ============================================================================
2216
+ buildReasonTail(structured, startTime, cipherTextResult) {
2217
+ return {
2218
+ blockReasons: structured.map((r) => r.message),
2219
+ blockReasonsStructured: structured,
2220
+ processingTime: Date.now() - startTime,
2221
+ cipherTextValidation: cipherTextResult
2222
+ };
2223
+ }
2155
2224
  shouldUpdateProfile(profile, newCity) {
2156
2225
  return !profile.location || !profile.location.includes(newCity);
2157
2226
  }
@@ -2228,7 +2297,8 @@ var ComplianceClient = class {
2228
2297
  is_blocked: risk.is_blocked,
2229
2298
  risk_level: risk.level,
2230
2299
  risk_score: risk.score,
2231
- risk_reasons: risk.is_blocked && risk.block_reasons ? risk.block_reasons : risk.factors ?? [],
2300
+ risk_reasons: [],
2301
+ risk_reasons_structured: risk.is_blocked && risk.block_reasons_structured ? risk.block_reasons_structured : [],
2232
2302
  jurisdiction: ct.jurisdiction,
2233
2303
  geofence_evaluation: ct.geofence_evaluation,
2234
2304
  record_id: ct.record_id ?? "",
@@ -2243,35 +2313,35 @@ var ComplianceClient = class {
2243
2313
  );
2244
2314
  }
2245
2315
  let riskScore = 0;
2246
- const factors = [];
2316
+ const structuredFactors = [];
2247
2317
  const normalizedAmount = this.normalizeToUSD(amount, currency);
2248
2318
  if (normalizedAmount > 1e4) {
2249
2319
  riskScore += 30;
2250
- factors.push("high_transaction_amount");
2320
+ structuredFactors.push(sdkReasons.transactionHighAmount(normalizedAmount, currency, 1e4));
2251
2321
  } else if (normalizedAmount > 5e3) {
2252
2322
  riskScore += 15;
2253
- factors.push("elevated_transaction_amount");
2323
+ structuredFactors.push(sdkReasons.transactionElevatedAmount(normalizedAmount, currency, 5e3));
2254
2324
  }
2255
2325
  riskScore += geoVerification.risk_score * 0.4;
2256
2326
  if (geoVerification.risk_level === "high" || geoVerification.risk_level === "critical") {
2257
- factors.push("high_risk_location");
2327
+ structuredFactors.push(sdkReasons.riskHighLocation());
2258
2328
  }
2259
2329
  riskScore += profile.risk_score * 0.3;
2260
2330
  if (profile.risk_category === "high" || profile.risk_category === "critical") {
2261
- factors.push("high_risk_customer");
2331
+ structuredFactors.push(sdkReasons.riskHighCustomer());
2262
2332
  }
2263
2333
  if (geoVerification.location.is_vpn || geoVerification.location.is_proxy) {
2264
2334
  riskScore += 20;
2265
- factors.push("anonymization_detected");
2335
+ structuredFactors.push(sdkReasons.anonymizationDetected());
2266
2336
  }
2267
2337
  if (profile.customer_status === "suspended") {
2268
2338
  riskScore += 50;
2269
- factors.push("account_suspended");
2339
+ structuredFactors.push(sdkReasons.accountSuspended());
2270
2340
  }
2271
2341
  if (cipherTextResult) {
2272
2342
  if (cipherTextResult.risk?.location_mismatch) {
2273
2343
  riskScore += 20;
2274
- factors.push("gps_ip_location_mismatch");
2344
+ structuredFactors.push(sdkReasons.gpsIPMismatch());
2275
2345
  }
2276
2346
  if (cipherTextResult.risk?.score) {
2277
2347
  riskScore += cipherTextResult.risk.score * 0.2;
@@ -2280,7 +2350,8 @@ var ComplianceClient = class {
2280
2350
  return {
2281
2351
  score: Math.min(riskScore, 100),
2282
2352
  level: this.getRiskLevel(riskScore),
2283
- factors,
2353
+ factors: structuredFactors.map((r) => r.message),
2354
+ factorsStructured: structuredFactors,
2284
2355
  allowed: riskScore < 70,
2285
2356
  requiresManualReview: riskScore >= 60 && riskScore < 70
2286
2357
  };
@@ -2305,52 +2376,62 @@ var ComplianceClient = class {
2305
2376
  getBlockReasons(geoVerification, profile, cipherTextResult) {
2306
2377
  const reasons = [];
2307
2378
  if (geoVerification.is_blocked) {
2308
- reasons.push(...geoVerification.risk_reasons ?? []);
2379
+ reasons.push(...geoVerification.risk_reasons_structured ?? []);
2309
2380
  }
2310
2381
  if (profile) {
2311
2382
  if (profile.customer_status === "suspended") {
2312
- reasons.push("account_suspended");
2383
+ reasons.push(sdkReasons.accountSuspended());
2313
2384
  }
2314
2385
  if (profile.has_sanctions) {
2315
- reasons.push("sanctions_match");
2386
+ reasons.push(sdkReasons.sanctionsMatch());
2316
2387
  }
2317
2388
  }
2318
2389
  if (cipherTextResult) {
2319
2390
  if (!cipherTextResult.valid) {
2320
- reasons.push("ciphertext_validation_failed");
2391
+ reasons.push(sdkReasons.ciphertextInvalid());
2321
2392
  }
2322
2393
  if (cipherTextResult.risk?.is_blocked) {
2323
- reasons.push(...cipherTextResult.risk.block_reasons || []);
2394
+ reasons.push(...cipherTextResult.risk.block_reasons_structured ?? []);
2324
2395
  }
2325
2396
  }
2326
2397
  if (geoVerification.gps_required && !cipherTextResult) {
2327
- reasons.push("gps_verification_required");
2398
+ reasons.push(sdkReasons.gpsRequired());
2328
2399
  }
2329
- return [...new Set(reasons)];
2400
+ const seen = /* @__PURE__ */ new Set();
2401
+ return reasons.filter((r) => {
2402
+ if (seen.has(r.code)) return false;
2403
+ seen.add(r.code);
2404
+ return true;
2405
+ });
2330
2406
  }
2331
2407
  getTransactionBlockReasons(geoVerification, transactionRisk, jurisdictionAllowed, cipherTextResult) {
2332
2408
  const reasons = [];
2333
2409
  if (!geoVerification.is_compliant) {
2334
- reasons.push("non_compliant_jurisdiction");
2410
+ reasons.push(sdkReasons.jurisdictionNonCompliant());
2335
2411
  }
2336
2412
  if (!jurisdictionAllowed) {
2337
- reasons.push("exceeds_jurisdiction_limit");
2413
+ reasons.push(sdkReasons.transactionJurisdictionLimit());
2338
2414
  }
2339
2415
  if (!transactionRisk.allowed) {
2340
- reasons.push(...transactionRisk.factors);
2416
+ reasons.push(...transactionRisk.factorsStructured ?? []);
2341
2417
  }
2342
2418
  if (cipherTextResult) {
2343
2419
  if (!cipherTextResult.valid) {
2344
- reasons.push("ciphertext_validation_failed");
2420
+ reasons.push(sdkReasons.ciphertextInvalid());
2345
2421
  }
2346
2422
  if (cipherTextResult.risk?.is_blocked) {
2347
- reasons.push(...cipherTextResult.risk.block_reasons || []);
2423
+ reasons.push(...cipherTextResult.risk.block_reasons_structured ?? []);
2348
2424
  }
2349
2425
  }
2350
2426
  if (geoVerification.gps_required && !cipherTextResult) {
2351
- reasons.push("gps_verification_required");
2427
+ reasons.push(sdkReasons.gpsRequired());
2352
2428
  }
2353
- return [...new Set(reasons)];
2429
+ const seen = /* @__PURE__ */ new Set();
2430
+ return reasons.filter((r) => {
2431
+ if (seen.has(r.code)) return false;
2432
+ seen.add(r.code);
2433
+ return true;
2434
+ });
2354
2435
  }
2355
2436
  // ============================================================================
2356
2437
  // Location Request Methods
@@ -2628,23 +2709,19 @@ var KycClient = class extends BaseClient {
2628
2709
  *
2629
2710
  * Generates a link that the user can visit to submit their KYC documents.
2630
2711
  *
2631
- * @param request - Request containing the user ID, redirect URL, callback URL, and trigger event
2632
- * @returns Response containing kyc_required, can_skip, and optionally the redirect link and KYC ID
2712
+ * @param request - Request containing the user ID, optional redirect URL, and optional callback URL (receives POST requests)
2713
+ * @returns Response containing the redirect link and KYC ID
2633
2714
  *
2634
2715
  * @example
2635
2716
  * ```typescript
2636
2717
  * const result = await client.requestKycSubmitLink({
2637
2718
  * user_id: "user_123",
2638
- * redirect_url: "https://merchant.com/kyc-complete",
2639
- * callback_url: "https://merchant.com/api/kyc-webhook",
2640
- * trigger_event: "onboarding"
2719
+ * redirect_url: "https://merchant.com/kyc-complete", // optional
2720
+ * callback_url: "https://merchant.com/api/kyc-webhook" // optional - receives POST requests on status change
2641
2721
  * });
2642
2722
  *
2643
- * if (result.kyc_required && result.link) {
2644
- * console.log(`Redirect user to: ${result.link}`);
2645
- * } else if (result.can_skip) {
2646
- * console.log("KYC not required, user can proceed");
2647
- * }
2723
+ * console.log(`Redirect user to: ${result.link}`);
2724
+ * console.log(`KYC ID: ${result.kyc_id}`);
2648
2725
  * ```
2649
2726
  */
2650
2727
  async requestKycSubmitLink(request) {
@@ -2655,40 +2732,88 @@ var KycClient = class extends BaseClient {
2655
2732
  });
2656
2733
  }
2657
2734
  /**
2658
- * Create a reuse KYC session for validate a user with existing KYC verification
2735
+ * Create a Event-Based Face Verification session.
2659
2736
  *
2660
- * @param request - Request containing the reference, customer_id, optional redirect URL, and callback URL (receives POST requests)
2737
+ * Inspect the response before showing UI:
2738
+ * - `is_required === false` → skip face capture; `reason` explains why.
2739
+ * - `device_type === 'desktop'` → render `qr_payload` as a QR; the
2740
+ * mobile device picks up the session via the connect endpoint.
2741
+ * - `device_type === 'mobile'` → open the face capture modal directly.
2742
+ *
2743
+ * @param request - Reference, customer_id, event, amount (for threshold events), optional URLs.
2661
2744
  */
2662
- async createReuseKycSession(request) {
2663
- return this.requestWithRetry("/api/v1/kyc/face/session", {
2745
+ async createEventBasedFaceVerificationSession(request) {
2746
+ return this.request("/api/v1/kyc/face/session", {
2664
2747
  method: "POST",
2665
2748
  body: JSON.stringify(request),
2666
2749
  headers: this.getUserHeaders()
2667
2750
  });
2668
2751
  }
2669
2752
  /**
2670
- * Submit a reuse KYC session for validate a user with existing KYC verification
2753
+ * Submit a real-time face capture for an active Event-Based Face Verification session.
2754
+ *
2755
+ * **Mobile-only.** The server rejects desktop User-Agents with HTTP
2756
+ * 400 (`face capture must be completed on a mobile device`). Use the
2757
+ * QR handoff from `createEventBasedFaceVerificationSession` for desktop callers.
2671
2758
  *
2672
- * @param request - Request containing the reference, token and proof (receives POST requests)
2759
+ * The `data` field on the response carries `retries_remaining`,
2760
+ * `retry_limit_exceeded`, and the reaction flags (`enforce_logout`,
2761
+ * `freeze_account`, etc.) so the tenant app can act on a final failure.
2762
+ *
2763
+ * @param request - Token from `createEventBasedFaceVerificationSession`, plus the base64 selfie.
2673
2764
  */
2674
- async submitReuseKycSession(request) {
2675
- return this.requestWithRetry("/api/v1/kyc/face/submit", {
2765
+ async submitEventBasedFaceVerificationSession(request) {
2766
+ return this.request("/api/v1/kyc/face/submit", {
2676
2767
  method: "POST",
2677
2768
  body: JSON.stringify(request),
2678
2769
  headers: this.getUserHeaders()
2679
2770
  });
2680
2771
  }
2681
2772
  /**
2682
- * Check reuse KYC session status for a reference
2683
- * @param reference - The unique reference used for the reuse KYC session (e.g., customer ID or transaction ID)
2684
- * @returns Response with kyc_status and message (reason)
2685
- * **/
2686
- async getReuseKycSessionStatus(reference) {
2687
- return this.requestWithRetry(`/api/v1/kyc/face/verify/${encodeURIComponent(reference)}`, {
2773
+ * Look up the current state of a Event-Based Face Verification session by its
2774
+ * session token. Useful for desktop pollers waiting on the mobile handoff.
2775
+ *
2776
+ * The lookup is scoped by the unguessable, server-issued session token (not
2777
+ * the enumerable forward reference): the endpoint is public/unauthenticated,
2778
+ * and scoping by the token is what prevents cross-tenant status reads.
2779
+ *
2780
+ * @param token - The session token returned by `createEventBasedFaceVerificationSession`.
2781
+ */
2782
+ async getEventBasedFaceVerificationSessionStatus(token) {
2783
+ return this.requestWithRetry(`/api/v1/kyc/face/verify/${encodeURIComponent(token)}`, {
2688
2784
  method: "GET",
2689
2785
  headers: this.getUserHeaders()
2690
2786
  });
2691
2787
  }
2788
+ /**
2789
+ * Fetch the Redis-backed handoff session for a token. Same backing
2790
+ * store as normal KYC (`kyc:session:<token>`, 15-minute TTL). Desktop
2791
+ * callers poll `mobile_connected` to detect when a mobile device has
2792
+ * scanned the QR and attached.
2793
+ *
2794
+ * @param token - The session token returned by `createEventBasedFaceVerificationSession`.
2795
+ */
2796
+ async getHandoffSession(token) {
2797
+ return this.request(
2798
+ `/api/v1/kyc/session${this.buildQueryString({ token })}`,
2799
+ { headers: this.getUserHeaders() }
2800
+ );
2801
+ }
2802
+ /**
2803
+ * Attach a mobile device to a desktop-initiated session. The mobile
2804
+ * client calls this after scanning the QR code. The desktop poller
2805
+ * sees `mobile_connected: true` on the next `getHandoffSession`.
2806
+ *
2807
+ * @param token - The session token transferred via the QR payload.
2808
+ * @param isDisconnect - Pass true to release the session (default false).
2809
+ */
2810
+ async connectMobileSession(token, isDisconnect = false) {
2811
+ return this.request("/api/v1/kyc/session/connect", {
2812
+ method: "PUT",
2813
+ body: JSON.stringify({ token, is_disconnect: isDisconnect }),
2814
+ headers: this.getUserHeaders()
2815
+ });
2816
+ }
2692
2817
  /**
2693
2818
  * Check KYC status for a user
2694
2819
  *
@@ -3047,8 +3172,9 @@ var KycClient = class extends BaseClient {
3047
3172
  */
3048
3173
  async riskProfileRequest(path, options = {}) {
3049
3174
  if (!this.riskProfileBaseURL) {
3050
- throw new Error(
3051
- "Risk Profile Service URL not configured. Please provide riskProfileBaseURL in KycClientConfig."
3175
+ throw new ValidationError(
3176
+ "Risk Profile Service URL not configured. Please provide riskProfileBaseURL in KycClientConfig.",
3177
+ ["riskProfileBaseURL"]
3052
3178
  );
3053
3179
  }
3054
3180
  return this.request(path, {
@@ -3160,6 +3286,19 @@ var KycClient = class extends BaseClient {
3160
3286
  // ============================================================================
3161
3287
  };
3162
3288
 
3289
+ // src/kyc/types.ts
3290
+ var KYC_DECLINED_DESCRIPTIONS = {
3291
+ KYC_DOCUMENT_EXPIRED: "The submitted document has expired",
3292
+ KYC_DOCUMENT_INVALID: "The submitted document could not be verified",
3293
+ KYC_FACE_MISMATCH: "Face verification did not match the identity document",
3294
+ KYC_AGE_REQUIREMENT: "Age requirement not met",
3295
+ KYC_DUPLICATE_IDENTITY: "This identity has already been verified under another account",
3296
+ KYC_ADDRESS_MISMATCH: "Address verification failed",
3297
+ KYC_NAME_MISMATCH: "Name on document does not match the registered name",
3298
+ KYC_PROVIDER_REJECTED: "Identity verification was rejected by the verification provider",
3299
+ KYC_DECLINED: "Identity verification was declined"
3300
+ };
3301
+
3163
3302
  // src/tax/client.ts
3164
3303
  var TaxClient = class extends BaseClient {
3165
3304
  constructor(config) {
@@ -3215,7 +3354,7 @@ var TaxClient = class extends BaseClient {
3215
3354
  }
3216
3355
  async getCustomerDocuments(customerID) {
3217
3356
  return this.request(
3218
- `/api/v1/tax/customer-tax-profiles/${customerID}/documents`
3357
+ `/api/v1/tm/customer-tax-profiles/${customerID}/documents`
3219
3358
  );
3220
3359
  }
3221
3360
  async downloadTaxForm(customerID, requestOptions) {
@@ -3226,41 +3365,6 @@ var TaxClient = class extends BaseClient {
3226
3365
  { ...requestOptions, responseType: "arraybuffer" }
3227
3366
  );
3228
3367
  }
3229
- async runReminders() {
3230
- return this.request("/api/v1/tax/reminders/run", {
3231
- method: "POST"
3232
- });
3233
- }
3234
- /**
3235
- * Update only the reminder configuration (frequency + max count) without
3236
- * touching any other tax rule settings. Fetches current rules first and
3237
- * merges the reminder fields before sending the update.
3238
- *
3239
- * Requires the caller to be authenticated as a Tenant Super Admin.
3240
- * Throws VesantError with status 403 if the role requirement is not met.
3241
- */
3242
- async updateReminderConfig(input) {
3243
- const current = await this.getTaxRules();
3244
- return this.updateTaxRules({
3245
- trigger_account_creation: current.trigger_account_creation,
3246
- trigger_first_withdrawal: current.trigger_first_withdrawal,
3247
- trigger_threshold: current.trigger_threshold,
3248
- trigger_manual: current.trigger_manual,
3249
- trigger_tin_invalid: current.trigger_tin_invalid,
3250
- trigger_w8ben_expiry: current.trigger_w8ben_expiry,
3251
- trigger_tin_expired: current.trigger_tin_expired,
3252
- us_withholding_enabled: current.us_withholding_enabled,
3253
- non_us_withholding_enabled: current.non_us_withholding_enabled,
3254
- transaction_action: current.transaction_action,
3255
- w8ben_expiry_warning_days: current.w8ben_expiry_warning_days,
3256
- tin_verification_due_date: current.tin_verification_due_date,
3257
- email_sending_method: current.email_sending_method,
3258
- display_tin_links_on_platform: current.display_tin_links_on_platform,
3259
- tax_treaty_support: current.tax_treaty_support,
3260
- reminder_frequency_days: input.reminder_frequency_days,
3261
- reminder_max_count: input.reminder_max_count
3262
- });
3263
- }
3264
3368
  // ==========================================================================
3265
3369
  // P2 — Tenant Tax Rules
3266
3370
  // ==========================================================================
@@ -3275,6 +3379,9 @@ var TaxClient = class extends BaseClient {
3275
3379
  });
3276
3380
  return res.version;
3277
3381
  }
3382
+ async runReminders() {
3383
+ return this.request("/api/v1/tax/reminders/run", { method: "POST" });
3384
+ }
3278
3385
  async getComplianceStats(filters) {
3279
3386
  const params = {};
3280
3387
  if (filters?.time_range) params.time_range = filters.time_range;
@@ -3304,136 +3411,15 @@ var TaxClient = class extends BaseClient {
3304
3411
  }
3305
3412
  };
3306
3413
 
3307
- // src/transaction/client.ts
3308
- var TransactionClient = class extends BaseClient {
3309
- constructor(config) {
3310
- super(config);
3311
- }
3312
- // ==========================================================================
3313
- // Transaction creation
3314
- // ==========================================================================
3315
- /**
3316
- * Submit a new transaction record to the monitoring service.
3317
- *
3318
- * The gateway endpoint is `POST /api/v1/tm/transactions` and returns 201
3319
- * with no body on success. The SDK method resolves to `void` to reflect
3320
- * that behaviour.
3321
- *
3322
- * @param request - Data required to create the transaction
3323
- * @param requestOptions - Optional request options (e.g. AbortSignal)
3324
- *
3325
- * @example
3326
- * ```ts
3327
- * const client = new TransactionClient({
3328
- * baseURL: process.env.API_GATEWAY_URL!,
3329
- * tenantId: 'tenant-123',
3330
- * apiKey: 'pk_test_...',
3331
- * });
3332
- *
3333
- * await client.createTransaction({
3334
- * tx_id: 'tx-1',
3335
- * reference: 'ref-1',
3336
- * tenant_id: 'tenant-123',
3337
- * customer_id: 'cust-1',
3338
- * transaction_type: 'deposit',
3339
- * transaction_mode: 'ach',
3340
- * amount: '100.00',
3341
- * currency: 'USD',
3342
- * status: 'pending',
3343
- * source_account: 'acct-1',
3344
- * destination_account: 'acct-2',
3345
- * country: 'US',
3346
- * ip_address: '10.0.0.1',
3347
- * metadata: {},
3348
- * benificiary_comment: '',
3349
- * transaction_date: new Date().toISOString(),
3350
- * });
3351
- * ```
3352
- */
3353
- async createTransaction(request, requestOptions) {
3354
- const data = await this.requestWithRetry("/api/v1/tm/transactions", {
3355
- method: "POST",
3356
- body: JSON.stringify(request)
3357
- }, void 0, void 0, requestOptions);
3358
- return data;
3359
- }
3360
- /**
3361
- *
3362
- * @param transactionId tx_id of the transaction
3363
- * @param requestOptions optional request options (e.g. AbortSignal)
3364
- */
3365
- async getTransaction(transactionId, requestOptions) {
3366
- await this.requestWithRetry(`/api/v1/tm/transactions/status/${transactionId}`, {
3367
- method: "GET"
3368
- }, void 0, void 0, requestOptions);
3369
- }
3370
- };
3371
-
3372
- // src/fraud/client.ts
3373
- var FraudClient = class extends BaseClient {
3374
- /**
3375
- * Submit a single fraud event for scoring.
3376
- */
3377
- async scoreEvent(request, requestOptions) {
3378
- this.validateScoreRequest(request);
3379
- return this.requestWithRetry(
3380
- "/api/v1/fraud/score",
3381
- {
3382
- method: "POST",
3383
- body: JSON.stringify(request)
3384
- },
3385
- void 0,
3386
- void 0,
3387
- requestOptions
3388
- );
3389
- }
3390
- /**
3391
- * Submit multiple fraud events for scoring.
3392
- */
3393
- async scoreEventsBulk(requests, requestOptions) {
3394
- if (!Array.isArray(requests) || requests.length === 0) {
3395
- throw new ValidationError(
3396
- "Invalid bulk score request: at least one score request is required",
3397
- ["requests"]
3398
- );
3399
- }
3400
- requests.forEach((request, index) => this.validateScoreRequest(request, index));
3401
- return this.requestWithRetry(
3402
- "/api/v1/fraud/score/bulk",
3403
- {
3404
- method: "POST",
3405
- body: JSON.stringify(requests)
3406
- },
3407
- void 0,
3408
- void 0,
3409
- requestOptions
3410
- );
3411
- }
3412
- validateScoreRequest(request, index) {
3413
- const errors = [];
3414
- const prefix = index === void 0 ? "" : `requests[${index}].`;
3415
- if (!request.customer_id?.trim()) {
3416
- errors.push(`${prefix}customer_id is required`);
3417
- }
3418
- if (!request.sift_user_id?.trim()) {
3419
- errors.push(`${prefix}sift_user_id is required`);
3420
- }
3421
- if (!request.event_type?.trim()) {
3422
- errors.push(`${prefix}event_type is required`);
3423
- }
3424
- if (errors.length > 0) {
3425
- throw new ValidationError(`Invalid fraud score request: ${errors.join(", ")}`, errors);
3426
- }
3427
- }
3428
- };
3429
-
3430
3414
  // src/webhooks/handler.ts
3431
3415
  var WebhookHandler = class {
3432
3416
  constructor(config) {
3433
3417
  this.handlers = /* @__PURE__ */ new Map();
3434
3418
  this.anyHandlers = [];
3419
+ this.seenEventIds = /* @__PURE__ */ new Map();
3435
3420
  this.secret = config.secret;
3436
3421
  this.tolerance = config.tolerance ?? 3e5;
3422
+ this.replayProtection = config.replayProtection ?? true;
3437
3423
  }
3438
3424
  /**
3439
3425
  * Register a handler for a specific event type.
@@ -3457,7 +3443,7 @@ var WebhookHandler = class {
3457
3443
  async verifyAndParse(body, signature) {
3458
3444
  const isValid = await verifyWebhookSignature(body, signature, this.secret);
3459
3445
  if (!isValid) {
3460
- throw new Error("Invalid webhook signature");
3446
+ throw new ValidationError("Invalid webhook signature", ["signature"]);
3461
3447
  }
3462
3448
  return this.parseAndValidate(body);
3463
3449
  }
@@ -3477,16 +3463,34 @@ var WebhookHandler = class {
3477
3463
  parseAndValidate(body) {
3478
3464
  const event = JSON.parse(body);
3479
3465
  if (!event.type || !event.id || !event.timestamp) {
3480
- throw new Error("Invalid webhook event: missing required fields (type, id, timestamp)");
3466
+ throw new ValidationError("Invalid webhook event: missing required fields (type, id, timestamp)", ["type", "id", "timestamp"]);
3481
3467
  }
3482
3468
  if (this.tolerance > 0) {
3483
3469
  const eventTime = new Date(event.timestamp).getTime();
3484
3470
  const now = Date.now();
3485
3471
  if (Math.abs(now - eventTime) > this.tolerance) {
3486
- throw new Error(
3487
- `Webhook event timestamp is outside tolerance window (${this.tolerance}ms)`
3472
+ throw new ValidationError(
3473
+ `Webhook event timestamp is outside tolerance window (${this.tolerance}ms)`,
3474
+ ["timestamp"]
3475
+ );
3476
+ }
3477
+ }
3478
+ if (this.replayProtection) {
3479
+ if (this.seenEventIds.has(event.id)) {
3480
+ throw new ValidationError(
3481
+ `Duplicate webhook event: ${event.id} has already been processed`,
3482
+ ["id"]
3488
3483
  );
3489
3484
  }
3485
+ const now = Date.now();
3486
+ this.seenEventIds.set(event.id, now);
3487
+ if (this.seenEventIds.size > 1e3) {
3488
+ for (const [id, seenAt] of this.seenEventIds) {
3489
+ if (now - seenAt > this.tolerance) {
3490
+ this.seenEventIds.delete(id);
3491
+ }
3492
+ }
3493
+ }
3490
3494
  }
3491
3495
  return event;
3492
3496
  }
@@ -3519,6 +3523,8 @@ function createWebhookMiddleware(options) {
3519
3523
  res.status(401).json({ error: message });
3520
3524
  } else if (message.includes("tolerance") || message.includes("timestamp")) {
3521
3525
  res.status(400).json({ error: message });
3526
+ } else if (message.includes("Duplicate")) {
3527
+ res.status(409).json({ error: message });
3522
3528
  } else if (next) {
3523
3529
  next(error);
3524
3530
  } else {
@@ -3547,7 +3553,7 @@ function createNextWebhookHandler(options) {
3547
3553
  });
3548
3554
  } catch (error) {
3549
3555
  const message = error instanceof Error ? error.message : "Webhook processing failed";
3550
- const status = message.includes("signature") ? 401 : message.includes("tolerance") || message.includes("timestamp") ? 400 : 500;
3556
+ const status = message.includes("signature") ? 401 : message.includes("tolerance") || message.includes("timestamp") ? 400 : message.includes("Duplicate") ? 409 : 500;
3551
3557
  return new Response(JSON.stringify({ error: message }), {
3552
3558
  status,
3553
3559
  headers: { "Content-Type": "application/json" }
@@ -3579,8 +3585,8 @@ exports.ComplianceBlockedError = ComplianceBlockedError;
3579
3585
  exports.ComplianceClient = ComplianceClient;
3580
3586
  exports.ComplianceError = ComplianceError;
3581
3587
  exports.DEFAULT_CURRENCY_RATES = DEFAULT_CURRENCY_RATES;
3582
- exports.FraudClient = FraudClient;
3583
3588
  exports.GeolocationClient = GeolocationClient;
3589
+ exports.KYC_DECLINED_DESCRIPTIONS = KYC_DECLINED_DESCRIPTIONS;
3584
3590
  exports.KycClient = KycClient;
3585
3591
  exports.NetworkError = NetworkError;
3586
3592
  exports.RateLimitError = RateLimitError;
@@ -3590,7 +3596,6 @@ exports.SDK_VERSION = SDK_VERSION;
3590
3596
  exports.ServiceUnavailableError = ServiceUnavailableError;
3591
3597
  exports.TaxClient = TaxClient;
3592
3598
  exports.TimeoutError = TimeoutError;
3593
- exports.TransactionClient = TransactionClient;
3594
3599
  exports.ValidationError = ValidationError;
3595
3600
  exports.VesantError = VesantError;
3596
3601
  exports.WebhookHandler = WebhookHandler;
@@ -3601,6 +3606,7 @@ exports.decodeCipherText = decodeCipherText;
3601
3606
  exports.generateCipherText = generateCipherText;
3602
3607
  exports.isCipherTextExpired = isCipherTextExpired;
3603
3608
  exports.noopLogger = noopLogger;
3609
+ exports.sdkReasons = sdkReasons;
3604
3610
  exports.verifyWebhookSignature = verifyWebhookSignature;
3605
3611
  //# sourceMappingURL=index.js.map
3606
3612
  //# sourceMappingURL=index.js.map