@retrivora-ai/rag-engine 2.3.6 → 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.
Files changed (34) hide show
  1. package/dist/{BatchProcessor-Dfn23VAd.d.mts → BatchProcessor-BhLczWj5.d.mts} +100 -2
  2. package/dist/{BatchProcessor-ByBl-1MA.d.ts → BatchProcessor-C42_RVWO.d.ts} +100 -2
  3. package/dist/handlers/index.d.mts +1 -1
  4. package/dist/handlers/index.d.ts +1 -1
  5. package/dist/handlers/index.js +340 -172
  6. package/dist/handlers/index.mjs +342 -174
  7. package/dist/{index-ejOWsaqb.d.ts → index-BQd6Bax0.d.ts} +1 -1
  8. package/dist/{index-xxQOFx-u.d.mts → index-C7aHK7_g.d.mts} +1 -1
  9. package/dist/index.d.mts +2 -2
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.js +114 -87
  12. package/dist/index.mjs +114 -87
  13. package/dist/server.d.mts +263 -37
  14. package/dist/server.d.ts +263 -37
  15. package/dist/server.js +957 -178
  16. package/dist/server.mjs +949 -180
  17. package/package.json +1 -1
  18. package/src/LicensedRetrivora.ts +273 -0
  19. package/src/components/ChatWidget.tsx +0 -1
  20. package/src/components/ConfigProvider.tsx +2 -1
  21. package/src/config/LicenseConfigResolver.ts +296 -0
  22. package/src/config/serverConfig.ts +75 -16
  23. package/src/core/ConfigFetcher.ts +36 -3
  24. package/src/core/DatabaseStorage.ts +13 -13
  25. package/src/core/LicenseValidator.ts +5 -3
  26. package/src/core/LicenseVerifier.ts +85 -120
  27. package/src/core/Retrivora.ts +1 -1
  28. package/src/core/VectorPlugin.ts +1 -1
  29. package/src/handlers/index.ts +25 -11
  30. package/src/index.ts +9 -0
  31. package/src/llm/providers/UniversalLLMAdapter.ts +67 -12
  32. package/src/providers/vectordb/PineconeProvider.ts +69 -2
  33. package/src/server.ts +23 -1
  34. package/src/telemetry/TelemetryService.ts +330 -0
@@ -26,6 +26,49 @@ import {
26
26
  EMBEDDING_PROVIDERS,
27
27
  } from './constants';
28
28
 
