@retrivora-ai/rag-engine 2.2.6 → 2.2.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/server.d.mts CHANGED
@@ -1,9 +1,9 @@
1
- import { V as VectorDBConfig, L as LLMConfig, d as EmbeddingConfig, i as RagConfig, n as UniversalRagConfig, o as UpsertDocument, q as VectorMatch, G as GraphDBConfig, r as GraphNode, s as Edge, t as GraphSearchResult, I as ILLMProvider, p as VectorDBProvider, g as LLMProvider, e as EmbeddingProvider, R as RAGConfig, m as UIConfig, C as ChatMessage, b as ChatOptions, E as EmbedOptions } from './ILLMProvider-BWa68XX5.mjs';
2
- export { B as BarChartData, u as CarouselProduct, c as ChatResponse, v as IRetriever, f as IngestDocument, h as LatencyBreakdown, w as LineChartDataPoint, M as MessageRole, x as MetricCardData, O as ObservabilityTrace, P as PieChartData, y as Product, j as RagMessage, k as RetrievalConfig, z as RetrievalResult, l as RetrievedChunk, A as RetrivoraChunkMetadata, D as RetrivoraIngestedDocument, S as ScatterPlotDataPoint, F as SuggestionsResponse, H as TableData, T as TokenUsage, J as UITransformationResponse, U as UseRagChatOptions, a as UseRagChatReturn, K as VisualizationType, W as WorkflowConfig } from './ILLMProvider-BWa68XX5.mjs';
3
- import { I as IRenderRule, i as DecisionContext, k as IntentCategory, n as RenderDecision } from './index-BbJGyNmW.mjs';
4
- export { x as ArchitectureCardProps, A as AuthenticationException, y as CarouselRendererStrategy, z as ChartRendererStrategy, e as ChartType, B as ChatViewportSize, C as ChatWidgetProps, a as ChatWindowProps, f as Chunk, g as ChunkOptions, c as ClientConfig, b as ConfigProviderProps, h as ConfigurationException, F as DocumentChunker, D as DocumentUploadProps, E as EmbeddingFailedException, j as IRendererStrategy, l as IntentClassifier, M as MessageBubbleProps, G as MixedRendererStrategy, H as Pipeline, J as PipelineStep, P as ProductCardProps, d as ProductCarouselProps, m as ProviderNotFoundException, K as ProviderPill, R as RateLimitException, L as RenderSectionDecision, o as RenderType, p as RendererRegistry, q as RetrievalException, r as Retrivora, s as RetrivoraError, t as RetrivoraErrorCode, u as RuleEngine, v as SDK_VERSION, N as Snippet, S as SourceCardProps, T as TableRendererStrategy, O as TextRendererStrategy, V as VisualizationDecisionEngine, w as decideVisualization, Q as wrapError } from './index-BbJGyNmW.mjs';
5
- import { H as HealthCheckResult, I as IProviderValidator, a as IProviderHealthChecker } from './index-DvbtNz7m.mjs';
6
- export { C as ConfigValidator, V as ValidationError, b as VectorPlugin, c as createChatHandler, d as createFeedbackHandler, e as createHealthHandler, f as createHistoryHandler, g as createIngestHandler, h as createRagHandler, i as createSessionsHandler, j as createStreamHandler, k as createUploadHandler, s as sseErrorFrame, l as sseFrame, m as sseMetaFrame, n as sseTextFrame } from './index-DvbtNz7m.mjs';
1
+ import { V as VectorDBConfig, L as LLMConfig, d as EmbeddingConfig, i as RagConfig, n as UniversalRagConfig, o as UpsertDocument, q as VectorMatch, G as GraphDBConfig, r as GraphNode, s as Edge, t as GraphSearchResult, I as ILLMProvider, p as VectorDBProvider, g as LLMProvider, e as EmbeddingProvider, R as RAGConfig, m as UIConfig, C as ChatMessage, b as ChatOptions, E as EmbedOptions } from './ILLMProvider-teTNQ1lh.mjs';
2
+ export { B as BarChartData, u as CarouselProduct, c as ChatResponse, v as IRetriever, f as IngestDocument, h as LatencyBreakdown, w as LineChartDataPoint, M as MessageRole, x as MetricCardData, O as ObservabilityTrace, P as PieChartData, y as Product, j as RagMessage, k as RetrievalConfig, z as RetrievalResult, l as RetrievedChunk, A as RetrivoraChunkMetadata, D as RetrivoraIngestedDocument, S as ScatterPlotDataPoint, F as SuggestionsResponse, H as TableData, T as TokenUsage, J as UITransformationResponse, U as UseRagChatOptions, a as UseRagChatReturn, K as VisualizationType, W as WorkflowConfig } from './ILLMProvider-teTNQ1lh.mjs';
3
+ import { I as IRenderRule, i as DecisionContext, k as IntentCategory, q as RenderDecision } from './LicenseValidator-CENvo9o2.mjs';
4
+ export { F as ArchitectureCardProps, A as AuthenticationException, G as CarouselRendererStrategy, H as ChartRendererStrategy, e as ChartType, J as ChatViewportSize, C as ChatWidgetProps, a as ChatWindowProps, f as Chunk, g as ChunkOptions, c as ClientConfig, b as ConfigProviderProps, h as ConfigurationException, K as DocumentChunker, D as DocumentUploadProps, E as EmbeddingFailedException, j as IRendererStrategy, l as IntentClassifier, L as LicenseValidationError, m as LicenseValidationRequest, n as LicenseValidationResponse, o as LicenseValidator, M as MessageBubbleProps, N as MixedRendererStrategy, O as Pipeline, Q as PipelineStep, P as ProductCardProps, d as ProductCarouselProps, p as ProviderNotFoundException, T as ProviderPill, R as RateLimitException, U as RenderSectionDecision, r as RenderType, s as RendererRegistry, t as RetrievalException, u as Retrivora, v as RetrivoraError, w as RetrivoraErrorCode, x as RuleEngine, y as SDKVersionUnsupportedError, z as SDK_VERSION, W as Snippet, S as SourceCardProps, X as TableRendererStrategy, Y as TextRendererStrategy, V as VisualizationDecisionEngine, B as decideVisualization, Z as wrapError } from './LicenseValidator-CENvo9o2.mjs';
5
+ import { H as HealthCheckResult, I as IProviderValidator, a as IProviderHealthChecker } from './index-Dmq5lH0j.mjs';
6
+ export { C as ConfigValidator, V as ValidationError, b as VectorPlugin, c as createChatHandler, d as createFeedbackHandler, e as createHealthHandler, f as createHistoryHandler, g as createIngestHandler, h as createRagHandler, i as createSessionsHandler, j as createStreamHandler, k as createUploadHandler, s as sseErrorFrame, l as sseFrame, m as sseMetaFrame, n as sseTextFrame } from './index-Dmq5lH0j.mjs';
7
7
  import 'react';
