@retrivora-ai/rag-engine 2.3.7 → 2.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -351,7 +351,7 @@ function projectSettingsToUiConfig(settings) {
351
351
  // package.json
352
352
  var package_default = {
353
353
  name: "@retrivora-ai/rag-engine",
354
- version: "2.3.7",
354
+ version: "2.3.8",
355
355
  description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
356
356
  author: "Abhinav Alkuchi",
357
357
  license: "UNLICENSED",
@@ -522,7 +522,12 @@ var ConfigFetcher = class {
522
522
  process.env.RETRIVORA_CONTROL_PLANE_URL,
523
523
  process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
524
524
  CONTROL_PLANE_URL
525
- ].filter((url) => Boolean(url) && !url.includes("localhost") && !url.includes("127.0.0.1")).map((url) => url.replace(/\/$/, ""));
525
+ ].filter((url) => {
526
+ if (!url) return false;
527
+ const isEnvVar = url === process.env.RETRIVORA_CONTROL_PLANE_URL || url === process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL;
528
+ if (!isEnvVar && (url.includes("localhost") || url.includes("127.0.0.1"))) return false;
529
+ return true;
530
+ }).map((url) => url.replace(/\/$/, ""));
526
531
  for (const baseUrl of controlPlaneUrls) {
527
532
  try {
528
533
  const url = `${baseUrl}/api/v1/config?projectId=${encodeURIComponent(projectId)}`;
@@ -543,8 +548,7 @@ var ConfigFetcher = class {
543
548
  isActive: data.isActive,
544
549
  expiresAt: data.expiresAt,
545
550
  vectorDb: {
546
- // apiKey is not returned by the config API — it's a server-only secret.
547
- // The SDK uses local PINECONE_API_KEY if available.
551
+ // Fetch apiKey from credentials API if available, else fallback to empty
548
552
  apiKey: data.vectorDb.apiKey || "",
549
553
  indexName: data.vectorDb.indexName || "retrivora-free",
550
554
  provider: data.vectorDb.provider || "pinecone",
@@ -576,6 +580,32 @@ var ConfigFetcher = class {
576
580
  data.projectSettings || data.settings
577
581
  )
578
582
  };
583
+ if (licenseKey) {
584
+ try {
585
+ const credUrl = `${baseUrl}/api/v1/credentials`;
586
+ const credRes = await fetch(credUrl, {
587
+ method: "POST",
588
+ headers: {
589
+ "Content-Type": "application/json"
590
+ },
591
+ body: JSON.stringify({ licenseKey, projectId: fetchedProjectId })
592
+ });
593
+ if (credRes.ok) {
594
+ const credData = await credRes.json();
595
+ if ((credData == null ? void 0 : credData.success) && (credData == null ? void 0 : credData.credentials)) {
596
+ if (credData.credentials.pineconeApiKey && !config.vectorDb.apiKey) {
597
+ config.vectorDb.apiKey = credData.credentials.pineconeApiKey;
598
+ }
599
+ if (credData.credentials.litellmApiKey) {
600
+ config.llm.apiKey = credData.credentials.litellmApiKey;
601
+ config.embedding.apiKey = credData.credentials.litellmApiKey;
602
+ }
603
+ }
604
+ }
605
+ } catch (e) {
606
+ console.warn("[ConfigFetcher] Failed to fetch credentials:", e);
607
+ }
608
+ }
579
609
  this.cache.set(cacheKey, { config, cachedAt: now });
580
610
  return config;
581
611
  }
@@ -610,7 +640,8 @@ function ConfigProvider({
610
640
  config,
611
641
  children
612
642
  }) {
613
- const projectId = (config == null ? void 0 : config.projectId) || DEFAULT_CONFIG.projectId;
643
+ const envProjectId = typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_PROJECT_ID || process.env.RETRIVORA_PROJECT_ID : "";
644
+ const projectId = (config == null ? void 0 : config.projectId) || envProjectId || DEFAULT_CONFIG.projectId;
614
645
  const projectSettingsInput = config == null ? void 0 : config.projectSettings;
615
646
  const autoLoadProjectSettings = config == null ? void 0 : config.autoLoadProjectSettings;
616
647
  const licenseKeyInput = config == null ? void 0 : config.licenseKey;
@@ -3571,30 +3602,18 @@ var LicenseValidationError = class extends RetrivoraError {
3571
3602
  };
3572
3603
 
3573
3604
  // src/core/LicenseVerifier.ts
3574
- var crypto = __toESM(require("crypto"));
3575
- var LicenseVerifier = class {
3605
+ var _LicenseVerifier = class _LicenseVerifier {
3606
+ // Cache verified license for 5 minutes
3576
3607
  /**
3577
- * Decodes, verifies signature, and checks metadata of a license key.
3608
+ * Validates the license key asynchronously by calling the Retrivora backend.
3578
3609
  *
3579
3610
  * @param licenseKey - Base64url signed JWT license key.
3580
3611
  * @param currentProjectId - Project namespace ID.
3581
- * @param publicKeyOverride - Optional override for unit/integration tests.
3612
+ * @param provider - Optional provider for tier checks.
3582
3613
  */
3583
- static verify(licenseKey, currentProjectId, provider, publicKeyOverride) {
3614
+ static async verifyAsync(licenseKey, currentProjectId, provider) {
3584
3615
  const isProduction = process.env.NODE_ENV === "production";
3585
3616
  const now = Date.now();
3586
- if (licenseKey) {
3587
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
3588
- const cached = this.cache.get(cacheKey);
3589
- if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
3590
- const currentTimestampSec = Math.floor(now / 1e3);
3591
- if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
3592
- this.cache.delete(cacheKey);
3593
- } else {
3594
- return cached.payload;
3595
- }
3596
- }
3597
- }
3598
3617
  if (!licenseKey) {
3599
3618
  if (isProduction) {
3600
3619
  throw new ConfigurationException(
@@ -3611,52 +3630,61 @@ var LicenseVerifier = class {
3611
3630
  tier: "hobby"
3612
3631
  };
3613
3632
  }
3614
- try {
3615
- const sanitizedKey = (licenseKey || "").trim().replace(/^["']|["']$/g, "").trim();
3616
- const rawToken = sanitizedKey.replace(/^rtv_/i, "").trim();
3617
- const parts = rawToken.split(".");
3618
- if (parts.length !== 3) {
3619
- throw new Error("Malformed token structure (expected 3 parts).");
3620
- }
3621
- const [headerB64, payloadB64, signatureB64] = parts;
3622
- const dataToVerify = `${headerB64}.${payloadB64}`;
3623
- const publicKey = publicKeyOverride != null ? publicKeyOverride : this.PUBLIC_KEY;
3624
- const signature = Buffer.from(signatureB64, "base64url");
3625
- const data = Buffer.from(dataToVerify);
3626
- const isValid = crypto.verify(
3627
- "sha256",
3628
- data,
3629
- publicKey,
3630
- signature
3631
- );
3632
- if (!isValid) {
3633
- throw new Error("Signature verification failed.");
3633
+ const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}`;
3634
+ const cached = this.cache.get(cacheKey);
3635
+ if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
3636
+ const currentTimestampSec = Math.floor(now / 1e3);
3637
+ if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
3638
+ this.cache.delete(cacheKey);
3639
+ } else {
3640
+ return cached.payload;
3634
3641
  }
3635
- const payload = JSON.parse(
3636
- Buffer.from(payloadB64, "base64url").toString("utf8")
3637
- );
3638
- if (!payload.projectId) {
3639
- throw new Error('License payload is missing "projectId".');
3642
+ }
3643
+ try {
3644
+ let baseUrl = typeof process !== "undefined" && process.env.RETRIVORA_CONTROL_PLANE_URL ? process.env.RETRIVORA_CONTROL_PLANE_URL : "https://retrivora.com";
3645
+ if (typeof process !== "undefined" && process.env.TELEMETRY_URL) {
3646
+ baseUrl = process.env.TELEMETRY_URL.replace(/\/api\/telemetry\/?$/, "");
3640
3647
  }
3641
- const isProjectMatch = payload.projectId === currentProjectId || payload.projectId === `retrivora-${currentProjectId}` || `retrivora-${payload.projectId}` === currentProjectId;
3642
- if (!isProjectMatch) {
3643
- throw new Error(
3644
- `Project ID mismatch. License is bound to project namespace "${payload.projectId}" but configuration has "${currentProjectId}".`
3645
- );
3648
+ const endpoint = `${baseUrl}/api/v1/license/validate`;
3649
+ const response = await fetch(endpoint, {
3650
+ method: "POST",
3651
+ headers: {
3652
+ "Content-Type": "application/json",
3653
+ "x-license-key": licenseKey
3654
+ },
3655
+ body: JSON.stringify({
3656
+ licenseKey,
3657
+ projectId: currentProjectId,
3658
+ provider
3659
+ })
3660
+ });
3661
+ if (!response.ok) {
3662
+ let errMessage = `HTTP ${response.status}`;
3663
+ try {
3664
+ const body = await response.json();
3665
+ if (body.message) errMessage = body.message;
3666
+ } catch (e) {
3667
+ }
3668
+ throw new Error(errMessage);
3646
3669
  }
3647
- if (!payload.expiresAt) {
3648
- throw new Error('License payload is missing expiration ("expiresAt").');
3670
+ const data = await response.json();
3671
+ if (!data.valid) {
3672
+ throw new Error(data.message || "License validation failed by server.");
3649
3673
  }
3650
- const currentTimestampSec = Math.floor(Date.now() / 1e3);
3651
- if (currentTimestampSec > payload.expiresAt) {
3652
- throw new Error(
3653
- `License key has expired. Expiration: ${new Date(
3654
- payload.expiresAt * 1e3
3655
- ).toDateString()}`
3656
- );
3674
+ let expiresAtNum = Math.floor(Date.now() / 1e3) + 100 * 365 * 24 * 60 * 60;
3675
+ if (data.expiresAt) {
3676
+ expiresAtNum = Math.floor(new Date(data.expiresAt).getTime() / 1e3);
3657
3677
  }
3678
+ const tier = _LicenseVerifier.extractTier(licenseKey);
3679
+ const payload = {
3680
+ projectId: currentProjectId,
3681
+ expiresAt: expiresAtNum,
3682
+ tier,
3683
+ licenseStatus: data.licenseStatus,
3684
+ minimumSupportedVersion: data.minimumSupportedVersion,
3685
+ forceUpgrade: data.forceUpgrade
3686
+ };
3658
3687
  if (isProduction && provider) {
3659
- const tier = (payload.tier || "").toLowerCase();
3660
3688
  const normalizedProvider = provider.toLowerCase();
3661
3689
  if (tier === "hobby") {
3662
3690
  const allowedHobby = ["postgresql", "pgvector", "supabase"];
@@ -3684,15 +3712,12 @@ var LicenseVerifier = class {
3684
3712
  }
3685
3713
  }
3686
3714
  }
3687
- if (licenseKey) {
3688
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
3689
- this.cache.set(cacheKey, { payload, cachedAt: now });
3690
- }
3715
+ this.cache.set(cacheKey, { payload, cachedAt: now });
3691
3716
  return payload;
3692
3717
  } catch (err) {
3693
3718
  const message = err instanceof Error ? err.message : String(err);
3694
3719
  throw new ConfigurationException(
3695
- `[Retrivora SDK] License key validation failed: ${message}`
3720
+ `[Retrivora SDK] License key validation failed via API: ${message}`
3696
3721
  );
3697
3722
  }
3698
3723
  }
@@ -3761,23 +3786,25 @@ var LicenseVerifier = class {
3761
3786
  }
3762
3787
  }
3763
3788
  }
3789
+ static extractTier(licenseKey) {
3790
+ if (!licenseKey) return "hobby";
3791
+ try {
3792
+ const sanitizedKey = licenseKey.trim().replace(/^["']|["']$/g, "").trim();
3793
+ const rawToken = sanitizedKey.replace(/^rtv_/i, "").trim();
3794
+ const parts = rawToken.split(".");
3795
+ if (parts.length === 3) {
3796
+ const decodedPayload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
3797
+ if (decodedPayload.tier) return decodedPayload.tier;
3798
+ }
3799
+ } catch (e) {
3800
+ }
3801
+ return "hobby";
3802
+ }
3764
3803
  };
3765
- // A simple in-memory cache to save CPU overhead of cryptographic signature checks.
3766
- LicenseVerifier.cache = /* @__PURE__ */ new Map();
3767
- LicenseVerifier.CACHE_TTL_MS = 60 * 1e3;
3768
- // Cache verified license for 60 seconds
3769
- // Retrivora's Public Key used to verify the license key signature.
3770
- // In production, this matches the private key held by Retrivora SaaS.
3771
- // Rotate this key only when the signing private key is replaced.
3772
- LicenseVerifier.PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
3773
- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyKvvOSYdCimG3b236ebV
3774
- jpG88xQiU8dSiaMahtBJDf4w0AewRj7hMNgmeZ1wyTOj8kVgeGBOolp1Z0QmTr6O
3775
- Tj4EDQ/zjsg12If7hSf3NiwLHCYmMLslyK0aaP6PQoTrYkBv3GNdkMecrIjKCijb
3776
- 6VvDLLF3X696melTVM0z/d2e50BW2AlRw/rf1EqYi10d0BcPo5zje0XETr/WGmqu
3777
- sDiXtsP5MlwkL9X7RQY2uovRa+l/vOAqAfdmJ+OzXuk5P7mDUPb+gCtKnoDbb1tr
3778
- 6UAu733dkUnetAcMqyT3fNPBLO66DCc6m9rGCYYAaG7piMEDwG0/ZySZBFbgllJc
3779
- 6QIDAQAB
3780
- -----END PUBLIC KEY-----`;
3804
+ // In-memory cache to save network overhead on hot paths.
3805
+ _LicenseVerifier.cache = /* @__PURE__ */ new Map();
3806
+ _LicenseVerifier.CACHE_TTL_MS = 5 * 60 * 1e3;
3807
+ var LicenseVerifier = _LicenseVerifier;
3781
3808
 
3782
3809
  // src/core/LicenseValidator.ts
3783
3810
  function canUseLocalValidationFallback(baseUrl, status) {
@@ -3839,6 +3866,7 @@ var _LicenseValidator = class _LicenseValidator {
3839
3866
  retrivoraApiBase,
3840
3867
  headers: customHeaders
3841
3868
  } = request;
3869
+ const effectiveProjectId = projectId || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_PROJECT_ID || process.env.RETRIVORA_PROJECT_ID : "") || "";
3842
3870
  const getHeader = (name) => {
3843
3871
  if (!customHeaders) return void 0;
3844
3872
  const target = name.toLowerCase();
@@ -3876,7 +3904,7 @@ var _LicenseValidator = class _LicenseValidator {
3876
3904
  }, customHeaders || {}),
3877
3905
  body: JSON.stringify({
3878
3906
  licenseKey: effectiveLicenseKey,
3879
- projectId,
3907
+ projectId: effectiveProjectId,
3880
3908
  sdkVersion,
3881
3909
  sdk,
3882
3910
  platform
@@ -3887,7 +3915,7 @@ var _LicenseValidator = class _LicenseValidator {
3887
3915
  if (!canUseLocalValidationFallback(base)) {
3888
3916
  throw err;
3889
3917
  }
3890
- const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || "");
3918
+ const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
3891
3919
  const fallbackResp = {
3892
3920
  valid: true,
3893
3921
  licenseStatus: "ACTIVE",
@@ -3906,7 +3934,7 @@ var _LicenseValidator = class _LicenseValidator {
3906
3934
  }
3907
3935
  if (res && !res.ok && canUseLocalValidationFallback(base, res.status)) {
3908
3936
  try {
3909
- const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || "");
3937
+ const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
3910
3938
  const fallbackResp = {
3911
3939
  valid: true,
3912
3940
  licenseStatus: "ACTIVE",
@@ -4688,7 +4716,6 @@ function ChatWidget({ position, onAddToCart, apiUrl, retrivoraApiBase, licenseKe
4688
4716
  "button",
4689
4717
  {
4690
4718
  onClick: isOpen ? () => setIsOpen(false) : handleOpen,
4691
- disabled: isWidgetLocked && !isOpen,
4692
4719
  "aria-label": isWidgetLocked ? "Chat unavailable - invalid or missing license key" : isOpen ? "Close chat" : "Open chat",
4693
4720
  "aria-disabled": isWidgetLocked && !isOpen,
4694
4721
  className: `group fixed z-[9999] w-14 h-14 drop-shadow-2xl flex items-center justify-center transition-all duration-300 ${positionClass} ${isWidgetLocked && !isOpen ? "grayscale opacity-60 cursor-not-allowed" : "cursor-pointer hover:scale-110 active:scale-95"}`,
package/dist/index.mjs CHANGED
@@ -307,7 +307,7 @@ function projectSettingsToUiConfig(settings) {
307
307
  // package.json
308
308
  var package_default = {
309
309
  name: "@retrivora-ai/rag-engine",
310
- version: "2.3.7",
310
+ version: "2.3.8",
311
311
  description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
312
312
  author: "Abhinav Alkuchi",
313
313
  license: "UNLICENSED",
@@ -478,7 +478,12 @@ var ConfigFetcher = class {
478
478
  process.env.RETRIVORA_CONTROL_PLANE_URL,
479
479
  process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
480
480
  CONTROL_PLANE_URL
481
- ].filter((url) => Boolean(url) && !url.includes("localhost") && !url.includes("127.0.0.1")).map((url) => url.replace(/\/$/, ""));
481
+ ].filter((url) => {
482
+ if (!url) return false;
483
+ const isEnvVar = url === process.env.RETRIVORA_CONTROL_PLANE_URL || url === process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL;
484
+ if (!isEnvVar && (url.includes("localhost") || url.includes("127.0.0.1"))) return false;
485
+ return true;
486
+ }).map((url) => url.replace(/\/$/, ""));
482
487
  for (const baseUrl of controlPlaneUrls) {
483
488
  try {
484
489
  const url = `${baseUrl}/api/v1/config?projectId=${encodeURIComponent(projectId)}`;
@@ -499,8 +504,7 @@ var ConfigFetcher = class {
499
504
  isActive: data.isActive,
500
505
  expiresAt: data.expiresAt,
501
506
  vectorDb: {
502
- // apiKey is not returned by the config API — it's a server-only secret.
503
- // The SDK uses local PINECONE_API_KEY if available.
507
+ // Fetch apiKey from credentials API if available, else fallback to empty
504
508
  apiKey: data.vectorDb.apiKey || "",
505
509
  indexName: data.vectorDb.indexName || "retrivora-free",
506
510
  provider: data.vectorDb.provider || "pinecone",
@@ -532,6 +536,32 @@ var ConfigFetcher = class {
532
536
  data.projectSettings || data.settings
533
537
  )
534
538
  };
539
+ if (licenseKey) {
540
+ try {
541
+ const credUrl = `${baseUrl}/api/v1/credentials`;
542
+ const credRes = await fetch(credUrl, {
543
+ method: "POST",
544
+ headers: {
545
+ "Content-Type": "application/json"
546
+ },
547
+ body: JSON.stringify({ licenseKey, projectId: fetchedProjectId })
548
+ });
549
+ if (credRes.ok) {
550
+ const credData = await credRes.json();
551
+ if ((credData == null ? void 0 : credData.success) && (credData == null ? void 0 : credData.credentials)) {
552
+ if (credData.credentials.pineconeApiKey && !config.vectorDb.apiKey) {
553
+ config.vectorDb.apiKey = credData.credentials.pineconeApiKey;
554
+ }
555
+ if (credData.credentials.litellmApiKey) {
556
+ config.llm.apiKey = credData.credentials.litellmApiKey;
557
+ config.embedding.apiKey = credData.credentials.litellmApiKey;
558
+ }
559
+ }
560
+ }
561
+ } catch (e) {
562
+ console.warn("[ConfigFetcher] Failed to fetch credentials:", e);
563
+ }
564
+ }
535
565
  this.cache.set(cacheKey, { config, cachedAt: now });
536
566
  return config;
537
567
  }
@@ -566,7 +596,8 @@ function ConfigProvider({
566
596
  config,
567
597
  children
568
598
  }) {
569
- const projectId = (config == null ? void 0 : config.projectId) || DEFAULT_CONFIG.projectId;
599
+ const envProjectId = typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_PROJECT_ID || process.env.RETRIVORA_PROJECT_ID : "";
600
+ const projectId = (config == null ? void 0 : config.projectId) || envProjectId || DEFAULT_CONFIG.projectId;
570
601
  const projectSettingsInput = config == null ? void 0 : config.projectSettings;
571
602
  const autoLoadProjectSettings = config == null ? void 0 : config.autoLoadProjectSettings;
572
603
  const licenseKeyInput = config == null ? void 0 : config.licenseKey;
@@ -3573,30 +3604,18 @@ var LicenseValidationError = class extends RetrivoraError {
3573
3604
  };
3574
3605
 
3575
3606
  // src/core/LicenseVerifier.ts
3576
- import * as crypto from "crypto";
3577
- var LicenseVerifier = class {
3607
+ var _LicenseVerifier = class _LicenseVerifier {
3608
+ // Cache verified license for 5 minutes
3578
3609
  /**
3579
- * Decodes, verifies signature, and checks metadata of a license key.
3610
+ * Validates the license key asynchronously by calling the Retrivora backend.
3580
3611
  *
3581
3612
  * @param licenseKey - Base64url signed JWT license key.
3582
3613
  * @param currentProjectId - Project namespace ID.
3583
- * @param publicKeyOverride - Optional override for unit/integration tests.
3614
+ * @param provider - Optional provider for tier checks.
3584
3615
  */
3585
- static verify(licenseKey, currentProjectId, provider, publicKeyOverride) {
3616
+ static async verifyAsync(licenseKey, currentProjectId, provider) {
3586
3617
  const isProduction = process.env.NODE_ENV === "production";
3587
3618
  const now = Date.now();
3588
- if (licenseKey) {
3589
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
3590
- const cached = this.cache.get(cacheKey);
3591
- if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
3592
- const currentTimestampSec = Math.floor(now / 1e3);
3593
- if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
3594
- this.cache.delete(cacheKey);
3595
- } else {
3596
- return cached.payload;
3597
- }
3598
- }
3599
- }
3600
3619
  if (!licenseKey) {
3601
3620
  if (isProduction) {
3602
3621
  throw new ConfigurationException(
@@ -3613,52 +3632,61 @@ var LicenseVerifier = class {
3613
3632
  tier: "hobby"
3614
3633
  };
3615
3634
  }
3616
- try {
3617
- const sanitizedKey = (licenseKey || "").trim().replace(/^["']|["']$/g, "").trim();
3618
- const rawToken = sanitizedKey.replace(/^rtv_/i, "").trim();
3619
- const parts = rawToken.split(".");
3620
- if (parts.length !== 3) {
3621
- throw new Error("Malformed token structure (expected 3 parts).");
3622
- }
3623
- const [headerB64, payloadB64, signatureB64] = parts;
3624
- const dataToVerify = `${headerB64}.${payloadB64}`;
3625
- const publicKey = publicKeyOverride != null ? publicKeyOverride : this.PUBLIC_KEY;
3626
- const signature = Buffer.from(signatureB64, "base64url");
3627
- const data = Buffer.from(dataToVerify);
3628
- const isValid = crypto.verify(
3629
- "sha256",
3630
- data,
3631
- publicKey,
3632
- signature
3633
- );
3634
- if (!isValid) {
3635
- throw new Error("Signature verification failed.");
3635
+ const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}`;
3636
+ const cached = this.cache.get(cacheKey);
3637
+ if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
3638
+ const currentTimestampSec = Math.floor(now / 1e3);
3639
+ if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
3640
+ this.cache.delete(cacheKey);
3641
+ } else {
3642
+ return cached.payload;
3636
3643
  }
3637
- const payload = JSON.parse(
3638
- Buffer.from(payloadB64, "base64url").toString("utf8")
3639
- );
3640
- if (!payload.projectId) {
3641
- throw new Error('License payload is missing "projectId".');
3644
+ }
3645
+ try {
3646
+ let baseUrl = typeof process !== "undefined" && process.env.RETRIVORA_CONTROL_PLANE_URL ? process.env.RETRIVORA_CONTROL_PLANE_URL : "https://retrivora.com";
3647
+ if (typeof process !== "undefined" && process.env.TELEMETRY_URL) {
3648
+ baseUrl = process.env.TELEMETRY_URL.replace(/\/api\/telemetry\/?$/, "");
3642
3649
  }
3643
- const isProjectMatch = payload.projectId === currentProjectId || payload.projectId === `retrivora-${currentProjectId}` || `retrivora-${payload.projectId}` === currentProjectId;
3644
- if (!isProjectMatch) {
3645
- throw new Error(
3646
- `Project ID mismatch. License is bound to project namespace "${payload.projectId}" but configuration has "${currentProjectId}".`
3647
- );
3650
+ const endpoint = `${baseUrl}/api/v1/license/validate`;
3651
+ const response = await fetch(endpoint, {
3652
+ method: "POST",
3653
+ headers: {
3654
+ "Content-Type": "application/json",
3655
+ "x-license-key": licenseKey
3656
+ },
3657
+ body: JSON.stringify({
3658
+ licenseKey,
3659
+ projectId: currentProjectId,
3660
+ provider
3661
+ })
3662
+ });
3663
+ if (!response.ok) {
3664
+ let errMessage = `HTTP ${response.status}`;
3665
+ try {
3666
+ const body = await response.json();
3667
+ if (body.message) errMessage = body.message;
3668
+ } catch (e) {
3669
+ }
3670
+ throw new Error(errMessage);
3648
3671
  }
3649
- if (!payload.expiresAt) {
3650
- throw new Error('License payload is missing expiration ("expiresAt").');
3672
+ const data = await response.json();
3673
+ if (!data.valid) {
3674
+ throw new Error(data.message || "License validation failed by server.");
3651
3675
  }
3652
- const currentTimestampSec = Math.floor(Date.now() / 1e3);
3653
- if (currentTimestampSec > payload.expiresAt) {
3654
- throw new Error(
3655
- `License key has expired. Expiration: ${new Date(
3656
- payload.expiresAt * 1e3
3657
- ).toDateString()}`
3658
- );
3676
+ let expiresAtNum = Math.floor(Date.now() / 1e3) + 100 * 365 * 24 * 60 * 60;
3677
+ if (data.expiresAt) {
3678
+ expiresAtNum = Math.floor(new Date(data.expiresAt).getTime() / 1e3);
3659
3679
  }
3680
+ const tier = _LicenseVerifier.extractTier(licenseKey);
3681
+ const payload = {
3682
+ projectId: currentProjectId,
3683
+ expiresAt: expiresAtNum,
3684
+ tier,
3685
+ licenseStatus: data.licenseStatus,
3686
+ minimumSupportedVersion: data.minimumSupportedVersion,
3687
+ forceUpgrade: data.forceUpgrade
3688
+ };
3660
3689
  if (isProduction && provider) {
3661
- const tier = (payload.tier || "").toLowerCase();
3662
3690
  const normalizedProvider = provider.toLowerCase();
3663
3691
  if (tier === "hobby") {
3664
3692
  const allowedHobby = ["postgresql", "pgvector", "supabase"];
@@ -3686,15 +3714,12 @@ var LicenseVerifier = class {
3686
3714
  }
3687
3715
  }
3688
3716
  }
3689
- if (licenseKey) {
3690
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
3691
- this.cache.set(cacheKey, { payload, cachedAt: now });
3692
- }
3717
+ this.cache.set(cacheKey, { payload, cachedAt: now });
3693
3718
  return payload;
3694
3719
  } catch (err) {
3695
3720
  const message = err instanceof Error ? err.message : String(err);
3696
3721
  throw new ConfigurationException(
3697
- `[Retrivora SDK] License key validation failed: ${message}`
3722
+ `[Retrivora SDK] License key validation failed via API: ${message}`
3698
3723
  );
3699
3724
  }
3700
3725
  }
@@ -3763,23 +3788,25 @@ var LicenseVerifier = class {
3763
3788
  }
3764
3789
  }
3765
3790
  }
3791
+ static extractTier(licenseKey) {
3792
+ if (!licenseKey) return "hobby";
3793
+ try {
3794
+ const sanitizedKey = licenseKey.trim().replace(/^["']|["']$/g, "").trim();
3795
+ const rawToken = sanitizedKey.replace(/^rtv_/i, "").trim();
3796
+ const parts = rawToken.split(".");
3797
+ if (parts.length === 3) {
3798
+ const decodedPayload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
3799
+ if (decodedPayload.tier) return decodedPayload.tier;
3800
+ }
3801
+ } catch (e) {
3802
+ }
3803
+ return "hobby";
3804
+ }
3766
3805
  };
3767
- // A simple in-memory cache to save CPU overhead of cryptographic signature checks.
3768
- LicenseVerifier.cache = /* @__PURE__ */ new Map();
3769
- LicenseVerifier.CACHE_TTL_MS = 60 * 1e3;
3770
- // Cache verified license for 60 seconds
3771
- // Retrivora's Public Key used to verify the license key signature.
3772
- // In production, this matches the private key held by Retrivora SaaS.
3773
- // Rotate this key only when the signing private key is replaced.
3774
- LicenseVerifier.PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
3775
- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyKvvOSYdCimG3b236ebV
3776
- jpG88xQiU8dSiaMahtBJDf4w0AewRj7hMNgmeZ1wyTOj8kVgeGBOolp1Z0QmTr6O
3777
- Tj4EDQ/zjsg12If7hSf3NiwLHCYmMLslyK0aaP6PQoTrYkBv3GNdkMecrIjKCijb
3778
- 6VvDLLF3X696melTVM0z/d2e50BW2AlRw/rf1EqYi10d0BcPo5zje0XETr/WGmqu
3779
- sDiXtsP5MlwkL9X7RQY2uovRa+l/vOAqAfdmJ+OzXuk5P7mDUPb+gCtKnoDbb1tr
3780
- 6UAu733dkUnetAcMqyT3fNPBLO66DCc6m9rGCYYAaG7piMEDwG0/ZySZBFbgllJc
3781
- 6QIDAQAB
3782
- -----END PUBLIC KEY-----`;
3806
+ // In-memory cache to save network overhead on hot paths.
3807
+ _LicenseVerifier.cache = /* @__PURE__ */ new Map();
3808
+ _LicenseVerifier.CACHE_TTL_MS = 5 * 60 * 1e3;
3809
+ var LicenseVerifier = _LicenseVerifier;
3783
3810
 
3784
3811
  // src/core/LicenseValidator.ts
3785
3812
  function canUseLocalValidationFallback(baseUrl, status) {
@@ -3841,6 +3868,7 @@ var _LicenseValidator = class _LicenseValidator {
3841
3868
  retrivoraApiBase,
3842
3869
  headers: customHeaders
3843
3870
  } = request;
3871
+ const effectiveProjectId = projectId || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_PROJECT_ID || process.env.RETRIVORA_PROJECT_ID : "") || "";
3844
3872
  const getHeader = (name) => {
3845
3873
  if (!customHeaders) return void 0;
3846
3874
  const target = name.toLowerCase();
@@ -3878,7 +3906,7 @@ var _LicenseValidator = class _LicenseValidator {
3878
3906
  }, customHeaders || {}),
3879
3907
  body: JSON.stringify({
3880
3908
  licenseKey: effectiveLicenseKey,
3881
- projectId,
3909
+ projectId: effectiveProjectId,
3882
3910
  sdkVersion,
3883
3911
  sdk,
3884
3912
  platform
@@ -3889,7 +3917,7 @@ var _LicenseValidator = class _LicenseValidator {
3889
3917
  if (!canUseLocalValidationFallback(base)) {
3890
3918
  throw err;
3891
3919
  }
3892
- const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || "");
3920
+ const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
3893
3921
  const fallbackResp = {
3894
3922
  valid: true,
3895
3923
  licenseStatus: "ACTIVE",
@@ -3908,7 +3936,7 @@ var _LicenseValidator = class _LicenseValidator {
3908
3936
  }
3909
3937
  if (res && !res.ok && canUseLocalValidationFallback(base, res.status)) {
3910
3938
  try {
3911
- const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || "");
3939
+ const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
3912
3940
  const fallbackResp = {
3913
3941
  valid: true,
3914
3942
  licenseStatus: "ACTIVE",
@@ -4690,7 +4718,6 @@ function ChatWidget({ position, onAddToCart, apiUrl, retrivoraApiBase, licenseKe
4690
4718
  "button",
4691
4719
  {
4692
4720
  onClick: isOpen ? () => setIsOpen(false) : handleOpen,
4693
- disabled: isWidgetLocked && !isOpen,
4694
4721
  "aria-label": isWidgetLocked ? "Chat unavailable - invalid or missing license key" : isOpen ? "Close chat" : "Open chat",
4695
4722
  "aria-disabled": isWidgetLocked && !isOpen,
4696
4723
  className: `group fixed z-[9999] w-14 h-14 drop-shadow-2xl flex items-center justify-center transition-all duration-300 ${positionClass} ${isWidgetLocked && !isOpen ? "grayscale opacity-60 cursor-not-allowed" : "cursor-pointer hover:scale-110 active:scale-95"}`,