@retrivora-ai/rag-engine 2.3.7 → 2.3.9

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@retrivora-ai/rag-engine",
3
- "version": "2.3.7",
3
+ "version": "2.3.9",
4
4
  "description": "Retrivora AI is a plug-and-play AI engine for RAG chat experiences — generic vector DB + LLM provider, embeddable or standalone.",
5
5
  "author": "Abhinav Alkuchi",
6
6
  "license": "UNLICENSED",
@@ -325,7 +325,6 @@ export function ChatWidget({ position, onAddToCart, apiUrl, retrivoraApiBase, li
325
325
  {/* ── Floating Action Button ── */}
326
326
  <button
327
327
  onClick={isOpen ? () => setIsOpen(false) : handleOpen}
328
- disabled={isWidgetLocked && !isOpen}
329
328
  aria-label={isWidgetLocked ? 'Chat unavailable - invalid or missing license key' : (isOpen ? 'Close chat' : 'Open chat')}
330
329
  aria-disabled={isWidgetLocked && !isOpen}
331
330
  className={`group fixed z-[9999] w-14 h-14 drop-shadow-2xl flex items-center justify-center transition-all duration-300 ${positionClass} ${
@@ -30,7 +30,8 @@ export function ConfigProvider({
30
30
  config,
31
31
  children,
32
32
  }: ConfigProviderProps) {
33
- const projectId = config?.projectId || DEFAULT_CONFIG.projectId;
33
+ const envProjectId = typeof process !== 'undefined' ? (process.env.NEXT_PUBLIC_RETRIVORA_PROJECT_ID || process.env.RETRIVORA_PROJECT_ID) : '';
34
+ const projectId = config?.projectId || envProjectId || DEFAULT_CONFIG.projectId;
34
35
  const projectSettingsInput = config?.projectSettings;
35
36
  const autoLoadProjectSettings = config?.autoLoadProjectSettings;
36
37
  const licenseKeyInput = config?.licenseKey;
@@ -11,6 +11,19 @@ interface FileState {
11
11
  error?: string;
12
12
  }
13
13
 
14
+ function decodeLicenseTier(licenseKey?: string): string {
15
+ if (!licenseKey) return 'free';
16
+ try {
17
+ const parts = licenseKey.split('.');
18
+ if (parts.length >= 2) {
19
+ const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
20
+ const payload = JSON.parse(atob(base64));
21
+ return payload?.tier || 'free';
22
+ }
23
+ } catch { /* ignore */ }
24
+ return 'free';
25
+ }
26
+
14
27
  export function DocumentUpload({ namespace, uploadUrl, retrivoraApiBase, onUploadComplete, className = '' }: DocumentUploadProps) {
15
28
  const { ui, embedding, projectId, licenseKey, headers: configHeaders, retrivoraApiBase: configuredApiBase } = useConfig();
16
29
  const [fileStates, setFileStates] = useState<FileState[]>([]);
@@ -25,7 +38,17 @@ export function DocumentUpload({ namespace, uploadUrl, retrivoraApiBase, onUploa
25
38
  namespaceUsed: string;
26
39
  } | null>(null);
27
40
 
28
- const isFreeTier = !projectId || projectId.includes('free') || projectId.includes('demo');
41
+ const resolvedLicenseKey = licenseKey ||
42
+ configHeaders?.['x-license-key'] ||
43
+ configHeaders?.['X-License-Key'] ||
44
+ configHeaders?.['authorization']?.replace(/^Bearer\s+/i, '') ||
45
+ configHeaders?.['Authorization']?.replace(/^Bearer\s+/i, '');
46
+
47
+ const licenseTier = decodeLicenseTier(resolvedLicenseKey);
48
+ const isFreeTier = !projectId ||
49
+ projectId.includes('free') ||
50
+ projectId.includes('demo') ||
51
+ ['free_trial', 'free_tier', 'free', 'hobby'].includes(licenseTier.toLowerCase());
29
52
 
30
53
  const MULTI_DIMENSION_MODELS: Record<string, number[]> = {
31
54
  'text-embedding-3-small': [512, 1536],
@@ -195,22 +218,18 @@ export function DocumentUpload({ namespace, uploadUrl, retrivoraApiBase, onUploa
195
218
  <select
196
219
  value={dimension}
197
220
  onChange={(e) => setDimension(Number(e.target.value))}
198
- disabled={isUploading}
221
+ disabled={isUploading || availableDimensions.length <= 1}
199
222
  className="px-3 py-1.5 rounded-lg bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 text-slate-800 dark:text-white/90 outline-none focus:border-emerald-500 transition-colors text-sm font-medium cursor-pointer"
200
223
  >
201
- {COMMON_DIMENSIONS.map(dim => {
202
- const isDisabled = isFreeTier && dim !== 768;
203
- return (
204
- <option
205
- key={dim}
206
- value={dim}
207
- disabled={isDisabled}
208
- className="bg-white dark:bg-slate-900 text-slate-800 dark:text-white disabled:text-slate-400 dark:disabled:text-white/30"
209
- >
210
- {dim}
211
- </option>
212
- );
213
- })}
224
+ {availableDimensions.map(dim => (
225
+ <option
226
+ key={dim}
227
+ value={dim}
228
+ className="bg-white dark:bg-slate-900 text-slate-800 dark:text-white"
229
+ >
230
+ {dim}
231
+ </option>
232
+ ))}
214
233
  </select>
215
234
  </div>
216
235
  </div>
@@ -220,8 +220,7 @@ export function getEnvConfig(env: Record<string, string | undefined> = process.e
220
220
  const isFreeTier = (() => {
221
221
  if (!licenseKey) return true;
222
222
  try {
223
- const payload = LicenseVerifier.verify(licenseKey, projectId);
224
- const tier = (payload.tier || '').toLowerCase();
223
+ const tier = LicenseVerifier.extractTier(licenseKey).toLowerCase();
225
224
  return tier === 'free_trial' || tier === 'free_tier' || tier === 'free' || tier === 'hobby';
226
225
  } catch {
227
226
  return true;
@@ -234,7 +233,10 @@ export function getEnvConfig(env: Record<string, string | undefined> = process.e
234
233
 
235
234
  // Default gateway: always use LiteLLM at llm.retrivora.com for end-users
236
235
  // End-users provide license key + project ID; the gateway validates and routes internally
237
- const defaultGatewayUrl = 'https://llm.retrivora.com/api/v1';
236
+ const controlPlaneUrl = readString(env, 'RETRIVORA_CONTROL_PLANE_URL') ?? readString(env, 'NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL');
237
+ const defaultGatewayUrl = controlPlaneUrl
238
+ ? `${controlPlaneUrl.replace(/\/$/, '')}/api/v1`
239
+ : 'https://llm.retrivora.com/api/v1';
238
240
 
239
241
  // ── Runtime-injected tier config (from /api/v1/config + /api/v1/credentials) ──
240
242
  // Priority: explicit env var > injected runtime config > static tier fallback
@@ -249,7 +251,7 @@ export function getEnvConfig(env: Record<string, string | undefined> = process.e
249
251
  // llmApiKey: LITELLM_MASTER_KEY env wins, then injected litellm key, then licenseKey
250
252
  const llmApiKey = readString(env, 'LITELLM_MASTER_KEY') ?? rt?.litellmApiKey ?? base?.llm?.apiKey ?? licenseKey;
251
253
  const llmProfile = readString(env, 'LLM_UNIVERSAL_PROFILE') ?? (base?.llm?.options?.profile as string) ?? 'litellm';
252
-
254
+
253
255
  console.log('[serverConfig] 🔧 LLM Configuration:', {
254
256
  baseUrl: llmBaseUrl,
255
257
  model: llmModel,
@@ -257,7 +259,7 @@ export function getEnvConfig(env: Record<string, string | undefined> = process.e
257
259
  hasApiKey: !!llmApiKey,
258
260
  source: rt?.llmModel ? 'runtime-injected' : 'env/fallback',
259
261
  });
260
-
262
+
261
263
  const defaultEmbeddingProvider = 'universal_rest';
262
264
  const embeddingProvider = (readEnum(env, 'EMBEDDING_PROVIDER', defaultEmbeddingProvider, EMBEDDING_PROVIDERS) ?? base?.embedding?.provider ?? defaultEmbeddingProvider) as EmbeddingProvider;
263
265
  const embeddingBaseUrl = readString(env, 'LITELLM_BASE_URL') ?? readString(env, 'EMBEDDING_BASE_URL') ?? readString(env, 'LLM_BASE_URL') ?? base?.embedding?.baseUrl ?? rt?.embeddingBaseUrl ?? rt?.llmBaseUrl ?? defaultGatewayUrl;
@@ -265,6 +267,14 @@ export function getEnvConfig(env: Record<string, string | undefined> = process.e
265
267
  // embeddingApiKey: same key as LLM (LiteLLM gateway handles both)
266
268
  const embeddingApiKey = readString(env, 'LITELLM_MASTER_KEY') ?? rt?.litellmApiKey ?? base?.embedding?.apiKey ?? licenseKey;
267
269
  const embeddingProfile = readString(env, 'EMBEDDING_UNIVERSAL_PROFILE') ?? (base?.embedding?.options?.profile as string) ?? 'litellm';
270
+
271
+ console.log('[serverConfig] 🔧 Embedding Configuration:', {
272
+ baseUrl: embeddingBaseUrl,
273
+ model: embeddingModel,
274
+ provider: embeddingProvider,
275
+ hasApiKey: !!embeddingApiKey,
276
+ source: rt?.embeddingModel ? 'runtime-injected' : 'env/fallback',
277
+ });
268
278
 
269
279
  return {
270
280
  projectId,
@@ -101,12 +101,19 @@ export class ConfigFetcher {
101
101
  process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
102
102
  CONTROL_PLANE_URL,
103
103
  ]
104
- .filter((url): url is string => Boolean(url) && !url!.includes('localhost') && !url!.includes('127.0.0.1'))
104
+ .filter((url): url is string => {
105
+ if (!url) return false;
106
+ // Allow localhost only if explicitly configured via env vars, otherwise prevent it for security
107
+ const isEnvVar = url === process.env.RETRIVORA_CONTROL_PLANE_URL || url === process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL;
108
+ if (!isEnvVar && (url.includes('localhost') || url.includes('127.0.0.1'))) return false;
109
+ return true;
110
+ })
105
111
  .map((url) => url.replace(/\/$/, ''));
106
112
 
107
113
  for (const baseUrl of controlPlaneUrls) {
108
114
  try {
109
115
  const url = `${baseUrl}/api/v1/config?projectId=${encodeURIComponent(projectId)}`;
116
+ console.log(`[ConfigFetcher] Fetching config from: ${url}`);
110
117
  const res = await fetch(url, {
111
118
  method: 'GET',
112
119
  headers: {
@@ -116,6 +123,11 @@ export class ConfigFetcher {
116
123
  },
117
124
  });
118
125
 
126
+ console.log(`[ConfigFetcher] Response status: ${res.status}`);
127
+ if (!res.ok) {
128
+ console.warn(`[ConfigFetcher] Error text: ${await res.text()}`);
129
+ }
130
+
119
131
  if (res.ok) {
120
132
  const data = await res.json();
121
133
  // NOTE: The config API intentionally does NOT return vectorDb.apiKey (server-only secret).
@@ -128,8 +140,7 @@ export class ConfigFetcher {
128
140
  isActive: data.isActive,
129
141
  expiresAt: data.expiresAt,
130
142
  vectorDb: {
131
- // apiKey is not returned by the config API — it's a server-only secret.
132
- // The SDK uses local PINECONE_API_KEY if available.
143
+ // Fetch apiKey from credentials API if available, else fallback to empty
133
144
  apiKey: data.vectorDb.apiKey || '',
134
145
  indexName: data.vectorDb.indexName || 'retrivora-free',
135
146
  provider: data.vectorDb.provider || 'pinecone',
@@ -161,6 +172,34 @@ export class ConfigFetcher {
161
172
  data.projectSettings || data.settings
162
173
  ),
163
174
  };
175
+ // Now fetch credentials if licenseKey is provided
176
+ if (licenseKey) {
177
+ try {
178
+ const credUrl = `${baseUrl}/api/v1/credentials`;
179
+ const credRes = await fetch(credUrl, {
180
+ method: 'POST',
181
+ headers: {
182
+ 'Content-Type': 'application/json',
183
+ },
184
+ body: JSON.stringify({ licenseKey, projectId: fetchedProjectId }),
185
+ });
186
+ if (credRes.ok) {
187
+ const credData = await credRes.json();
188
+ if (credData?.success && credData?.credentials) {
189
+ if (credData.credentials.pineconeApiKey && !config.vectorDb.apiKey) {
190
+ config.vectorDb.apiKey = credData.credentials.pineconeApiKey;
191
+ }
192
+ if (credData.credentials.litellmApiKey) {
193
+ config.llm.apiKey = credData.credentials.litellmApiKey;
194
+ config.embedding.apiKey = credData.credentials.litellmApiKey;
195
+ }
196
+ }
197
+ }
198
+ } catch (e) {
199
+ console.warn('[ConfigFetcher] Failed to fetch credentials:', e);
200
+ }
201
+ }
202
+
164
203
  this.cache.set(cacheKey, { config, cachedAt: now });
165
204
  return config;
166
205
  }
@@ -59,7 +59,7 @@ export class DatabaseStorage {
59
59
  * In non-production (development / test) environments this is a complete no-op —
60
60
  * all History and Feedback features are freely accessible for local development.
61
61
  */
62
- private checkPremiumSubscription() {
62
+ private async checkPremiumSubscription() {
63
63
  // ── Development / test: fully open, no checks ────────────────────────────
64
64
  if (process.env.NODE_ENV !== 'production') {
65
65
  return;
@@ -73,7 +73,7 @@ export class DatabaseStorage {
73
73
  }
74
74
 
75
75
  try {
76
- const payload = LicenseVerifier.verify(this.config.licenseKey, this.config.projectId);
76
+ const payload = await LicenseVerifier.verifyAsync(this.config.licenseKey, this.config.projectId);
77
77
  const tier = (payload.tier || '').toLowerCase();
78
78
  if (
79
79
  tier !== 'premium' &&
@@ -98,15 +98,15 @@ export class DatabaseStorage {
98
98
  }
99
99
  }
100
100
 
101
- private checkHistoryEnabled() {
102
- this.checkPremiumSubscription();
101
+ private async checkHistoryEnabled() {
102
+ await this.checkPremiumSubscription();
103
103
  if (this.config.rag?.history?.enabled === false) {
104
104
  throw new Error('[Retrivora SDK] Chat History is disabled in RagConfig.');
105
105
  }
106
106
  }
107
107
 
108
- private checkFeedbackEnabled() {
109
- this.checkPremiumSubscription();
108
+ private async checkFeedbackEnabled() {
109
+ await this.checkPremiumSubscription();
110
110
  if (this.config.rag?.feedback?.enabled === false) {
111
111
  throw new Error('[Retrivora SDK] User Feedback is disabled in RagConfig.');
112
112
  }
@@ -225,7 +225,7 @@ export class DatabaseStorage {
225
225
  sessionId: string,
226
226
  message: Omit<HistoryMessage, 'createdAt'>
227
227
  ): Promise<void> {
228
- this.checkHistoryEnabled();
228
+ await this.checkHistoryEnabled();
229
229
  const createdAt = new Date().toISOString();
230
230
  const msgId = message.id || `msg_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
231
231
 
@@ -292,7 +292,7 @@ export class DatabaseStorage {
292
292
  }
293
293
 
294
294
  async getHistory(sessionId: string, projectIds?: string[]): Promise<HistoryMessage[]> {
295
- this.checkHistoryEnabled();
295
+ await this.checkHistoryEnabled();
296
296
  if (projectIds && projectIds.length > 0 && !this.sessionInScope(sessionId, projectIds)) {
297
297
  return [];
298
298
  }
@@ -332,7 +332,7 @@ export class DatabaseStorage {
332
332
  }
333
333
 
334
334
  async clearHistory(sessionId: string, projectIds?: string[]): Promise<void> {
335
- this.checkHistoryEnabled();
335
+ await this.checkHistoryEnabled();
336
336
  if (projectIds && projectIds.length > 0 && !this.sessionInScope(sessionId, projectIds)) {
337
337
  return;
338
338
  }
@@ -371,7 +371,7 @@ export class DatabaseStorage {
371
371
  }
372
372
 
373
373
  async listSessions(projectIds?: string[]): Promise<string[]> {
374
- this.checkHistoryEnabled();
374
+ await this.checkHistoryEnabled();
375
375
  let raw: string[] = [];
376
376
  if (this.provider === 'postgresql' || this.provider === 'pgvector') {
377
377
  const pool = await this.getPGPool();
@@ -392,7 +392,7 @@ export class DatabaseStorage {
392
392
  // ─── Feedback Operations ──────────────────────────────────────────────────
393
393
 
394
394
  async saveFeedback(feedback: Omit<FeedbackItem, 'id' | 'createdAt'>): Promise<void> {
395
- this.checkFeedbackEnabled();
395
+ await this.checkFeedbackEnabled();
396
396
  const id = `fb_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
397
397
  const createdAt = new Date().toISOString();
398
398
 
@@ -445,7 +445,7 @@ export class DatabaseStorage {
445
445
  }
446
446
 
447
447
  async getFeedback(messageId: string, projectIds?: string[]): Promise<FeedbackItem | null> {
448
- this.checkFeedbackEnabled();
448
+ await this.checkFeedbackEnabled();
449
449
  let item: FeedbackItem | null = null;
450
450
  if (this.provider === 'postgresql' || this.provider === 'pgvector') {
451
451
  const pool = await this.getPGPool();
@@ -482,7 +482,7 @@ export class DatabaseStorage {
482
482
  }
483
483
 
484
484
  async listFeedback(projectIds?: string[]): Promise<FeedbackItem[]> {
485
- this.checkFeedbackEnabled();
485
+ await this.checkFeedbackEnabled();
486
486
  let raw: FeedbackItem[] = [];
487
487
  if (this.provider === 'postgresql' || this.provider === 'pgvector') {
488
488
  const pool = await this.getPGPool();
@@ -143,6 +143,8 @@ export class LicenseValidator {
143
143
  headers: customHeaders,
144
144
  } = request;
145
145
 
146
+ const effectiveProjectId = projectId || (typeof process !== 'undefined' ? (process.env.NEXT_PUBLIC_RETRIVORA_PROJECT_ID || process.env.RETRIVORA_PROJECT_ID) : '') || '';
147
+
146
148
  const getHeader = (name: string): string | undefined => {
147
149
  if (!customHeaders) return undefined;
148
150
  const target = name.toLowerCase();
@@ -196,7 +198,7 @@ export class LicenseValidator {
196
198
  },
197
199
  body: JSON.stringify({
198
200
  licenseKey: effectiveLicenseKey,
199
- projectId,
201
+ projectId: effectiveProjectId,
200
202
  sdkVersion,
201
203
  sdk,
202
204
  platform,
@@ -208,7 +210,7 @@ export class LicenseValidator {
208
210
  if (!canUseLocalValidationFallback(base)) {
209
211
  throw err;
210
212
  }
211
- const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || '');
213
+ const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
212
214
  const fallbackResp: LicenseValidationResponse = {
213
215
  valid: true,
214
216
  licenseStatus: 'ACTIVE',
@@ -231,7 +233,7 @@ export class LicenseValidator {
231
233
  // Authoritative denials (403 revoked/expired, 426 unsupported SDK, etc.) must not
232
234
  // be bypassed by local JWT verification.
233
235
  try {
234
- const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || '');
236
+ const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
235
237
  const fallbackResp: LicenseValidationResponse = {
236
238
  valid: true,
237
239
  licenseStatus: 'ACTIVE',
@@ -1,96 +1,44 @@
1
- import * as crypto from 'crypto';
2
1
  import { ConfigurationException } from '../exceptions';
3
2
 
4
3
  /**
5
4
  * Decoded payload of a Retrivora license JWT.
6
- *
7
- * Retrivora licenses are signed with RS256 using a key held exclusively by
8
- * Retrivora SaaS. They carry the project binding, the expiration time, and
9
- * the customer tier, which the SDK uses to enforce per-tier feature limits
10
- * (vector DB provider whitelist).
11
5
  */
12
6
  export interface LicensePayload {
13
- /** Project ID this license is bound to — used to prevent cross-tenant reuse. */
14
7
  projectId: string;
15
- /** UNIX timestamp in seconds after which the license must be considered expired. */
16
8
  expiresAt: number;
17
- /** Customer tier (hobby | pro | enterprise). */
18
9
  tier: string;
19
- /** Optional: License lifecycle status propagated by the server validator (ACTIVE/TERMINATED/etc). */
20
10
  licenseStatus?: string;
11
+ minimumSupportedVersion?: string;
12
+ forceUpgrade?: boolean;
21
13
  }
22
14
 
23
15
  /**
24
- * Zero-latency cryptographic license verifier.
25
- *
26
- * Responsibilities:
27
- * 1. Parse the `rtv_`-prefixed JWT (base64url header.payload.signature)
28
- * 2. Verify the RS256 signature against Retrivora's embedded PUBLIC_KEY
29
- * 3. Match the license's projectId to the currently configured projectId
30
- * 4. Enforce expiration (current UNIX seconds > expiresAt)
31
- * 5. Enforce per-tier vector DB provider whitelist in production
32
- *
33
- * Fail-open policy: In non-production environments a missing license key
34
- * produces a console-warning and a synthetic 24h "hobby" payload so that
35
- * local development continues to work without signing up. In production
36
- * any missing/invalid key throws `ConfigurationException`.
37
- *
38
- * Caching: Cryptographic verification is CPU-expensive — successful results
39
- * are cached for 60 seconds keyed by (licenseKey, projectId, provider,
40
- * publicKeyOverride). Cache hits still re-verify expiresAt.
16
+ * Validates licenses against the central Retrivora API.
17
+ * Replaces the old zero-latency local cryptographic verifier.
41
18
  */
42
19
  export class LicenseVerifier {
43
- // A simple in-memory cache to save CPU overhead of cryptographic signature checks.
20
+ // In-memory cache to save network overhead on hot paths.
44
21
  private static readonly cache = new Map<
45
22
  string,
46
23
  { payload: LicensePayload; cachedAt: number }
47
24
  >();
48
- private static readonly CACHE_TTL_MS = 60 * 1000; // Cache verified license for 60 seconds
49
-
50
- // Retrivora's Public Key used to verify the license key signature.
51
- // In production, this matches the private key held by Retrivora SaaS.
52
- // Rotate this key only when the signing private key is replaced.
53
- private static readonly PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
54
- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyKvvOSYdCimG3b236ebV
55
- jpG88xQiU8dSiaMahtBJDf4w0AewRj7hMNgmeZ1wyTOj8kVgeGBOolp1Z0QmTr6O
56
- Tj4EDQ/zjsg12If7hSf3NiwLHCYmMLslyK0aaP6PQoTrYkBv3GNdkMecrIjKCijb
57
- 6VvDLLF3X696melTVM0z/d2e50BW2AlRw/rf1EqYi10d0BcPo5zje0XETr/WGmqu
58
- sDiXtsP5MlwkL9X7RQY2uovRa+l/vOAqAfdmJ+OzXuk5P7mDUPb+gCtKnoDbb1tr
59
- 6UAu733dkUnetAcMqyT3fNPBLO66DCc6m9rGCYYAaG7piMEDwG0/ZySZBFbgllJc
60
- 6QIDAQAB
61
- -----END PUBLIC KEY-----`;
25
+ private static readonly CACHE_TTL_MS = 5 * 60 * 1000; // Cache verified license for 5 minutes
62
26
 
63
27
  /**
64
- * Decodes, verifies signature, and checks metadata of a license key.
28
+ * Validates the license key asynchronously by calling the Retrivora backend.
65
29
  *
66
30
  * @param licenseKey - Base64url signed JWT license key.
67
31
  * @param currentProjectId - Project namespace ID.
68
- * @param publicKeyOverride - Optional override for unit/integration tests.
32
+ * @param provider - Optional provider for tier checks.
69
33
  */
70
- static verify(
34
+ static async verifyAsync(
71
35
  licenseKey: string | undefined,
72
36
  currentProjectId: string,
73
- provider?: string,
74
- publicKeyOverride?: string
75
- ): LicensePayload {
37
+ provider?: string
38
+ ): Promise<LicensePayload> {
76
39
  const isProduction = process.env.NODE_ENV === 'production';
77
40
  const now = Date.now();
78
41
 
79
- // Check verification cache to bypass crypto computations on hot paths
80
- if (licenseKey) {
81
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ''}:${publicKeyOverride || ''}`;
82
- const cached = this.cache.get(cacheKey);
83
- if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
84
- // Enforce expiration check even for cached items
85
- const currentTimestampSec = Math.floor(now / 1000);
86
- if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
87
- this.cache.delete(cacheKey);
88
- } else {
89
- return cached.payload;
90
- }
91
- }
92
- }
93
-
94
42
  // 1. Development Fallback (Fail-open locally but log warning)
95
43
  if (!licenseKey) {
96
44
  if (isProduction) {
@@ -108,71 +56,78 @@ sDiXtsP5MlwkL9X7RQY2uovRa+l/vOAqAfdmJ+OzXuk5P7mDUPb+gCtKnoDbb1tr
108
56
  };
109
57
  }
110
58
 
111
- try {
112
- const sanitizedKey = (licenseKey || '').trim().replace(/^["']|["']$/g, '').trim();
113
- const rawToken = sanitizedKey.replace(/^rtv_/i, '').trim();
114
- const parts = rawToken.split('.');
115
- if (parts.length !== 3) {
116
- throw new Error('Malformed token structure (expected 3 parts).');
59
+ // Check verification cache to bypass network computations on hot paths
60
+ const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ''}`;
61
+ const cached = this.cache.get(cacheKey);
62
+ if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
63
+ // Enforce expiration check even for cached items
64
+ const currentTimestampSec = Math.floor(now / 1000);
65
+ if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
66
+ this.cache.delete(cacheKey);
67
+ } else {
68
+ return cached.payload;
117
69
  }
70
+ }
118
71
 
119
- const [headerB64, payloadB64, signatureB64] = parts;
120
- const dataToVerify = `${headerB64}.${payloadB64}`;
121
-
122
- const publicKey = publicKeyOverride ?? this.PUBLIC_KEY;
123
-
124
- // 2. Cryptographic signature check
125
- const signature = Buffer.from(signatureB64, 'base64url');
126
- const data = Buffer.from(dataToVerify);
127
-
128
- const isValid = crypto.verify(
129
- 'sha256',
130
- data,
131
- publicKey,
132
- signature
133
- );
134
-
135
- if (!isValid) {
136
- throw new Error('Signature verification failed.');
72
+ try {
73
+ let baseUrl = typeof process !== 'undefined' && process.env.RETRIVORA_CONTROL_PLANE_URL
74
+ ? process.env.RETRIVORA_CONTROL_PLANE_URL
75
+ : 'https://retrivora.com';
76
+
77
+ if (typeof process !== 'undefined' && process.env.TELEMETRY_URL) {
78
+ // Handle case where TELEMETRY_URL includes /api/telemetry path
79
+ baseUrl = process.env.TELEMETRY_URL.replace(/\/api\/telemetry\/?$/, '');
137
80
  }
81
+
82
+ const endpoint = `${baseUrl}/api/v1/license/validate`;
83
+
84
+ const response = await fetch(endpoint, {
85
+ method: 'POST',
86
+ headers: {
87
+ 'Content-Type': 'application/json',
88
+ 'x-license-key': licenseKey,
89
+ },
90
+ body: JSON.stringify({
91
+ licenseKey,
92
+ projectId: currentProjectId,
93
+ provider
94
+ }),
95
+ });
138
96
 
139
- // 3. Decode & validate payload checks
140
- const payload: LicensePayload = JSON.parse(
141
- Buffer.from(payloadB64, 'base64url').toString('utf8')
142
- );
143
-
144
- if (!payload.projectId) {
145
- throw new Error('License payload is missing "projectId".');
97
+ if (!response.ok) {
98
+ let errMessage = `HTTP ${response.status}`;
99
+ try {
100
+ const body = await response.json();
101
+ if (body.message) errMessage = body.message;
102
+ } catch(e) {}
103
+ throw new Error(errMessage);
146
104
  }
147
105
 
148
- const isProjectMatch =
149
- payload.projectId === currentProjectId ||
150
- payload.projectId === `retrivora-${currentProjectId}` ||
151
- `retrivora-${payload.projectId}` === currentProjectId;
106
+ const data = await response.json();
152
107
 
153
- if (!isProjectMatch) {
154
- throw new Error(
155
- `Project ID mismatch. License is bound to project namespace "${payload.projectId}" ` +
156
- `but configuration has "${currentProjectId}".`
157
- );
108
+ if (!data.valid) {
109
+ throw new Error(data.message || 'License validation failed by server.');
158
110
  }
159
111
 
160
- if (!payload.expiresAt) {
161
- throw new Error('License payload is missing expiration ("expiresAt").');
112
+ // Reconstruct payload shape based on what the rest of the SDK expects
113
+ let expiresAtNum = Math.floor(Date.now() / 1000) + (100 * 365 * 24 * 60 * 60); // 100 years fallback
114
+ if (data.expiresAt) {
115
+ expiresAtNum = Math.floor(new Date(data.expiresAt).getTime() / 1000);
162
116
  }
163
117
 
164
- const currentTimestampSec = Math.floor(Date.now() / 1000);
165
- if (currentTimestampSec > payload.expiresAt) {
166
- throw new Error(
167
- `License key has expired. Expiration: ${new Date(
168
- payload.expiresAt * 1000
169
- ).toDateString()}`
170
- );
171
- }
118
+ const tier = LicenseVerifier.extractTier(licenseKey);
119
+
120
+ const payload: LicensePayload = {
121
+ projectId: currentProjectId,
122
+ expiresAt: expiresAtNum,
123
+ tier: tier,
124
+ licenseStatus: data.licenseStatus,
125
+ minimumSupportedVersion: data.minimumSupportedVersion,
126
+ forceUpgrade: data.forceUpgrade
127
+ };
172
128
 
173
129
  // 4. Validate Vector DB Provider against Tier (Production only)
174
130
  if (isProduction && provider) {
175
- const tier = (payload.tier || '').toLowerCase();
176
131
  const normalizedProvider = provider.toLowerCase();
177
132
 
178
133
  if (tier === 'hobby') {
@@ -199,19 +154,15 @@ sDiXtsP5MlwkL9X7RQY2uovRa+l/vOAqAfdmJ+OzXuk5P7mDUPb+gCtKnoDbb1tr
199
154
  );
200
155
  }
201
156
  }
202
- // Enterprise has access to all databases (including redis, weaviate, custom ones)
203
157
  }
204
158
 
205
- if (licenseKey) {
206
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ''}:${publicKeyOverride || ''}`;
207
- this.cache.set(cacheKey, { payload, cachedAt: now });
208
- }
159
+ this.cache.set(cacheKey, { payload, cachedAt: now });
209
160
 
210
161
  return payload;
211
162
  } catch (err) {
212
163
  const message = err instanceof Error ? err.message : String(err);
213
164
  throw new ConfigurationException(
214
- `[Retrivora SDK] License key validation failed: ${message}`
165
+ `[Retrivora SDK] License key validation failed via API: ${message}`
215
166
  );
216
167
  }
217
168
  }
@@ -293,4 +244,18 @@ sDiXtsP5MlwkL9X7RQY2uovRa+l/vOAqAfdmJ+OzXuk5P7mDUPb+gCtKnoDbb1tr
293
244
  }
294
245
  }
295
246
  }
247
+
248
+ static extractTier(licenseKey: string | undefined): string {
249
+ if (!licenseKey) return 'hobby';
250
+ try {
251
+ const sanitizedKey = licenseKey.trim().replace(/^["']|["']$/g, '').trim();
252
+ const rawToken = sanitizedKey.replace(/^rtv_/i, '').trim();
253
+ const parts = rawToken.split('.');
254
+ if (parts.length === 3) {
255
+ const decodedPayload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
256
+ if (decodedPayload.tier) return decodedPayload.tier;
257
+ }
258
+ } catch (e) {}
259
+ return 'hobby';
260
+ }
296
261
  }
@@ -24,7 +24,7 @@ export class Retrivora {
24
24
  async initialize(): Promise<void> {
25
25
  try {
26
26
  await ConfigValidator.validateAndThrow(this.config);
27
- LicenseVerifier.verify(
27
+ await LicenseVerifier.verifyAsync(
28
28
  this.config.licenseKey,
29
29
  this.config.projectId,
30
30
  this.config.vectorDb?.provider