8
8
  import 'next/server';
9
9
 
package/dist/server.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { V as VectorDBConfig, L as LLMConfig, d as EmbeddingConfig, i as RagConfig, n as UniversalRagConfig, o as UpsertDocument, q as VectorMatch, G as GraphDBConfig, r as GraphNode, s as Edge, t as GraphSearchResult, I as ILLMProvider, p as VectorDBProvider, g as LLMProvider, e as EmbeddingProvider, R as RAGConfig, m as UIConfig, C as ChatMessage, b as ChatOptions, E as EmbedOptions } from './ILLMProvider-BWa68XX5.js';
2
- export { B as BarChartData, u as CarouselProduct, c as ChatResponse, v as IRetriever, f as IngestDocument, h as LatencyBreakdown, w as LineChartDataPoint, M as MessageRole, x as MetricCardData, O as ObservabilityTrace, P as PieChartData, y as Product, j as RagMessage, k as RetrievalConfig, z as RetrievalResult, l as RetrievedChunk, A as RetrivoraChunkMetadata, D as RetrivoraIngestedDocument, S as ScatterPlotDataPoint, F as SuggestionsResponse, H as TableData, T as TokenUsage, J as UITransformationResponse, U as UseRagChatOptions, a as UseRagChatReturn, K as VisualizationType, W as WorkflowConfig } from './ILLMProvider-BWa68XX5.js';
3
- import { I as IRenderRule, i as DecisionContext, k as IntentCategory, n as RenderDecision } from './index-BCbeeh74.js';
4
- export { x as ArchitectureCardProps, A as AuthenticationException, y as CarouselRendererStrategy, z as ChartRendererStrategy, e as ChartType, B as ChatViewportSize, C as ChatWidgetProps, a as ChatWindowProps, f as Chunk, g as ChunkOptions, c as ClientConfig, b as ConfigProviderProps, h as ConfigurationException, F as DocumentChunker, D as DocumentUploadProps, E as EmbeddingFailedException, j as IRendererStrategy, l as IntentClassifier, M as MessageBubbleProps, G as MixedRendererStrategy, H as Pipeline, J as PipelineStep, P as ProductCardProps, d as ProductCarouselProps, m as ProviderNotFoundException, K as ProviderPill, R as RateLimitException, L as RenderSectionDecision, o as RenderType, p as RendererRegistry, q as RetrievalException, r as Retrivora, s as RetrivoraError, t as RetrivoraErrorCode, u as RuleEngine, v as SDK_VERSION, N as Snippet, S as SourceCardProps, T as TableRendererStrategy, O as TextRendererStrategy, V as VisualizationDecisionEngine, w as decideVisualization, Q as wrapError } from './index-BCbeeh74.js';
5
- import { H as HealthCheckResult, I as IProviderValidator, a as IProviderHealthChecker } from './index-B5TTZWkx.js';
6
- export { C as ConfigValidator, V as ValidationError, b as VectorPlugin, c as createChatHandler, d as createFeedbackHandler, e as createHealthHandler, f as createHistoryHandler, g as createIngestHandler, h as createRagHandler, i as createSessionsHandler, j as createStreamHandler, k as createUploadHandler, s as sseErrorFrame, l as sseFrame, m as sseMetaFrame, n as sseTextFrame } from './index-B5TTZWkx.js';
1
+ import { V as VectorDBConfig, L as LLMConfig, d as EmbeddingConfig, i as RagConfig, n as UniversalRagConfig, o as UpsertDocument, q as VectorMatch, G as GraphDBConfig, r as GraphNode, s as Edge, t as GraphSearchResult, I as ILLMProvider, p as VectorDBProvider, g as LLMProvider, e as EmbeddingProvider, R as RAGConfig, m as UIConfig, C as ChatMessage, b as ChatOptions, E as EmbedOptions } from './ILLMProvider-teTNQ1lh.js';
2
+ export { B as BarChartData, u as CarouselProduct, c as ChatResponse, v as IRetriever, f as IngestDocument, h as LatencyBreakdown, w as LineChartDataPoint, M as MessageRole, x as MetricCardData, O as ObservabilityTrace, P as PieChartData, y as Product, j as RagMessage, k as RetrievalConfig, z as RetrievalResult, l as RetrievedChunk, A as RetrivoraChunkMetadata, D as RetrivoraIngestedDocument, S as ScatterPlotDataPoint, F as SuggestionsResponse, H as TableData, T as TokenUsage, J as UITransformationResponse, U as UseRagChatOptions, a as UseRagChatReturn, K as VisualizationType, W as WorkflowConfig } from './ILLMProvider-teTNQ1lh.js';
3
+ import { I as IRenderRule, i as DecisionContext, k as IntentCategory, q as RenderDecision } from './LicenseValidator-CsjJp2PP.js';
4
+ export { F as ArchitectureCardProps, A as AuthenticationException, G as CarouselRendererStrategy, H as ChartRendererStrategy, e as ChartType, J as ChatViewportSize, C as ChatWidgetProps, a as ChatWindowProps, f as Chunk, g as ChunkOptions, c as ClientConfig, b as ConfigProviderProps, h as ConfigurationException, K as DocumentChunker, D as DocumentUploadProps, E as EmbeddingFailedException, j as IRendererStrategy, l as IntentClassifier, L as LicenseValidationError, m as LicenseValidationRequest, n as LicenseValidationResponse, o as LicenseValidator, M as MessageBubbleProps, N as MixedRendererStrategy, O as Pipeline, Q as PipelineStep, P as ProductCardProps, d as ProductCarouselProps, p as ProviderNotFoundException, T as ProviderPill, R as RateLimitException, U as RenderSectionDecision, r as RenderType, s as RendererRegistry, t as RetrievalException, u as Retrivora, v as RetrivoraError, w as RetrivoraErrorCode, x as RuleEngine, y as SDKVersionUnsupportedError, z as SDK_VERSION, W as Snippet, S as SourceCardProps, X as TableRendererStrategy, Y as TextRendererStrategy, V as VisualizationDecisionEngine, B as decideVisualization, Z as wrapError } from './LicenseValidator-CsjJp2PP.js';
5
+ import { H as HealthCheckResult, I as IProviderValidator, a as IProviderHealthChecker } from './index-BPJ3KDYI.js';
6
+ export { C as ConfigValidator, V as ValidationError, b as VectorPlugin, c as createChatHandler, d as createFeedbackHandler, e as createHealthHandler, f as createHistoryHandler, g as createIngestHandler, h as createRagHandler, i as createSessionsHandler, j as createStreamHandler, k as createUploadHandler, s as sseErrorFrame, l as sseFrame, m as sseMetaFrame, n as sseTextFrame } from './index-BPJ3KDYI.js';
7
7
  import 'react';
