@retrivora-ai/rag-engine 2.4.3 → 2.4.6

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 (142) hide show
  1. package/README.md +22 -0
  2. package/dist/{BatchProcessor-zbQMaZHm.d.mts → BatchProcessor-BGslIR5l.d.mts} +65 -4
  3. package/dist/{BatchProcessor-D42E706a.d.ts → BatchProcessor-C3gY6kZ0.d.ts} +65 -4
  4. package/dist/handlers/index.js +668 -837
  5. package/dist/handlers/index.mjs +678 -837
  6. package/dist/index.css +5 -0
  7. package/dist/index.d.mts +4 -28
  8. package/dist/index.d.ts +4 -28
  9. package/dist/index.js +91 -43
  10. package/dist/index.min.css +1 -1
  11. package/dist/index.mjs +91 -43
  12. package/dist/server.d.mts +21 -7
  13. package/dist/server.d.ts +21 -7
  14. package/dist/server.js +731 -875
  15. package/dist/server.mjs +741 -875
  16. package/package.json +11 -4
  17. package/src/LicensedRetrivora.ts +0 -278
  18. package/src/app/api/chat/route.ts +0 -4
  19. package/src/app/api/health/route.ts +0 -5
  20. package/src/app/api/ingest/route.ts +0 -27
  21. package/src/app/api/suggestions/route.ts +0 -5
  22. package/src/app/api/upload/route.ts +0 -5
  23. package/src/app/constants.tsx +0 -270
  24. package/src/app/favicon.ico +0 -0
  25. package/src/app/globals.css +0 -449
  26. package/src/app/layout.tsx +0 -22
  27. package/src/app/page.tsx +0 -64
  28. package/src/app/types.ts +0 -30
  29. package/src/browser.tsx +0 -127
  30. package/src/components/ChatWidget.tsx +0 -393
  31. package/src/components/ChatWindow.tsx +0 -952
  32. package/src/components/CodeViewer.tsx +0 -56
  33. package/src/components/ConfigProvider.tsx +0 -141
  34. package/src/components/DocumentUpload.tsx +0 -354
  35. package/src/components/DynamicChart.tsx +0 -297
  36. package/src/components/HourglassLoader.tsx +0 -87
  37. package/src/components/MarkdownComponents.tsx +0 -186
  38. package/src/components/MessageBubble.tsx +0 -498
  39. package/src/components/ObservabilityPanel.tsx +0 -374
  40. package/src/components/ProductCard.tsx +0 -107
  41. package/src/components/ProductCarousel.tsx +0 -97
  42. package/src/components/SourceCard.tsx +0 -61
  43. package/src/components/ThemeProvider.tsx +0 -8
  44. package/src/components/ThemeToggle.tsx +0 -29
  45. package/src/components/ThinkingBlock.tsx +0 -75
  46. package/src/components/UIDispatcher.tsx +0 -342
  47. package/src/components/VisualizationRenderer.tsx +0 -621
  48. package/src/components/constants.tsx +0 -503
  49. package/src/config/ConfigBuilder.ts +0 -285
  50. package/src/config/EmbeddingStrategy.ts +0 -148
  51. package/src/config/LicenseConfigResolver.ts +0 -298
  52. package/src/config/RagConfig.ts +0 -328
  53. package/src/config/UniversalProfiles.ts +0 -82
  54. package/src/config/constants.ts +0 -64
  55. package/src/config/serverConfig.ts +0 -378
  56. package/src/config/uiConstants.ts +0 -47
  57. package/src/core/BatchProcessor.ts +0 -385
  58. package/src/core/CircuitBreaker.ts +0 -118
  59. package/src/core/ConfigFetcher.ts +0 -220
  60. package/src/core/ConfigResolver.ts +0 -165
  61. package/src/core/ConfigValidator.ts +0 -197
  62. package/src/core/DatabaseStorage.ts +0 -526
  63. package/src/core/FreeTierLimitsGuard.ts +0 -281
  64. package/src/core/LLMRouter.ts +0 -79
  65. package/src/core/LangChainAgent.ts +0 -132
  66. package/src/core/LicenseValidator.ts +0 -284
  67. package/src/core/LicenseVerifier.ts +0 -261
  68. package/src/core/MultiAgentCoordinator.ts +0 -239
  69. package/src/core/Pipeline.ts +0 -1279
  70. package/src/core/PluginManager.ts +0 -277
  71. package/src/core/ProjectSettings.ts +0 -247
  72. package/src/core/ProviderHealthCheck.ts +0 -133
  73. package/src/core/ProviderInterfaces.ts +0 -37
  74. package/src/core/ProviderRegistry.ts +0 -156
  75. package/src/core/QueryProcessor.ts +0 -399
  76. package/src/core/Retrivora.ts +0 -98
  77. package/src/core/VectorPlugin.ts +0 -193
  78. package/src/core/mcp.ts +0 -261
  79. package/src/exceptions/index.ts +0 -131
  80. package/src/handlers/index.ts +0 -1625
  81. package/src/hooks/useHydrated.ts +0 -13
  82. package/src/hooks/useProjectSettings.ts +0 -105
  83. package/src/hooks/useRagChat.ts +0 -436
  84. package/src/hooks/useStoredMessages.ts +0 -64
  85. package/src/index.css +0 -4269
  86. package/src/index.ts +0 -137
  87. package/src/lib/plugin.ts +0 -24
  88. package/src/llm/ILLMProvider.ts +0 -60
  89. package/src/llm/LLMFactory.ts +0 -141
  90. package/src/llm/providers/AnthropicProvider.ts +0 -215
  91. package/src/llm/providers/GeminiProvider.ts +0 -311
  92. package/src/llm/providers/GroqProvider.ts +0 -184
  93. package/src/llm/providers/OllamaProvider.ts +0 -232
  94. package/src/llm/providers/OpenAIProvider.ts +0 -188
  95. package/src/llm/providers/QwenProvider.ts +0 -199
  96. package/src/llm/providers/UniversalLLMAdapter.ts +0 -422
  97. package/src/llm/utils.ts +0 -46
  98. package/src/providers/graphdb/BaseGraphProvider.ts +0 -43
  99. package/src/providers/graphdb/SimpleGraphProvider.ts +0 -66
  100. package/src/providers/vectordb/BaseVectorProvider.ts +0 -98
  101. package/src/providers/vectordb/ChromaDBProvider.ts +0 -130
  102. package/src/providers/vectordb/MilvusProvider.ts +0 -134
  103. package/src/providers/vectordb/MongoDBProvider.ts +0 -250
  104. package/src/providers/vectordb/MultiTablePostgresProvider.ts +0 -461
  105. package/src/providers/vectordb/PineconeProvider.ts +0 -295
  106. package/src/providers/vectordb/PostgreSQLProvider.ts +0 -227
  107. package/src/providers/vectordb/QdrantProvider.ts +0 -294
  108. package/src/providers/vectordb/RedisProvider.ts +0 -105
  109. package/src/providers/vectordb/UniversalVectorProvider.ts +0 -221
  110. package/src/providers/vectordb/WeaviateProvider.ts +0 -172
  111. package/src/rag/DocumentChunker.ts +0 -144
  112. package/src/rag/EntityExtractor.ts +0 -90
  113. package/src/rag/LlamaIndexIngestor.ts +0 -60
  114. package/src/rag/Reranker.ts +0 -106
  115. package/src/rendering/IntentClassifier.ts +0 -167
  116. package/src/rendering/RendererRegistry.ts +0 -164
  117. package/src/rendering/RuleEngine.ts +0 -67
  118. package/src/rendering/VisualizationDecisionEngine.ts +0 -164
  119. package/src/rendering/__tests__/VisualizationDecisionEngine.test.ts +0 -237
  120. package/src/rendering/index.ts +0 -12
  121. package/src/rendering/rules/Rule1SpecificInfoRule.ts +0 -28
  122. package/src/rendering/rules/Rule2ComparisonRule.ts +0 -24
  123. package/src/rendering/rules/Rule3ProductDiscoveryRule.ts +0 -28
  124. package/src/rendering/rules/Rule4AnalyticalRule.ts +0 -38
  125. package/src/rendering/rules/Rule5MixedResponseRule.ts +0 -29
  126. package/src/rendering/rules/Rule6SmallResultSetRule.ts +0 -24
  127. package/src/rendering/rules/Rule7LargeTableRule.ts +0 -35
  128. package/src/rendering/types.ts +0 -96
  129. package/src/server.ts +0 -156
  130. package/src/tailwind.css +0 -194
  131. package/src/telemetry/TelemetryService.ts +0 -330
  132. package/src/types/chat.ts +0 -89
  133. package/src/types/index.ts +0 -278
  134. package/src/types/pdf-parse.d.ts +0 -13
  135. package/src/types/props.ts +0 -169
  136. package/src/utils/DocumentParser.ts +0 -111
  137. package/src/utils/ProductExtractor.ts +0 -350
  138. package/src/utils/SchemaMapper.ts +0 -176
  139. package/src/utils/UITransformer.ts +0 -1812
  140. package/src/utils/synonyms.ts +0 -80
  141. package/src/utils/templateUtils.ts +0 -78
  142. 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
- }