@retrivora-ai/rag-engine 2.4.2 → 2.4.5

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 (140) hide show
  1. package/dist/{BatchProcessor-zbQMaZHm.d.mts → BatchProcessor-Csy_K1qQ.d.mts} +2 -0
  2. package/dist/{BatchProcessor-D42E706a.d.ts → BatchProcessor-Dg18zZGk.d.ts} +2 -0
  3. package/dist/handlers/index.js +31 -5
  4. package/dist/handlers/index.mjs +31 -5
  5. package/dist/index.d.mts +3 -3
  6. package/dist/index.d.ts +3 -3
  7. package/dist/index.js +41 -21
  8. package/dist/index.min.css +2 -0
  9. package/dist/index.mjs +41 -21
  10. package/dist/server.d.mts +2 -2
  11. package/dist/server.d.ts +2 -2
  12. package/dist/server.js +32 -5
  13. package/dist/server.mjs +32 -5
  14. package/package.json +5 -4
  15. package/src/LicensedRetrivora.ts +0 -278
  16. package/src/app/api/chat/route.ts +0 -4
  17. package/src/app/api/health/route.ts +0 -5
  18. package/src/app/api/ingest/route.ts +0 -27
  19. package/src/app/api/suggestions/route.ts +0 -5
  20. package/src/app/api/upload/route.ts +0 -5
  21. package/src/app/constants.tsx +0 -270
  22. package/src/app/favicon.ico +0 -0
  23. package/src/app/globals.css +0 -449
  24. package/src/app/layout.tsx +0 -22
  25. package/src/app/page.tsx +0 -64
  26. package/src/app/types.ts +0 -30
  27. package/src/browser.tsx +0 -139
  28. package/src/components/ChatWidget.tsx +0 -393
  29. package/src/components/ChatWindow.tsx +0 -952
  30. package/src/components/CodeViewer.tsx +0 -56
  31. package/src/components/ConfigProvider.tsx +0 -123
  32. package/src/components/DocumentUpload.tsx +0 -354
  33. package/src/components/DynamicChart.tsx +0 -297
  34. package/src/components/HourglassLoader.tsx +0 -87
  35. package/src/components/MarkdownComponents.tsx +0 -186
  36. package/src/components/MessageBubble.tsx +0 -498
  37. package/src/components/ObservabilityPanel.tsx +0 -374
  38. package/src/components/ProductCard.tsx +0 -107
  39. package/src/components/ProductCarousel.tsx +0 -97
  40. package/src/components/SourceCard.tsx +0 -61
  41. package/src/components/ThemeProvider.tsx +0 -8
  42. package/src/components/ThemeToggle.tsx +0 -29
  43. package/src/components/ThinkingBlock.tsx +0 -75
  44. package/src/components/UIDispatcher.tsx +0 -342
  45. package/src/components/VisualizationRenderer.tsx +0 -621
  46. package/src/components/constants.tsx +0 -503
  47. package/src/config/ConfigBuilder.ts +0 -285
  48. package/src/config/EmbeddingStrategy.ts +0 -148
  49. package/src/config/LicenseConfigResolver.ts +0 -298
  50. package/src/config/RagConfig.ts +0 -328
  51. package/src/config/UniversalProfiles.ts +0 -82
  52. package/src/config/constants.ts +0 -64
  53. package/src/config/serverConfig.ts +0 -378
  54. package/src/config/uiConstants.ts +0 -47
  55. package/src/core/BatchProcessor.ts +0 -385
  56. package/src/core/CircuitBreaker.ts +0 -118
  57. package/src/core/ConfigFetcher.ts +0 -220
  58. package/src/core/ConfigResolver.ts +0 -165
  59. package/src/core/ConfigValidator.ts +0 -197
  60. package/src/core/DatabaseStorage.ts +0 -526
  61. package/src/core/FreeTierLimitsGuard.ts +0 -281
  62. package/src/core/LLMRouter.ts +0 -79
  63. package/src/core/LangChainAgent.ts +0 -132
  64. package/src/core/LicenseValidator.ts +0 -284
  65. package/src/core/LicenseVerifier.ts +0 -261
  66. package/src/core/MultiAgentCoordinator.ts +0 -239
  67. package/src/core/Pipeline.ts +0 -1279
  68. package/src/core/PluginManager.ts +0 -277
  69. package/src/core/ProjectSettings.ts +0 -247
  70. package/src/core/ProviderHealthCheck.ts +0 -133
  71. package/src/core/ProviderInterfaces.ts +0 -37
  72. package/src/core/ProviderRegistry.ts +0 -156
  73. package/src/core/QueryProcessor.ts +0 -399
  74. package/src/core/Retrivora.ts +0 -98
  75. package/src/core/VectorPlugin.ts +0 -193
  76. package/src/core/mcp.ts +0 -261
  77. package/src/exceptions/index.ts +0 -131
  78. package/src/handlers/index.ts +0 -1625
  79. package/src/hooks/useHydrated.ts +0 -13
  80. package/src/hooks/useProjectSettings.ts +0 -105
  81. package/src/hooks/useRagChat.ts +0 -436
  82. package/src/hooks/useStoredMessages.ts +0 -64
  83. package/src/index.css +0 -4269
  84. package/src/index.ts +0 -137
  85. package/src/lib/plugin.ts +0 -24
  86. package/src/llm/ILLMProvider.ts +0 -60
  87. package/src/llm/LLMFactory.ts +0 -141
  88. package/src/llm/providers/AnthropicProvider.ts +0 -215
  89. package/src/llm/providers/GeminiProvider.ts +0 -311
  90. package/src/llm/providers/GroqProvider.ts +0 -184
  91. package/src/llm/providers/OllamaProvider.ts +0 -232
  92. package/src/llm/providers/OpenAIProvider.ts +0 -188
  93. package/src/llm/providers/QwenProvider.ts +0 -199
  94. package/src/llm/providers/UniversalLLMAdapter.ts +0 -422
  95. package/src/llm/utils.ts +0 -46
  96. package/src/providers/graphdb/BaseGraphProvider.ts +0 -43
  97. package/src/providers/graphdb/SimpleGraphProvider.ts +0 -66
  98. package/src/providers/vectordb/BaseVectorProvider.ts +0 -98
  99. package/src/providers/vectordb/ChromaDBProvider.ts +0 -130
  100. package/src/providers/vectordb/MilvusProvider.ts +0 -134
  101. package/src/providers/vectordb/MongoDBProvider.ts +0 -250
  102. package/src/providers/vectordb/MultiTablePostgresProvider.ts +0 -461
  103. package/src/providers/vectordb/PineconeProvider.ts +0 -295
  104. package/src/providers/vectordb/PostgreSQLProvider.ts +0 -227
  105. package/src/providers/vectordb/QdrantProvider.ts +0 -294
  106. package/src/providers/vectordb/RedisProvider.ts +0 -105
  107. package/src/providers/vectordb/UniversalVectorProvider.ts +0 -221
  108. package/src/providers/vectordb/WeaviateProvider.ts +0 -172
  109. package/src/rag/DocumentChunker.ts +0 -144
  110. package/src/rag/EntityExtractor.ts +0 -90
  111. package/src/rag/LlamaIndexIngestor.ts +0 -60
  112. package/src/rag/Reranker.ts +0 -106
  113. package/src/rendering/IntentClassifier.ts +0 -167
  114. package/src/rendering/RendererRegistry.ts +0 -164
  115. package/src/rendering/RuleEngine.ts +0 -67
  116. package/src/rendering/VisualizationDecisionEngine.ts +0 -164
  117. package/src/rendering/__tests__/VisualizationDecisionEngine.test.ts +0 -237
  118. package/src/rendering/index.ts +0 -12
  119. package/src/rendering/rules/Rule1SpecificInfoRule.ts +0 -28
  120. package/src/rendering/rules/Rule2ComparisonRule.ts +0 -24
  121. package/src/rendering/rules/Rule3ProductDiscoveryRule.ts +0 -28
  122. package/src/rendering/rules/Rule4AnalyticalRule.ts +0 -38
  123. package/src/rendering/rules/Rule5MixedResponseRule.ts +0 -29
  124. package/src/rendering/rules/Rule6SmallResultSetRule.ts +0 -24
  125. package/src/rendering/rules/Rule7LargeTableRule.ts +0 -35
  126. package/src/rendering/types.ts +0 -96
  127. package/src/server.ts +0 -156
  128. package/src/tailwind.css +0 -194
  129. package/src/telemetry/TelemetryService.ts +0 -330
  130. package/src/types/chat.ts +0 -89
  131. package/src/types/index.ts +0 -278
  132. package/src/types/pdf-parse.d.ts +0 -13
  133. package/src/types/props.ts +0 -169
  134. package/src/utils/DocumentParser.ts +0 -111
  135. package/src/utils/ProductExtractor.ts +0 -350
  136. package/src/utils/SchemaMapper.ts +0 -176
  137. package/src/utils/UITransformer.ts +0 -1812
  138. package/src/utils/synonyms.ts +0 -80
  139. package/src/utils/templateUtils.ts +0 -78
  140. package/src/version.ts +0 -6
