Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

feat: implement openapi spec, dashboard UI reference, and centralized middleware token auth (#1349)

Aman Agarwalb1c498528ebe
diff --git a/openapi.yaml b/openapi.yaml
new file mode 100644
index 00000000..8560915c
--- /dev/null
+++ b/openapi.yaml
@@ -0,0 +1,1015 @@
+openapi: 3.0.3
+info:
+ title: OpenLIT Client API
+ description: |
+ API specification for the OpenLIT client application.
+ This includes telemetry retrieval APIs (authorized via browser session or `OPENLIT_API_KEY`), prompt hub management, rule engine evaluation, and other controller/platform APIs.
+ version: 1.23.0
+servers:
+ - url: http://localhost:3000
+ description: Local development server
+tags:
+ - name: Telemetry
+ description: Telemetry retrieval and observability querying APIs
+ - name: Prompt Hub
+ description: Manage and compile prompt templates
+ - name: Secret Vault
+ description: Manage credentials and secrets inside Vault
+ - name: Rule Engine
+ description: Evaluate guardrails and redaction rules
+ - name: Controller
+ description: Sync state and heartbeat polling for OpenLIT controllers
+ - name: Evaluation Engine
+ description: Offline LLM evaluations
+ - name: API Keys
+ description: Manage browser/SDK access keys
+
+paths:
+ /api/telemetry/logs:
+ post:
+ tags:
+ - Telemetry
+ summary: Query logs
+ description: Retrieve a paginated list of telemetry logs matching the provided filters. Can be authenticated using session cookies or an API key.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/MetricParams'
+ responses:
+ '200':
+ description: A list of logs and total count.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ records:
+ type: array
+ items:
+ type: object
+ total:
+ type: integer
+ example: 150
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/telemetry/logs/{id}:
+ get:
+ tags:
+ - Telemetry
+ summary: Get log detail by row ID
+ description: Retrieve detail of a specific log entry by its hash/row ID.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ parameters:
+ - name: id
+ in: path
+ required: true
+ description: The cityHash64 row ID of the log.
+ schema:
+ type: string
+ responses:
+ '200':
+ description: Log details retrieved successfully.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ record:
+ type: object
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
+ /api/telemetry/logs/attribute-keys:
+ post:
+ tags:
+ - Telemetry
+ summary: Query log attribute keys
+ description: Retrieve unique attribute keys for log attributes, resource attributes, and scope attributes.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ timeLimit:
+ $ref: '#/components/schemas/TimeLimit'
+ responses:
+ '200':
+ description: Unique attribute keys.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ logAttributeKeys:
+ type: array
+ items:
+ type: string
+ resourceAttributeKeys:
+ type: array
+ items:
+ type: string
+ scopeAttributeKeys:
+ type: array
+ items:
+ type: string
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/telemetry/logs/config:
+ post:
+ tags:
+ - Telemetry
+ summary: Query logs config options
+ description: Retrieve configuration metadata such as available service names, severities, and total log rows.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ timeLimit:
+ $ref: '#/components/schemas/TimeLimit'
+ responses:
+ '200':
+ description: Configuration metadata.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ services:
+ type: array
+ items:
+ type: string
+ severities:
+ type: array
+ items:
+ type: string
+ totalRows:
+ type: integer
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
+ /api/telemetry/metrics:
+ post:
+ tags:
+ - Telemetry
+ summary: Query metrics list
+ description: Retrieve a list of aggregated metrics matching the filters.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/MetricParams'
+ responses:
+ '200':
+ description: A list of metrics.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ records:
+ type: array
+ items:
+ type: object
+ total:
+ type: integer
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/telemetry/metrics/{name}:
+ post:
+ tags:
+ - Telemetry
+ summary: Get metric detail
+ description: Retrieve time-series graph points and detail records for a specific metric name.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ parameters:
+ - name: name
+ in: path
+ required: true
+ description: The name of the metric.
+ schema:
+ type: string
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ timeLimit:
+ $ref: '#/components/schemas/TimeLimit'
+ metricType:
+ type: string
+ serviceName:
+ type: string
+ selectedConfig:
+ type: object
+ responses:
+ '200':
+ description: Metric graph and data points.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ series:
+ type: array
+ items:
+ type: object
+ points:
+ type: array
+ items:
+ type: object
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
+ /api/telemetry/metrics/attribute-keys:
+ post:
+ tags:
+ - Telemetry
+ summary: Query metric attribute keys
+ description: Retrieve unique attribute keys for metrics.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ timeLimit:
+ $ref: '#/components/schemas/TimeLimit'
+ responses:
+ '200':
+ description: Metric attributes keys.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ metricAttributeKeys:
+ type: array
+ items:
+ type: string
+ resourceAttributeKeys:
+ type: array
+ items:
+ type: string
+ scopeAttributeKeys:
+ type: array
+ items:
+ type: string
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
+ /api/telemetry/metrics/config:
+ post:
+ tags:
+ - Telemetry
+ summary: Query metrics configuration metadata
+ description: Retrieve list of available services, metric names, types, and counts.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ timeLimit:
+ $ref: '#/components/schemas/TimeLimit'
+ responses:
+ '200':
+ description: Config metadata.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ services:
+ type: array
+ items:
+ type: string
+ metricNames:
+ type: array
+ items:
+ type: string
+ metricTypes:
+ type: array
+ items:
+ type: string
+ totalRows:
+ type: integer
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
+ /api/telemetry/summary/{signal}:
+ post:
+ tags:
+ - Telemetry
+ summary: Query signal summary data
+ description: Retrieve aggregated time-series summary bucketed counts and metrics (e.g. costs, latency, or token counts) for traces, exceptions, logs, or metrics.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ parameters:
+ - name: signal
+ in: path
+ required: true
+ description: The telemetry signal type.
+ schema:
+ type: string
+ enum: [traces, exceptions, logs, metrics]
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ timeLimit:
+ $ref: '#/components/schemas/TimeLimit'
+ selectedConfig:
+ type: object
+ responses:
+ '200':
+ description: Aggregated summary stats bucketed by time interval.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ bucket:
+ type: string
+ example: hour
+ buckets:
+ type: array
+ items:
+ type: object
+ total:
+ type: integer
+ peak:
+ type: number
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/telemetry/trace:
+ post:
+ tags:
+ - Telemetry
+ summary: Query traces list
+ description: Retrieve a paginated list of trace spans matching the provided filters. Can be authenticated using session cookies or an API key.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/MetricParams'
+ responses:
+ '200':
+ description: A list of traces and total count.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ records:
+ type: array
+ items:
+ type: object
+ total:
+ type: integer
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/telemetry/exception:
+ post:
+ tags:
+ - Telemetry
+ summary: Query exceptions list
+ description: Retrieve a paginated list of exceptions matching the provided filters. Can be authenticated using session cookies or an API key.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/MetricParams'
+ responses:
+ '200':
+ description: A list of exceptions and total count.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ records:
+ type: array
+ items:
+ type: object
+ total:
+ type: integer
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/telemetry/trace/span/{id}:
+ get:
+ tags:
+ - Telemetry
+ summary: Get span detail by ID
+ description: Retrieve details of a specific trace span by its ID (along with optional evaluation summary data).
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ parameters:
+ - name: id
+ in: path
+ required: true
+ description: The ID of the span.
+ schema:
+ type: string
+ responses:
+ '200':
+ description: Span details retrieved successfully.
+ content:
+ application/json:
+ schema:
+ type: object
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/telemetry/trace/trace/{id}:
+ get:
+ tags:
+ - Telemetry
+ summary: Get trace detail by Trace ID
+ description: Retrieve details of a trace (such as its root span or transaction info) using the Trace ID.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ parameters:
+ - name: id
+ in: path
+ required: true
+ description: The ID of the trace (Trace ID).
+ schema:
+ type: string
+ responses:
+ '200':
+ description: Trace details retrieved successfully.
+ content:
+ application/json:
+ schema:
+ type: object
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/telemetry/trace/span/{id}/heirarchy:
+ get:
+ tags:
+ - Telemetry
+ summary: Get trace span hierarchy tree
+ description: Retrieve the tree hierarchy representation of all related spans (e.g. parents, subagents, child operations) associated with a trace span.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ parameters:
+ - name: id
+ in: path
+ required: true
+ description: The ID of the root/anchor span.
+ schema:
+ type: string
+ responses:
+ '200':
+ description: Span hierarchy tree.
+ content:
+ application/json:
+ schema:
+ type: object
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/api-key:
+ get:
+ tags:
+ - API Keys
+ summary: List all API Keys
+ description: Retrieve all API keys associated with the user's active database configuration.
+ security:
+ - CookieAuth: []
+ responses:
+ '200':
+ description: A list of API Keys.
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/ApiKey'
+ post:
+ tags:
+ - API Keys
+ summary: Generate an API Key
+ description: Create a new API key prefixed with `openlit-` linked to the active database configuration.
+ security:
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required:
+ - name
+ properties:
+ name:
+ type: string
+ example: my-sdk-key
+ responses:
+ '200':
+ description: API key created successfully.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ apiKey:
+ type: string
+ example: openlit-uHpx834Jsa...
+ databaseConfigId:
+ type: string
+ example: db-config-id
+ '400':
+ description: Bad Request.
+
+ /api/api-key/{id}:
+ delete:
+ tags:
+ - API Keys
+ summary: Delete an API Key
+ description: Mark an API key as deleted.
+ security:
+ - CookieAuth: []
+ parameters:
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: API key deleted successfully.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ success:
+ type: boolean
+ example: true
+ '400':
+ description: Bad request or key not found.
+
+ /api/db-config:
+ get:
+ summary: List database configurations
+ description: Retrieve database configurations the current user has access to.
+ security:
+ - CookieAuth: []
+ responses:
+ '200':
+ description: Database configurations list.
+ post:
+ summary: Save database configuration
+ description: Create or update a ClickHouse database configuration connection parameters.
+ security:
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required:
+ - host
+ - port
+ - username
+ - password
+ properties:
+ host:
+ type: string
+ port:
+ type: integer
+ username:
+ type: string
+ password:
+ type: string
+ responses:
+ '200':
+ description: Saved successfully.
+
+ /api/prompt:
+ post:
+ tags:
+ - Prompt Hub
+ summary: Create a prompt
+ description: Create a new prompt entry or version.
+ security:
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PromptInput'
+ responses:
+ '200':
+ description: Prompt created successfully.
+
+ /api/prompt/get:
+ post:
+ tags:
+ - Prompt Hub
+ summary: Retrieve a prompt by name or ID
+ description: Retrieve details of a prompt version.
+ security:
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ name:
+ type: string
+ responses:
+ '200':
+ description: Prompt details.
+
+ /api/prompt/get-compiled:
+ get:
+ tags:
+ - Prompt Hub
+ summary: Fetch compiled prompt
+ description: Fetch and compile a prompt by name with dynamic variable interpolation. Does not require browser session cookie if authenticated by API key.
+ security:
+ - ApiKeyAuth: []
+ parameters:
+ - name: name
+ in: query
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: Compiled prompt text.
+
+ /api/vault/get-secrets:
+ get:
+ tags:
+ - Secret Vault
+ summary: Fetch secrets from Vault
+ description: Safely retrieve API keys or credentials stored in the OpenLIT Vault.
+ security:
+ - ApiKeyAuth: []
+ responses:
+ '200':
+ description: Key-value secrets retrieved.
+
+ /api/rule-engine/evaluate:
+ post:
+ tags:
+ - Rule Engine
+ summary: Evaluate rule engine config
+ description: Evaluate rules (e.g. redaction, prompts, guardrails) against inputs.
+ security:
+ - ApiKeyAuth: []
+ responses:
+ '200':
+ description: Rules evaluated.
+
+ /api/evaluation/offline:
+ post:
+ tags:
+ - Evaluation Engine
+ summary: Run offline LLM evaluation
+ description: Run LLM evaluation (e.g. toxicity, hallucination, bias, pii) on user-provided prompt and response. Can be authenticated using session cookies or an API key.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OfflineEvaluationInput'
+ responses:
+ '200':
+ description: Evaluation results.
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OfflineEvaluationResponse'
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/controller/poll:
+ post:
+ tags:
+ - Controller
+ summary: Controller poll heartbeat
+ description: Heartbeat and state synchronization endpoint for OpenLIT controllers.
+ security:
+ - ApiKeyAuth: []
+ responses:
+ '200':
+ description: Acknowledged.
+
+components:
+ securitySchemes:
+ CookieAuth:
+ type: apiKey
+ in: cookie
+ name: next-auth.session-token
+ description: Standard NextAuth browser session token cookie.
+ ApiKeyAuth:
+ type: http
+ scheme: bearer
+ bearerFormat: OPENLIT_API_KEY
+ description: Bearer token format (`Authorization: Bearer openlit-...`).
+
+ schemas:
+ TimeLimit:
+ type: object
+ required:
+ - start
+ - end
+ - type
+ properties:
+ start:
+ type: string
+ format: date-time
+ example: '2026-07-01T00:00:00.000Z'
+ end:
+ type: string
+ format: date-time
+ example: '2026-07-02T00:00:00.000Z'
+ type:
+ type: string
+ enum: [24H, 7D, 1M, 3M, CUSTOM]
+ example: 24H
+
+ MetricParams:
+ type: object
+ required:
+ - timeLimit
+ properties:
+ timeLimit:
+ $ref: '#/components/schemas/TimeLimit'
+ limit:
+ type: integer
+ default: 25
+ example: 50
+ offset:
+ type: integer
+ default: 0
+ example: 0
+ selectedConfig:
+ type: object
+ description: "Filters telemetry records by matching key-value criteria."
+ properties:
+ models:
+ type: array
+ description: "Filter telemetry by model names (e.g. ['gpt-4o', 'claude-3-5-sonnet'])."
+ items:
+ type: string
+ example: ["gpt-4o", "claude-3-5-sonnet"]
+ providers:
+ type: array
+ description: "Filter telemetry by provider names (e.g. ['openai', 'anthropic', 'cohere', 'ollama'])."
+ items:
+ type: string
+ example: ["openai", "anthropic"]
+ serviceNames:
+ type: array
+ description: "Filter telemetry by service names (e.g. ['web-app', 'backend-api'])."
+ items:
+ type: string
+ example: ["web-app"]
+ environments:
+ type: array
+ description: "Filter telemetry by deployment environment names (e.g. ['production', 'staging'])."
+ items:
+ type: string
+ example: ["production"]
+ severities:
+ type: array
+ description: "Filter logs by severity levels (e.g. ['INFO', 'ERROR', 'WARN'])."
+ items:
+ type: string
+ example: ["ERROR", "WARN"]
+ sorting:
+ type: object
+ description: "Defines the sorting column and order for returned records."
+ properties:
+ type:
+ type: string
+ description: "Field name to sort by (e.g. Timestamp, cost, duration, prompt_tokens, completion_tokens, total_tokens)."
+ example: Timestamp
+ direction:
+ type: string
+ description: "Sort order direction."
+ enum: [asc, desc]
+ example: desc
+
+ PromptInput:
+ type: object
+ required:
+ - name
+ - prompt
+ properties:
+ name:
+ type: string
+ prompt:
+ type: string
+ version:
+ type: string
+ status:
+ type: string
+ tags:
+ type: array
+ items:
+ type: string
+ metaProperties:
+ type: object
+
+ ApiKey:
+ type: object
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ apiKey:
+ type: string
+ createdAt:
+ type: string
+ format: date-time
+
+ OfflineEvaluationInput:
+ type: object
+ required:
+ - prompt
+ - response
+ properties:
+ prompt:
+ type: string
+ description: "The prompt text to evaluate."
+ example: "I need to reset my password, my email is [email protected]"
+ response:
+ type: string
+ description: "The LLM generated response to evaluate."
+ example: "I can help with that. Please verify your identity."
+ contexts:
+ type: array
+ description: "Retrieved context document texts used by the LLM."
+ items:
+ type: string
+ example: ["User password reset procedure document."]
+ eval_types:
+ type: array
+ description: "Scorers to execute. Can be toxicity, hallucination, bias, pii."
+ items:
+ type: string
+ example: ["toxicity", "pii"]
+ threshold_score:
+ type: number
+ default: 0.5
+ description: "Minimum score required to trigger validation flags."
+ example: 0.5
+ store_results:
+ type: boolean
+ default: true
+ description: "Persist the evaluation metrics run results to ClickHouse."
+ example: true
+ run_id:
+ type: string
+ description: "Optional external execution or batch tracking ID."
+ example: "run-998877"
+ metadata:
+ type: object
+ description: "Custom metadata key-value properties dictionary (max 20 entries)."
+ additionalProperties:
+ type: string
+ example: { "environment": "production", "version": "1.0" }
+ attributes:
+ type: object
+ description: "Custom payload attributes dictionary."
+
+ OfflineEvaluationResponse:
+ type: object
+ properties:
+ success:
+ type: boolean
+ example: true
+ evaluations:
+ type: array
+ items:
+ type: object
+ properties:
+ type:
+ type: string
+ example: toxicity
+ score:
+ type: number
+ example: 0.1
+ verdict:
+ type: string
+ example: passed
+ classification:
+ type: string
+ example: safe
+ explanation:
+ type: string
+ example: "No toxic language detected in the input."
+ context_applied:
+ type: boolean
+ example: false
+ metadata:
+ type: object
+
+ responses:
+ UnauthorizedError:
+ description: Authentication failed or credentials missing.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ error:
+ type: string
+ example: Unauthorized
+ BadRequestError:
+ description: Invalid request parameters or body.
+ content:
+ application/json:
+ schema:
+ type: string
+ example: Start date or End date missing!
diff --git a/src/client/public/openapi.yaml b/src/client/public/openapi.yaml
new file mode 100644
index 00000000..8560915c
--- /dev/null
+++ b/src/client/public/openapi.yaml
@@ -0,0 +1,1015 @@
+openapi: 3.0.3
+info:
+ title: OpenLIT Client API
+ description: |
+ API specification for the OpenLIT client application.
+ This includes telemetry retrieval APIs (authorized via browser session or `OPENLIT_API_KEY`), prompt hub management, rule engine evaluation, and other controller/platform APIs.
+ version: 1.23.0
+servers:
+ - url: http://localhost:3000
+ description: Local development server
+tags:
+ - name: Telemetry
+ description: Telemetry retrieval and observability querying APIs
+ - name: Prompt Hub
+ description: Manage and compile prompt templates
+ - name: Secret Vault
+ description: Manage credentials and secrets inside Vault
+ - name: Rule Engine
+ description: Evaluate guardrails and redaction rules
+ - name: Controller
+ description: Sync state and heartbeat polling for OpenLIT controllers
+ - name: Evaluation Engine
+ description: Offline LLM evaluations
+ - name: API Keys
+ description: Manage browser/SDK access keys
+
+paths:
+ /api/telemetry/logs:
+ post:
+ tags:
+ - Telemetry
+ summary: Query logs
+ description: Retrieve a paginated list of telemetry logs matching the provided filters. Can be authenticated using session cookies or an API key.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/MetricParams'
+ responses:
+ '200':
+ description: A list of logs and total count.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ records:
+ type: array
+ items:
+ type: object
+ total:
+ type: integer
+ example: 150
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/telemetry/logs/{id}:
+ get:
+ tags:
+ - Telemetry
+ summary: Get log detail by row ID
+ description: Retrieve detail of a specific log entry by its hash/row ID.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ parameters:
+ - name: id
+ in: path
+ required: true
+ description: The cityHash64 row ID of the log.
+ schema:
+ type: string
+ responses:
+ '200':
+ description: Log details retrieved successfully.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ record:
+ type: object
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
+ /api/telemetry/logs/attribute-keys:
+ post:
+ tags:
+ - Telemetry
+ summary: Query log attribute keys
+ description: Retrieve unique attribute keys for log attributes, resource attributes, and scope attributes.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ timeLimit:
+ $ref: '#/components/schemas/TimeLimit'
+ responses:
+ '200':
+ description: Unique attribute keys.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ logAttributeKeys:
+ type: array
+ items:
+ type: string
+ resourceAttributeKeys:
+ type: array
+ items:
+ type: string
+ scopeAttributeKeys:
+ type: array
+ items:
+ type: string
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/telemetry/logs/config:
+ post:
+ tags:
+ - Telemetry
+ summary: Query logs config options
+ description: Retrieve configuration metadata such as available service names, severities, and total log rows.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ timeLimit:
+ $ref: '#/components/schemas/TimeLimit'
+ responses:
+ '200':
+ description: Configuration metadata.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ services:
+ type: array
+ items:
+ type: string
+ severities:
+ type: array
+ items:
+ type: string
+ totalRows:
+ type: integer
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
+ /api/telemetry/metrics:
+ post:
+ tags:
+ - Telemetry
+ summary: Query metrics list
+ description: Retrieve a list of aggregated metrics matching the filters.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/MetricParams'
+ responses:
+ '200':
+ description: A list of metrics.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ records:
+ type: array
+ items:
+ type: object
+ total:
+ type: integer
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/telemetry/metrics/{name}:
+ post:
+ tags:
+ - Telemetry
+ summary: Get metric detail
+ description: Retrieve time-series graph points and detail records for a specific metric name.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ parameters:
+ - name: name
+ in: path
+ required: true
+ description: The name of the metric.
+ schema:
+ type: string
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ timeLimit:
+ $ref: '#/components/schemas/TimeLimit'
+ metricType:
+ type: string
+ serviceName:
+ type: string
+ selectedConfig:
+ type: object
+ responses:
+ '200':
+ description: Metric graph and data points.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ series:
+ type: array
+ items:
+ type: object
+ points:
+ type: array
+ items:
+ type: object
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
+ /api/telemetry/metrics/attribute-keys:
+ post:
+ tags:
+ - Telemetry
+ summary: Query metric attribute keys
+ description: Retrieve unique attribute keys for metrics.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ timeLimit:
+ $ref: '#/components/schemas/TimeLimit'
+ responses:
+ '200':
+ description: Metric attributes keys.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ metricAttributeKeys:
+ type: array
+ items:
+ type: string
+ resourceAttributeKeys:
+ type: array
+ items:
+ type: string
+ scopeAttributeKeys:
+ type: array
+ items:
+ type: string
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
+ /api/telemetry/metrics/config:
+ post:
+ tags:
+ - Telemetry
+ summary: Query metrics configuration metadata
+ description: Retrieve list of available services, metric names, types, and counts.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ timeLimit:
+ $ref: '#/components/schemas/TimeLimit'
+ responses:
+ '200':
+ description: Config metadata.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ services:
+ type: array
+ items:
+ type: string
+ metricNames:
+ type: array
+ items:
+ type: string
+ metricTypes:
+ type: array
+ items:
+ type: string
+ totalRows:
+ type: integer
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
+ /api/telemetry/summary/{signal}:
+ post:
+ tags:
+ - Telemetry
+ summary: Query signal summary data
+ description: Retrieve aggregated time-series summary bucketed counts and metrics (e.g. costs, latency, or token counts) for traces, exceptions, logs, or metrics.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ parameters:
+ - name: signal
+ in: path
+ required: true
+ description: The telemetry signal type.
+ schema:
+ type: string
+ enum: [traces, exceptions, logs, metrics]
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ timeLimit:
+ $ref: '#/components/schemas/TimeLimit'
+ selectedConfig:
+ type: object
+ responses:
+ '200':
+ description: Aggregated summary stats bucketed by time interval.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ bucket:
+ type: string
+ example: hour
+ buckets:
+ type: array
+ items:
+ type: object
+ total:
+ type: integer
+ peak:
+ type: number
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/telemetry/trace:
+ post:
+ tags:
+ - Telemetry
+ summary: Query traces list
+ description: Retrieve a paginated list of trace spans matching the provided filters. Can be authenticated using session cookies or an API key.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/MetricParams'
+ responses:
+ '200':
+ description: A list of traces and total count.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ records:
+ type: array
+ items:
+ type: object
+ total:
+ type: integer
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/telemetry/exception:
+ post:
+ tags:
+ - Telemetry
+ summary: Query exceptions list
+ description: Retrieve a paginated list of exceptions matching the provided filters. Can be authenticated using session cookies or an API key.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/MetricParams'
+ responses:
+ '200':
+ description: A list of exceptions and total count.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ records:
+ type: array
+ items:
+ type: object
+ total:
+ type: integer
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/telemetry/trace/span/{id}:
+ get:
+ tags:
+ - Telemetry
+ summary: Get span detail by ID
+ description: Retrieve details of a specific trace span by its ID (along with optional evaluation summary data).
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ parameters:
+ - name: id
+ in: path
+ required: true
+ description: The ID of the span.
+ schema:
+ type: string
+ responses:
+ '200':
+ description: Span details retrieved successfully.
+ content:
+ application/json:
+ schema:
+ type: object
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/telemetry/trace/trace/{id}:
+ get:
+ tags:
+ - Telemetry
+ summary: Get trace detail by Trace ID
+ description: Retrieve details of a trace (such as its root span or transaction info) using the Trace ID.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ parameters:
+ - name: id
+ in: path
+ required: true
+ description: The ID of the trace (Trace ID).
+ schema:
+ type: string
+ responses:
+ '200':
+ description: Trace details retrieved successfully.
+ content:
+ application/json:
+ schema:
+ type: object
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/telemetry/trace/span/{id}/heirarchy:
+ get:
+ tags:
+ - Telemetry
+ summary: Get trace span hierarchy tree
+ description: Retrieve the tree hierarchy representation of all related spans (e.g. parents, subagents, child operations) associated with a trace span.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ parameters:
+ - name: id
+ in: path
+ required: true
+ description: The ID of the root/anchor span.
+ schema:
+ type: string
+ responses:
+ '200':
+ description: Span hierarchy tree.
+ content:
+ application/json:
+ schema:
+ type: object
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/api-key:
+ get:
+ tags:
+ - API Keys
+ summary: List all API Keys
+ description: Retrieve all API keys associated with the user's active database configuration.
+ security:
+ - CookieAuth: []
+ responses:
+ '200':
+ description: A list of API Keys.
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/ApiKey'
+ post:
+ tags:
+ - API Keys
+ summary: Generate an API Key
+ description: Create a new API key prefixed with `openlit-` linked to the active database configuration.
+ security:
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required:
+ - name
+ properties:
+ name:
+ type: string
+ example: my-sdk-key
+ responses:
+ '200':
+ description: API key created successfully.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ apiKey:
+ type: string
+ example: openlit-uHpx834Jsa...
+ databaseConfigId:
+ type: string
+ example: db-config-id
+ '400':
+ description: Bad Request.
+
+ /api/api-key/{id}:
+ delete:
+ tags:
+ - API Keys
+ summary: Delete an API Key
+ description: Mark an API key as deleted.
+ security:
+ - CookieAuth: []
+ parameters:
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: API key deleted successfully.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ success:
+ type: boolean
+ example: true
+ '400':
+ description: Bad request or key not found.
+
+ /api/db-config:
+ get:
+ summary: List database configurations
+ description: Retrieve database configurations the current user has access to.
+ security:
+ - CookieAuth: []
+ responses:
+ '200':
+ description: Database configurations list.
+ post:
+ summary: Save database configuration
+ description: Create or update a ClickHouse database configuration connection parameters.
+ security:
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required:
+ - host
+ - port
+ - username
+ - password
+ properties:
+ host:
+ type: string
+ port:
+ type: integer
+ username:
+ type: string
+ password:
+ type: string
+ responses:
+ '200':
+ description: Saved successfully.
+
+ /api/prompt:
+ post:
+ tags:
+ - Prompt Hub
+ summary: Create a prompt
+ description: Create a new prompt entry or version.
+ security:
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PromptInput'
+ responses:
+ '200':
+ description: Prompt created successfully.
+
+ /api/prompt/get:
+ post:
+ tags:
+ - Prompt Hub
+ summary: Retrieve a prompt by name or ID
+ description: Retrieve details of a prompt version.
+ security:
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ name:
+ type: string
+ responses:
+ '200':
+ description: Prompt details.
+
+ /api/prompt/get-compiled:
+ get:
+ tags:
+ - Prompt Hub
+ summary: Fetch compiled prompt
+ description: Fetch and compile a prompt by name with dynamic variable interpolation. Does not require browser session cookie if authenticated by API key.
+ security:
+ - ApiKeyAuth: []
+ parameters:
+ - name: name
+ in: query
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: Compiled prompt text.
+
+ /api/vault/get-secrets:
+ get:
+ tags:
+ - Secret Vault
+ summary: Fetch secrets from Vault
+ description: Safely retrieve API keys or credentials stored in the OpenLIT Vault.
+ security:
+ - ApiKeyAuth: []
+ responses:
+ '200':
+ description: Key-value secrets retrieved.
+
+ /api/rule-engine/evaluate:
+ post:
+ tags:
+ - Rule Engine
+ summary: Evaluate rule engine config
+ description: Evaluate rules (e.g. redaction, prompts, guardrails) against inputs.
+ security:
+ - ApiKeyAuth: []
+ responses:
+ '200':
+ description: Rules evaluated.
+
+ /api/evaluation/offline:
+ post:
+ tags:
+ - Evaluation Engine
+ summary: Run offline LLM evaluation
+ description: Run LLM evaluation (e.g. toxicity, hallucination, bias, pii) on user-provided prompt and response. Can be authenticated using session cookies or an API key.
+ security:
+ - ApiKeyAuth: []
+ - CookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OfflineEvaluationInput'
+ responses:
+ '200':
+ description: Evaluation results.
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OfflineEvaluationResponse'
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+
+ /api/controller/poll:
+ post:
+ tags:
+ - Controller
+ summary: Controller poll heartbeat
+ description: Heartbeat and state synchronization endpoint for OpenLIT controllers.
+ security:
+ - ApiKeyAuth: []
+ responses:
+ '200':
+ description: Acknowledged.
+
+components:
+ securitySchemes:
+ CookieAuth:
+ type: apiKey
+ in: cookie
+ name: next-auth.session-token
+ description: Standard NextAuth browser session token cookie.
+ ApiKeyAuth:
+ type: http
+ scheme: bearer
+ bearerFormat: OPENLIT_API_KEY
+ description: Bearer token format (`Authorization: Bearer openlit-...`).
+
+ schemas:
+ TimeLimit:
+ type: object
+ required:
+ - start
+ - end
+ - type
+ properties:
+ start:
+ type: string
+ format: date-time
+ example: '2026-07-01T00:00:00.000Z'
+ end:
+ type: string
+ format: date-time
+ example: '2026-07-02T00:00:00.000Z'
+ type:
+ type: string
+ enum: [24H, 7D, 1M, 3M, CUSTOM]
+ example: 24H
+
+ MetricParams:
+ type: object
+ required:
+ - timeLimit
+ properties:
+ timeLimit:
+ $ref: '#/components/schemas/TimeLimit'
+ limit:
+ type: integer
+ default: 25
+ example: 50
+ offset:
+ type: integer
+ default: 0
+ example: 0
+ selectedConfig:
+ type: object
+ description: "Filters telemetry records by matching key-value criteria."
+ properties:
+ models:
+ type: array
+ description: "Filter telemetry by model names (e.g. ['gpt-4o', 'claude-3-5-sonnet'])."
+ items:
+ type: string
+ example: ["gpt-4o", "claude-3-5-sonnet"]
+ providers:
+ type: array
+ description: "Filter telemetry by provider names (e.g. ['openai', 'anthropic', 'cohere', 'ollama'])."
+ items:
+ type: string
+ example: ["openai", "anthropic"]
+ serviceNames:
+ type: array
+ description: "Filter telemetry by service names (e.g. ['web-app', 'backend-api'])."
+ items:
+ type: string
+ example: ["web-app"]
+ environments:
+ type: array
+ description: "Filter telemetry by deployment environment names (e.g. ['production', 'staging'])."
+ items:
+ type: string
+ example: ["production"]
+ severities:
+ type: array
+ description: "Filter logs by severity levels (e.g. ['INFO', 'ERROR', 'WARN'])."
+ items:
+ type: string
+ example: ["ERROR", "WARN"]
+ sorting:
+ type: object
+ description: "Defines the sorting column and order for returned records."
+ properties:
+ type:
+ type: string
+ description: "Field name to sort by (e.g. Timestamp, cost, duration, prompt_tokens, completion_tokens, total_tokens)."
+ example: Timestamp
+ direction:
+ type: string
+ description: "Sort order direction."
+ enum: [asc, desc]
+ example: desc
+
+ PromptInput:
+ type: object
+ required:
+ - name
+ - prompt
+ properties:
+ name:
+ type: string
+ prompt:
+ type: string
+ version:
+ type: string
+ status:
+ type: string
+ tags:
+ type: array
+ items:
+ type: string
+ metaProperties:
+ type: object
+
+ ApiKey:
+ type: object
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ apiKey:
+ type: string
+ createdAt:
+ type: string
+ format: date-time
+
+ OfflineEvaluationInput:
+ type: object
+ required:
+ - prompt
+ - response
+ properties:
+ prompt:
+ type: string
+ description: "The prompt text to evaluate."
+ example: "I need to reset my password, my email is [email protected]"
+ response:
+ type: string
+ description: "The LLM generated response to evaluate."
+ example: "I can help with that. Please verify your identity."
+ contexts:
+ type: array
+ description: "Retrieved context document texts used by the LLM."
+ items:
+ type: string
+ example: ["User password reset procedure document."]
+ eval_types:
+ type: array
+ description: "Scorers to execute. Can be toxicity, hallucination, bias, pii."
+ items:
+ type: string
+ example: ["toxicity", "pii"]
+ threshold_score:
+ type: number
+ default: 0.5
+ description: "Minimum score required to trigger validation flags."
+ example: 0.5
+ store_results:
+ type: boolean
+ default: true
+ description: "Persist the evaluation metrics run results to ClickHouse."
+ example: true
+ run_id:
+ type: string
+ description: "Optional external execution or batch tracking ID."
+ example: "run-998877"
+ metadata:
+ type: object
+ description: "Custom metadata key-value properties dictionary (max 20 entries)."
+ additionalProperties:
+ type: string
+ example: { "environment": "production", "version": "1.0" }
+ attributes:
+ type: object
+ description: "Custom payload attributes dictionary."
+
+ OfflineEvaluationResponse:
+ type: object
+ properties:
+ success:
+ type: boolean
+ example: true
+ evaluations:
+ type: array
+ items:
+ type: object
+ properties:
+ type:
+ type: string
+ example: toxicity
+ score:
+ type: number
+ example: 0.1
+ verdict:
+ type: string
+ example: passed
+ classification:
+ type: string
+ example: safe
+ explanation:
+ type: string
+ example: "No toxic language detected in the input."
+ context_applied:
+ type: boolean
+ example: false
+ metadata:
+ type: object
+
+ responses:
+ UnauthorizedError:
+ description: Authentication failed or credentials missing.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ error:
+ type: string
+ example: Unauthorized
+ BadRequestError:
+ description: Invalid request parameters or body.
+ content:
+ application/json:
+ schema:
+ type: string
+ example: Start date or End date missing!
diff --git a/src/client/src/__tests__/helpers/client/observability-registry.test.ts b/src/client/src/__tests__/helpers/client/observability-registry.test.ts
index 0489d00c..53cc7e02 100644
--- a/src/client/src/__tests__/helpers/client/observability-registry.test.ts
+++ b/src/client/src/__tests__/helpers/client/observability-registry.test.ts
@@ -14,7 +14,7 @@ describe("observability signal registry", () => {
const traces = getSignalConfig("traces");
expect(traces.key).toBe("traces");
- expect(traces.listUrl).toBe("/api/metrics/request");
+ expect(traces.listUrl).toBe("/api/telemetry/trace");
expect(traces.getRowId({ spanId: "span-1" })).toBe("span-1");
expect(traces.getDetailHref({ spanId: "span-1" }, "/agents/a?tab=monitoring")).toBe(
"/telemetry/traces/span-1?from=%2Fagents%2Fa%3Ftab%3Dmonitoring"
diff --git a/src/client/src/app/(playground)/openapi-spec/page.tsx b/src/client/src/app/(playground)/openapi-spec/page.tsx
new file mode 100644
index 00000000..b1974114
--- /dev/null
+++ b/src/client/src/app/(playground)/openapi-spec/page.tsx
@@ -0,0 +1,26 @@
+"use client";
+import ApiReference from "@/components/(playground)/api-keys/api-reference";
+import FeaturePageHeader from "@/components/(playground)/feature-page-header";
+import { ApiKey } from "@/types/api-key";
+import { BookText } from "lucide-react";
+import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
+
+export default function OpenApiPage() {
+ const { data } = useFetchWrapper<ApiKey[]>();
+
+ const userApiKey = data && data.length > 0 ? data[0].apiKey : undefined;
+
+ return (
+ <div className="flex flex-col grow w-full h-full overflow-hidden">
+ <FeaturePageHeader
+ eyebrow="Documentation"
+ title="Open API Spec"
+ icon={<BookText className="h-4 w-4" />}
+ tone="border-primary/20 bg-primary/10 text-primary dark:border-primary/30 dark:bg-primary/15"
+ />
+ <div className="flex-1 w-full p-4 overflow-hidden grow overflow-hidden">
+ <ApiReference userApiKey={userApiKey} />
+ </div>
+ </div>
+ );
+}
diff --git a/src/client/src/app/(playground)/settings/api-keys/page.tsx b/src/client/src/app/(playground)/settings/api-keys/page.tsx
index 9f568e5a..a6aeb91c 100644
--- a/src/client/src/app/(playground)/settings/api-keys/page.tsx
+++ b/src/client/src/app/(playground)/settings/api-keys/page.tsx
@@ -13,8 +13,7 @@ export default function APIKeys() {
return (
<div className="flex w-full flex-1 overflow-hidden">
- <div className="flex flex-col grow w-full rounded overflow-auto text-sm text-stone-900 dark:text-stone-300 gap-4">
-
+ <div className="flex flex-col grow w-full rounded overflow-auto text-stone-900 dark:text-stone-300 gap-4">
<ManageKeys />
</div>
</div>
diff --git a/src/client/src/app/api/auth/verify-key/route.ts b/src/client/src/app/api/auth/verify-key/route.ts
new file mode 100644
index 00000000..56dfae29
--- /dev/null
+++ b/src/client/src/app/api/auth/verify-key/route.ts
@@ -0,0 +1,34 @@
+import { NextRequest, NextResponse } from "next/server";
+import prisma from "@/lib/prisma";
+
+export async function GET(request: NextRequest) {
+ const authHeader = request.headers.get("Authorization") || "";
+ if (!authHeader.startsWith("Bearer ")) {
+ return NextResponse.json({ valid: false }, { status: 401 });
+ }
+
+ const apiKey = authHeader.replace(/^Bearer /, "").trim();
+ if (!apiKey) {
+ return NextResponse.json({ valid: false }, { status: 401 });
+ }
+
+ try {
+ const apiInfo = await prisma.aPIKeys.findFirst({
+ where: {
+ apiKey,
+ isDeleted: false,
+ },
+ });
+
+ if (apiInfo?.databaseConfigId) {
+ return NextResponse.json({
+ valid: true,
+ databaseConfigId: apiInfo.databaseConfigId,
+ });
+ }
+ } catch (e) {
+ console.error("Auth verification route error:", e);
+ }
+
+ return NextResponse.json({ valid: false }, { status: 401 });
+}
diff --git a/src/client/src/app/api/controller/poll/route.ts b/src/client/src/app/api/controller/poll/route.ts
index 08614c53..49c49bea 100644
--- a/src/client/src/app/api/controller/poll/route.ts
+++ b/src/client/src/app/api/controller/poll/route.ts
@@ -51,6 +51,11 @@ function sanitizeLogValue(val: unknown): string {
async function authenticatePollRequest(
request: Request
): Promise<{ dbId: string } | Response> {
+ const dbConfigIdHeader = request.headers.get("x-database-config-id");
+ if (dbConfigIdHeader) {
+ return { dbId: dbConfigIdHeader };
+ }
+
const authHeader = request.headers.get("Authorization") || "";
if (authHeader.startsWith("Bearer ")) {
diff --git a/src/client/src/app/api/metrics/exception/route.ts b/src/client/src/app/api/metrics/exception/route.ts
deleted file mode 100644
index 7ea101bd..00000000
--- a/src/client/src/app/api/metrics/exception/route.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { MetricParams, TimeLimit } from "@/lib/platform/common";
-import {
- validateMetricsRequest,
- validateMetricsRequestType,
-} from "@/helpers/server/platform";
-import { getRequests } from "@/lib/platform/request";
-
-export async function POST(request: Request) {
- const formData = await request.json();
- const timeLimit = formData.timeLimit as TimeLimit;
- const limit = formData.limit || 10;
- const offset = formData.offset || 0;
- const selectedConfig = formData.selectedConfig || {};
- const sorting = formData.sorting || {};
-
- const params: MetricParams = {
- timeLimit,
- limit,
- offset,
- selectedConfig,
- sorting,
- statusCode: ["STATUS_CODE_ERROR", "Error"],
- };
-
- const validationParam = validateMetricsRequest(
- params,
- validateMetricsRequestType.GET_ALL
- );
-
- if (!validationParam.success)
- return Response.json(validationParam.err, {
- status: 400,
- });
-
- const res: any = await getRequests(params);
- return Response.json(res);
-}
diff --git a/src/client/src/app/api/metrics/request/route.ts b/src/client/src/app/api/metrics/request/route.ts
deleted file mode 100644
index de1ff75b..00000000
--- a/src/client/src/app/api/metrics/request/route.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { MetricParams, TimeLimit } from "@/lib/platform/common";
-import { getRequests } from "@/lib/platform/request";
-import {
- validateMetricsRequest,
- validateMetricsRequestType,
-} from "@/helpers/server/platform";
-
-export async function POST(request: Request) {
- const formData = await request.json();
- const timeLimit = formData.timeLimit as TimeLimit;
- const limit = formData.limit || 10;
- const offset = formData.offset || 0;
- const selectedConfig = formData.selectedConfig || {};
- const sorting = formData.sorting || {};
-
- const params: MetricParams = {
- timeLimit,
- limit,
- offset,
- selectedConfig,
- sorting,
- };
-
- const validationParam = validateMetricsRequest(
- params,
- validateMetricsRequestType.GET_ALL
- );
-
- if (!validationParam.success)
- return Response.json(validationParam.err, {
- status: 400,
- });
-
- const res: any = await getRequests(params);
- return Response.json(res);
-}
diff --git a/src/client/src/app/api/metrics/request/span/[id]/heirarchy/route.ts b/src/client/src/app/api/metrics/request/span/[id]/heirarchy/route.ts
deleted file mode 100644
index 9658aaad..00000000
--- a/src/client/src/app/api/metrics/request/span/[id]/heirarchy/route.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { getHeirarchyViaSpanId } from "@/lib/platform/request";
-
-export async function GET(_: Request, context: any) {
- const { id } = context.params || {};
-
- if (!id) {
- return Response.json("No span id provided", {
- status: 400,
- });
- }
-
- const res: any = await getHeirarchyViaSpanId(id);
- return Response.json(res);
-}
diff --git a/src/client/src/app/api/metrics/request/trace/[id]/route.ts b/src/client/src/app/api/metrics/request/trace/[id]/route.ts
deleted file mode 100644
index 5320b585..00000000
--- a/src/client/src/app/api/metrics/request/trace/[id]/route.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { getRequestViaTraceId } from "@/lib/platform/request";
-
-export async function GET(_: Request, context: any) {
- const { id } = context.params || {};
-
- if (!id)
- return Response.json("No parent span id provided", {
- status: 400,
- });
-
- const res: any = await getRequestViaTraceId(id);
- return Response.json(res);
-}
diff --git a/src/client/src/app/api/prompt/get/route.ts b/src/client/src/app/api/prompt/get/route.ts
index c3dad098..f3a2b049 100644
--- a/src/client/src/app/api/prompt/get/route.ts
+++ b/src/client/src/app/api/prompt/get/route.ts
@@ -1,8 +1,14 @@
import { getPrompts } from "@/lib/platform/prompt";
import { errorResponse } from "@/helpers/server/response";
+import { resolveDbConfigId } from "@/helpers/server/auth";
-export async function POST() {
- const { err, data }: any = await getPrompts();
+export async function POST(request: Request) {
+ const [authErr, databaseConfigId] = await resolveDbConfigId(request);
+ if (authErr) {
+ return Response.json({ err: authErr }, { status: 401 });
+ }
+
+ const { err, data }: any = await getPrompts({ databaseConfigId });
if (err) {
return errorResponse(err);
}
diff --git a/src/client/src/app/api/rule-engine/evaluate/route.ts b/src/client/src/app/api/rule-engine/evaluate/route.ts
index 7e66e507..e07ceb48 100644
--- a/src/client/src/app/api/rule-engine/evaluate/route.ts
+++ b/src/client/src/app/api/rule-engine/evaluate/route.ts
@@ -1,37 +1,16 @@
import { SERVER_EVENTS } from "@/constants/events";
import { EvaluateInput } from "@/types/rule-engine";
import { evaluateRules } from "@/lib/platform/rule-engine/evaluate";
-import { getAPIKeyInfo } from "@/lib/platform/api-keys";
-import { getCurrentUser } from "@/lib/session";
-import getMessage from "@/constants/messages";
import PostHogServer from "@/lib/posthog";
import asaw from "@/utils/asaw";
+import { resolveDbConfigId } from "@/helpers/server/auth";
export async function POST(request: Request) {
const startTimestamp = Date.now();
// --- Authentication ---
- // Prefer Bearer token (external API usage); fall back to session auth.
- const authorizationHeader = request.headers.get("Authorization") || "";
- let databaseConfigId: string | undefined;
-
- if (authorizationHeader.startsWith("Bearer ")) {
- const apiKey = authorizationHeader.replace(/^Bearer /, "").trim();
- if (!apiKey) {
- return Response.json({ err: getMessage().NO_API_KEY }, { status: 401 });
- }
-
- const [keyErr, apiInfo] = await getAPIKeyInfo({ apiKey });
- if (keyErr || !apiInfo?.databaseConfigId) {
- return Response.json({ err: getMessage().NO_API_KEY }, { status: 401 });
- }
-
- databaseConfigId = apiInfo.databaseConfigId;
- } else {
- // Session-based auth (dashboard usage)
- const user = await getCurrentUser();
- if (!user) {
- return Response.json({ err: getMessage().UNAUTHORIZED_USER }, { status: 401 });
- }
+ const [authErr, databaseConfigId] = await resolveDbConfigId(request);
+ if (authErr) {
+ return Response.json({ err: authErr }, { status: 401 });
}
// --- Parse request body ---
diff --git a/src/client/src/app/api/rule-engine/rules/route.ts b/src/client/src/app/api/rule-engine/rules/route.ts
index 5d04e442..89e31e03 100644
--- a/src/client/src/app/api/rule-engine/rules/route.ts
+++ b/src/client/src/app/api/rule-engine/rules/route.ts
@@ -4,9 +4,16 @@ import { getRules, createRule } from "@/lib/platform/rule-engine";
import PostHogServer from "@/lib/posthog";
import asaw from "@/utils/asaw";
-export async function GET() {
+import { resolveDbConfigId } from "@/helpers/server/auth";
+
+export async function GET(request: Request) {
+ const [authErr, databaseConfigId] = await resolveDbConfigId(request);
+ if (authErr) {
+ return Response.json({ err: authErr }, { status: 401 });
+ }
+
const startTimestamp = Date.now();
- const { err, data }: any = await getRules();
+ const { err, data }: any = await getRules(databaseConfigId);
if (err) {
PostHogServer.fireEvent({
event: SERVER_EVENTS.RULE_LIST_FAILURE,
diff --git a/src/client/src/app/api/telemetry/exception/route.ts b/src/client/src/app/api/telemetry/exception/route.ts
new file mode 100644
index 00000000..c0c1f53d
--- /dev/null
+++ b/src/client/src/app/api/telemetry/exception/route.ts
@@ -0,0 +1,59 @@
+import { MetricParams, TimeLimit } from "@/lib/platform/common";
+import {
+ validateMetricsRequest,
+ validateMetricsRequestType,
+} from "@/helpers/server/platform";
+import { getRequests, getRequestsConfig } from "@/lib/platform/request";
+import { resolveDbConfigId } from "@/helpers/server/auth";
+
+export async function POST(request: Request) {
+ try {
+ const [authErr, databaseConfigId] = await resolveDbConfigId(request);
+ if (authErr) {
+ return Response.json({ err: authErr }, { status: 401 });
+ }
+
+ const formData = await request.json();
+ const timeLimit = formData.timeLimit as TimeLimit;
+ const limit = formData.limit || 10;
+ const offset = formData.offset || 0;
+ const selectedConfig = formData.selectedConfig || {};
+ const sorting = formData.sorting || {};
+
+ const params: MetricParams = {
+ timeLimit,
+ limit,
+ offset,
+ selectedConfig,
+ sorting,
+ statusCode: ["STATUS_CODE_ERROR", "Error"],
+ databaseConfigId,
+ };
+
+ const validationParam = validateMetricsRequest(
+ params,
+ validateMetricsRequestType.GET_ALL
+ );
+
+ if (!validationParam.success)
+ return Response.json(validationParam.err, {
+ status: 400,
+ });
+
+ const res: any = await getRequests(params);
+
+ const { searchParams } = new URL(request.url);
+ const includeFilters = (searchParams.get("includeFilters") === "true") || (formData.includeFilters === true);
+
+ if (includeFilters && !res.err) {
+ const configRes = await getRequestsConfig(params);
+ res.pagination = { limit, offset, total: res.total || 0 };
+ res.filters = (configRes.data as any)?.[0] || {};
+ }
+
+ return Response.json(res);
+ } catch (error: any) {
+ console.error("Error in telemetry exception route:", error);
+ return Response.json({ err: error.message || "Internal Server Error" }, { status: 500 });
+ }
+}
diff --git a/src/client/src/app/api/telemetry/metrics/[name]/route.ts b/src/client/src/app/api/telemetry/metrics/[name]/route.ts
index 1b2968ba..455b935c 100644
--- a/src/client/src/app/api/telemetry/metrics/[name]/route.ts
+++ b/src/client/src/app/api/telemetry/metrics/[name]/route.ts
@@ -1,10 +1,16 @@
import { MetricParams, TimeLimit } from "@/lib/platform/common";
import { getMetricDetail } from "@/lib/platform/observability";
+import { resolveDbConfigId } from "@/helpers/server/auth";
export async function POST(
request: Request,
{ params }: { params: { name: string } }
) {
+ const [authErr, databaseConfigId] = await resolveDbConfigId(request);
+ if (authErr) {
+ return Response.json({ err: authErr }, { status: 401 });
+ }
+
const formData = await request.json();
const metricName = decodeURIComponent(params.name);
const metricType = formData.metricType as string | undefined;
@@ -12,6 +18,7 @@ export async function POST(
const metricParams: MetricParams = {
timeLimit: formData.timeLimit as TimeLimit,
selectedConfig: formData.selectedConfig || {},
+ databaseConfigId,
};
return Response.json(
diff --git a/src/client/src/app/api/telemetry/metrics/attribute-keys/route.ts b/src/client/src/app/api/telemetry/metrics/attribute-keys/route.ts
index 935d2690..116030df 100644
--- a/src/client/src/app/api/telemetry/metrics/attribute-keys/route.ts
+++ b/src/client/src/app/api/telemetry/metrics/attribute-keys/route.ts
@@ -4,11 +4,18 @@ import {
validateMetricsRequest,
validateMetricsRequestType,
} from "@/helpers/server/platform";
+import { resolveDbConfigId } from "@/helpers/server/auth";
export async function POST(request: Request) {
+ const [authErr, databaseConfigId] = await resolveDbConfigId(request);
+ if (authErr) {
+ return Response.json({ err: authErr }, { status: 401 });
+ }
+
const formData = await request.json();
const params: MetricParams = {
timeLimit: formData.timeLimit as TimeLimit,
+ databaseConfigId,
};
const validation = validateMetricsRequest(
params,
diff --git a/src/client/src/app/api/telemetry/metrics/config/route.ts b/src/client/src/app/api/telemetry/metrics/config/route.ts
index 754b0d1a..9f2903b8 100644
--- a/src/client/src/app/api/telemetry/metrics/config/route.ts
+++ b/src/client/src/app/api/telemetry/metrics/config/route.ts
@@ -4,11 +4,18 @@ import {
validateMetricsRequest,
validateMetricsRequestType,
} from "@/helpers/server/platform";
+import { resolveDbConfigId } from "@/helpers/server/auth";
export async function POST(request: Request) {
+ const [authErr, databaseConfigId] = await resolveDbConfigId(request);
+ if (authErr) {
+ return Response.json({ err: authErr }, { status: 401 });
+ }
+
const formData = await request.json();
const params: MetricParams = {
timeLimit: formData.timeLimit as TimeLimit,
+ databaseConfigId,
};
const validation = validateMetricsRequest(
params,
diff --git a/src/client/src/app/api/telemetry/metrics/route.ts b/src/client/src/app/api/telemetry/metrics/route.ts
index 8b4d91dc..05782692 100644
--- a/src/client/src/app/api/telemetry/metrics/route.ts
+++ b/src/client/src/app/api/telemetry/metrics/route.ts
@@ -1,24 +1,50 @@
import { MetricParams, TimeLimit } from "@/lib/platform/common";
-import { getMetrics } from "@/lib/platform/observability";
+import { getMetrics, getMetricsConfig } from "@/lib/platform/observability";
import {
validateMetricsRequest,
validateMetricsRequestType,
} from "@/helpers/server/platform";
+import { resolveDbConfigId } from "@/helpers/server/auth";
export async function POST(request: Request) {
- const formData = await request.json();
- const params: MetricParams = {
- timeLimit: formData.timeLimit as TimeLimit,
- limit: formData.limit || 25,
- offset: formData.offset || 0,
- selectedConfig: formData.selectedConfig || {},
- sorting: formData.sorting || {},
- };
- const validation = validateMetricsRequest(
- params,
- validateMetricsRequestType.GET_ALL
- );
- if (!validation.success) return Response.json(validation.err, { status: 400 });
+ try {
+ const [authErr, databaseConfigId] = await resolveDbConfigId(request);
+ if (authErr) {
+ return Response.json({ err: authErr }, { status: 401 });
+ }
- return Response.json(await getMetrics(params));
+ const formData = await request.json();
+ const limit = formData.limit || 25;
+ const offset = formData.offset || 0;
+ const params: MetricParams = {
+ timeLimit: formData.timeLimit as TimeLimit,
+ limit,
+ offset,
+ selectedConfig: formData.selectedConfig || {},
+ sorting: formData.sorting || {},
+ databaseConfigId,
+ };
+
+ const validation = validateMetricsRequest(
+ params,
+ validateMetricsRequestType.GET_ALL
+ );
+ if (!validation.success) return Response.json(validation.err, { status: 400 });
+
+ const res: any = await getMetrics(params);
+
+ const { searchParams } = new URL(request.url);
+ const includeFilters = (searchParams.get("includeFilters") === "true") || (formData.includeFilters === true);
+
+ if (includeFilters && !res.err) {
+ const configRes = await getMetricsConfig(params);
+ res.pagination = { limit, offset, total: res.total || 0 };
+ res.filters = (configRes.data as any)?.[0] || {};
+ }
+
+ return Response.json(res);
+ } catch (error: any) {
+ console.error("Error in telemetry metrics route:", error);
+ return Response.json({ err: error.message || "Internal Server Error" }, { status: 500 });
+ }
}
diff --git a/src/client/src/app/api/telemetry/summary/[signal]/route.ts b/src/client/src/app/api/telemetry/summary/[signal]/route.ts
index d48eb17c..157dc1a6 100644
--- a/src/client/src/app/api/telemetry/summary/[signal]/route.ts
+++ b/src/client/src/app/api/telemetry/summary/[signal]/route.ts
@@ -4,6 +4,7 @@ import {
validateMetricsRequest,
validateMetricsRequestType,
} from "@/helpers/server/platform";
+import { resolveDbConfigId } from "@/helpers/server/auth";
const VALID_SIGNALS = new Set(["traces", "exceptions", "logs", "metrics"]);
@@ -11,6 +12,11 @@ export async function POST(
request: Request,
{ params }: { params: { signal: string } }
) {
+ const [authErr, databaseConfigId] = await resolveDbConfigId(request);
+ if (authErr) {
+ return Response.json({ err: authErr }, { status: 401 });
+ }
+
if (!VALID_SIGNALS.has(params.signal)) {
return Response.json({ err: "Invalid signal" }, { status: 400 });
}
@@ -19,6 +25,7 @@ export async function POST(
const metricParams: MetricParams = {
timeLimit: formData.timeLimit as TimeLimit,
selectedConfig: formData.selectedConfig || {},
+ databaseConfigId,
};
const validation = validateMetricsRequest(
diff --git a/src/client/src/app/api/telemetry/trace/route.ts b/src/client/src/app/api/telemetry/trace/route.ts
new file mode 100644
index 00000000..417f2a17
--- /dev/null
+++ b/src/client/src/app/api/telemetry/trace/route.ts
@@ -0,0 +1,58 @@
+import { MetricParams, TimeLimit } from "@/lib/platform/common";
+import { getRequests, getRequestsConfig } from "@/lib/platform/request";
+import {
+ validateMetricsRequest,
+ validateMetricsRequestType,
+} from "@/helpers/server/platform";
+import { resolveDbConfigId } from "@/helpers/server/auth";
+
+export async function POST(request: Request) {
+ try {
+ const [authErr, databaseConfigId] = await resolveDbConfigId(request);
+ if (authErr) {
+ return Response.json({ err: authErr }, { status: 401 });
+ }
+
+ const formData = await request.json();
+ const timeLimit = formData.timeLimit as TimeLimit;
+ const limit = formData.limit || 10;
+ const offset = formData.offset || 0;
+ const selectedConfig = formData.selectedConfig || {};
+ const sorting = formData.sorting || {};
+
+ const params: MetricParams = {
+ timeLimit,
+ limit,
+ offset,
+ selectedConfig,
+ sorting,
+ databaseConfigId,
+ };
+
+ const validationParam = validateMetricsRequest(
+ params,
+ validateMetricsRequestType.GET_ALL
+ );
+
+ if (!validationParam.success)
+ return Response.json(validationParam.err, {
+ status: 400,
+ });
+
+ const res: any = await getRequests(params);
+
+ const { searchParams } = new URL(request.url);
+ const includeFilters = (searchParams.get("includeFilters") === "true") || (formData.includeFilters === true);
+
+ if (includeFilters && !res.err) {
+ const configRes = await getRequestsConfig(params);
+ res.pagination = { limit, offset, total: res.total || 0 };
+ res.filters = (configRes.data as any)?.[0] || {};
+ }
+
+ return Response.json(res);
+ } catch (error: any) {
+ console.error("Error in telemetry trace route:", error);
+ return Response.json({ err: error.message || "Internal Server Error" }, { status: 500 });
+ }
+}
diff --git a/src/client/src/app/api/telemetry/trace/span/[id]/heirarchy/route.ts b/src/client/src/app/api/telemetry/trace/span/[id]/heirarchy/route.ts
new file mode 100644
index 00000000..e760488c
--- /dev/null
+++ b/src/client/src/app/api/telemetry/trace/span/[id]/heirarchy/route.ts
@@ -0,0 +1,20 @@
+import { getHeirarchyViaSpanId } from "@/lib/platform/request";
+import { resolveDbConfigId } from "@/helpers/server/auth";
+
+export async function GET(request: Request, context: any) {
+ const [authErr, databaseConfigId] = await resolveDbConfigId(request);
+ if (authErr) {
+ return Response.json({ err: authErr }, { status: 401 });
+ }
+
+ const { id } = context.params || {};
+
+ if (!id) {
+ return Response.json("No span id provided", {
+ status: 400,
+ });
+ }
+
+ const res: any = await getHeirarchyViaSpanId(id, databaseConfigId);
+ return Response.json(res);
+}
diff --git a/src/client/src/app/api/metrics/request/span/[id]/route.ts b/src/client/src/app/api/telemetry/trace/span/[id]/route.ts
similarity index 56%
rename from src/client/src/app/api/metrics/request/span/[id]/route.ts
rename to src/client/src/app/api/telemetry/trace/span/[id]/route.ts
index 99973ade..a63cace0 100644
--- a/src/client/src/app/api/metrics/request/span/[id]/route.ts
+++ b/src/client/src/app/api/telemetry/trace/span/[id]/route.ts
@@ -1,7 +1,13 @@
import { getRequestViaSpanId } from "@/lib/platform/request";
import { getEvaluationSummaryForSpanId } from "@/lib/platform/evaluation";
+import { resolveDbConfigId } from "@/helpers/server/auth";
+
+export async function GET(request: Request, context: any) {
+ const [authErr, databaseConfigId] = await resolveDbConfigId(request);
+ if (authErr) {
+ return Response.json({ err: authErr }, { status: 401 });
+ }
-export async function GET(_: Request, context: any) {
const { id } = context.params || {};
if (!id)
@@ -10,8 +16,8 @@ export async function GET(_: Request, context: any) {
});
const [spanRes, evalSummary] = await Promise.all([
- getRequestViaSpanId(id),
- getEvaluationSummaryForSpanId(id),
+ getRequestViaSpanId(id, databaseConfigId),
+ getEvaluationSummaryForSpanId(id, databaseConfigId),
]);
const res: any = { ...spanRes };
diff --git a/src/client/src/app/api/telemetry/trace/trace/[id]/route.ts b/src/client/src/app/api/telemetry/trace/trace/[id]/route.ts
new file mode 100644
index 00000000..e8433504
--- /dev/null
+++ b/src/client/src/app/api/telemetry/trace/trace/[id]/route.ts
@@ -0,0 +1,19 @@
+import { getRequestViaTraceId } from "@/lib/platform/request";
+import { resolveDbConfigId } from "@/helpers/server/auth";
+
+export async function GET(request: Request, context: any) {
+ const [authErr, databaseConfigId] = await resolveDbConfigId(request);
+ if (authErr) {
+ return Response.json({ err: authErr }, { status: 401 });
+ }
+
+ const { id } = context.params || {};
+
+ if (!id)
+ return Response.json("No parent span id provided", {
+ status: 400,
+ });
+
+ const res: any = await getRequestViaTraceId(id, databaseConfigId);
+ return Response.json(res);
+}
diff --git a/src/client/src/app/api/vault/get/route.ts b/src/client/src/app/api/vault/get/route.ts
index 3b1b4ae4..bd34827a 100644
--- a/src/client/src/app/api/vault/get/route.ts
+++ b/src/client/src/app/api/vault/get/route.ts
@@ -1,13 +1,20 @@
import { SecretGetFilters } from "@/types/vault";
import { getSecrets } from "@/lib/platform/vault";
import { errorResponse } from "@/helpers/server/response";
+import { resolveDbConfigId } from "@/helpers/server/auth";
export async function POST(request: Request) {
+ const [authErr, databaseConfigId] = await resolveDbConfigId(request);
+ if (authErr) {
+ return Response.json({ err: authErr }, { status: 401 });
+ }
+
const formData = await request.json();
const filters: SecretGetFilters = {
key: formData.key,
tags: formData.tags,
+ databaseConfigId,
};
const { err, data }: any = await getSecrets(filters);
diff --git a/src/client/src/components/(playground)/api-keys/api-reference.tsx b/src/client/src/components/(playground)/api-keys/api-reference.tsx
new file mode 100644
index 00000000..5a6265bb
--- /dev/null
+++ b/src/client/src/components/(playground)/api-keys/api-reference.tsx
@@ -0,0 +1,726 @@
+"use client";
+import React, { useState } from "react";
+import { Badge } from "@/components/ui/badge";
+import { toast } from "sonner";
+import { CopyIcon, Terminal, FileText, ChevronRight, Check } from "lucide-react";
+import copy from "copy-to-clipboard";
+import getMessage from "@/constants/messages";
+
+import { ApiEndpoint, API_REFERENCE_ENDPOINTS } from "@/constants/api-reference";
+
+interface ParameterDoc {
+ name: string;
+ type: string;
+ required: boolean;
+ description: string;
+ allowedValues?: string[];
+ example?: string;
+}
+
+interface ApiReferenceProps {
+ userApiKey?: string;
+}
+
+export default function ApiReference({ userApiKey }: ApiReferenceProps) {
+ const activeKey = userApiKey || "YOUR_OPENLIT_API_KEY";
+ const [selectedEndpoint, setSelectedEndpoint] = useState<ApiEndpoint>(API_REFERENCE_ENDPOINTS[0]);
+ const [copiedField, setCopiedField] = useState<string | null>(null);
+ const messages = getMessage();
+
+ const getParameterDocs = (endpointId: string): ParameterDoc[] => {
+ if (
+ endpointId === "query-traces" ||
+ endpointId === "query-exceptions" ||
+ endpointId === "query-logs" ||
+ endpointId === "query-metrics" ||
+ endpointId === "get-metric-detail"
+ ) {
+ const isLog = endpointId === "query-logs";
+ const isMetric = endpointId === "query-metrics" || endpointId === "get-metric-detail";
+ const docs: ParameterDoc[] = [
+ {
+ name: "timeLimit",
+ type: "object",
+ required: true,
+ description: "Specifies the time range window to query telemetry.",
+ },
+ {
+ name: "timeLimit.type",
+ type: "string",
+ required: true,
+ description: "Predefined relative duration or custom time range.",
+ allowedValues: ["24H", "7D", "1M", "3M", "CUSTOM"],
+ example: "24H",
+ },
+ {
+ name: "timeLimit.start",
+ type: "string",
+ required: false,
+ description: "ISO-8601 start timestamp. Required if type is CUSTOM.",
+ example: "2026-07-09T13:08:52.311Z",
+ },
+ {
+ name: "timeLimit.end",
+ type: "string",
+ required: false,
+ description: "ISO-8601 end timestamp. Required if type is CUSTOM.",
+ example: "2026-07-10T13:09:17.114Z",
+ },
+ {
+ name: "limit",
+ type: "number",
+ required: false,
+ description: `Pagination limit. Defaults to ${isLog || isMetric ? 25 : 10}.`,
+ example: "50",
+ },
+ {
+ name: "offset",
+ type: "number",
+ required: false,
+ description: "Pagination offset index. Defaults to 0.",
+ example: "0",
+ },
+ {
+ name: "selectedConfig",
+ type: "object",
+ required: false,
+ description: "Structured filter properties for telemetry queries.",
+ },
+ {
+ name: "selectedConfig.models",
+ type: "string[]",
+ required: false,
+ description: "Filter records by specific AI model names.",
+ example: '["gpt-4o", "claude-3-5-sonnet"]',
+ },
+ {
+ name: "selectedConfig.providers",
+ type: "string[]",
+ required: false,
+ description: "Filter records by specific LLM providers.",
+ example: '["openai", "anthropic"]',
+ },
+ {
+ name: "selectedConfig.serviceNames",
+ type: "string[]",
+ required: false,
+ description: "Filter records by specific client service names.",
+ example: '["web-app"]',
+ },
+ {
+ name: "selectedConfig.environments",
+ type: "string[]",
+ required: false,
+ description: "Filter records by deployment environment.",
+ example: '["production"]',
+ },
+ ];
+
+ if (isLog) {
+ docs.push({
+ name: "selectedConfig.severities",
+ type: "string[]",
+ required: false,
+ description: "Filter logs by severity levels.",
+ allowedValues: ["INFO", "WARN", "ERROR", "DEBUG", "FATAL"],
+ example: '["ERROR", "WARN"]',
+ });
+ }
+
+ if (endpointId !== "get-metric-detail" && endpointId !== "query-metrics") {
+ docs.push(
+ {
+ name: "sorting",
+ type: "object",
+ required: false,
+ description: "Database sorting order rules.",
+ },
+ {
+ name: "sorting.type",
+ type: "string",
+ required: false,
+ description: "Field name to sort by (e.g. Timestamp, cost, duration, prompt_tokens, completion_tokens).",
+ example: "Timestamp",
+ },
+ {
+ name: "sorting.direction",
+ type: "string",
+ required: false,
+ description: "Sorting direction.",
+ allowedValues: ["asc", "desc"],
+ example: "desc",
+ }
+ );
+ }
+
+ docs.push({
+ name: "includeFilters",
+ type: "boolean",
+ required: false,
+ description: "If true, appends the pagination and dynamic filter metadata inline in the response.",
+ example: "true",
+ });
+
+ return docs;
+ }
+
+ if (endpointId === "get-log") {
+ return [
+ {
+ name: "id",
+ type: "string",
+ required: true,
+ description: "Path parameter. Unique hash/row identifier of the log record.",
+ example: "18446744073709551615",
+ },
+ ];
+ }
+
+ if (endpointId === "get-compiled-prompt") {
+ return [
+ {
+ name: "name",
+ type: "string",
+ required: true,
+ description: "Query parameter. Prompt template identifier name.",
+ example: "summarize-prompt",
+ },
+ ];
+ }
+
+ if (endpointId === "get-secrets") {
+ return [
+ {
+ name: "keys",
+ type: "string",
+ required: false,
+ description: "Query parameter. Comma-separated list of keys to fetch from the vault.",
+ example: "OPENAI_API_KEY,ANTHROPIC_API_KEY",
+ },
+ ];
+ }
+
+ if (endpointId === "evaluate-rules") {
+ return [
+ {
+ name: "entity_type",
+ type: "string",
+ required: true,
+ description: "Type of rule engine entity to evaluate.",
+ allowedValues: ["prompt", "span"],
+ example: "prompt",
+ },
+ {
+ name: "fields",
+ type: "object",
+ required: true,
+ description: "Input fields to run redaction, guardrail, or format rules against.",
+ example: "{ \"input_text\": \"...\" }",
+ },
+ ];
+ }
+
+ if (endpointId === "controller-poll") {
+ return [
+ {
+ name: "instance_id",
+ type: "string",
+ required: true,
+ description: "Unique identifier for the polling client agent instance.",
+ example: "client-instance-xyz-123",
+ },
+ {
+ name: "config_hash",
+ type: "string",
+ required: false,
+ description: "MD5 hash of the cached controller config on the client side.",
+ example: "88863aa992efcc3c48bc625d97f26c51",
+ },
+ ];
+ }
+
+ if (endpointId === "evaluation-offline") {
+ return [
+ {
+ name: "prompt",
+ type: "string",
+ required: true,
+ description: "The prompt text to evaluate.",
+ example: "I need to reset my password, my email is [email protected]",
+ },
+ {
+ name: "response",
+ type: "string",
+ required: true,
+ description: "The LLM generated response to evaluate.",
+ example: "I can help with that. Please verify your identity.",
+ },
+ {
+ name: "contexts",
+ type: "string[]",
+ required: false,
+ description: "Retrieved context document texts used by the LLM.",
+ example: '["User password reset procedure document."]',
+ },
+ {
+ name: "eval_types",
+ type: "string[]",
+ required: false,
+ description: "Scorers to execute. Can be toxicity, hallucination, bias, pii.",
+ example: '["toxicity", "pii"]',
+ },
+ {
+ name: "threshold_score",
+ type: "number",
+ required: false,
+ description: "Minimum score required to trigger validation flags. Defaults to 0.5.",
+ example: "0.5",
+ },
+ {
+ name: "store_results",
+ type: "boolean",
+ required: false,
+ description: "Persist the evaluation metrics run results to ClickHouse. Defaults to true.",
+ example: "true",
+ },
+ {
+ name: "run_id",
+ type: "string",
+ required: false,
+ description: "Optional external execution or batch tracking ID.",
+ example: "run-998877",
+ },
+ {
+ name: "metadata",
+ type: "object",
+ required: false,
+ description: "Custom metadata key-value properties dictionary (max 20 entries).",
+ },
+ {
+ name: "attributes",
+ type: "object",
+ required: false,
+ description: "Custom payload attributes dictionary.",
+ },
+ ];
+ }
+
+ if (endpointId === "create-prompt") {
+ return [
+ {
+ name: "name",
+ type: "string",
+ required: true,
+ description: "Unique prompt identification name.",
+ example: "rag-generation-prompt",
+ },
+ {
+ name: "prompt",
+ type: "string",
+ required: true,
+ description: "Prompt template string with support for variable placeholders.",
+ example: "Answer the query: {{query}} using context: {{context}}",
+ },
+ {
+ name: "version",
+ type: "string",
+ required: false,
+ description: "Optional semantic version for this prompt release.",
+ example: "1.0.0",
+ },
+ {
+ name: "status",
+ type: "string",
+ required: false,
+ description: "Release status of the prompt.",
+ allowedValues: ["active", "draft", "retired"],
+ example: "active",
+ },
+ {
+ name: "tags",
+ type: "string[]",
+ required: false,
+ description: "Labels to categorize the prompt.",
+ example: '["production", "rag"]',
+ },
+ {
+ name: "metaProperties",
+ type: "object",
+ required: false,
+ description: "Arbitrary key-value metadata properties dict.",
+ },
+ ];
+ }
+
+ if (endpointId === "get-prompt") {
+ return [
+ {
+ name: "name",
+ type: "string",
+ required: true,
+ description: "Prompt identifier name to retrieve detail configurations for.",
+ example: "summarize-prompt",
+ },
+ ];
+ }
+
+ if (endpointId === "upsert-secret") {
+ return [
+ {
+ name: "key",
+ type: "string",
+ required: true,
+ description: "Secret key name stored in the vault.",
+ example: "OPENAI_API_KEY",
+ },
+ {
+ name: "value",
+ type: "string",
+ required: true,
+ description: "Unencrypted credentials value that will be encrypted on write.",
+ example: "sk-proj-...",
+ },
+ {
+ name: "tags",
+ type: "string[]",
+ required: false,
+ description: "Secret classification labels.",
+ example: '["production"]',
+ },
+ ];
+ }
+
+ if (
+ endpointId === "get-span-detail" ||
+ endpointId === "get-trace-detail" ||
+ endpointId === "get-span-hierarchy"
+ ) {
+ return [
+ {
+ name: "id",
+ type: "string",
+ required: true,
+ description: "Path parameter. Span ID, Trace ID, or Anchor Span ID to fetch.",
+ example: "557a2bd43ff129ad",
+ },
+ ];
+ }
+
+ return [];
+ };
+
+ const getEndpointGroup = (endpoint: ApiEndpoint): string => {
+ const path = endpoint.path;
+ if (path.startsWith("/api/telemetry") || path.startsWith("/api/metrics")) {
+ return "Telemetry";
+ }
+ if (path.startsWith("/api/prompt")) {
+ return "Prompt Hub";
+ }
+ if (path.startsWith("/api/vault")) {
+ return "Secret Vault";
+ }
+ if (path.startsWith("/api/rule-engine")) {
+ return "Rule Engine";
+ }
+ if (path.startsWith("/api/controller")) {
+ return "Controller";
+ }
+ if (path.startsWith("/api/evaluation")) {
+ return "Evaluation Engine";
+ }
+ if (path.startsWith("/api/api-key")) {
+ return "API Keys";
+ }
+ return "Other";
+ };
+
+ const groups = [
+ "Telemetry",
+ "Prompt Hub",
+ "Secret Vault",
+ "Rule Engine",
+ "Controller",
+ "Evaluation Engine",
+ "API Keys"
+ ];
+
+ const [expandedGroups, setExpandedGroups] = useState<Record<string, boolean>>({
+ "Telemetry": true,
+ "Prompt Hub": true,
+ "Secret Vault": true,
+ "Rule Engine": true,
+ "Controller": true,
+ "Evaluation Engine": true,
+ "API Keys": true,
+ });
+
+ const toggleGroup = (group: string) => {
+ setExpandedGroups(prev => ({
+ ...prev,
+ [group]: !prev[group]
+ }));
+ };
+
+ const handleCopy = (text: string, fieldId: string) => {
+ copy(text);
+ setCopiedField(fieldId);
+ toast.success(messages.COPIED_TO_CLIPBOARD);
+ setTimeout(() => setCopiedField(null), 2000);
+ };
+
+ const getMethodColor = (method: string) => {
+ switch (method) {
+ case "GET":
+ return "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20";
+ case "POST":
+ return "bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20";
+ case "DELETE":
+ return "bg-rose-500/10 text-rose-600 dark:text-rose-400 border-rose-500/20";
+ default:
+ return "bg-stone-500/10 text-stone-600 dark:text-stone-400 border-stone-500/20";
+ }
+ };
+
+ return (
+ <div className="flex flex-col border border-stone-200 dark:border-stone-800 rounded-lg overflow-hidden bg-white dark:bg-stone-900 shadow-sm h-full">
+ <div className="flex items-center gap-2 border-b border-stone-200 dark:border-stone-800 bg-stone-50 dark:bg-stone-950 px-4 py-3">
+ <Terminal className="h-4 w-4 text-stone-500 dark:text-stone-400" />
+ <h3 className="font-semibold text-stone-900 dark:text-stone-100">{messages.INTERACTIVE_API_REFERENCE}</h3>
+ <span className="text-xs text-stone-500 dark:text-stone-400 ml-auto">
+ {messages.OPENAPI_SPEC_BEARER_AUTH}
+ </span>
+ </div>
+
+ <div className="flex flex-col lg:flex-row divide-y lg:divide-y-0 lg:divide-x divide-stone-200 dark:divide-stone-800 min-h-[450px] h-full overflow-hidden">
+ {/* Sidebar list */}
+ <div className="w-full lg:w-80 shrink-0 bg-stone-50/50 dark:bg-stone-950/20 py-2 overflow-y-auto h-full">
+ <div className="space-y-2 px-2">
+ {groups.map((group) => {
+ const endpointsInGroup = API_REFERENCE_ENDPOINTS.filter(
+ (ep) => getEndpointGroup(ep) === group
+ );
+ if (endpointsInGroup.length === 0) return null;
+ const isExpanded = expandedGroups[group] ?? true;
+
+ return (
+ <div key={group} className="flex flex-col">
+ <button
+ onClick={() => toggleGroup(group)}
+ className="flex items-center justify-between w-full px-3 py-1.5 text-left text-[11px] font-semibold text-stone-500 dark:text-stone-400 hover:text-stone-800 dark:hover:text-stone-200 transition-colors uppercase tracking-wider"
+ >
+ <span>{group}</span>
+ <ChevronRight
+ className={`h-3 w-3 text-stone-400 dark:text-stone-505 transition-transform ${
+ isExpanded ? "rotate-90" : ""
+ }`}
+ />
+ </button>
+ {isExpanded && (
+ <div className="mt-1 space-y-0.5 pl-2 border-l border-stone-200 dark:border-stone-800 ml-3">
+ {endpointsInGroup.map((endpoint) => (
+ <button
+ key={endpoint.id}
+ onClick={() => setSelectedEndpoint(endpoint)}
+ className={`w-full flex items-center text-left px-3 py-2 rounded-md text-xs transition-colors ${
+ selectedEndpoint.id === endpoint.id
+ ? "bg-stone-100 dark:bg-stone-800 text-stone-900 dark:text-stone-100 font-medium"
+ : "text-stone-600 dark:text-stone-400 hover:bg-stone-50 dark:hover:bg-stone-900/50 hover:text-stone-900 dark:hover:text-stone-200"
+ }`}
+ >
+ <Badge
+ variant="outline"
+ className={`mr-2.5 text-[9px] px-1 py-0 rounded font-bold shrink-0 ${getMethodColor(
+ endpoint.method
+ )}`}
+ >
+ {endpoint.method}
+ </Badge>
+ <span className="truncate flex-1">{endpoint.summary}</span>
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+
+ {/* Detail pane */}
+ <div className="flex-1 p-6 overflow-y-auto h-full bg-stone-50/10 dark:bg-stone-950/10">
+ <div className="flex flex-wrap items-center gap-3 mb-2">
+ <Badge
+ variant="outline"
+ className={`text-xs px-2 py-0.5 rounded font-bold ${getMethodColor(
+ selectedEndpoint.method
+ )}`}
+ >
+ {selectedEndpoint.method}
+ </Badge>
+ <span className="font-mono text-xs text-stone-800 dark:text-stone-200 font-semibold bg-stone-100 dark:bg-stone-800 px-2 py-1 rounded">
+ {selectedEndpoint.path}
+ </span>
+ <button
+ onClick={() => handleCopy(selectedEndpoint.path, "path")}
+ className="text-stone-400 hover:text-stone-600 dark:hover:text-stone-300"
+ title="Copy Path"
+ >
+ {copiedField === "path" ? (
+ <Check className="h-3.5 w-3.5 text-emerald-500" />
+ ) : (
+ <CopyIcon className="h-3.5 w-3.5" />
+ )}
+ </button>
+ </div>
+
+ <h4 className="text-base font-semibold text-stone-900 dark:text-stone-100 mb-2">
+ {selectedEndpoint.summary}
+ </h4>
+ <p className="text-xs text-stone-500 dark:text-stone-400 mb-6 leading-relaxed">
+ {selectedEndpoint.description}
+ </p>
+
+ {/* Parameters Reference */}
+ {getParameterDocs(selectedEndpoint.id).length > 0 && (
+ <div className="mb-6">
+ <details className="group border border-stone-200 dark:border-stone-800 rounded-md bg-stone-50/50 dark:bg-stone-900/30">
+ <summary className="flex items-center justify-between p-3 font-semibold text-xs text-stone-700 dark:text-stone-300 cursor-pointer hover:bg-stone-50 dark:hover:bg-stone-900/60 select-none">
+ <span>Parameters Reference ({getParameterDocs(selectedEndpoint.id).length})</span>
+ <ChevronRight className="h-4 w-4 text-stone-400 transition-transform group-open:rotate-90" />
+ </summary>
+ <div className="p-3 border-t border-stone-200 dark:border-stone-800 overflow-x-auto">
+ <table className="w-full text-left text-xs border-collapse">
+ <thead>
+ <tr className="border-b border-stone-200 dark:border-stone-800 text-stone-500 font-medium">
+ <th className="pb-2 pr-4 font-mono text-[10px]">Parameter</th>
+ <th className="pb-2 pr-4 font-mono text-[10px]">Type</th>
+ <th className="pb-2 pr-4 font-mono text-[10px]">Required</th>
+ <th className="pb-2">Description</th>
+ </tr>
+ </thead>
+ <tbody>
+ {getParameterDocs(selectedEndpoint.id).map((doc) => (
+ <tr key={doc.name} className="border-b border-stone-100 dark:border-stone-900/40 last:border-0 hover:bg-stone-50/50 dark:hover:bg-stone-900/20">
+ <td className="py-2.5 pr-4 font-mono text-[11px] font-semibold text-stone-800 dark:text-stone-200">
+ {doc.name}
+ </td>
+ <td className="py-2.5 pr-4 font-mono text-[11px] text-stone-500">
+ {doc.type}
+ </td>
+ <td className="py-2.5 pr-4">
+ {doc.required ? (
+ <Badge className="bg-red-50 text-red-600 dark:bg-red-950/30 dark:text-red-400 border-red-100 dark:border-red-900/30 text-[9px] px-1.5 py-0 font-bold">Required</Badge>
+ ) : (
+ <span className="text-[10px] text-stone-400 font-medium">Optional</span>
+ )}
+ </td>
+ <td className="py-2.5 text-stone-600 dark:text-stone-400 leading-relaxed text-[11px]">
+ <div>{doc.description}</div>
+ {doc.allowedValues && (
+ <div className="mt-1 text-[10px] text-stone-500 flex flex-wrap gap-1 items-center">
+ <span className="font-semibold text-stone-400">Allowed: </span>
+ {doc.allowedValues.map(val => <code key={val} className="bg-stone-100 dark:bg-stone-800 px-1 py-0.5 rounded text-[10px] text-stone-600 dark:text-stone-300">{val}</code>)}
+ </div>
+ )}
+ {doc.example && (
+ <div className="mt-1 text-[10px] text-stone-500">
+ <span className="font-semibold text-stone-400">Example: </span>
+ <code className="bg-stone-100 dark:bg-stone-800 px-1 py-0.5 rounded text-[10px] text-stone-600 dark:text-stone-300">{doc.example}</code>
+ </div>
+ )}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </details>
+ </div>
+ )}
+
+ {/* CURL Example Section */}
+ <div className="mb-6">
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-xs font-semibold text-stone-700 dark:text-stone-300 flex items-center gap-1.5">
+ <Terminal className="h-3.5 w-3.5 text-stone-400" /> {messages.REQUEST_CURL_EXAMPLE}
+ </span>
+ <button
+ onClick={() =>
+ handleCopy(selectedEndpoint.curlExample(activeKey), "curl")
+ }
+ className="text-xs flex items-center gap-1 text-stone-500 hover:text-stone-700 dark:hover:text-stone-300"
+ >
+ {copiedField === "curl" ? (
+ <>
+ <Check className="h-3 w-3 text-emerald-500" /> {messages.COPIED}
+ </>
+ ) : (
+ <>
+ <CopyIcon className="h-3 w-3" /> {messages.COPY_SNIPPET}
+ </>
+ )}
+ </button>
+ </div>
+ <pre className="p-3 bg-stone-900 text-stone-200 rounded-md font-mono text-[11px] overflow-x-auto leading-relaxed border border-stone-800">
+ {selectedEndpoint.curlExample(activeKey)}
+ </pre>
+ </div>
+
+ {/* Request Body & Response Tabs */}
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ {selectedEndpoint.requestBody && (
+ <div>
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-xs font-semibold text-stone-700 dark:text-stone-300 flex items-center gap-1.5">
+ <FileText className="h-3.5 w-3.5 text-stone-400" /> {messages.REQUEST_PAYLOAD_JSON}
+ </span>
+ <button
+ onClick={() =>
+ handleCopy(selectedEndpoint.requestBody || "", "payload")
+ }
+ className="text-xs text-stone-400 hover:text-stone-600 dark:hover:text-stone-300"
+ >
+ {copiedField === "payload" ? (
+ <Check className="h-3 w-3 text-emerald-500" />
+ ) : (
+ <CopyIcon className="h-3 w-3" />
+ )}
+ </button>
+ </div>
+ <pre className="p-3 bg-stone-50 dark:bg-stone-900 text-stone-700 dark:text-stone-300 rounded-md font-mono text-[10px] overflow-x-auto border border-stone-200 dark:border-stone-800">
+ {selectedEndpoint.requestBody}
+ </pre>
+ </div>
+ )}
+
+ {selectedEndpoint.responseBody && (
+ <div className={selectedEndpoint.requestBody ? "" : "col-span-2"}>
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-xs font-semibold text-stone-700 dark:text-stone-300 flex items-center gap-1.5">
+ <FileText className="h-3.5 w-3.5 text-stone-400" /> {messages.RESPONSE_BODY_JSON}
+ </span>
+ <button
+ onClick={() =>
+ handleCopy(selectedEndpoint.responseBody || "", "response")
+ }
+ className="text-xs text-stone-400 hover:text-stone-600 dark:hover:text-stone-300"
+ >
+ {copiedField === "response" ? (
+ <Check className="h-3 w-3 text-emerald-500" />
+ ) : (
+ <CopyIcon className="h-3 w-3" />
+ )}
+ </button>
+ </div>
+ <pre className="p-3 bg-stone-50 dark:bg-stone-900 text-stone-700 dark:text-stone-300 rounded-md font-mono text-[10px] overflow-x-auto border border-stone-200 dark:border-stone-800">
+ {selectedEndpoint.responseBody}
+ </pre>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/client/src/components/(playground)/api-keys/generate.tsx b/src/client/src/components/(playground)/api-keys/generate.tsx
index 1356ae8f..667f5393 100644
--- a/src/client/src/components/(playground)/api-keys/generate.tsx
+++ b/src/client/src/components/(playground)/api-keys/generate.tsx
@@ -16,9 +16,11 @@ import { useState } from "react";
import { usePostHog } from "posthog-js/react";
import { CLIENT_EVENTS } from "@/constants/events";
import { FieldProps, FormBuilderEvent } from "@/types/form";
+import getMessage from "@/constants/messages";
export default function Generate({ refresh }: { refresh: () => void }) {
const posthog = usePostHog();
+ const messages = getMessage();
const [isOpen, setIsOpen] = useState(false);
const { fireRequest: fireCreateRequest, isLoading: isCreating } =
useFetchWrapper();
@@ -77,15 +79,16 @@ export default function Generate({ refresh }: { refresh: () => void }) {
<DialogTrigger asChild>
<Button
variant="secondary"
+ size={"sm"}
className="bg-primary hover:bg-primary dark:bg-primary dark:hover:bg-primary text-stone-100 dark:text-stone-100 px-8 h-8 self-end"
>
- Generate New API Key
+ {messages.GENERATE_NEW_API_KEY}
</Button>
</DialogTrigger>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle className="dark:text-stone-200 text-stone-800">
- Create a new api key
+ {messages.CREATE_NEW_KEY}
</DialogTitle>
</DialogHeader>
<div className="flex items-center overflow-y-auto">
@@ -94,7 +97,7 @@ export default function Generate({ refresh }: { refresh: () => void }) {
fields={formFields}
isLoading={isCreating}
onSubmit={isCreating ? noop : handleCreation}
- submitButtonText="Create"
+ submitButtonText={messages.CREATE}
/>
</div>
</DialogContent>
diff --git a/src/client/src/components/(playground)/api-keys/manage.tsx b/src/client/src/components/(playground)/api-keys/manage.tsx
index 2c2670db..cd0c0585 100644
--- a/src/client/src/components/(playground)/api-keys/manage.tsx
+++ b/src/client/src/components/(playground)/api-keys/manage.tsx
@@ -14,9 +14,11 @@ import { ApiKey } from "@/types/api-key";
import { Columns } from "@/components/data-table/columns";
import DataTable from "@/components/data-table/table";
import { escapeEmailForDisplay } from "@/utils/string";
-import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
-import { Key, Shield, RotateCcw, Trash2 } from "lucide-react";
+import { Key, Shield, RotateCcw, Trash2, BookOpen } from "lucide-react";
+import Link from "next/link";
import FeaturePageHeader from "@/components/(playground)/feature-page-header";
+import getMessage from "@/constants/messages";
+import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
const columns: Columns<string, ApiKey> = {
name: {
@@ -77,6 +79,7 @@ const columns: Columns<string, ApiKey> = {
}
export default function ManageKeys() {
+ const messages = getMessage();
const { data, fireRequest, isFetched, isLoading } = useFetchWrapper<ApiKey[]>();
const { fireRequest: fireDeleteRequest } = useFetchWrapper();
const pingStatus = useRootStore(getPingStatus);
@@ -119,11 +122,22 @@ export default function ManageKeys() {
return (
<div className="flex flex-col grow w-full overflow-hidden">
<FeaturePageHeader
- eyebrow="Settings"
- title="API Keys"
+ eyebrow={messages.SETTINGS}
+ title={messages.API_KEYS}
icon={<Key className="h-4 w-4" />}
tone="border-primary/20 bg-primary/10 text-primary dark:border-primary/30 dark:bg-primary/15"
- actions={<Generate refresh={fetchData} />}
+ actions={
+ <div className="flex items-center gap-2">
+ <Link
+ href="/openapi-spec"
+ className="inline-flex items-center justify-center gap-1.5 rounded-md border border-stone-200 bg-white px-3 py-1.5 text-xs font-semibold text-stone-700 hover:bg-stone-50 dark:border-stone-800 dark:bg-stone-900 dark:text-stone-300 dark:hover:bg-stone-800 transition-colors"
+ >
+ <BookOpen className="h-4 w-4" />
+ <span>{messages.OPENAPI_SPECIFICATION}</span>
+ </Link>
+ <Generate refresh={fetchData} />
+ </div>
+ }
/>
<div className="flex flex-col w-full h-full p-4 gap-4">
<Alert className="border-amber-200 bg-amber-50/70 py-3 text-stone-700 dark:border-amber-900/60 dark:bg-amber-950/20 dark:text-stone-300">
diff --git a/src/client/src/components/(playground)/chat/message-bubble.tsx b/src/client/src/components/(playground)/chat/message-bubble.tsx
index 109e1372..d6f46c83 100644
--- a/src/client/src/components/(playground)/chat/message-bubble.tsx
+++ b/src/client/src/components/(playground)/chat/message-bubble.tsx
@@ -213,7 +213,7 @@ function TraceReferencePills({ refs }: { refs: TraceReference[] }) {
return;
}
try {
- const res = await fetch(`/api/metrics/request/trace/${ref.id}`);
+ const res = await fetch(`/api/telemetry/trace/trace/${ref.id}`);
const result = await res.json();
const record = result?.record || result?.data?.record || result?.data;
const spanId = record?.SpanId || record?.spanId;
diff --git a/src/client/src/components/(playground)/observability/registry.tsx b/src/client/src/components/(playground)/observability/registry.tsx
index ed0ebf32..333c0d3c 100644
--- a/src/client/src/components/(playground)/observability/registry.tsx
+++ b/src/client/src/components/(playground)/observability/registry.tsx
@@ -69,7 +69,7 @@ export const OBSERVABILITY_SIGNALS: ObservabilitySignalConfig[] = [
tone: "text-sky-600 dark:text-sky-400 bg-sky-50 dark:bg-sky-950/40 border-sky-200 dark:border-sky-900",
summary: m.OBSERVABILITY_TRACE_SUMMARY,
icon: Activity,
- listUrl: "/api/metrics/request",
+ listUrl: "/api/telemetry/trace",
summaryUrl: "/api/telemetry/summary/traces",
configUrl: "/api/metrics/request/config",
attributeKeysUrl: "/api/metrics/request/attribute-keys",
@@ -91,7 +91,7 @@ export const OBSERVABILITY_SIGNALS: ObservabilitySignalConfig[] = [
tone: "text-rose-600 dark:text-rose-400 bg-rose-50 dark:bg-rose-950/40 border-rose-200 dark:border-rose-900",
summary: m.OBSERVABILITY_EXCEPTION_SUMMARY,
icon: ShieldAlert,
- listUrl: "/api/metrics/exception",
+ listUrl: "/api/telemetry/exception",
summaryUrl: "/api/telemetry/summary/exceptions",
configUrl: "/api/metrics/request/config",
attributeKeysUrl: "/api/metrics/request/attribute-keys",
diff --git a/src/client/src/components/(playground)/observability/span-hierarchy-explorer.tsx b/src/client/src/components/(playground)/observability/span-hierarchy-explorer.tsx
index 02da9ede..464b7b1d 100644
--- a/src/client/src/components/(playground)/observability/span-hierarchy-explorer.tsx
+++ b/src/client/src/components/(playground)/observability/span-hierarchy-explorer.tsx
@@ -108,7 +108,7 @@ function SpanHierarchyExplorerInner({
useEffect(() => {
fireRequest({
requestType: "GET",
- url: `/api/metrics/request/span/${hierarchySpanId}/heirarchy`,
+ url: `/api/telemetry/trace/span/${hierarchySpanId}/heirarchy`,
});
}, [fireRequest, hierarchySpanId]);
diff --git a/src/client/src/components/(playground)/observability/trace-detail-page.tsx b/src/client/src/components/(playground)/observability/trace-detail-page.tsx
index fbaaa672..3d0fa4ac 100644
--- a/src/client/src/components/(playground)/observability/trace-detail-page.tsx
+++ b/src/client/src/components/(playground)/observability/trace-detail-page.tsx
@@ -359,7 +359,7 @@ export function TraceDetailView({
total?: number;
} | null>(null);
const fromRef = useRef(from);
- const listUrlRef = useRef(type === "exceptions" ? "/api/metrics/exception" : "/api/metrics/request");
+ const listUrlRef = useRef(type === "exceptions" ? "/api/telemetry/exception" : "/api/telemetry/trace");
const detailBasePathRef = useRef(
type === "exceptions" ? "/telemetry/exceptions" : "/telemetry/traces"
);
@@ -372,7 +372,7 @@ export function TraceDetailView({
const fetchData = useCallback(() => {
fireRequest({
requestType: "GET",
- url: `/api/metrics/request/span/${selectedSpanId}`,
+ url: `/api/telemetry/trace/span/${selectedSpanId}`,
});
}, [fireRequest, selectedSpanId]);
diff --git a/src/client/src/constants/api-reference.ts b/src/client/src/constants/api-reference.ts
new file mode 100644
index 00000000..3306f200
--- /dev/null
+++ b/src/client/src/constants/api-reference.ts
@@ -0,0 +1,522 @@
+export interface ApiEndpoint {
+ id: string;
+ method: "GET" | "POST" | "DELETE" | "PUT";
+ path: string;
+ summary: string;
+ description: string;
+ requestBody?: string;
+ responseBody?: string;
+ curlExample: (apiKey: string) => string;
+}
+
+export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
+ {
+ id: "query-logs",
+ method: "POST",
+ path: "/api/telemetry/logs",
+ summary: "Query logs",
+ description: "Retrieve a paginated list of telemetry logs matching the provided filters.",
+ requestBody: `{
+ "timeLimit": {
+ "type": "24H",
+ "start": "2026-07-07T13:08:52.311Z",
+ "end": "2026-07-08T13:09:17.114Z"
+ },
+ "limit": 25,
+ "offset": 0
+}`,
+ responseBody: `{
+ "records": [
+ {
+ "rowId": "18446744073709551615",
+ "Timestamp": "2026-07-08 00:00:00",
+ "TraceId": "a1b2c3d4e5f6g7h8",
+ "SpanId": "9a8b7c6d5e4f",
+ "SeverityText": "INFO",
+ "Body": "Application started successfully",
+ "ServiceName": "my-llm-service"
+ }
+ ],
+ "total": 1
+}`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/telemetry/logs \\
+ -H "Authorization: Bearer ${apiKey}" \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "timeLimit": {
+ "type": "24H",
+ "start": "2026-07-07T13:08:52.311Z",
+ "end": "2026-07-08T13:09:17.114Z"
+ },
+ "limit": 25
+ }'`,
+ },
+ {
+ id: "get-log",
+ method: "GET",
+ path: "/api/telemetry/logs/{id}",
+ summary: "Get log detail",
+ description: "Retrieve details of a specific log entry by its hash/row ID.",
+ responseBody: `{
+ "record": {
+ "Timestamp": "2026-07-08 00:00:00",
+ "TraceId": "a1b2c3d4e5f6g7h8",
+ "SpanId": "9a8b7c6d5e4f",
+ "SeverityText": "INFO",
+ "Body": "Application started successfully",
+ "ServiceName": "my-llm-service",
+ "LogAttributes": {
+ "environment": "production",
+ "version": "1.0.0"
+ }
+ }
+}`,
+ curlExample: (apiKey) => `curl -X GET http://localhost:3000/api/telemetry/logs/18446744073709551615 \\
+ -H "Authorization: Bearer ${apiKey}"`,
+ },
+ {
+ id: "query-metrics",
+ method: "POST",
+ path: "/api/telemetry/metrics",
+ summary: "Query metrics list",
+ description: "Retrieve list of aggregated metrics matching the filters.",
+ requestBody: `{
+ "timeLimit": {
+ "type": "24H",
+ "start": "2026-07-07T13:08:52.311Z",
+ "end": "2026-07-08T13:09:17.114Z"
+ }
+}`,
+ responseBody: `{
+ "records": [
+ {
+ "metricName": "gen_ai.usage.total_tokens",
+ "metricType": "Sum",
+ "serviceName": "chat-service",
+ "latestValue": 1024,
+ "avgValue": 512,
+ "minValue": 12,
+ "maxValue": 2048,
+ "pointCount": 84,
+ "observationCount": 84,
+ "lastSeen": "2026-07-08 00:50:00"
+ }
+ ],
+ "total": 1
+}`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/telemetry/metrics \\
+ -H "Authorization: Bearer ${apiKey}" \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "timeLimit": {
+ "type": "24H",
+ "start": "2026-07-07T13:08:52.311Z",
+ "end": "2026-07-08T13:09:17.114Z"
+ }
+ }'`,
+ },
+ {
+ id: "get-metric-detail",
+ method: "POST",
+ path: "/api/telemetry/metrics/{name}",
+ summary: "Get metric detail",
+ description: "Retrieve time-series graph points and detail records for a specific metric.",
+ requestBody: `{
+ "timeLimit": {
+ "type": "24H",
+ "start": "2026-07-07T13:08:52.311Z",
+ "end": "2026-07-08T13:09:17.114Z"
+ },
+ "metricType": "Sum",
+ "serviceName": "chat-service"
+}`,
+ responseBody: `{
+ "series": [
+ {
+ "request_time": "2026/07/08 00:00",
+ "value": 512
+ }
+ ],
+ "points": []
+}`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/telemetry/metrics/gen_ai.usage.total_tokens \\
+ -H "Authorization: Bearer ${apiKey}" \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "timeLimit": {
+ "type": "24H",
+ "start": "2026-07-07T13:08:52.311Z",
+ "end": "2026-07-08T13:09:17.114Z"
+ },
+ "metricType": "Sum"
+ }'`,
+ },
+ {
+ id: "get-compiled-prompt",
+ method: "GET",
+ path: "/api/prompt/get-compiled",
+ summary: "Fetch compiled prompt",
+ description: "Fetch and compile a prompt by name with dynamic variable interpolation.",
+ curlExample: (apiKey) => `curl -X GET "http://localhost:3000/api/prompt/get-compiled?name=summarize-prompt" \\
+ -H "Authorization: Bearer ${apiKey}"`,
+ },
+ {
+ id: "get-secrets",
+ method: "GET",
+ path: "/api/vault/get-secrets",
+ summary: "Fetch secrets from Vault",
+ description: "Safely retrieve API keys or credentials stored in the OpenLIT Vault.",
+ curlExample: (apiKey) => `curl -X GET http://localhost:3000/api/vault/get-secrets \\
+ -H "Authorization: Bearer ${apiKey}"`,
+ },
+ {
+ id: "evaluate-rules",
+ method: "POST",
+ path: "/api/rule-engine/evaluate",
+ summary: "Evaluate rule engine config",
+ description: "Evaluate rules (e.g. redaction, prompts, guardrails) against inputs.",
+ requestBody: `{
+ "entity_type": "prompt",
+ "fields": {
+ "input_text": "I need to reset my password, my email is [email protected]"
+ }
+}`,
+ responseBody: `{
+ "isRedacted": true,
+ "redactedText": "I need to reset my password, my email is [REDACTED]"
+}`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/rule-engine/evaluate \\
+ -H "Authorization: Bearer ${apiKey}" \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "entity_type": "prompt",
+ "fields": {
+ "input_text": "I need to reset my password, my email is [email protected]"
+ }
+ }'`,
+ },
+ {
+ id: "rule-list",
+ method: "GET",
+ path: "/api/rule-engine/rules",
+ summary: "List rules",
+ description: "Retrieve a list of all defined rules in the rule engine.",
+ requestBody: ``,
+ responseBody: `[]`,
+ curlExample: (apiKey) => `curl -X GET http://localhost:3000/api/rule-engine/rules \\
+ -H "Authorization: Bearer ${apiKey}"`,
+ },
+ {
+ id: "controller-poll",
+ method: "POST",
+ path: "/api/controller/poll",
+ summary: "Controller poll heartbeat",
+ description: "Heartbeat and state synchronization endpoint for OpenLIT controllers.",
+ requestBody: `{
+ "instance_id": "controller-instance-abc",
+ "cluster_id": "default",
+ "version": "1.0.0",
+ "services": []
+}`,
+ responseBody: `{
+ "config_changed": false,
+ "config_hash": "a1b2c3d4",
+ "actions": []
+}`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/controller/poll \\
+ -H "Authorization: Bearer ${apiKey}" \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "instance_id": "controller-instance-abc",
+ "cluster_id": "default",
+ "version": "1.0.0",
+ "services": []
+ }'`,
+ },
+ {
+ id: "evaluation-offline",
+ method: "POST",
+ path: "/api/evaluation/offline",
+ summary: "Offline LLM evaluation",
+ description: "Run LLM evaluation on historical or external data.",
+ requestBody: `{
+ "prompt": "I need to reset my password, my email is [email protected]",
+ "response": "I can help with that. Please verify your identity.",
+ "contexts": [
+ "User password reset procedure document."
+ ],
+ "eval_types": [
+ "toxicity",
+ "pii"
+ ],
+ "threshold_score": 0.5,
+ "store_results": true,
+ "run_id": "run-998877",
+ "metadata": {
+ "environment": "production"
+ }
+}`,
+ responseBody: `{
+ "success": true,
+ "evaluations": [
+ {
+ "type": "toxicity",
+ "score": 0.1,
+ "verdict": "passed",
+ "classification": "safe",
+ "explanation": "No toxic language detected."
+ }
+ ],
+ "context_applied": false,
+ "metadata": {}
+}`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/evaluation/offline \\
+ -H "Authorization: Bearer ${apiKey}" \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "prompt": "I need to reset my password, my email is [email protected]",
+ "response": "I can help with that. Please verify your identity.",
+ "contexts": ["User password reset procedure document."],
+ "eval_types": ["toxicity", "pii"],
+ "threshold_score": 0.5,
+ "store_results": true,
+ "run_id": "run-998877",
+ "metadata": {
+ "environment": "production"
+ }
+ }'`,
+ },
+ {
+ id: "create-prompt",
+ method: "POST",
+ path: "/api/prompt",
+ summary: "Create prompt",
+ description: "Create or save prompt configurations in OpenLIT Prompt Hub.",
+ requestBody: `{
+ "name": "summarize-prompt",
+ "prompt": "Summarize this: {{text}}",
+ "version": "1.0.0"
+}`,
+ responseBody: `{
+ "success": true
+}`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/prompt \\
+ -H "Authorization: Bearer ${apiKey}" \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "name": "summarize-prompt",
+ "prompt": "Summarize this: {{text}}",
+ "version": "1.0.0"
+ }'`,
+ },
+ {
+ id: "get-prompt",
+ method: "POST",
+ path: "/api/prompt/get",
+ summary: "Get prompt details",
+ description: "Retrieve details of a prompt version by its name.",
+ requestBody: `{
+ "name": "summarize-prompt"
+}`,
+ responseBody: `{
+ "id": "prompt-id-123",
+ "name": "summarize-prompt",
+ "prompt": "Summarize this: {{text}}",
+ "version": "1.0.0"
+}`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/prompt/get \\
+ -H "Authorization: Bearer ${apiKey}" \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "name": "summarize-prompt"
+ }'`,
+ },
+ {
+ id: "list-prompts",
+ method: "POST",
+ path: "/api/prompt/get",
+ summary: "List prompts",
+ description: "Retrieve a list of all prompt configurations saved in the Prompt Hub.",
+ requestBody: ``,
+ responseBody: `[]`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/prompt/get \\
+ -H "Authorization: Bearer ${apiKey}"`,
+ },
+ {
+ id: "upsert-secret",
+ method: "POST",
+ path: "/api/vault",
+ summary: "Upsert Vault secret",
+ description: "Add or update secrets inside the Vault store.",
+ requestBody: `{
+ "key": "OPENAI_API_KEY",
+ "value": "sk-proj-...",
+ "tags": ["production"]
+}`,
+ responseBody: `{
+ "id": "secret-id-123",
+ "key": "OPENAI_API_KEY",
+ "tags": ["production"]
+}`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/vault \\
+ -H "Authorization: Bearer ${apiKey}" \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "key": "OPENAI_API_KEY",
+ "value": "sk-proj-...",
+ "tags": ["production"]
+ }'`,
+ },
+ {
+ id: "query-traces",
+ method: "POST",
+ path: "/api/telemetry/trace",
+ summary: "Query traces list",
+ description: "Retrieve a paginated list of telemetry trace spans matching the provided filters. Pass `includeFilters=true` as a query parameter or `includeFilters: true` in the JSON body to retrieve inline pagination and dynamic filter metadata.",
+ requestBody: `{
+ "timeLimit": {
+ "type": "24H",
+ "start": "${new Date(Date.now() - 24 * 3600 * 1000).toISOString()}",
+ "end": "${new Date().toISOString()}"
+ },
+ "limit": 10,
+ "offset": 0,
+ "selectedConfig": {
+ "models": ["gpt-4o", "claude-3-5-sonnet"],
+ "providers": ["openai", "anthropic"],
+ "serviceNames": ["web-app"],
+ "environments": ["production"]
+ },
+ "sorting": {
+ "type": "Timestamp",
+ "direction": "desc"
+ },
+ "includeFilters": true
+}`,
+ responseBody: `{
+ "records": [],
+ "total": 0,
+ "pagination": {
+ "limit": 10,
+ "offset": 0,
+ "total": 0
+ },
+ "filters": {
+ "models": ["gpt-4o", "claude-3-5-sonnet"],
+ "providers": ["openai", "anthropic"],
+ "serviceNames": ["web-app"],
+ "environments": ["production"],
+ "maxCost": 0.05,
+ "totalRows": 150
+ }
+}`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/telemetry/trace?includeFilters=true \\
+ -H "Authorization: Bearer ${apiKey}" \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "timeLimit": {
+ "type": "24H",
+ "start": "${new Date(Date.now() - 24 * 3600 * 1000).toISOString()}",
+ "end": "${new Date().toISOString()}"
+ },
+ "limit": 10
+ }'`,
+ },
+ {
+ id: "query-exceptions",
+ method: "POST",
+ path: "/api/telemetry/exception",
+ summary: "Query exceptions list",
+ description: "Retrieve a paginated list of telemetry exception spans matching the provided filters. Pass `includeFilters=true` as a query parameter or `includeFilters: true` in the JSON body to retrieve inline pagination and dynamic filter metadata.",
+ requestBody: `{
+ "timeLimit": {
+ "type": "24H",
+ "start": "${new Date(Date.now() - 24 * 3600 * 1000).toISOString()}",
+ "end": "${new Date().toISOString()}"
+ },
+ "limit": 10,
+ "offset": 0,
+ "selectedConfig": {
+ "models": ["gpt-4o", "claude-3-5-sonnet"],
+ "providers": ["openai", "anthropic"],
+ "serviceNames": ["web-app"],
+ "environments": ["production"]
+ },
+ "sorting": {
+ "type": "Timestamp",
+ "direction": "desc"
+ },
+ "includeFilters": true
+}`,
+ responseBody: `{
+ "records": [],
+ "total": 0,
+ "pagination": {
+ "limit": 10,
+ "offset": 0,
+ "total": 0
+ },
+ "filters": {
+ "models": ["gpt-4o", "claude-3-5-sonnet"],
+ "providers": ["openai", "anthropic"],
+ "serviceNames": ["web-app"],
+ "environments": ["production"],
+ "maxCost": 0.05,
+ "totalRows": 12
+ }
+}`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/telemetry/exception?includeFilters=true \\
+ -H "Authorization: Bearer ${apiKey}" \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "timeLimit": {
+ "type": "24H",
+ "start": "${new Date(Date.now() - 24 * 3600 * 1000).toISOString()}",
+ "end": "${new Date().toISOString()}"
+ },
+ "limit": 10
+ }'`,
+ },
+ {
+ id: "get-span-detail",
+ method: "GET",
+ path: "/api/telemetry/trace/span/{id}",
+ summary: "Get span detail by ID",
+ description: "Retrieve details of a specific trace span by its ID (along with optional evaluation summary data).",
+ requestBody: ``,
+ responseBody: `{
+ "err": null,
+ "record": {}
+}`,
+ curlExample: (apiKey) => `curl -X GET http://localhost:3000/api/telemetry/trace/span/some-span-id \\
+ -H "Authorization: Bearer ${apiKey}"`,
+ },
+ {
+ id: "get-trace-detail",
+ method: "GET",
+ path: "/api/telemetry/trace/trace/{id}",
+ summary: "Get trace detail by Trace ID",
+ description: "Retrieve details of a trace (such as its root span or transaction info) using the Trace ID.",
+ requestBody: ``,
+ responseBody: `{
+ "err": null,
+ "record": {}
+}`,
+ curlExample: (apiKey) => `curl -X GET http://localhost:3000/api/telemetry/trace/trace/some-trace-id \\
+ -H "Authorization: Bearer ${apiKey}"`,
+ },
+ {
+ id: "get-span-hierarchy",
+ method: "GET",
+ path: "/api/telemetry/trace/span/{id}/heirarchy",
+ summary: "Get trace span hierarchy tree",
+ description: "Retrieve the tree hierarchy representation of all related spans associated with a trace span.",
+ requestBody: ``,
+ responseBody: `{
+ "err": null,
+ "record": {}
+}`,
+ curlExample: (apiKey) => `curl -X GET http://localhost:3000/api/telemetry/trace/span/some-span-id/heirarchy \\
+ -H "Authorization: Bearer ${apiKey}"`,
+ },
+];
diff --git a/src/client/src/constants/messages/en.ts b/src/client/src/constants/messages/en.ts
index 0b10f46b..e9c1061c 100644
--- a/src/client/src/constants/messages/en.ts
+++ b/src/client/src/constants/messages/en.ts
@@ -8,6 +8,21 @@ export const OPERATION_FAILED = "Operation failed!";
// API Keys
export const NO_API_KEY = "No such apiKey exists!";
+export const MANAGE_API_KEYS = "Manage API Keys";
+export const OPENAI_SPEC = "OpenAPI Specification";
+export const GENERATE_NEW_API_KEY = "Generate New API Key";
+export const CREATE_NEW_KEY = "Create a new api key";
+export const SETTINGS = "Settings";
+export const OPENAPI_SPECIFICATION = "OpenAPI Specification";
+export const OPENAPI_SPECIFICATION_UI = "OpenAPI Specification UI";
+export const INTERACTIVE_API_REFERENCE = "Interactive API Reference";
+export const OPENAPI_SPEC_BEARER_AUTH = "OpenAPI 3.0 Spec • Bearer Auth Authorized";
+export const REQUEST_CURL_EXAMPLE = "Request Curl Example";
+export const COPY_SNIPPET = "Copy Snippet";
+export const COPIED = "Copied";
+export const REQUEST_PAYLOAD_JSON = "Request Payload (JSON)";
+export const RESPONSE_BODY_JSON = "Response Body (JSON)";
+export const COPIED_TO_CLIPBOARD = "Copied to clipboard!";
// Prompts
export const PROMPT_NAME_TAKEN = "Prompt name is already taken!";
diff --git a/src/client/src/constants/route.ts b/src/client/src/constants/route.ts
index 6d33fb01..a2c49846 100644
--- a/src/client/src/constants/route.ts
+++ b/src/client/src/constants/route.ts
@@ -13,6 +13,23 @@ export const ALLOWED_OPENLIT_ROUTE_PREFIXES_WITHOUT_TOKEN = [
"/api/evaluation/offline/",
];
+export const ALLOWED_OPENLIT_ROUTES_WITH_TOKEN = [
+ "/api/prompt/get-compiled",
+ "/api/vault/get-secrets",
+ "/api/rule-engine/evaluate",
+ "/api/controller/poll",
+];
+
+export const ALLOWED_OPENLIT_ROUTE_PREFIXES_WITH_TOKEN = [
+ "/api/telemetry/",
+ "/api/rule-engine/",
+ "/api/evaluation/",
+ "/api/controller/",
+ "/api/prompt/",
+ "/api/vault/",
+ "/api/metrics/",
+];
+
export const CRON_JOB_ROUTES = [
"/api/evaluation/auto",
"/api/pricing/auto",
diff --git a/src/client/src/constants/sidebar.tsx b/src/client/src/constants/sidebar.tsx
index fdc9c1dc..341ade66 100644
--- a/src/client/src/constants/sidebar.tsx
+++ b/src/client/src/constants/sidebar.tsx
@@ -151,6 +151,12 @@ export const SIDEBAR_ITEMS: SidebarItemProps[] = [
link: "/settings/api-keys",
type: "action",
},
+ {
+ icon: <BookOpen className={ICON_CLASSES} />,
+ text: "OpenAPI Spec",
+ link: "/openapi-spec",
+ type: "action",
+ },
],
},
{
diff --git a/src/client/src/helpers/server/auth.ts b/src/client/src/helpers/server/auth.ts
new file mode 100644
index 00000000..94e57916
--- /dev/null
+++ b/src/client/src/helpers/server/auth.ts
@@ -0,0 +1,19 @@
+import { getCurrentUser } from "@/lib/session";
+
+/**
+ * Resolves the database configuration ID from the request headers or the current user session.
+ * Returns a tuple of [error, databaseConfigId].
+ */
+export async function resolveDbConfigId(request: Request): Promise<[string | null, string | undefined]> {
+ const dbConfigId = request.headers.get("x-database-config-id");
+ if (dbConfigId) {
+ return [null, dbConfigId];
+ }
+
+ const user = await getCurrentUser();
+ if (!user) {
+ return ["Unauthorized", undefined];
+ }
+
+ return [null, undefined];
+}
diff --git a/src/client/src/lib/platform/common.ts b/src/client/src/lib/platform/common.ts
index 74c6d80e..e2a0e4c2 100644
--- a/src/client/src/lib/platform/common.ts
+++ b/src/client/src/lib/platform/common.ts
@@ -35,6 +35,7 @@ export interface MetricParams {
sorting?: any;
operationType?: OPERATION_TYPE;
statusCode?: string[];
+ databaseConfigId?: string;
}
export type GPU_TYPE_KEY =
diff --git a/src/client/src/lib/platform/evaluation/index.ts b/src/client/src/lib/platform/evaluation/index.ts
index e6ee3bdb..f4988404 100644
--- a/src/client/src/lib/platform/evaluation/index.ts
+++ b/src/client/src/lib/platform/evaluation/index.ts
@@ -72,9 +72,11 @@ function estimateEvaluationCost(
);
}
-export async function getEvaluationSummaryForSpanId(spanId: string) {
- const user = await getCurrentUser();
- if (!user) return null;
+export async function getEvaluationSummaryForSpanId(spanId: string, dbConfigId?: string) {
+ if (!dbConfigId) {
+ const user = await getCurrentUser();
+ if (!user) return null;
+ }
const sanitizedSpanId = Sanitizer.sanitizeValue(spanId);
const query = `
@@ -86,7 +88,7 @@ export async function getEvaluationSummaryForSpanId(spanId: string) {
WHERE span_id = '${sanitizedSpanId}' AND meta['source'] NOT IN ('${EVALUATION_SOURCE.MANUAL_FEEDBACK}', '${EVALUATION_SOURCE.AUTO_SKIPPED}');
`;
- const { data, err } = await dataCollector({ query });
+ const { data, err } = await dataCollector({ query }, "query", dbConfigId);
if (err || !(data as any[])?.[0]) return null;
const row = (data as any[])[0];
diff --git a/src/client/src/lib/platform/observability.ts b/src/client/src/lib/platform/observability.ts
index 82c11c07..61a0cb69 100644
--- a/src/client/src/lib/platform/observability.ts
+++ b/src/client/src/lib/platform/observability.ts
@@ -186,7 +186,7 @@ export async function getLogsConfig(params: MetricParams) {
FROM ${OTEL_LOGS_TABLE_NAME}
WHERE ${buildWhere(params, "logs")}
`;
- return dataCollector({ query });
+ return dataCollector({ query }, "query", params.databaseConfigId);
}
export async function getLogAttributeKeys(params: MetricParams) {
@@ -205,7 +205,7 @@ export async function getLogAttributeKeys(params: MetricParams) {
query: `SELECT DISTINCT arrayJoin(mapKeys(ScopeAttributes)) AS key FROM ${OTEL_LOGS_TABLE_NAME} WHERE ${where} ORDER BY key LIMIT 500`,
},
];
- const results = await Promise.all(queries.map(({ query }) => dataCollector({ query })));
+ const results = await Promise.all(queries.map(({ query }) => dataCollector({ query }, "query", params.databaseConfigId)));
return {
err: results.find((result) => result.err)?.err ?? null,
spanAttributeKeys: [],
@@ -222,10 +222,10 @@ export async function getLogs(params: MetricParams) {
const { limit = 25, offset = 0 } = params;
const where = buildWhere(params, "logs");
const countQuery = `SELECT CAST(COUNT(*) AS INTEGER) AS total FROM ${OTEL_LOGS_TABLE_NAME} WHERE ${where}`;
- const { data: countData, err: countErr } = await dataCollector({ query: countQuery });
+ const { data: countData, err: countErr } = await dataCollector({ query: countQuery }, "query", params.databaseConfigId);
if (countErr) return { err: countErr };
- const orderBy = params.sorting?.type
+ const orderBy = params.sorting?.type && params.sorting?.direction
? `${params.sorting.type.replace(/[^A-Za-z0-9_.]/g, "")} ${params.sorting.direction}`
: "Timestamp desc";
const query = `
@@ -238,7 +238,7 @@ export async function getLogs(params: MetricParams) {
LIMIT ${limit}
OFFSET ${offset}
`;
- const { data, err } = await dataCollector({ query });
+ const { data, err } = await dataCollector({ query }, "query", params.databaseConfigId);
return {
err,
records: data,
@@ -301,7 +301,7 @@ export async function getSignalSummary(
`;
}
- const { data, err } = await dataCollector({ query });
+ const { data, err } = await dataCollector({ query }, "query", params.databaseConfigId);
const buckets = (data as any[]) || [];
const total = buckets.reduce((sum, row) => sum + Number(row.count || 0), 0);
@@ -314,7 +314,7 @@ export async function getSignalSummary(
};
}
-export async function getLogByRowId(rowId: string) {
+export async function getLogByRowId(rowId: string, dbConfigId?: string) {
const safeRowId = rowId.replace(/[^0-9]/g, "");
const query = `
SELECT
@@ -324,7 +324,7 @@ export async function getLogByRowId(rowId: string) {
WHERE cityHash64(toString(Timestamp), TraceId, SpanId, SeverityText, Body) = ${safeRowId || "0"}
LIMIT 1
`;
- const { data, err } = await dataCollector({ query });
+ const { data, err } = await dataCollector({ query }, "query", dbConfigId);
return { err, record: (data as any[])?.[0] };
}
@@ -337,7 +337,7 @@ export async function getMetricsConfig(params: MetricParams) {
CAST(COUNT(*) AS INTEGER) AS totalRows
FROM (${metricUnionSelect(params, "ServiceName, MetricName")})
`;
- return dataCollector({ query });
+ return dataCollector({ query }, "query", params.databaseConfigId);
}
export async function getMetricAttributeKeys(params: MetricParams) {
@@ -349,13 +349,13 @@ export async function getMetricAttributeKeys(params: MetricParams) {
const [metricResult, resourceResult, scopeResult] = await Promise.all([
dataCollector({
query: `${queries.map((q) => q.metric).join(" UNION DISTINCT ")} ORDER BY key LIMIT 500`,
- }),
+ }, "query", params.databaseConfigId),
dataCollector({
query: `${queries.map((q) => q.resource).join(" UNION DISTINCT ")} ORDER BY key LIMIT 500`,
- }),
+ }, "query", params.databaseConfigId),
dataCollector({
query: `${queries.map((q) => q.scope).join(" UNION DISTINCT ")} ORDER BY key LIMIT 500`,
- }),
+ }, "query", params.databaseConfigId),
]);
return {
err: metricResult.err || resourceResult.err || scopeResult.err,
@@ -383,7 +383,7 @@ export async function getMetrics(params: MetricParams) {
GROUP BY MetricName, metric_type, ServiceName
)
`;
- const { data: countData, err: countErr } = await dataCollector({ query: countQuery });
+ const { data: countData, err: countErr } = await dataCollector({ query: countQuery }, "query", params.databaseConfigId);
if (countErr) return { err: countErr };
const query = `
@@ -406,7 +406,7 @@ export async function getMetrics(params: MetricParams) {
LIMIT ${limit}
OFFSET ${offset}
`;
- const { data, err } = await dataCollector({ query });
+ const { data, err } = await dataCollector({ query }, "query", params.databaseConfigId);
return {
err,
records: data,
@@ -454,8 +454,8 @@ export async function getMetricDetail(metricName: string, metricType?: string, s
LIMIT 100
`;
const [series, points] = await Promise.all([
- dataCollector({ query: seriesQuery }),
- dataCollector({ query: pointsQuery }),
+ dataCollector({ query: seriesQuery }, "query", params?.databaseConfigId),
+ dataCollector({ query: pointsQuery }, "query", params?.databaseConfigId),
]);
return {
err: series.err || points.err,
diff --git a/src/client/src/lib/platform/prompt/index.ts b/src/client/src/lib/platform/prompt/index.ts
index d342b091..d78aaef3 100644
--- a/src/client/src/lib/platform/prompt/index.ts
+++ b/src/client/src/lib/platform/prompt/index.ts
@@ -91,9 +91,11 @@ export async function createPrompt(promptInputParams: PromptInput) {
};
}
-export async function getPrompts() {
- const user = await getCurrentUser();
- throwIfError(!user, getMessage().UNAUTHORIZED_USER);
+export async function getPrompts({ databaseConfigId }: { databaseConfigId?: string } = {}) {
+ if (!databaseConfigId) {
+ const user = await getCurrentUser();
+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);
+ }
const query = `SELECT
p.id AS promptId,
@@ -117,7 +119,7 @@ export async function getPrompts() {
p.created_at DESC;
`;
- return await dataCollector({ query });
+ return await dataCollector({ query }, "query", databaseConfigId);
}
export async function getSpecificPrompt(
diff --git a/src/client/src/lib/platform/request/index.ts b/src/client/src/lib/platform/request/index.ts
index e323908c..5b85ad59 100644
--- a/src/client/src/lib/platform/request/index.ts
+++ b/src/client/src/lib/platform/request/index.ts
@@ -209,7 +209,7 @@ export async function getRequestsConfig(params: MetricParams) {
const query = `SELECT ${select.join(", ")} FROM ${OTEL_TRACES_TABLE_NAME}
WHERE ${getFilterWhereCondition(params, true)}`;
- return dataCollector({ query });
+ return dataCollector({ query }, "query", params.databaseConfigId);
}
export async function getRequests(params: MetricParams) {
@@ -218,9 +218,11 @@ export async function getRequests(params: MetricParams) {
const countQuery = `SELECT CAST(COUNT(*) AS INTEGER) AS total FROM ${OTEL_TRACES_TABLE_NAME}
WHERE ${getFilterWhereCondition(params, true)}`;
- const { data: dataTotal, err: errTotal } = await dataCollector({
- query: countQuery,
- });
+ const { data: dataTotal, err: errTotal } = await dataCollector(
+ { query: countQuery },
+ "query",
+ params.databaseConfigId
+ );
if (errTotal) {
return {
err: errTotal,
@@ -229,7 +231,7 @@ export async function getRequests(params: MetricParams) {
const query = `SELECT * FROM ${OTEL_TRACES_TABLE_NAME}
WHERE ${getFilterWhereCondition(params, true)}
- ${params.sorting
+ ${params.sorting && params.sorting.type && params.sorting.direction
? params.sorting.type.includes("cost")
? `ORDER BY toFloat64OrZero(${params.sorting.type}) ${params.sorting.direction} `
: params.sorting.type.includes("tokens")
@@ -240,7 +242,7 @@ export async function getRequests(params: MetricParams) {
LIMIT ${limit}
OFFSET ${offset}`;
- const { data, err } = await dataCollector({ query });
+ const { data, err } = await dataCollector({ query }, "query", params.databaseConfigId);
return {
err,
records: data,
@@ -248,32 +250,32 @@ export async function getRequests(params: MetricParams) {
};
}
-export async function getRequestViaSpanId(spanId: string) {
+export async function getRequestViaSpanId(spanId: string, dbConfigId?: string) {
const safeSpanId = escapeClickHouseString(String(spanId ?? ""));
const query = `SELECT * FROM ${OTEL_TRACES_TABLE_NAME}
WHERE SpanId='${safeSpanId}'`;
- const { data, err } = await dataCollector({ query });
+ const { data, err } = await dataCollector({ query }, "query", dbConfigId);
return {
err,
record: (data as unknown[])?.[0],
};
}
-export async function getRequestViaTraceId(traceId: string) {
+export async function getRequestViaTraceId(traceId: string, dbConfigId?: string) {
const safeTraceId = escapeClickHouseString(String(traceId ?? ""));
const query = `SELECT * FROM ${OTEL_TRACES_TABLE_NAME} WHERE ${getTraceMappingKeyFullPath(
"id"
)}='${safeTraceId}'`;
- const { data, err } = await dataCollector({ query });
+ const { data, err } = await dataCollector({ query }, "query", dbConfigId);
return {
err,
record: (data as unknown[])?.[0],
};
}
-export async function getHeirarchyViaSpanId(spanId: string) {
+export async function getHeirarchyViaSpanId(spanId: string, dbConfigId?: string) {
// Step 1: resolve the source span. We need:
// - TraceId (the usual "show every span in the trace" path)
// - coding_agent.session.id (so coding-agent sessions whose CLI
@@ -297,9 +299,11 @@ export async function getHeirarchyViaSpanId(spanId: string) {
WHERE SpanId = '${safeSpanId}'
LIMIT 1`;
- const { data: sourceData, err: sourceErr } = await dataCollector({
- query: sourceSpanQuery,
- });
+ const { data: sourceData, err: sourceErr } = await dataCollector(
+ { query: sourceSpanQuery },
+ "query",
+ dbConfigId
+ );
if (sourceErr || !Array.isArray(sourceData) || sourceData.length === 0) {
return { err: "Span not found", record: {} };
@@ -356,9 +360,11 @@ export async function getHeirarchyViaSpanId(spanId: string) {
ORDER BY Timestamp ASC
LIMIT 5000`;
- const { data: allSpans, err: allSpansErr } = await dataCollector({
- query: allSpansQuery,
- });
+ const { data: allSpans, err: allSpansErr } = await dataCollector(
+ { query: allSpansQuery },
+ "query",
+ dbConfigId
+ );
if (allSpansErr || !Array.isArray(allSpans) || allSpans.length === 0) {
return { err: "Failed to fetch trace spans", record: {} };
diff --git a/src/client/src/lib/platform/rule-engine/index.ts b/src/client/src/lib/platform/rule-engine/index.ts
index 2336ae00..55136e35 100644
--- a/src/client/src/lib/platform/rule-engine/index.ts
+++ b/src/client/src/lib/platform/rule-engine/index.ts
@@ -30,8 +30,10 @@ function shouldEmitAlert(options?: RuleMutationOptions) {
}
export async function getRules(databaseConfigId?: string) {
- const user = await getCurrentUser();
- throwIfError(!user, getMessage().UNAUTHORIZED_USER);
+ if (!databaseConfigId) {
+ const user = await getCurrentUser();
+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);
+ }
const query = `
SELECT * FROM ${OPENLIT_RULES_TABLE_NAME}
@@ -42,8 +44,10 @@ export async function getRules(databaseConfigId?: string) {
}
export async function getRuleById(id: string, databaseConfigId?: string) {
- const user = await getCurrentUser();
- throwIfError(!user, getMessage().UNAUTHORIZED_USER);
+ if (!databaseConfigId) {
+ const user = await getCurrentUser();
+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);
+ }
const safeId = Sanitizer.sanitizeValue(id);
diff --git a/src/client/src/middleware/check-auth.ts b/src/client/src/middleware/check-auth.ts
index 86660ea8..235a05d8 100644
--- a/src/client/src/middleware/check-auth.ts
+++ b/src/client/src/middleware/check-auth.ts
@@ -10,6 +10,8 @@ import {
DEFAULT_LOGGED_IN_ROUTE,
ALLOWED_OPENLIT_ROUTES_WITHOUT_TOKEN,
ALLOWED_OPENLIT_ROUTE_PREFIXES_WITHOUT_TOKEN,
+ ALLOWED_OPENLIT_ROUTES_WITH_TOKEN,
+ ALLOWED_OPENLIT_ROUTE_PREFIXES_WITH_TOKEN,
CRON_JOB_ROUTES,
ONBOARDING_WHITELIST_ROUTES,
ONBOARDING_WHITELIST_ROUTE_PREFIXES,
@@ -86,6 +88,8 @@ function isRateLimited(request: NextRequest) {
return window.count > SENSITIVE_API_RATE_LIMIT;
}
+
+
export default function checkAuth(next: NextMiddleware) {
return withAuth(
async function middleware(request: NextRequest, _next: NextFetchEvent) {
@@ -93,7 +97,8 @@ export default function checkAuth(next: NextMiddleware) {
if (
pathname.startsWith("/_next") ||
pathname.startsWith("/static") ||
- pathname.startsWith("/images")
+ pathname.startsWith("/images") ||
+ pathname === "/api/auth/verify-key"
) {
// Static assets: skip all auth logic and let the request
// continue to the underlying resource. We must return a
@@ -106,6 +111,51 @@ export default function checkAuth(next: NextMiddleware) {
return NextResponse.next();
}
+ const isWithTokenRoute =
+ ALLOWED_OPENLIT_ROUTES_WITH_TOKEN.includes(pathname) ||
+ ALLOWED_OPENLIT_ROUTE_PREFIXES_WITH_TOKEN.some((prefix) =>
+ pathname.startsWith(prefix)
+ );
+
+ const authHeader = request.headers.get("Authorization") || "";
+ if (authHeader.startsWith("Bearer ")) {
+ if (!isWithTokenRoute) {
+ return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+ }
+
+ const apiKey = authHeader.replace(/^Bearer /, "").trim();
+ if (!apiKey) {
+ return NextResponse.json({ error: "Invalid API key" }, { status: 401 });
+ }
+
+ try {
+ const verifyUrl = new URL("/api/auth/verify-key", request.url);
+ const res = await fetch(verifyUrl, {
+ headers: {
+ Authorization: authHeader,
+ },
+ });
+
+ if (res.ok) {
+ const data = await res.json();
+ if (data.valid && data.databaseConfigId) {
+ const requestHeaders = new Headers(request.headers);
+ requestHeaders.set("x-database-config-id", data.databaseConfigId);
+ return next(
+ new NextRequest(request, {
+ headers: requestHeaders,
+ }),
+ _next
+ );
+ }
+ }
+ } catch (e) {
+ console.error("Middleware API key validation error:", e);
+ }
+
+ return NextResponse.json({ error: "Invalid API key" }, { status: 401 });
+ }
+
try {
const token = await getToken({ req: request });
const isAuth = !!token;
@@ -198,6 +248,9 @@ export default function checkAuth(next: NextMiddleware) {
}
if (!isAuth) {
+ if (isApiPage) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
let from = pathname;
if (request.nextUrl.search) {
from += request.nextUrl.search;
diff --git a/src/client/src/middleware/check-csrf.ts b/src/client/src/middleware/check-csrf.ts
index 649c9de8..8788db80 100644
--- a/src/client/src/middleware/check-csrf.ts
+++ b/src/client/src/middleware/check-csrf.ts
@@ -35,11 +35,14 @@ function isSameOrigin(request: NextRequest) {
export default function checkCsrf(next: NextMiddleware) {
return async (request: NextRequest, event: NextFetchEvent) => {
const { pathname } = request.nextUrl;
+ const authHeader = request.headers.get("Authorization") || "";
+ const hasBearerToken = authHeader.startsWith("Bearer ");
if (
STATE_CHANGING_METHODS.has(request.method.toUpperCase()) &&
pathname.startsWith("/api/") &&
!isExemptPath(pathname) &&
+ !hasBearerToken &&
!isSameOrigin(request)
) {
return NextResponse.json("Forbidden", { status: 403 });