8
8
  import 'next/server';
9
9
 
package/dist/server.js CHANGED
@@ -2224,6 +2224,8 @@ __export(server_exports, {
2224
2224
  IntentClassifier: () => IntentClassifier,
2225
2225
  LLMFactory: () => LLMFactory,
2226
2226
  LLM_PROFILES: () => LLM_PROFILES,
2227
+ LicenseValidationError: () => LicenseValidationError,
2228
+ LicenseValidator: () => LicenseValidator,
2227
2229
  LicenseVerifier: () => LicenseVerifier,
2228
2230
  MilvusProvider: () => MilvusProvider,
2229
2231
  MixedRendererStrategy: () => MixedRendererStrategy,
@@ -2254,6 +2256,7 @@ __export(server_exports, {
2254
2256
  Rule6SmallResultSetRule: () => Rule6SmallResultSetRule,
2255
2257
  Rule7LargeTableRule: () => Rule7LargeTableRule,
2256
2258
  RuleEngine: () => RuleEngine,
2259
+ SDKVersionUnsupportedError: () => SDKVersionUnsupportedError,
2257
2260
  SDK_VERSION: () => SDK_VERSION,
2258
2261
  TableRendererStrategy: () => TableRendererStrategy,
2259
2262
  TextRendererStrategy: () => TextRendererStrategy,
@@ -2328,6 +2331,16 @@ var AuthenticationException = class extends RetrivoraError {
2328
2331
  super(message, "AUTHENTICATION_ERROR", details);
2329
2332
  }
2330
2333
  };
2334
+ var SDKVersionUnsupportedError = class extends RetrivoraError {
2335
+ constructor(message = "This SDK version is no longer supported.", details) {
2336
+ super(message, "SDK_VERSION_UNSUPPORTED", details);
2337
+ }
2338
+ };
2339
+ var LicenseValidationError = class extends RetrivoraError {
2340
+ constructor(message = "License validation failed.", details) {
2341
+ super(message, "LICENSE_VALIDATION_ERROR", details);
2342
+ }
2343
+ };
2331
2344
  function wrapError(err, defaultCode, defaultMessage) {
2332
2345
  var _a2;
2333
2346
  if (err instanceof RetrivoraError) {
@@ -2340,8 +2353,10 @@ function wrapError(err, defaultCode, defaultMessage) {
2340
2353
  if (status === 429 || /rate[- ]?limit/i.test(message) || code === "RATE_LIMIT_EXCEEDED") {
2341
2354
  return new RateLimitException(message, err);
2342
2355
  }
2343
- if (status === 401 || status === 403 || /unauthorized|auth|api[- ]?key/i.test(message) || code === "INVALID_API_KEY") {
2344
- return new AuthenticationException(message, err);
2356
+ if (status === 401 || status === 403 || /unauthorized|auth|license|revoked|terminated|api[- ]?key/i.test(message) || code === "INVALID_API_KEY" || code === "LICENSE_DELETED" || code === "LICENSE_INACTIVE") {
2357
+ const isLicenseError = /403|license|revoked|terminated/i.test(message) || status === 403;
2358
+ const cleanMsg = isLicenseError ? "Your Retrivora license key has been terminated, suspended, or revoked. Access denied." : message;
2359
+ return new AuthenticationException(cleanMsg, err);
2345
2360
  }
2346
2361
  switch (defaultCode) {
2347
2362
  case "PROVIDER_NOT_FOUND":
@@ -4808,7 +4823,7 @@ var ConfigValidator = class {
4808
4823
  // package.json
4809
4824
  var package_default = {
4810
4825
  name: "@retrivora-ai/rag-engine",
4811
- version: "2.2.6",
4826
+ version: "2.2.8",
4812
4827
  description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
4813
4828
  author: "Abhinav Alkuchi",
4814
4829
  license: "UNLICENSED",
@@ -10924,7 +10939,10 @@ function createStreamHandler(configOrPlugin, options) {
10924
10939
  }
10925
10940
  } catch (streamError) {
10926
10941
  if (isActive) {
10927
- const errorMessage = streamError instanceof Error ? streamError.message : String(streamError);
10942
+ let errorMessage = streamError instanceof Error ? streamError.message : String(streamError);
10943
+ if (errorMessage.includes("403") || errorMessage.toLowerCase().includes("license") || errorMessage.toLowerCase().includes("revoked") || errorMessage.toLowerCase().includes("terminated")) {
10944
+ errorMessage = "Your Retrivora license key has been terminated, suspended, or revoked. Access denied.";
10945
+ }
10928
10946
  console.error("[createStreamHandler] Stream error:", streamError);
10929
10947
  reportTelemetry(req, plugin, "QUERY_GENERATION", "error", errorMessage);
10930
10948
  try {
@@ -10994,6 +11012,46 @@ function createHealthHandler(configOrPlugin, options) {
10994
11012
  }
10995
11013
  };
10996
11014
  }
11015
+ function createLicenseHandler(configOrPlugin, options) {
11016
+ const plugin = getOrCreatePlugin(configOrPlugin);
11017
+ const onAuthorize = options == null ? void 0 : options.onAuthorize;
11018
+ return async function POST(req) {
11019
+ var _a2;
11020
+ if (req) {
11021
+ const authResult = await checkAuth(req, onAuthorize);
11022
+ if (authResult) return authResult;
11023
+ }
11024
+ try {
11025
+ const body = await req.json().catch(() => ({}));
11026
+ const config = plugin.getConfig();
11027
+ const licenseKey = req.headers.get("x-license-key") || (body == null ? void 0 : body.licenseKey) || ((_a2 = req.headers.get("authorization")) == null ? void 0 : _a2.replace(/^Bearer\s+/i, "")) || config.licenseKey || process.env.RETRIVORA_LICENSE_KEY || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY || "";
11028
+ const projectId = (body == null ? void 0 : body.projectId) || config.projectId || "my-rag-app";
11029
+ const payload = LicenseVerifier.verify(licenseKey, projectId);
11030
+ return import_server.NextResponse.json({
11031
+ valid: true,
11032
+ licenseStatus: "ACTIVE",
11033
+ minimumSupportedVersion: "2.1.0",
11034
+ latestVersion: SDK_VERSION,
11035
+ forceUpgrade: false,
11036
+ expiresAt: payload.expiresAt ? new Date(payload.expiresAt * 1e3).toISOString() : null,
11037
+ message: "License key is active and valid."
11038
+ });
11039
+ } catch (err) {
11040
+ return import_server.NextResponse.json(
11041
+ {
11042
+ valid: false,
11043
+ licenseStatus: "REVOKED",
11044
+ minimumSupportedVersion: "2.1.0",
11045
+ latestVersion: SDK_VERSION,
11046
+ forceUpgrade: false,
11047
+ expiresAt: null,
11048
+ message: (err == null ? void 0 : err.message) || "License validation failed."
11049
+ },
11050
+ { status: 400 }
11051
+ );
11052
+ }
11053
+ };
11054
+ }
10997
11055
  function createUploadHandler(configOrPlugin, options) {
10998
11056
  const plugin = getOrCreatePlugin(configOrPlugin);
10999
11057
  const onAuthorize = options == null ? void 0 : options.onAuthorize;
@@ -11245,6 +11303,7 @@ function createRagHandler(configOrPlugin, options) {
11245
11303
  const historyHandler = createHistoryHandler(plugin, { onAuthorize });
11246
11304
  const feedbackHandler = createFeedbackHandler(plugin, { onAuthorize });
11247
11305
  const sessionsHandler = createSessionsHandler(plugin, { onAuthorize });
11306
+ const licenseHandler = createLicenseHandler(plugin, { onAuthorize });
11248
11307
  async function routePostRequest(req, segment) {
11249
11308
  switch (segment) {
11250
11309
  case "chat":
@@ -11262,6 +11321,9 @@ function createRagHandler(configOrPlugin, options) {
11262
11321
  return historyHandler(req);
11263
11322
  case "feedback":
11264
11323
  return feedbackHandler(req);
11324
+ case "license/validate":
11325
+ case "v1/license/validate":
11326
+ return licenseHandler(req);
11265
11327
  default:
11266
11328
  return import_server.NextResponse.json({ error: `Not Found: POST segment "${segment}" not supported.` }, { status: 404 });
11267
11329
  }
@@ -11291,6 +11353,7 @@ function createRagHandler(configOrPlugin, options) {
11291
11353
  try {
11292
11354
  const url = new URL(req.url);
11293
11355
  const pathname = url.pathname;
11356
+ if (pathname.includes("/license/validate")) return "v1/license/validate";
11294
11357
  if (pathname.endsWith("/upload")) return "upload";
11295
11358
  if (pathname.endsWith("/chat") || pathname.endsWith("/chat-sync")) return "chat";
11296
11359
  if (pathname.endsWith("/health")) return "health";
@@ -11325,6 +11388,150 @@ function createRagHandler(configOrPlugin, options) {
11325
11388
  }
11326
11389
  };
11327
11390
  }
11391
+
11392
+ // src/core/LicenseValidator.ts
11393
+ var _LicenseValidator = class _LicenseValidator {
11394
+ // 5-minute TTL for successful validation only
11395
+ constructor() {
11396
+ this.cache = /* @__PURE__ */ new Map();
11397
+ }
11398
+ static getInstance() {
11399
+ if (!_LicenseValidator.instance) {
11400
+ _LicenseValidator.instance = new _LicenseValidator();
11401
+ }
11402
+ return _LicenseValidator.instance;
11403
+ }
11404
+ /**
11405
+ * Invalidate local validation cache for a license key
11406
+ */
11407
+ purgeCache(licenseKey) {
11408
+ if (licenseKey) {
11409
+ this.cache.delete(licenseKey);
11410
+ } else {
11411
+ this.cache.clear();
11412
+ }
11413
+ }
11414
+ /**
11415
+ * Validate license status and SDK version against Retrivora License Service
11416
+ */
11417
+ async validate(request) {
11418
+ var _a2;
11419
+ const {
11420
+ licenseKey,
11421
+ projectId,
11422
+ sdkVersion = SDK_VERSION,
11423
+ sdk = "@retrivora-ai/rag-engine",
11424
+ platform = typeof window !== "undefined" ? "browser" : "node",
11425
+ retrivoraApiBase,
11426
+ headers: customHeaders
11427
+ } = request;
11428
+ const getHeader = (name) => {
11429
+ if (!customHeaders) return void 0;
11430
+ const target = name.toLowerCase();
11431
+ for (const [k, v] of Object.entries(customHeaders)) {
11432
+ if (k.toLowerCase() === target) return v;
11433
+ }
11434
+ return void 0;
11435
+ };
11436
+ const effectiveLicenseKey = licenseKey || getHeader("x-license-key") || ((_a2 = getHeader("authorization")) == null ? void 0 : _a2.replace(/^Bearer\s+/i, "")) || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY : "") || "";
11437
+ if (!effectiveLicenseKey) {
11438
+ this.purgeCache(effectiveLicenseKey);
11439
+ throw new LicenseValidationError("Missing RETRIVORA_LICENSE_KEY in request.");
11440
+ }
11441
+ const cached = this.cache.get(effectiveLicenseKey);
11442
+ if (cached) {
11443
+ const isFresh = Date.now() - cached.timestamp < _LicenseValidator.SUCCESS_CACHE_TTL_MS;
11444
+ if (isFresh && cached.response.valid && cached.response.licenseStatus === "ACTIVE" && !cached.response.forceUpgrade) {
11445
+ return cached.response;
11446
+ } else {
11447
+ this.cache.delete(effectiveLicenseKey);
11448
+ }
11449
+ }
11450
+ const base = retrivoraApiBase || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_API_BASE || process.env.RETRIVORA_API_BASE : "") || "/api/retrivora";
11451
+ const validateUrl = `${base.replace(/\/$/, "")}/v1/license/validate`;
11452
+ let res = null;
11453
+ try {
11454
+ res = await fetch(validateUrl, {
11455
+ method: "POST",
11456
+ cache: "no-store",
11457
+ headers: __spreadValues({
11458
+ "Content-Type": "application/json",
11459
+ "x-license-key": effectiveLicenseKey,
11460
+ "x-sdk-version": sdkVersion
11461
+ }, customHeaders || {}),
11462
+ body: JSON.stringify({
11463
+ licenseKey,
11464
+ projectId,
11465
+ sdkVersion,
11466
+ sdk,
11467
+ platform
11468
+ })
11469
+ });
11470
+ } catch (err) {
11471
+ try {
11472
+ const payload = LicenseVerifier.verify(licenseKey, projectId || "my-rag-app");
11473
+ const fallbackResp = {
11474
+ valid: true,
11475
+ licenseStatus: "ACTIVE",
11476
+ minimumSupportedVersion: "2.1.0",
11477
+ latestVersion: SDK_VERSION,
11478
+ forceUpgrade: false,
11479
+ expiresAt: payload.expiresAt ? new Date(payload.expiresAt * 1e3).toISOString() : null,
11480
+ message: "Local license verification active."
11481
+ };
11482
+ this.cache.set(licenseKey, { response: fallbackResp, timestamp: Date.now() });
11483
+ return fallbackResp;
11484
+ } catch (e) {
11485
+ this.purgeCache(licenseKey);
11486
+ throw new LicenseValidationError(`License validation request failed: ${(err == null ? void 0 : err.message) || "Network error"}`);
11487
+ }
11488
+ }
11489
+ if (res && !res.ok) {
11490
+ try {
11491
+ const payload = LicenseVerifier.verify(licenseKey, projectId || "my-rag-app");
11492
+ const fallbackResp = {
11493
+ valid: true,
11494
+ licenseStatus: "ACTIVE",
11495
+ minimumSupportedVersion: "2.1.0",
11496
+ latestVersion: SDK_VERSION,
11497
+ forceUpgrade: false,
11498
+ expiresAt: payload.expiresAt ? new Date(payload.expiresAt * 1e3).toISOString() : null,
11499
+ message: "Local license verification active."
11500
+ };
11501
+ this.cache.set(licenseKey, { response: fallbackResp, timestamp: Date.now() });
11502
+ return fallbackResp;
11503
+ } catch (e) {
11504
+ }
11505
+ }
11506
+ const data = await res.json().catch(() => ({
11507
+ valid: false,
11508
+ licenseStatus: "REVOKED",
11509
+ minimumSupportedVersion: "2.1.0",
11510
+ latestVersion: SDK_VERSION,
11511
+ forceUpgrade: false,
11512
+ expiresAt: null,
11513
+ message: "Failed to parse license validation response."
11514
+ }));
11515
+ if (!res.ok || !data.valid || data.licenseStatus !== "ACTIVE" || data.forceUpgrade) {
11516
+ this.purgeCache(licenseKey);
11517
+ if (data.forceUpgrade || res.status === 426) {
11518
+ throw new SDKVersionUnsupportedError(
11519
+ data.message || `This SDK version (${sdkVersion}) is no longer supported. Upgrade to version ${data.latestVersion || "2.2.6"} or later.`,
11520
+ data
11521
+ );
11522
+ }
11523
+ const errMsg = data.message || `License validation failed with status: ${data.licenseStatus}. Access denied.`;
11524
+ throw new LicenseValidationError(errMsg, data);
11525
+ }
11526
+ this.cache.set(licenseKey, {
11527
+ response: data,
11528
+ timestamp: Date.now()
11529
+ });
11530
+ return data;
11531
+ }
11532
+ };
11533
+ _LicenseValidator.SUCCESS_CACHE_TTL_MS = 5 * 60 * 1e3;
11534
+ var LicenseValidator = _LicenseValidator;
11328
11535
  // Annotate the CommonJS export names for ESM import in node:
11329
11536
  0 && (module.exports = {
11330
11537
  AnthropicProvider,
@@ -11347,6 +11554,8 @@ function createRagHandler(configOrPlugin, options) {
11347
11554
  IntentClassifier,
11348
11555
  LLMFactory,
11349
11556
  LLM_PROFILES,
11557
+ LicenseValidationError,
11558
+ LicenseValidator,
11350
11559
  LicenseVerifier,
11351
11560
  MilvusProvider,
11352
11561
  MixedRendererStrategy,
@@ -11377,6 +11586,7 @@ function createRagHandler(configOrPlugin, options) {
11377
11586
  Rule6SmallResultSetRule,
11378
11587
  Rule7LargeTableRule,
11379
11588
  RuleEngine,
11589
+ SDKVersionUnsupportedError,
11380
11590
  SDK_VERSION,
11381
11591
  TableRendererStrategy,
11382
11592
  TextRendererStrategy,
package/dist/server.mjs CHANGED
@@ -2231,6 +2231,16 @@ var AuthenticationException = class extends RetrivoraError {
2231
2231
  super(message, "AUTHENTICATION_ERROR", details);
2232
2232
  }
2233
2233
  };
2234
+ var SDKVersionUnsupportedError = class extends RetrivoraError {
2235
+ constructor(message = "This SDK version is no longer supported.", details) {
2236
+ super(message, "SDK_VERSION_UNSUPPORTED", details);
2237
+ }
2238
+ };
2239
+ var LicenseValidationError = class extends RetrivoraError {
2240
+ constructor(message = "License validation failed.", details) {
2241
+ super(message, "LICENSE_VALIDATION_ERROR", details);
2242
+ }
2243
+ };
2234
2244
  function wrapError(err, defaultCode, defaultMessage) {
2235
2245
  var _a2;
2236
2246
  if (err instanceof RetrivoraError) {
@@ -2243,8 +2253,10 @@ function wrapError(err, defaultCode, defaultMessage) {
2243
2253
  if (status === 429 || /rate[- ]?limit/i.test(message) || code === "RATE_LIMIT_EXCEEDED") {
2244
2254
  return new RateLimitException(message, err);
2245
2255
  }
2246
- if (status === 401 || status === 403 || /unauthorized|auth|api[- ]?key/i.test(message) || code === "INVALID_API_KEY") {
2247
- return new AuthenticationException(message, err);
2256
+ if (status === 401 || status === 403 || /unauthorized|auth|license|revoked|terminated|api[- ]?key/i.test(message) || code === "INVALID_API_KEY" || code === "LICENSE_DELETED" || code === "LICENSE_INACTIVE") {
2257
+ const isLicenseError = /403|license|revoked|terminated/i.test(message) || status === 403;
2258
+ const cleanMsg = isLicenseError ? "Your Retrivora license key has been terminated, suspended, or revoked. Access denied." : message;
2259
+ return new AuthenticationException(cleanMsg, err);
2248
2260
  }
2249
2261
  switch (defaultCode) {
2250
2262
  case "PROVIDER_NOT_FOUND":
@@ -4711,7 +4723,7 @@ var ConfigValidator = class {
4711
4723
  // package.json
4712
4724
  var package_default = {
4713
4725
  name: "@retrivora-ai/rag-engine",
4714
- version: "2.2.6",
4726
+ version: "2.2.8",
4715
4727
  description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
4716
4728
  author: "Abhinav Alkuchi",
4717
4729
  license: "UNLICENSED",
@@ -10827,7 +10839,10 @@ function createStreamHandler(configOrPlugin, options) {
10827
10839
  }
10828
10840
  } catch (streamError) {
10829
10841
  if (isActive) {
10830
- const errorMessage = streamError instanceof Error ? streamError.message : String(streamError);
10842
+ let errorMessage = streamError instanceof Error ? streamError.message : String(streamError);
10843
+ if (errorMessage.includes("403") || errorMessage.toLowerCase().includes("license") || errorMessage.toLowerCase().includes("revoked") || errorMessage.toLowerCase().includes("terminated")) {
10844
+ errorMessage = "Your Retrivora license key has been terminated, suspended, or revoked. Access denied.";
10845
+ }
10831
10846
  console.error("[createStreamHandler] Stream error:", streamError);
10832
10847
  reportTelemetry(req, plugin, "QUERY_GENERATION", "error", errorMessage);
10833
10848
  try {
@@ -10897,6 +10912,46 @@ function createHealthHandler(configOrPlugin, options) {
10897
10912
  }
10898
10913
  };
10899
10914
  }
10915
+ function createLicenseHandler(configOrPlugin, options) {
10916
+ const plugin = getOrCreatePlugin(configOrPlugin);
10917
+ const onAuthorize = options == null ? void 0 : options.onAuthorize;
10918
+ return async function POST(req) {
10919
+ var _a2;
10920
+ if (req) {
10921
+ const authResult = await checkAuth(req, onAuthorize);
10922
+ if (authResult) return authResult;
10923
+ }
10924
+ try {
10925
+ const body = await req.json().catch(() => ({}));
10926
+ const config = plugin.getConfig();
10927
+ const licenseKey = req.headers.get("x-license-key") || (body == null ? void 0 : body.licenseKey) || ((_a2 = req.headers.get("authorization")) == null ? void 0 : _a2.replace(/^Bearer\s+/i, "")) || config.licenseKey || process.env.RETRIVORA_LICENSE_KEY || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY || "";
10928
+ const projectId = (body == null ? void 0 : body.projectId) || config.projectId || "my-rag-app";
10929
+ const payload = LicenseVerifier.verify(licenseKey, projectId);
10930
+ return NextResponse.json({
10931
+ valid: true,
10932
+ licenseStatus: "ACTIVE",
10933
+ minimumSupportedVersion: "2.1.0",
10934
+ latestVersion: SDK_VERSION,
10935
+ forceUpgrade: false,
10936
+ expiresAt: payload.expiresAt ? new Date(payload.expiresAt * 1e3).toISOString() : null,
10937
+ message: "License key is active and valid."
10938
+ });
10939
+ } catch (err) {
10940
+ return NextResponse.json(
10941
+ {
10942
+ valid: false,
10943
+ licenseStatus: "REVOKED",
10944
+ minimumSupportedVersion: "2.1.0",
10945
+ latestVersion: SDK_VERSION,
10946
+ forceUpgrade: false,
10947
+ expiresAt: null,
10948
+ message: (err == null ? void 0 : err.message) || "License validation failed."
10949
+ },
10950
+ { status: 400 }
10951
+ );
10952
+ }
10953
+ };
10954
+ }
10900
10955
  function createUploadHandler(configOrPlugin, options) {
10901
10956
  const plugin = getOrCreatePlugin(configOrPlugin);
10902
10957
  const onAuthorize = options == null ? void 0 : options.onAuthorize;
@@ -11148,6 +11203,7 @@ function createRagHandler(configOrPlugin, options) {
11148
11203
  const historyHandler = createHistoryHandler(plugin, { onAuthorize });
11149
11204
  const feedbackHandler = createFeedbackHandler(plugin, { onAuthorize });
11150
11205
  const sessionsHandler = createSessionsHandler(plugin, { onAuthorize });
11206
+ const licenseHandler = createLicenseHandler(plugin, { onAuthorize });
11151
11207
  async function routePostRequest(req, segment) {
11152
11208
  switch (segment) {
11153
11209
  case "chat":
@@ -11165,6 +11221,9 @@ function createRagHandler(configOrPlugin, options) {
11165
11221
  return historyHandler(req);
11166
11222
  case "feedback":
11167
11223
  return feedbackHandler(req);
11224
+ case "license/validate":
11225
+ case "v1/license/validate":
11226
+ return licenseHandler(req);
11168
11227
  default:
11169
11228
  return NextResponse.json({ error: `Not Found: POST segment "${segment}" not supported.` }, { status: 404 });
11170
11229
  }
@@ -11194,6 +11253,7 @@ function createRagHandler(configOrPlugin, options) {
11194
11253
  try {
11195
11254
  const url = new URL(req.url);
11196
11255
  const pathname = url.pathname;
11256
+ if (pathname.includes("/license/validate")) return "v1/license/validate";
11197
11257
  if (pathname.endsWith("/upload")) return "upload";
11198
11258
  if (pathname.endsWith("/chat") || pathname.endsWith("/chat-sync")) return "chat";
11199
11259
  if (pathname.endsWith("/health")) return "health";
@@ -11228,6 +11288,150 @@ function createRagHandler(configOrPlugin, options) {
11228
11288
  }
11229
11289
  };
11230
11290
  }
11291
+
11292
+ // src/core/LicenseValidator.ts
11293
+ var _LicenseValidator = class _LicenseValidator {
11294
+ // 5-minute TTL for successful validation only
11295
+ constructor() {
11296
+ this.cache = /* @__PURE__ */ new Map();
11297
+ }
11298
+ static getInstance() {
11299
+ if (!_LicenseValidator.instance) {
11300
+ _LicenseValidator.instance = new _LicenseValidator();
11301
+ }
11302
+ return _LicenseValidator.instance;
11303
+ }
11304
+ /**
11305
+ * Invalidate local validation cache for a license key
11306
+ */
11307
+ purgeCache(licenseKey) {
11308
+ if (licenseKey) {
11309
+ this.cache.delete(licenseKey);
11310
+ } else {
11311
+ this.cache.clear();
11312
+ }
11313
+ }
11314
+ /**
11315
+ * Validate license status and SDK version against Retrivora License Service
11316
+ */
11317
+ async validate(request) {
11318
+ var _a2;
11319
+ const {
11320
+ licenseKey,
11321
+ projectId,
11322
+ sdkVersion = SDK_VERSION,
11323
+ sdk = "@retrivora-ai/rag-engine",
11324
+ platform = typeof window !== "undefined" ? "browser" : "node",
11325
+ retrivoraApiBase,
11326
+ headers: customHeaders
11327
+ } = request;
11328
+ const getHeader = (name) => {
11329
+ if (!customHeaders) return void 0;
11330
+ const target = name.toLowerCase();
11331
+ for (const [k, v] of Object.entries(customHeaders)) {
11332
+ if (k.toLowerCase() === target) return v;
11333
+ }
11334
+ return void 0;
11335
+ };
11336
+ const effectiveLicenseKey = licenseKey || getHeader("x-license-key") || ((_a2 = getHeader("authorization")) == null ? void 0 : _a2.replace(/^Bearer\s+/i, "")) || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY : "") || "";
11337
+ if (!effectiveLicenseKey) {
11338
+ this.purgeCache(effectiveLicenseKey);
11339
+ throw new LicenseValidationError("Missing RETRIVORA_LICENSE_KEY in request.");
11340
+ }
11341
+ const cached = this.cache.get(effectiveLicenseKey);
11342
+ if (cached) {
11343
+ const isFresh = Date.now() - cached.timestamp < _LicenseValidator.SUCCESS_CACHE_TTL_MS;
11344
+ if (isFresh && cached.response.valid && cached.response.licenseStatus === "ACTIVE" && !cached.response.forceUpgrade) {
11345
+ return cached.response;
11346
+ } else {
11347
+ this.cache.delete(effectiveLicenseKey);
11348
+ }
11349
+ }
11350
+ const base = retrivoraApiBase || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_API_BASE || process.env.RETRIVORA_API_BASE : "") || "/api/retrivora";
11351
+ const validateUrl = `${base.replace(/\/$/, "")}/v1/license/validate`;
11352
+ let res = null;
11353
+ try {
11354
+ res = await fetch(validateUrl, {
11355
+ method: "POST",
11356
+ cache: "no-store",
11357
+ headers: __spreadValues({
11358
+ "Content-Type": "application/json",
11359
+ "x-license-key": effectiveLicenseKey,
11360
+ "x-sdk-version": sdkVersion
11361
+ }, customHeaders || {}),
11362
+ body: JSON.stringify({
11363
+ licenseKey,
11364
+ projectId,
11365
+ sdkVersion,
11366
+ sdk,
11367
+ platform
11368
+ })
11369
+ });
11370
+ } catch (err) {
11371
+ try {
11372
+ const payload = LicenseVerifier.verify(licenseKey, projectId || "my-rag-app");
11373
+ const fallbackResp = {
11374
+ valid: true,
11375
+ licenseStatus: "ACTIVE",
11376
+ minimumSupportedVersion: "2.1.0",
11377
+ latestVersion: SDK_VERSION,
11378
+ forceUpgrade: false,
11379
+ expiresAt: payload.expiresAt ? new Date(payload.expiresAt * 1e3).toISOString() : null,
11380
+ message: "Local license verification active."
11381
+ };
11382
+ this.cache.set(licenseKey, { response: fallbackResp, timestamp: Date.now() });
11383
+ return fallbackResp;
11384
+ } catch (e) {
11385
+ this.purgeCache(licenseKey);
11386
+ throw new LicenseValidationError(`License validation request failed: ${(err == null ? void 0 : err.message) || "Network error"}`);
11387
+ }
11388
+ }
11389
+ if (res && !res.ok) {
11390
+ try {
11391
+ const payload = LicenseVerifier.verify(licenseKey, projectId || "my-rag-app");
11392
+ const fallbackResp = {
11393
+ valid: true,
11394
+ licenseStatus: "ACTIVE",
11395
+ minimumSupportedVersion: "2.1.0",
11396
+ latestVersion: SDK_VERSION,
11397
+ forceUpgrade: false,
11398
+ expiresAt: payload.expiresAt ? new Date(payload.expiresAt * 1e3).toISOString() : null,
11399
+ message: "Local license verification active."
11400
+ };
11401
+ this.cache.set(licenseKey, { response: fallbackResp, timestamp: Date.now() });
11402
+ return fallbackResp;
11403
+ } catch (e) {
11404
+ }
11405
+ }
11406
+ const data = await res.json().catch(() => ({
11407
+ valid: false,
11408
+ licenseStatus: "REVOKED",
11409
+ minimumSupportedVersion: "2.1.0",
11410
+ latestVersion: SDK_VERSION,
11411
+ forceUpgrade: false,
11412
+ expiresAt: null,
11413
+ message: "Failed to parse license validation response."
11414
+ }));
11415
+ if (!res.ok || !data.valid || data.licenseStatus !== "ACTIVE" || data.forceUpgrade) {
11416
+ this.purgeCache(licenseKey);
11417
+ if (data.forceUpgrade || res.status === 426) {
11418
+ throw new SDKVersionUnsupportedError(
11419
+ data.message || `This SDK version (${sdkVersion}) is no longer supported. Upgrade to version ${data.latestVersion || "2.2.6"} or later.`,
11420
+ data
11421
+ );
11422
+ }
11423
+ const errMsg = data.message || `License validation failed with status: ${data.licenseStatus}. Access denied.`;
11424
+ throw new LicenseValidationError(errMsg, data);
11425
+ }
11426
+ this.cache.set(licenseKey, {
11427
+ response: data,
11428
+ timestamp: Date.now()
11429
+ });
11430
+ return data;
11431
+ }
11432
+ };
11433
+ _LicenseValidator.SUCCESS_CACHE_TTL_MS = 5 * 60 * 1e3;
11434
+ var LicenseValidator = _LicenseValidator;
11231
11435
  export {
11232
11436
  AnthropicProvider,
11233
11437
  AuthenticationException,
@@ -11249,6 +11453,8 @@ export {
11249
11453
  IntentClassifier,
11250
11454
  LLMFactory,
11251
11455
  LLM_PROFILES,
11456
+ LicenseValidationError,
11457
+ LicenseValidator,
11252
11458
  LicenseVerifier,
11253
11459
  MilvusProvider,
11254
11460
  MixedRendererStrategy,
@@ -11279,6 +11485,7 @@ export {
11279
11485
  Rule6SmallResultSetRule,
11280
11486
  Rule7LargeTableRule,
11281
11487
  RuleEngine,
11488
+ SDKVersionUnsupportedError,
11282
11489
  SDK_VERSION,
11283
11490
  TableRendererStrategy,
11284
11491
  TextRendererStrategy,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@retrivora-ai/rag-engine",
3
- "version": "2.2.6",
3
+ "version": "2.2.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",