vesant-sdk 1.7.0-dev.6f300f7 → 1.7.0-dev.6f4bf05

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 (61) hide show
  1. package/dist/{client-D9JZgN3X.d.ts → client-0NOPDnT0.d.ts} +15 -25
  2. package/dist/{client-BG8KtVMc.d.mts → client-CvWNRwwg.d.mts} +15 -25
  3. package/dist/{client-CRZea-eJ.d.mts → client-Dps40EtF.d.mts} +1 -1
  4. package/dist/{client-749WqhDT.d.ts → client-SMxqod4j.d.ts} +1 -1
  5. package/dist/compliance/index.d.mts +2 -2
  6. package/dist/compliance/index.d.ts +2 -2
  7. package/dist/compliance/index.js +71 -12
  8. package/dist/compliance/index.js.map +1 -1
  9. package/dist/compliance/index.mjs +71 -12
  10. package/dist/compliance/index.mjs.map +1 -1
  11. package/dist/decisions/index.js +6 -0
  12. package/dist/decisions/index.js.map +1 -1
  13. package/dist/decisions/index.mjs +6 -0
  14. package/dist/decisions/index.mjs.map +1 -1
  15. package/dist/geolocation/index.d.mts +58 -3
  16. package/dist/geolocation/index.d.ts +58 -3
  17. package/dist/geolocation/index.js +74 -12
  18. package/dist/geolocation/index.js.map +1 -1
  19. package/dist/geolocation/index.mjs +72 -13
  20. package/dist/geolocation/index.mjs.map +1 -1
  21. package/dist/index-CPOrMRaH.d.ts +264 -0
  22. package/dist/index-CimDmgZb.d.mts +264 -0
  23. package/dist/index.d.mts +23 -6
  24. package/dist/index.d.ts +23 -6
  25. package/dist/index.js +186 -33
  26. package/dist/index.js.map +1 -1
  27. package/dist/index.mjs +181 -34
  28. package/dist/index.mjs.map +1 -1
  29. package/dist/kyc/core.js +6 -0
  30. package/dist/kyc/core.js.map +1 -1
  31. package/dist/kyc/core.mjs +6 -0
  32. package/dist/kyc/core.mjs.map +1 -1
  33. package/dist/kyc/index.js +6 -0
  34. package/dist/kyc/index.js.map +1 -1
  35. package/dist/kyc/index.mjs +6 -0
  36. package/dist/kyc/index.mjs.map +1 -1
  37. package/dist/react.d.mts +6 -2
  38. package/dist/react.d.ts +6 -2
  39. package/dist/react.js +68 -4
  40. package/dist/react.js.map +1 -1
  41. package/dist/react.mjs +68 -4
  42. package/dist/react.mjs.map +1 -1
  43. package/dist/risk-profile/index.js +6 -0
  44. package/dist/risk-profile/index.js.map +1 -1
  45. package/dist/risk-profile/index.mjs +6 -0
  46. package/dist/risk-profile/index.mjs.map +1 -1
  47. package/dist/scores/index.js +6 -0
  48. package/dist/scores/index.js.map +1 -1
  49. package/dist/scores/index.mjs +6 -0
  50. package/dist/scores/index.mjs.map +1 -1
  51. package/dist/tax/index.js +6 -0
  52. package/dist/tax/index.js.map +1 -1
  53. package/dist/tax/index.mjs +6 -0
  54. package/dist/tax/index.mjs.map +1 -1
  55. package/dist/webhooks/index.d.mts +2 -189
  56. package/dist/webhooks/index.d.ts +2 -189
  57. package/dist/webhooks/index.js +85 -21
  58. package/dist/webhooks/index.js.map +1 -1
  59. package/dist/webhooks/index.mjs +85 -22
  60. package/dist/webhooks/index.mjs.map +1 -1
  61. package/package.json +4 -1
package/dist/index.mjs CHANGED
@@ -378,6 +378,12 @@ var BaseClient = class {
378
378
  if (!config.tenantId?.trim()) {
379
379
  throw new ValidationError("tenantId is required and must be a non-empty string", ["tenantId"]);
380
380
  }
381
+ if (typeof fetch === "undefined") {
382
+ throw new VesantError(
383
+ "The Vesant SDK requires a global fetch (Node.js >= 18). Upgrade Node or provide a fetch polyfill.",
384
+ "RUNTIME_UNSUPPORTED"
385
+ );
386
+ }
381
387
  this.interceptors = config.interceptors || [];
382
388
  this.logger = config.logger || createConsoleLogger();
383
389
  let environment = config.environment;
@@ -722,8 +728,46 @@ var BaseClient = class {
722
728
  }
723
729
  };