@@ -1,284 +0,0 @@
1
- import { SDK_VERSION } from '../version';
2
- import { SDKVersionUnsupportedError, LicenseValidationError } from '../exceptions';
3
- import { LicenseVerifier } from './LicenseVerifier';
4
-
5
- /**
6
- * Input contract for `LicenseValidator.validate()`.
7
- *
8
- * At least one source must yield a license key: `licenseKey` field, an
9
- * `x-license-key` entry in `headers`, or the process environment variables
10
- * (NEXT_PUBLIC_RETRIVORA_LICENSE_KEY / RETRIVORA_LICENSE_KEY).
11
- */
12
- export interface LicenseValidationRequest {
13
- /** Explicit `rtv_`-prefixed license key passed as a prop (highest priority). */
14
- licenseKey: string;
15
- /** Project ID the caller is running under, checked for license binding match. */
16
- projectId?: string;
17
- /** SDK version reported for minimum-supported-version enforcement (defaults to SDK_VERSION). */
18
- sdkVersion?: string;
19
- /** SDK package identifier sent to server for observability. */
20
- sdk?: string;
21
- /** browser | node — reported for observability only. */
22
- platform?: string;
23
- /** Override base URL of the Retrivora API endpoint. Defaults to env or '/api/retrivora'. */
24
- retrivoraApiBase?: string;
25
- /** Custom headers that may contain `x-license-key` or `Authorization: Bearer`. */
26
- headers?: Record<string, string>;
27
- }
28
-
29
- /**
30
- * Response contract returned from `LicenseValidator.validate()`.
31
- *
32
- * Status enumerations are ordered — anything other than ACTIVE means the
33
- * widget/chat must be disabled and must not pass server-side handler checks.
34
- */
35
- export interface LicenseValidationResponse {
36
- /** True only when `licenseStatus` is ACTIVE and SDK version is supported. */
37
- valid: boolean;
38
- /** Lifecycle state of the license record. TERMINATED/SUSPENDED/EXPIRED/REVOKED must block chat. */
39
- licenseStatus: 'ACTIVE' | 'SUSPENDED' | 'TERMINATED' | 'EXPIRED' | 'REVOKED';
40
- /** Minimum SDK version that the server will accept (semver-compare). */
41
- minimumSupportedVersion: string;
42
- /** Latest generally-available SDK version (for upgrade prompts). */
43
- latestVersion: string;
44
- /** True when the SDK version is older than minimumSupportedVersion — UI must force upgrade. */
45
- forceUpgrade: boolean;
46
- /** RFC3339 expiration timestamp or null for perpetual licenses. */
47
- expiresAt: string | null;
48
- /** Human-readable status/reason string, suitable for tooltips/toasts. */
49
- message: string;
50
- }
51
-
52
- /** Internal cache entry shape for successful validations only (failures are never cached). */
53
- interface CachedSuccessValidation {
54
- response: LicenseValidationResponse;
55
- timestamp: number;
56
- }
57
-
58
- function canUseLocalValidationFallback(baseUrl: string, status?: number): boolean {
59
- const explicitFallback =
60
- typeof process !== 'undefined' &&
61
- process.env.RETRIVORA_ALLOW_LOCAL_LICENSE_FALLBACK === 'true';
62
- const isLocalSdkRoute = baseUrl.startsWith('/api/retrivora') || baseUrl.includes('/api/retrivora');
63
-
64
- if (status !== undefined) {
65
- return status === 404 && (explicitFallback || isLocalSdkRoute);
66
- }
67
-
68
- return explicitFallback || isLocalSdkRoute;
69
- }
70
-
71
- /**
72
- * Client-side orchestrator for license validation.
73
- *
74
- * Flow:
75
- * 1. Resolve the license key (prop → header → env)
76
- * 2. Return any fresh (< 5 min old) successful cached result
77
- * 3. POST to `{retrivoraApiBase}/v1/license/validate` for server-side DB-backed status
78
- * 4. On network or HTTP error, fall back to zero-latency local RSA signature
79
- * verification via `LicenseVerifier.verify()`.
80
- *
81
- * Caching policy:
82
- * - ONLY successful (valid + ACTIVE + !forceUpgrade) responses are cached
83
- * - Any failed validation immediately purges the cache entry
84
- * - TTL is 5 minutes for success cache to allow TERMINATED/REVOKED status
85
- * changes on the server to propagate quickly.
86
- *
87
- * Thread safety: Singleton pattern via `getInstance()`. Used by ChatWidget,
88
- * useRagChat hook, and the server-side `createLicenseHandler` indirectly through
89
- * its own `LicenseVerifier.verify()` path.
90
- */
91
- export class LicenseValidator {
92
- private static instance: LicenseValidator;
93
- private cache: Map<string, CachedSuccessValidation> = new Map();
94
- private static readonly SUCCESS_CACHE_TTL_MS = 5 * 60 * 1000; // 5-minute TTL for successful validation only
95
-
96
- private constructor() {}
97
-
98
- /** @returns Singleton instance of the validator (shared cache across all consumers). */
99
- public static getInstance(): LicenseValidator {
100
- if (!LicenseValidator.instance) {
101
- LicenseValidator.instance = new LicenseValidator();
102
- }
103
- return LicenseValidator.instance;
104
- }
105
-
106
- /**
107
- * Purge entries from the local success cache.
108
- *
109
- * @param licenseKey - Optional. If provided, only that key's cache entry is
110
- * removed. If omitted the entire cache is cleared.
111
- * Callers use this after any 401/403 to ensure the next
112
- * validate() call re-validates against the server.
113
- */
114
- public purgeCache(licenseKey?: string): void {
115
- if (licenseKey) {
116
- this.cache.delete(licenseKey);
117
- } else {
118
- this.cache.clear();
119
- }
120
- }
121
-
122
- /**
123
- * Primary validation entry-point for UI / hook consumers.
124
- *
125
- * Resolves the license key, consults the local success cache, performs a
126
- * server POST for authoritative status, and falls back to local RSA
127
- * signature verification if the server can't be reached.
128
- *
129
- * @throws LicenseValidationError - When no key is provided OR both the
130
- * server call AND the local-RSA fallback report an invalid/expired key.
131
- * @throws SDKVersionUnsupportedError - When server reports forceUpgrade=true.
132
- * @returns A `LicenseValidationResponse` that the UI can use to enable or
133
- * lock the chat widget.
134
- */
135
- public async validate(request: LicenseValidationRequest): Promise<LicenseValidationResponse> {
136
- const {
137
- licenseKey,
138
- projectId,
139
- sdkVersion = SDK_VERSION,
140
- sdk = '@retrivora-ai/rag-engine',
141
- platform = typeof window !== 'undefined' ? 'browser' : 'node',
142
- retrivoraApiBase,
143
- headers: customHeaders,
144
- } = request;
145
-
146
- const effectiveProjectId = projectId || (typeof process !== 'undefined' ? (process.env.NEXT_PUBLIC_RETRIVORA_PROJECT_ID || process.env.RETRIVORA_PROJECT_ID) : '') || '';
147
-
148
- const getHeader = (name: string): string | undefined => {
149
- if (!customHeaders) return undefined;
150
- const target = name.toLowerCase();
151
- for (const [k, v] of Object.entries(customHeaders)) {
152
- if (k.toLowerCase() === target) return v;
153
- }
154
- return undefined;
155
- };
156
-
157
- const rawKey =
158
- licenseKey ||
159
- getHeader('x-license-key') ||
160
- getHeader('authorization')?.replace(/^Bearer\s+/i, '') ||
161
- (typeof process !== 'undefined'
162
- ? (process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY)
163
- : '') ||
164
- '';
165
-
166
- const effectiveLicenseKey = (rawKey || '').trim().replace(/^["']|["']$/g, '').trim();
167
-
168
- if (!effectiveLicenseKey) {
169
- this.purgeCache(effectiveLicenseKey);
170
- throw new LicenseValidationError('Missing RETRIVORA_LICENSE_KEY in request. Set NEXT_PUBLIC_RETRIVORA_LICENSE_KEY in your environment or pass licenseKey as a prop.');
171
- }
172
-
173
- // 1. Check successful 5-minute cache
174
- const cached = this.cache.get(effectiveLicenseKey);
175
- if (cached) {
176
- const isFresh = Date.now() - cached.timestamp < LicenseValidator.SUCCESS_CACHE_TTL_MS;
177
- if (isFresh && cached.response.valid && cached.response.licenseStatus === 'ACTIVE' && !cached.response.forceUpgrade) {
178
- return cached.response;
179
- } else {
180
- this.cache.delete(effectiveLicenseKey);
181
- }
182
- }
183
-
184
- // 2. Fetch live validation from Retrivora backend API / local catch-all route
185
- const base = retrivoraApiBase || (typeof process !== 'undefined' ? process.env.NEXT_PUBLIC_RETRIVORA_API_BASE || process.env.RETRIVORA_API_BASE : '') || 'https://www.retrivora.com/api';
186
- const validateUrl = `${base.replace(/\/$/, '')}/v1/license/validate`;
187
-
188
- let res: Response | null = null;
189
- try {
190
- res = await fetch(validateUrl, {
191
- method: 'POST',
192
- cache: 'no-store',
193
- headers: {
194
- 'Content-Type': 'application/json',
195
- 'x-license-key': effectiveLicenseKey,
196
- 'x-sdk-version': sdkVersion,
197
- ...(customHeaders || {}),
198
- },
199
- body: JSON.stringify({
200
- licenseKey: effectiveLicenseKey,
201
- projectId: effectiveProjectId,
202
- sdkVersion,
203
- sdk,
204
- platform,
205
- }),
206
- });
207
- } catch (err: any) {
208
- // Fallback: If network error occurs, verify locally via RSA LicenseVerifier
209
- try {
210
- if (!canUseLocalValidationFallback(base)) {
211
- throw err;
212
- }
213
- const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
214
- const fallbackResp: LicenseValidationResponse = {
215
- valid: true,
216
- licenseStatus: 'ACTIVE',
217
- minimumSupportedVersion: '2.1.0',
218
- latestVersion: SDK_VERSION,
219
- forceUpgrade: false,
220
- expiresAt: payload.expiresAt ? new Date(payload.expiresAt * 1000).toISOString() : null,
221
- message: 'Local license verification active.',
222
- };
223
- this.cache.set(effectiveLicenseKey, { response: fallbackResp, timestamp: Date.now() });
224
- return fallbackResp;
225
- } catch {
226
- this.purgeCache(effectiveLicenseKey);
227
- throw new LicenseValidationError(`License validation request failed: ${err?.message || 'Network error'}`);
228
- }
229
- }
230
-
231
- if (res && !res.ok && canUseLocalValidationFallback(base, res.status)) {
232
- // Attempt local verification fallback only for missing local SDK validation routes.
233
- // Authoritative denials (403 revoked/expired, 426 unsupported SDK, etc.) must not
234
- // be bypassed by local JWT verification.
235
- try {
236
- const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
237
- const fallbackResp: LicenseValidationResponse = {
238
- valid: true,
239
- licenseStatus: 'ACTIVE',
240
- minimumSupportedVersion: '2.1.0',
241
- latestVersion: SDK_VERSION,
242
- forceUpgrade: false,
243
- expiresAt: payload.expiresAt ? new Date(payload.expiresAt * 1000).toISOString() : null,
244
- message: 'Local license verification active.',
245
- };
246
- this.cache.set(effectiveLicenseKey, { response: fallbackResp, timestamp: Date.now() });
247
- return fallbackResp;
248
- } catch { /* proceed to parse error response */ }
249
- }
250
-
251
- const data: LicenseValidationResponse = await res!.json().catch(() => ({
252
- valid: false,
253
- licenseStatus: 'REVOKED' as const,
254
- minimumSupportedVersion: '2.1.0',
255
- latestVersion: SDK_VERSION,
256
- forceUpgrade: false,
257
- expiresAt: null,
258
- message: 'Failed to parse license validation response.',
259
- }));
260
-
261
- // 3. Negative validation responses immediately purge any existing cache
262
- if (!res.ok || !data.valid || data.licenseStatus !== 'ACTIVE' || data.forceUpgrade) {
263
- this.purgeCache(effectiveLicenseKey);
264
-
265
- if (data.forceUpgrade || res.status === 426) {
266
- throw new SDKVersionUnsupportedError(
267
- data.message || `This SDK version (${sdkVersion}) is no longer supported. Upgrade to version ${data.latestVersion || '2.2.6'} or later.`,
268
- data
269
- );
270
- }
271
-
272
- const errMsg = data.message || `License validation failed with status: ${data.licenseStatus}. Access denied.`;
273
- throw new LicenseValidationError(errMsg, data);
274
- }
275
-
276
- // 4. Cache SUCCESSFUL validation only (TTL = 5 minutes)
277
- this.cache.set(effectiveLicenseKey, {
278
- response: data,
279
- timestamp: Date.now(),
280
- });
281
-
282
- return data;
283
- }
284
- }
@@ -1,261 +0,0 @@
1
- import { ConfigurationException } from '../exceptions';
2
-
3
- /**
4
- * Decoded payload of a Retrivora license JWT.
5
- */
6
- export interface LicensePayload {
7
- projectId: string;
8
- expiresAt: number;
9
- tier: string;
10
- licenseStatus?: string;
11
- minimumSupportedVersion?: string;
12
- forceUpgrade?: boolean;
13
- }
14
-
15
- /**
16
- * Validates licenses against the central Retrivora API.
17
- * Replaces the old zero-latency local cryptographic verifier.
18
- */
19
- export class LicenseVerifier {
20
- // In-memory cache to save network overhead on hot paths.
21
- private static readonly cache = new Map<
22
- string,
23
- { payload: LicensePayload; cachedAt: number }
24
- >();
25
- private static readonly CACHE_TTL_MS = 5 * 60 * 1000; // Cache verified license for 5 minutes
26
-
27
- /**
28
- * Validates the license key asynchronously by calling the Retrivora backend.
29
- *
30
- * @param licenseKey - Base64url signed JWT license key.
31
- * @param currentProjectId - Project namespace ID.
32
- * @param provider - Optional provider for tier checks.
33
- */
34
- static async verifyAsync(
35
- licenseKey: string | undefined,
36
- currentProjectId: string,
37
- provider?: string
38
- ): Promise<LicensePayload> {
39
- const isProduction = process.env.NODE_ENV === 'production';
40
- const now = Date.now();
41
-
42
- // 1. Development Fallback (Fail-open locally but log warning)
43
- if (!licenseKey) {
44
- if (isProduction) {
45
- throw new ConfigurationException(
46
- '[Retrivora SDK] License key (licenseKey) is required in production environments.'
47
- );
48
- }
49
- console.warn(
50
- `\x1b[33m[Retrivora SDK] WARNING: Running without a license key. This namespace (${currentProjectId}) is permitted for local development only.\x1b[0m`
51
- );
52
- return {
53
- projectId: currentProjectId,
54
- expiresAt: Math.floor(Date.now() / 1000) + 86400, // Valid for 24h
55
- tier: 'hobby',
56
- };
57
- }
58
-
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;
69
- }
70
- }
71
-
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\/?$/, '');
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
- });
96
-
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);
104
- }
105
-
106
- const data = await response.json();
107
-
108
- if (!data.valid) {
109
- throw new Error(data.message || 'License validation failed by server.');
110
- }
111
-
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);
116
- }
117
-
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
- };
128
-
129
- // 4. Validate Vector DB Provider against Tier (Production only)
130
- if (isProduction && provider) {
131
- const normalizedProvider = provider.toLowerCase();
132
-
133
- if (tier === 'hobby') {
134
- // Hobby tier only supports PostgreSQL/pgvector/Supabase
135
- const allowedHobby = ['postgresql', 'pgvector', 'supabase'];
136
- if (!allowedHobby.includes(normalizedProvider)) {
137
- throw new Error(
138
- `The database provider "${provider}" is not allowed on the Hobby tier. ` +
139
- `Hobby tier is restricted to PostgreSQL and Supabase. ` +
140
- `Please upgrade to a Developer Pro or Enterprise plan.`
141
- );
142
- }
143
- } else if (tier === 'pro' || tier === 'developer_pro' || tier === 'premium' || tier === 'growth' || tier === 'free_trial' || tier === 'free_tier' || tier === 'free') {
144
- // Developer Pro supports: PostgreSQL, Pinecone, Qdrant, MongoDB, Milvus, ChromaDB
145
- const allowedPro = [
146
- 'postgresql', 'pgvector', 'supabase',
147
- 'pinecone', 'qdrant', 'mongodb', 'milvus',
148
- 'chroma', 'chromadb'
149
- ];
150
- if (!allowedPro.includes(normalizedProvider)) {
151
- throw new Error(
152
- `The database provider "${provider}" is not allowed on the Developer Pro tier. ` +
153
- `Please upgrade to an Enterprise plan.`
154
- );
155
- }
156
- }
157
- }
158
-
159
- this.cache.set(cacheKey, { payload, cachedAt: now });
160
-
161
- return payload;
162
- } catch (err) {
163
- const message = err instanceof Error ? err.message : String(err);
164
- throw new ConfigurationException(
165
- `[Retrivora SDK] License key validation failed via API: ${message}`
166
- );
167
- }
168
- }
169
-
170
- static async verifyIP(licenseKey: string | undefined): Promise<void> {
171
- if (!licenseKey) return;
172
- try {
173
- const parts = licenseKey.split('.');
174
- if (parts.length !== 3) return;
175
- const [, payloadB64] = parts;
176
- const payload: LicensePayload & { ipv4?: string; ipv6?: string } = JSON.parse(
177
- Buffer.from(payloadB64, 'base64url').toString('utf8')
178
- );
179
-
180
- const tier = (payload.tier || '').toLowerCase();
181
- // Skip check if Enterprise or Custom
182
- if (tier === 'enterprise' || tier === 'custom') {
183
- return;
184
- }
185
-
186
- // If Hobby (free_trial) or Developer Pro, perform the check
187
- if (payload.ipv4 || payload.ipv6) {
188
- let currentIpv4 = '';
189
- let currentIpv6 = '';
190
-
191
- try {
192
- const res = await fetch('https://api4.ipify.org?format=json', { signal: AbortSignal.timeout(3000) });
193
- const data = await res.json();
194
- currentIpv4 = data.ip;
195
- } catch (e) { }
196
-
197
- try {
198
- const res = await fetch('https://api6.ipify.org?format=json', { signal: AbortSignal.timeout(3000) });
199
- const data = await res.json();
200
- currentIpv6 = data.ip;
201
- } catch (e) { }
202
-
203
- const localIps: string[] = [];
204
- try {
205
- const osModule = require('os');
206
- const interfaces = osModule.networkInterfaces();
207
- for (const name of Object.keys(interfaces)) {
208
- for (const iface of interfaces[name] || []) {
209
- if (!iface.internal) {
210
- localIps.push(iface.address);
211
- }
212
- }
213
- }
214
- } catch (e) { }
215
-
216
- const isIpv4Match = payload.ipv4 && (
217
- currentIpv4 === payload.ipv4 ||
218
- localIps.includes(payload.ipv4)
219
- );
220
- const isIpv6Match = payload.ipv6 && (
221
- currentIpv6 === payload.ipv6 ||
222
- localIps.includes(payload.ipv6)
223
- );
224
-
225
- if (payload.ipv4 && payload.ipv6) {
226
- if (!isIpv4Match && !isIpv6Match) {
227
- throw new Error(
228
- `License key access restricted. This license key was created for a different system (authorized IPv4: ${payload.ipv4}, IPv6: ${payload.ipv6}) and cannot be used on this machine.`
229
- );
230
- }
231
- } else if (payload.ipv4 && !isIpv4Match) {
232
- throw new Error(
233
- `License key access restricted. This license key was created for a different system (authorized IPv4: ${payload.ipv4}) and cannot be used on this machine.`
234
- );
235
- } else if (payload.ipv6 && !isIpv6Match) {
236
- throw new Error(
237
- `License key access restricted. This license key was created for a different system (authorized IPv6: ${payload.ipv6}) and cannot be used on this machine.`
238
- );
239
- }
240
- }
241
- } catch (err: any) {
242
- if (err.message.includes('License key access restricted')) {
243
- throw new ConfigurationException(`[Retrivora SDK] ${err.message}`);
244
- }
245
- }
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
- }
261
- }