@retrivora-ai/rag-engine 2.3.7 → 2.3.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/handlers/index.d.mts +1 -1
- package/dist/handlers/index.d.ts +1 -1
- package/dist/handlers/index.js +227 -117
- package/dist/handlers/index.mjs +229 -119
- package/dist/{index-ejOWsaqb.d.ts → index-BQd6Bax0.d.ts} +1 -1
- package/dist/{index-xxQOFx-u.d.mts → index-C7aHK7_g.d.mts} +1 -1
- package/dist/index.js +114 -87
- package/dist/index.mjs +114 -87
- package/dist/server.d.mts +12 -32
- package/dist/server.d.ts +12 -32
- package/dist/server.js +232 -121
- package/dist/server.mjs +234 -123
- package/package.json +1 -1
- package/src/components/ChatWidget.tsx +0 -1
- package/src/components/ConfigProvider.tsx +2 -1
- package/src/config/serverConfig.ts +1 -2
- package/src/core/ConfigFetcher.ts +36 -3
- package/src/core/DatabaseStorage.ts +13 -13
- package/src/core/LicenseValidator.ts +5 -3
- package/src/core/LicenseVerifier.ts +85 -120
- package/src/core/Retrivora.ts +1 -1
- package/src/core/VectorPlugin.ts +1 -1
- package/src/handlers/index.ts +23 -13
- package/src/providers/vectordb/PineconeProvider.ts +69 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@retrivora-ai/rag-engine",
|
|
3
|
-
"version": "2.3.
|
|
3
|
+
"version": "2.3.8",
|
|
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
|
|
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;
|
|
@@ -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
|
|
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;
|
|
@@ -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 =>
|
|
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
|
|
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.
|
|
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.
|
|
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.
|
|
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
|
-
*
|
|
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
|
-
//
|
|
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
|
|
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
|
-
*
|
|
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
|
|
32
|
+
* @param provider - Optional provider for tier checks.
|
|
69
33
|
*/
|
|
70
|
-
static
|
|
34
|
+
static async verifyAsync(
|
|
71
35
|
licenseKey: string | undefined,
|
|
72
36
|
currentProjectId: string,
|
|
73
|
-
provider?: string
|
|
74
|
-
|
|
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
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
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
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
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
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
throw new Error(
|
|
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
|
|
149
|
-
payload.projectId === currentProjectId ||
|
|
150
|
-
payload.projectId === `retrivora-${currentProjectId}` ||
|
|
151
|
-
`retrivora-${payload.projectId}` === currentProjectId;
|
|
106
|
+
const data = await response.json();
|
|
152
107
|
|
|
153
|
-
if (!
|
|
154
|
-
|
|
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
|
-
|
|
161
|
-
|
|
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
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
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
|
-
|
|
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
|
}
|
package/src/core/Retrivora.ts
CHANGED
|
@@ -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.
|
|
27
|
+
await LicenseVerifier.verifyAsync(
|
|
28
28
|
this.config.licenseKey,
|
|
29
29
|
this.config.projectId,
|
|
30
30
|
this.config.vectorDb?.provider
|
package/src/core/VectorPlugin.ts
CHANGED
|
@@ -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.
|
|
35
|
+
await LicenseVerifier.verifyAsync(
|
|
36
36
|
resolvedConfig.licenseKey,
|
|
37
37
|
resolvedConfig.projectId,
|
|
38
38
|
resolvedConfig.vectorDb?.provider
|
package/src/handlers/index.ts
CHANGED
|
@@ -206,19 +206,29 @@ function resolveLicenseKey(
|
|
|
206
206
|
* console warning but passes (fail-open local-dev behavior); in production any
|
|
207
207
|
* invalid / expired / missing key produces a hard 403.
|
|
208
208
|
*/
|
|
209
|
-
function enforceLicense(
|
|
209
|
+
async function enforceLicense(
|
|
210
210
|
req: NextRequest,
|
|
211
211
|
config: RagConfig,
|
|
212
212
|
bodyLicenseKey?: string
|
|
213
|
-
): { ok: true; payload: LicensePayload } | { ok: false; response: Response } {
|
|
213
|
+
): Promise<{ ok: true; payload: LicensePayload } | { ok: false; response: Response }> {
|
|
214
214
|
const rawKey = resolveLicenseKey(req, config, bodyLicenseKey);
|
|
215
215
|
const licenseKey = (rawKey || '').trim().replace(/^["']|["']$/g, '').trim();
|
|
216
216
|
const projectId = config.projectId || '';
|
|
217
217
|
|
|
218
218
|
try {
|
|
219
|
-
// Always use the
|
|
220
|
-
|
|
221
|
-
|
|
219
|
+
// Always use the async verifier which hits the Retrivora backend API.
|
|
220
|
+
let payload;
|
|
221
|
+
try {
|
|
222
|
+
payload = await LicenseVerifier.verifyAsync(licenseKey, projectId);
|
|
223
|
+
} catch (err: any) {
|
|
224
|
+
return {
|
|
225
|
+
ok: false,
|
|
226
|
+
response: NextResponse.json(
|
|
227
|
+
{ error: `License validation failed: ${err.message}` },
|
|
228
|
+
{ status: 401 }
|
|
229
|
+
)
|
|
230
|
+
};
|
|
231
|
+
}
|
|
222
232
|
return { ok: true, payload };
|
|
223
233
|
} catch (err: any) {
|
|
224
234
|
const message =
|
|
@@ -492,7 +502,7 @@ export function createChatHandler(
|
|
|
492
502
|
const bodyObj = (body ?? {}) as any;
|
|
493
503
|
|
|
494
504
|
// 2. License enforcement (after body parse so we can read body.licenseKey)
|
|
495
|
-
const licenseCheck = enforceLicense(req as NextRequest, config, bodyObj?.licenseKey);
|
|
505
|
+
const licenseCheck = await enforceLicense(req as NextRequest, config, bodyObj?.licenseKey);
|
|
496
506
|
if (!licenseCheck.ok) return licenseCheck.response as any;
|
|
497
507
|
|
|
498
508
|
// 2b. Free Tier limits check (hobby / free / free_trial tiers)
|
|
@@ -643,7 +653,7 @@ export function createStreamHandler(
|
|
|
643
653
|
const bodyObj = (body ?? {}) as any;
|
|
644
654
|
|
|
645
655
|
// 2b. License enforcement (for JSON-body requests)
|
|
646
|
-
const licenseCheck = enforceLicense(req as NextRequest, config, bodyObj?.licenseKey);
|
|
656
|
+
const licenseCheck = await enforceLicense(req as NextRequest, config, bodyObj?.licenseKey);
|
|
647
657
|
if (!licenseCheck.ok) return licenseCheck.response as any;
|
|
648
658
|
|
|
649
659
|
// 2c. Free Tier limits check (hobby / free / free_trial tiers)
|
|
@@ -843,7 +853,7 @@ export function createIngestHandler(
|
|
|
843
853
|
const body = await req.json();
|
|
844
854
|
|
|
845
855
|
// License enforcement before ingestion
|
|
846
|
-
const licenseCheck = enforceLicense(req as NextRequest, config, body?.licenseKey);
|
|
856
|
+
const licenseCheck = await enforceLicense(req as NextRequest, config, body?.licenseKey);
|
|
847
857
|
if (!licenseCheck.ok) return licenseCheck.response as any;
|
|
848
858
|
|
|
849
859
|
const { documents, namespace } = body as {
|
|
@@ -949,7 +959,7 @@ export function createHealthHandler(
|
|
|
949
959
|
*
|
|
950
960
|
* Client flow: `LicenseValidator.validate()` calls this URL, receives
|
|
951
961
|
* authoritative DB-backed status (ACTIVE / TERMINATED / SUSPENDED / EXPIRED /
|
|
952
|
-
|
|
962
|
+
// REVOKED), and falls back to pure-local `LicenseVerifier.verifyAsync()` if the
|
|
953
963
|
* server is unreachable or returns an error.
|
|
954
964
|
*
|
|
955
965
|
* This handler does NOT enforce license — it is the verifier itself. It does,
|
|
@@ -988,7 +998,7 @@ export function createLicenseHandler(
|
|
|
988
998
|
|
|
989
999
|
const projectId = body?.projectId || config.projectId || '';
|
|
990
1000
|
|
|
991
|
-
const payload = LicenseVerifier.
|
|
1001
|
+
const payload = await LicenseVerifier.verifyAsync(licenseKey, projectId);
|
|
992
1002
|
|
|
993
1003
|
return NextResponse.json({
|
|
994
1004
|
valid: true,
|
|
@@ -1047,7 +1057,7 @@ export function createUploadHandler(
|
|
|
1047
1057
|
|
|
1048
1058
|
// License enforcement (uploads use headers/env for license key, no JSON body)
|
|
1049
1059
|
const config = plugin.getConfig();
|
|
1050
|
-
const licenseCheck = enforceLicense(req as NextRequest, config);
|
|
1060
|
+
const licenseCheck = await enforceLicense(req as NextRequest, config);
|
|
1051
1061
|
if (!licenseCheck.ok) return licenseCheck.response as any;
|
|
1052
1062
|
|
|
1053
1063
|
try {
|
|
@@ -1239,7 +1249,7 @@ export function createSuggestionsHandler(
|
|
|
1239
1249
|
|
|
1240
1250
|
// License enforcement for auto-suggestions endpoint
|
|
1241
1251
|
const config = plugin.getConfig();
|
|
1242
|
-
const licenseCheck = enforceLicense(req, config);
|
|
1252
|
+
const licenseCheck = await enforceLicense(req, config);
|
|
1243
1253
|
if (!licenseCheck.ok) return licenseCheck.response as any;
|
|
1244
1254
|
let effectiveLicensePayload = licenseCheck.payload;
|
|
1245
1255
|
|
|
@@ -1255,7 +1265,7 @@ export function createSuggestionsHandler(
|
|
|
1255
1265
|
bodyLicenseKey = body.licenseKey;
|
|
1256
1266
|
// Re-check license if body contained a key override
|
|
1257
1267
|
if (bodyLicenseKey) {
|
|
1258
|
-
const recheck = enforceLicense(req, config, bodyLicenseKey);
|
|
1268
|
+
const recheck = await enforceLicense(req, config, bodyLicenseKey);
|
|
1259
1269
|
if (!recheck.ok) return recheck.response as any;
|
|
1260
1270
|
effectiveLicensePayload = recheck.payload;
|
|
1261
1271
|
}
|