724
730
 
731
+ // src/core/pagination.ts
732
+ async function* paginate(fetchPage) {
733
+ let page = 1;
734
+ let totalPages;
735
+ do {
736
+ const response = await fetchPage(page);
737
+ const items = response.data ?? [];
738
+ for (const item of items) {
739
+ yield item;
740
+ }
741
+ totalPages = response.total_pages ?? page;
742
+ if (items.length === 0) {
743
+ break;
744
+ }
745
+ page += 1;
746
+ } while (page <= totalPages);
747
+ }
748
+ async function collectAll(fetchPage) {
749
+ const items = [];
750
+ for await (const item of paginate(fetchPage)) {
751
+ items.push(item);
752
+ }
753
+ return items;
754
+ }
755
+
725
756
  // src/core/webhook-utils.ts
726
- async function verifyWebhookSignature(payload, signature, secret) {
757
+ async function verifyWebhookSignature(payload, signature, secret, opts = {}) {
758
+ const signed = parseSignedTimestamp(signature);
759
+ if (signed) {
760
+ const tolerance = opts.tolerance ?? 3e5;
761
+ const now = opts.now?.() ?? Date.now();
762
+ if (tolerance > 0 && Math.abs(now - signed.t * 1e3) > tolerance) {
763
+ return false;
764
+ }
765
+ const expected = await computeHmacSha256(`${signed.t}.${payload}`, secret);
766
+ return constantTimeEqual(signed.v1, expected);
767
+ }
768
+ if (opts.allowLegacy === false) {
769
+ return false;
770
+ }
727
771
  const hexDigest = await computeHmacSha256(payload, secret);
728
772
  const expectedPrefixed = `sha256=${hexDigest}`;
729
773
  if (signature.startsWith("sha256=")) {
@@ -731,6 +775,25 @@ async function verifyWebhookSignature(payload, signature, secret) {
731
775
  }
732
776
  return constantTimeEqual(signature, hexDigest);
733
777
  }
778
+ function parseSignedTimestamp(signature) {
779
+ if (!signature.includes("t=") || !signature.includes("v1=")) {
780
+ return null;
781
+ }
782
+ let t;
783
+ let v1;
784
+ for (const part of signature.split(",")) {
785
+ const eq = part.indexOf("=");
786
+ if (eq === -1) continue;
787
+ const key = part.slice(0, eq).trim();
788
+ const value = part.slice(eq + 1).trim();
789
+ if (key === "t") t = Number(value);
790
+ else if (key === "v1") v1 = value;
791
+ }
792
+ if (t === void 0 || Number.isNaN(t) || !v1) {
793
+ return null;
794
+ }
795
+ return { t, v1 };
796
+ }
734
797
  async function computeHmacSha256(message, secret) {
735
798
  if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
736
799
  const encoder = new TextEncoder();
@@ -765,6 +828,61 @@ function constantTimeEqual(a, b) {
765
828
  return result === 0;
766
829
  }
767
830
 
831
+ // src/geolocation/integrity.ts
832
+ var isNil = (v) => v === null || v === void 0;
833
+ function assessGpsIntegrity(input, opts = {}) {
834
+ const flags = [];
835
+ const now = opts.now ?? (() => Date.now());
836
+ const maxAgeMs = opts.maxAgeMs ?? 6e4;
837
+ const minAccuracy = opts.minAccuracyMeters ?? 1;
838
+ const { accuracy, altitude, altitudeAccuracy, heading, speed, timestamp } = input;
839
+ if (isNil(accuracy)) {
840
+ flags.push("accuracy_missing");
841
+ } else if (accuracy === 0) {
842
+ flags.push("accuracy_zero");
843
+ } else if (accuracy < minAccuracy) {
844
+ flags.push("accuracy_implausibly_small");
845
+ }
846
+ const hasMotion = !isNil(heading) || !isNil(speed);
847
+ if (hasMotion && (isNil(accuracy) || accuracy === 0)) {
848
+ flags.push("motion_without_accuracy");
849
+ }
850
+ if (!isNil(altitude) && isNil(altitudeAccuracy)) {
851
+ flags.push("altitude_without_accuracy");
852
+ }
853
+ if (timestamp !== void 0 && now() - timestamp > maxAgeMs) {
854
+ flags.push("stale_timestamp");
855
+ }
856
+ if (opts.permissionState === "denied" || opts.permissionState === "prompt") {
857
+ flags.push(`permission_${opts.permissionState}`);
858
+ }
859
+ return { suspicious: flags.length > 0, flags };
860
+ }
861
+ function gpsIntegrityInputFromPosition(position) {
862
+ const c = position.coords;
863
+ return {
864
+ latitude: c.latitude,
865
+ longitude: c.longitude,
866
+ accuracy: c.accuracy,
867
+ altitude: c.altitude,
868
+ altitudeAccuracy: c.altitudeAccuracy,
869
+ heading: c.heading,
870
+ speed: c.speed,
871
+ timestamp: position.timestamp
872
+ };
873
+ }
874
+ async function probeGeolocationPermission() {
875
+ try {
876
+ if (typeof navigator === "undefined" || !navigator.permissions?.query) {
877
+ return "unavailable";
878
+ }
879
+ const status = await navigator.permissions.query({ name: "geolocation" });
880
+ return status.state;
881
+ } catch {
882
+ return "unavailable";
883
+ }
884
+ }
885
+
768
886
  // src/geolocation/ciphertext.ts
769
887
  var CIPHER_TEXT_EXPIRY_MINUTES = 5;
770
888
  async function computeHMAC(key, message) {
@@ -817,6 +935,7 @@ async function requestGPSLocation(timeout = 1e4, highAccuracy = true) {
817
935
  if (typeof navigator === "undefined" || !navigator.geolocation) {
818
936
  return null;
819
937
  }
938
+ const permissionState = await probeGeolocationPermission();
820
939
  return new Promise((resolve) => {
821
940
  navigator.geolocation.getCurrentPosition(
822
941
  (position) => {
@@ -833,6 +952,7 @@ async function requestGPSLocation(timeout = 1e4, highAccuracy = true) {
833
952
  resolve(null);
834
953
  return;
835
954
  }
955
+ const { flags } = assessGpsIntegrity(gpsIntegrityInputFromPosition(position), { permissionState });
836
956
  resolve({
837
957
  latitude,
838
958
  longitude,
@@ -841,7 +961,8 @@ async function requestGPSLocation(timeout = 1e4, highAccuracy = true) {
841
961
  altitude_accuracy: position.coords.altitudeAccuracy ?? void 0,
842
962
  heading: position.coords.heading ?? void 0,
843
963
  speed: position.coords.speed ?? void 0,
844
- timestamp: position.timestamp
964
+ timestamp: position.timestamp,
965
+ integrity_flags: flags.length ? flags : void 0
845
966
  });
846
967
  },
847
968
  () => {
@@ -908,6 +1029,9 @@ async function generateCipherText(options, config) {
908
1029
  );
909
1030
  if (location) {
910
1031
  locationData = location;
1032
+ if (location.integrity_flags?.length) {
1033
+ warnings.push(`GPS integrity flags (advisory): ${location.integrity_flags.join(", ")}`);
1034
+ }
911
1035
  } else if (gpsRequiredByConfig) {
912
1036
  throw new VesantError(
913
1037
  `GPS location is required for ${options.reason} by tenant configuration, but GPS was not available or permission was denied`,
@@ -1027,8 +1151,8 @@ var GeolocationClient = class extends BaseClient {
1027
1151
  * ```
1028
1152
  */
1029
1153
  async verifyIP(request, requestOptions) {
1030
- if (!request.ip_address?.trim()) {
1031
- throw new ValidationError("ip_address is required and must be a non-empty string", ["ip_address"]);
1154
+ if (request.ip_address !== void 0 && !request.ip_address.trim()) {
1155
+ throw new ValidationError("ip_address, when provided, must be a non-empty string", ["ip_address"]);
1032
1156
  }
1033
1157
  return this.requestWithRetry("/api/v1/geo/verify", {
1034
1158
  method: "POST",
@@ -1378,20 +1502,12 @@ var GeolocationClient = class extends BaseClient {
1378
1502
  *
1379
1503
  * @example
1380
1504
  * ```typescript
1381
- * // Using GPS (preferred)
1505
+ * // GPS (the web SDK is GPS + IP only; the server handles the IP fallback)
1382
1506
  * const result = await client.captureLocation(token, {
1383
1507
  * latitude: 37.7749,
1384
1508
  * longitude: -122.4194,
1385
1509
  * accuracy: 10
1386
1510
  * });
1387
- *
1388
- * // Using WiFi positioning (fallback)
1389
- * const result = await client.captureLocation(token, {
1390
- * wifi_networks: [
1391
- * { macAddress: "00:11:22:33:44:55", signalStrength: -50 },
1392
- * { macAddress: "AA:BB:CC:DD:EE:FF", signalStrength: -70 }
1393
- * ]
1394
- * });
1395
1511
  * ```
1396
1512
  */
1397
1513
  async captureLocation(token, capture, requestOptions) {
@@ -3524,15 +3640,48 @@ var TaxClient = class extends BaseClient {
3524
3640
  }
3525
3641
  };
3526
3642
 
3643
+ // src/webhooks/dedup.ts
3644
+ var InMemoryDedupStore = class {
3645
+ constructor(opts = {}) {
3646
+ this.expiryById = /* @__PURE__ */ new Map();
3647
+ this.maxEntries = opts.maxEntries ?? 1e3;
3648
+ this.now = opts.now ?? (() => Date.now());
3649
+ }
3650
+ async seen(id) {
3651
+ return this.expiryById.has(id);
3652
+ }
3653
+ async mark(id, ttlMs) {
3654
+ const now = this.now();
3655
+ this.expiryById.set(id, now + ttlMs);
3656
+ if (this.expiryById.size > this.maxEntries) {
3657
+ for (const [key, expiresAt] of this.expiryById) {
3658
+ if (now > expiresAt) {
3659
+ this.expiryById.delete(key);
3660
+ }
3661
+ }
3662
+ }
3663
+ }
3664
+ };
3665
+
3527
3666
  // src/webhooks/handler.ts
3667
+ function resolveEventId(event) {
3668
+ if (event.id) {
3669
+ return event.id;
3670
+ }
3671
+ if (event.event_type === "notification.created") {
3672
+ return event.notification?.id;
3673
+ }
3674
+ return void 0;
3675
+ }
3528
3676
  var WebhookHandler = class {
3529
3677
  constructor(config) {
3530
3678
  this.handlers = /* @__PURE__ */ new Map();
3531
3679
  this.anyHandlers = [];
3532
- this.seenEventIds = /* @__PURE__ */ new Map();
3533
3680
  this.secret = config.secret;
3534
3681
  this.tolerance = config.tolerance ?? 3e5;
3535
3682
  this.replayProtection = config.replayProtection ?? true;
3683
+ this.allowLegacySignature = config.allowLegacySignature ?? true;
3684
+ this.dedupStore = config.dedupStore ?? new InMemoryDedupStore();
3536
3685
  }
3537
3686
  /**
3538
3687
  * Register a handler for a specific event type.
@@ -3554,7 +3703,10 @@ var WebhookHandler = class {
3554
3703
  * Verify signature and parse the webhook body.
3555
3704
  */
3556
3705
  async verifyAndParse(body, signature) {
3557
- const isValid = await verifyWebhookSignature(body, signature, this.secret);
3706
+ const isValid = await verifyWebhookSignature(body, signature, this.secret, {
3707
+ tolerance: this.tolerance,
3708
+ allowLegacy: this.allowLegacySignature
3709
+ });
3558
3710
  if (!isValid) {
3559
3711
  throw new ValidationError("Invalid webhook signature", ["signature"]);
3560
3712
  }
@@ -3570,18 +3722,21 @@ var WebhookHandler = class {
3570
3722
  /**
3571
3723
  * Parse an event without signature verification (for testing).
3572
3724
  */
3573
- parseEvent(body) {
3725
+ async parseEvent(body) {
3574
3726
  return this.parseAndValidate(body);
3575
3727
  }
3576
- parseAndValidate(body) {
3728
+ async parseAndValidate(body) {
3577
3729
  const event = JSON.parse(body);
3578
- if (!event.type || !event.id || !event.timestamp) {
3579
- throw new ValidationError("Invalid webhook event: missing required fields (type, id, timestamp)", ["type", "id", "timestamp"]);
3730
+ const eventId = resolveEventId(event);
3731
+ if (!event.event_type || !eventId || !event.timestamp) {
3732
+ throw new ValidationError(
3733
+ "Invalid webhook event: missing required fields (event_type, id, timestamp)",
3734
+ ["event_type", "id", "timestamp"]
3735
+ );
3580
3736
  }
3581
3737
  if (this.tolerance > 0) {
3582
3738
  const eventTime = new Date(event.timestamp).getTime();
3583
- const now = Date.now();
3584
- if (Math.abs(now - eventTime) > this.tolerance) {
3739
+ if (Math.abs(Date.now() - eventTime) > this.tolerance) {
3585
3740
  throw new ValidationError(
3586
3741
  `Webhook event timestamp is outside tolerance window (${this.tolerance}ms)`,
3587
3742
  ["timestamp"]
@@ -3589,26 +3744,18 @@ var WebhookHandler = class {
3589
3744
  }
3590
3745
  }
3591
3746
  if (this.replayProtection) {
3592
- if (this.seenEventIds.has(event.id)) {
3747
+ if (await this.dedupStore.seen(eventId)) {
3593
3748
  throw new ValidationError(
3594
- `Duplicate webhook event: ${event.id} has already been processed`,
3749
+ `Duplicate webhook event: ${eventId} has already been processed`,
3595
3750
  ["id"]
3596
3751
  );
3597
3752
  }
3598
- const now = Date.now();
3599
- this.seenEventIds.set(event.id, now);
3600
- if (this.seenEventIds.size > 1e3) {
3601
- for (const [id, seenAt] of this.seenEventIds) {
3602
- if (now - seenAt > this.tolerance) {
3603
- this.seenEventIds.delete(id);
3604
- }
3605
- }
3606
- }
3753
+ await this.dedupStore.mark(eventId, this.tolerance);
3607
3754
  }
3608
3755
  return event;
3609
3756
  }
3610
3757
  async dispatch(event) {
3611
- const typeHandlers = this.handlers.get(event.type) || [];
3758
+ const typeHandlers = this.handlers.get(event.event_type) || [];
3612
3759
  const allHandlers = [...typeHandlers, ...this.anyHandlers];
3613
3760
  for (const handler of allHandlers) {
3614
3761
  await handler(event);
@@ -3689,6 +3836,6 @@ function buildHandler(options) {
3689
3836
  return handler;
3690
3837
  }
3691
3838
 
3692
- export { AuthenticationError, BaseClient, CGSError, CircuitBreaker, CircuitBreakerOpenError, ComplianceBlockedError, ComplianceClient, ComplianceError, DEFAULT_CURRENCY_RATES, GeolocationClient, KYC_DECLINED_DESCRIPTIONS, KycClient, NetworkError, RateLimitError, RateLimitTracker, RefreshingTokenProvider, RiskProfileClient, SDK_VERSION, ServiceUnavailableError, StaticApiKeyProvider, TaxClient, TimeoutError, ValidationError, VesantError, WebhookHandler, createConsoleLogger, createNextWebhookHandler, createWebhookMiddleware, decodeCipherText, generateCipherText, isCipherTextExpired, noopLogger, sdkReasons, verifyWebhookSignature };
3839
+ export { AuthenticationError, BaseClient, CGSError, CircuitBreaker, CircuitBreakerOpenError, ComplianceBlockedError, ComplianceClient, ComplianceError, DEFAULT_CURRENCY_RATES, GeolocationClient, InMemoryDedupStore, KYC_DECLINED_DESCRIPTIONS, KycClient, NetworkError, RateLimitError, RateLimitTracker, RefreshingTokenProvider, RiskProfileClient, SDK_VERSION, ServiceUnavailableError, StaticApiKeyProvider, TaxClient, TimeoutError, ValidationError, VesantError, WebhookHandler, assessGpsIntegrity, collectAll, createConsoleLogger, createNextWebhookHandler, createWebhookMiddleware, decodeCipherText, generateCipherText, gpsIntegrityInputFromPosition, isCipherTextExpired, noopLogger, paginate, probeGeolocationPermission, sdkReasons, verifyWebhookSignature };
3693
3840
  //# sourceMappingURL=index.mjs.map
3694
3841
  //# sourceMappingURL=index.mjs.map