29
+ /**
30
+ * Runtime tier configuration injected from the /api/v1/config + /api/v1/credentials
31
+ * API responses at app startup. This overrides static env-var defaults so that
32
+ * the tier-based model selection from the license is applied to all SDK calls.
33
+ */
34
+ export interface RuntimeTierConfig {
35
+ llmModel?: string;
36
+ embeddingModel?: string;
37
+ /** LiteLLM master key for authenticating with llm.retrivora.com */
38
+ litellmApiKey?: string;
39
+ /** LiteLLM gateway base URL (defaults to https://llm.retrivora.com/api/v1) */
40
+ llmBaseUrl?: string;
41
+ embeddingBaseUrl?: string;
42
+ maxTokens?: number;
43
+ topK?: number;
44
+ chunkSize?: number;
45
+ chunkOverlap?: number;
46
+ tier?: string;
47
+ }
48
+
49
+ /** Module-level store for runtime-injected tier config */
50
+ let _runtimeConfig: RuntimeTierConfig | null = null;
51
+
52
+ /**
53
+ * Inject tier-based config fetched from /api/v1/config + /api/v1/credentials.
54
+ * Call this once after successful license init (e.g. in validate-env.ts).
55
+ */
56
+ export function injectRuntimeConfig(config: RuntimeTierConfig): void {
57
+ _runtimeConfig = config;
58
+ console.log('[serverConfig] ✅ Runtime tier config injected:', {
59
+ tier: config.tier,
60
+ llmModel: config.llmModel,
61
+ embeddingModel: config.embeddingModel,
62
+ llmBaseUrl: config.llmBaseUrl,
63
+ hasLitellmKey: !!config.litellmApiKey,
64
+ });
65
+ }
66
+
67
+ /** Returns the currently injected runtime config, or null if not yet set. */
68
+ export function getRuntimeConfig(): RuntimeTierConfig | null {
69
+ return _runtimeConfig;
70
+ }
71
+
29
72
  function readString(env: Record<string, string | undefined>, name: string): string | undefined {
30
73
  const value = env[name]?.trim();
31
74
  return value ? value : undefined;
@@ -177,33 +220,49 @@ export function getEnvConfig(env: Record<string, string | undefined> = process.e
177
220
  const isFreeTier = (() => {
178
221
  if (!licenseKey) return true;
179
222
  try {
180
- const payload = LicenseVerifier.verify(licenseKey, projectId);
181
- const tier = (payload.tier || '').toLowerCase();
223
+ const tier = LicenseVerifier.extractTier(licenseKey).toLowerCase();
182
224
  return tier === 'free_trial' || tier === 'free_tier' || tier === 'free' || tier === 'hobby';
183
225
  } catch {
184
226
  return true;
185
227
  }
186
228
  })();
187
229
 
188
- // Default gateway: retrivora.com/api/v1 acts as a secure proxy that validates the license key
189
- // and forwards to llm.retrivora.com with LITELLM_MASTER_KEY (which end-users never need to know).
190
- const defaultGatewayUrl =
191
- readString(env, 'LITELLM_BASE_URL') ??
192
- readString(env, 'LLM_BASE_URL') ??
193
- 'https://www.retrivora.com/api/v1';
230
+ // Tier-based model selection (resolved from license tier)
231
+ const tierBasedLLMModel = isFreeTier ? 'llama-3.1-8b-instant' : 'llama-3.3-70b-versatile';
232
+ const tierBasedEmbeddingModel = isFreeTier ? 'text-embedding-004' : 'text-embedding-004';
194
233
 
195
- const defaultLlmProvider = isFreeTier ? 'universal_rest' : 'universal_rest';
234
+ // Default gateway: always use LiteLLM at llm.retrivora.com for end-users
235
+ // End-users provide license key + project ID; the gateway validates and routes internally
236
+ const defaultGatewayUrl = 'https://llm.retrivora.com/api/v1';
237
+
238
+ // ── Runtime-injected tier config (from /api/v1/config + /api/v1/credentials) ──
239
+ // Priority: explicit env var > injected runtime config > static tier fallback
240
+ const rt = _runtimeConfig;
241
+
242
+ const defaultLlmProvider = 'universal_rest';
196
243
  const llmProvider = (readEnum(env, 'LLM_PROVIDER', defaultLlmProvider, LLM_PROVIDERS) ?? base?.llm?.provider ?? defaultLlmProvider) as LLMProvider;
197
- const llmBaseUrl = readString(env, 'LITELLM_BASE_URL') ?? readString(env, 'LLM_BASE_URL') ?? base?.llm?.baseUrl ?? defaultGatewayUrl;
198
- const llmModel = readString(env, 'LLM_MODEL') ?? base?.llm?.model ?? (isFreeTier ? 'llama-3.1-8b-instant' : (DEFAULT_MODEL_BY_PROVIDER[llmProvider] ?? 'gpt-4o'));
199
- const llmApiKey = llmApiKeyByProvider[llmProvider] ?? readString(env, 'LLM_API_KEY') ?? readString(env, 'LITELLM_MASTER_KEY') ?? readString(env, 'LITELLM_API_KEY') ?? base?.llm?.apiKey ?? licenseKey;
244
+ // llmBaseUrl: env var wins, then injected gateway URL, then static default
245
+ const llmBaseUrl = readString(env, 'LITELLM_BASE_URL') ?? readString(env, 'LLM_BASE_URL') ?? base?.llm?.baseUrl ?? rt?.llmBaseUrl ?? defaultGatewayUrl;
246
+ // llmModel: env var wins, then injected tier model, then static tier fallback
247
+ const llmModel = readString(env, 'LLM_MODEL') ?? base?.llm?.model ?? rt?.llmModel ?? tierBasedLLMModel;
248
+ // llmApiKey: LITELLM_MASTER_KEY env wins, then injected litellm key, then licenseKey
249
+ const llmApiKey = readString(env, 'LITELLM_MASTER_KEY') ?? rt?.litellmApiKey ?? base?.llm?.apiKey ?? licenseKey;
200
250
  const llmProfile = readString(env, 'LLM_UNIVERSAL_PROFILE') ?? (base?.llm?.options?.profile as string) ?? 'litellm';
201
251
 
202
- const defaultEmbeddingProvider = isFreeTier ? 'universal_rest' : 'universal_rest';
252
+ console.log('[serverConfig] 🔧 LLM Configuration:', {
253
+ baseUrl: llmBaseUrl,
254
+ model: llmModel,
255
+ provider: llmProvider,
256
+ hasApiKey: !!llmApiKey,
257
+ source: rt?.llmModel ? 'runtime-injected' : 'env/fallback',
258
+ });
259
+
260
+ const defaultEmbeddingProvider = 'universal_rest';
203
261
  const embeddingProvider = (readEnum(env, 'EMBEDDING_PROVIDER', defaultEmbeddingProvider, EMBEDDING_PROVIDERS) ?? base?.embedding?.provider ?? defaultEmbeddingProvider) as EmbeddingProvider;
204
- const embeddingBaseUrl = readString(env, 'LITELLM_BASE_URL') ?? readString(env, 'EMBEDDING_BASE_URL') ?? readString(env, 'LLM_BASE_URL') ?? base?.embedding?.baseUrl ?? defaultGatewayUrl;
205
- const embeddingModel = readString(env, 'EMBEDDING_MODEL') ?? base?.embedding?.model ?? 'text-embedding-004';
206
- const embeddingApiKey = embeddingApiKeyByProvider[embeddingProvider] ?? readString(env, 'EMBEDDING_API_KEY') ?? readString(env, 'LLM_API_KEY') ?? readString(env, 'LITELLM_MASTER_KEY') ?? readString(env, 'LITELLM_API_KEY') ?? base?.embedding?.apiKey ?? licenseKey;
262
+ 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;
263
+ const embeddingModel = readString(env, 'EMBEDDING_MODEL') ?? base?.embedding?.model ?? rt?.embeddingModel ?? tierBasedEmbeddingModel;
264
+ // embeddingApiKey: same key as LLM (LiteLLM gateway handles both)
265
+ const embeddingApiKey = readString(env, 'LITELLM_MASTER_KEY') ?? rt?.litellmApiKey ?? base?.embedding?.apiKey ?? licenseKey;
207
266
  const embeddingProfile = readString(env, 'EMBEDDING_UNIVERSAL_PROFILE') ?? (base?.embedding?.options?.profile as string) ?? 'litellm';
208
267
 
209
268
  return {
@@ -101,7 +101,13 @@ 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) {
@@ -128,8 +134,7 @@ export class ConfigFetcher {
128
134
  isActive: data.isActive,
129
135
  expiresAt: data.expiresAt,
130
136
  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.
137
+ // Fetch apiKey from credentials API if available, else fallback to empty
133
138
  apiKey: data.vectorDb.apiKey || '',
134
139
  indexName: data.vectorDb.indexName || 'retrivora-free',
135
140
  provider: data.vectorDb.provider || 'pinecone',
@@ -161,6 +166,34 @@ export class ConfigFetcher {
161
166
  data.projectSettings || data.settings
162
167
  ),
163
168
  };
169
+ // Now fetch credentials if licenseKey is provided
170
+ if (licenseKey) {
171
+ try {
172
+ const credUrl = `${baseUrl}/api/v1/credentials`;
173
+ const credRes = await fetch(credUrl, {
174
+ method: 'POST',
175
+ headers: {
176
+ 'Content-Type': 'application/json',
177
+ },
178
+ body: JSON.stringify({ licenseKey, projectId: fetchedProjectId }),
179
+ });
180
+ if (credRes.ok) {
181
+ const credData = await credRes.json();
182
+ if (credData?.success && credData?.credentials) {
183
+ if (credData.credentials.pineconeApiKey && !config.vectorDb.apiKey) {
184
+ config.vectorDb.apiKey = credData.credentials.pineconeApiKey;
185
+ }
186
+ if (credData.credentials.litellmApiKey) {
187
+ config.llm.apiKey = credData.credentials.litellmApiKey;
188
+ config.embedding.apiKey = credData.credentials.litellmApiKey;
189
+ }
190
+ }
191
+ }
192
+ } catch (e) {
193
+ console.warn('[ConfigFetcher] Failed to fetch credentials:', e);
194
+ }
195
+ }
196
+
164
197
  this.cache.set(cacheKey, { config, cachedAt: now });
165
198
  return config;
166
199
  }
@@ -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
- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoOQlmDSKfCZaRy06rxwa
55
- chuDimlF134xTCitKDTPTPizF23oSn34pGDJakm/0T09JVUX8L/cvhGPe/3lf/g9
56
- 4Y1q+Gb2KVM17KNGeT1Aj9Ua3BKz/yao/oFhi/r3Zt3cWY13B/Rd6clqY9WshIAV
57
- NqZNM8ilTl777cMbyym+6D+mzGXgmnJAO5brddIAI9FPLW0T3Znt8vEqDOIljEkC
58
- HCGHeirKABLbjKSJ4hljCa3vVitWqndhiq8CBSJG6HatiSGYotgMWGRY+0EbdlEv
59
- OJP4SqafQ3aD6YnL9q1n15QKwxu/uMK+JGM2VxxuyUi9GANtMIkCYy9xya73P4Qc
60
- gQIDAQAB
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 @@ gQIDAQAB
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 @@ gQIDAQAB
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 @@ gQIDAQAB
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
@@ -32,7 +32,7 @@ export class VectorPlugin {
32
32
  // Start validation early
33
33
  this.validationPromise = (async () => {
34
34
  await ConfigValidator.validateAndThrow(resolvedConfig);
35
- LicenseVerifier.verify(
35
+ await LicenseVerifier.verifyAsync(
36
36
  resolvedConfig.licenseKey,
37
37
  resolvedConfig.projectId,
38
38
  resolvedConfig.vectorDb?.provider