Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
feat: add enterprise extension fallbacks (#1271)
Aman Agarwala689421b306c
diff --git a/.claude/commands/project-hierarchy-check.md b/.claude/commands/project-hierarchy-check.mdindex cec24f06..6b353d67 100644--- a/.claude/commands/project-hierarchy-check.md+++ b/.claude/commands/project-hierarchy-check.md@@ -2,12 +2,15 @@Use this command before changing organisation, project, or database config behavior.-1. Confirm the code follows `Organisation -> Project -> Database configuration`.-2. Check that database config reads and writes are scoped by current project.-3. Check that project list and switch routes validate organisation membership.-4. Check that switching organisation refreshes projects and database config state.-5. Add or update tests for membership denial, selected project, cross-project denial, and invalid JSON.-6. Run:+1. Confirm this is shared CE behavior. Enterprise-only implementation must stay in `openlit-enterprise/src/client/src/ee/`.+2. Confirm any enterprise extension point has only an OSS-safe no-op fallback in CE.+3. Confirm CE strings go in `src/client/src/constants/messages/en.ts`; enterprise-only strings stay in the private EE message file.+4. Confirm the code follows `Organisation -> Project -> Database configuration`.+5. Check that database config reads and writes are scoped by current project.+6. Check that project list and switch routes validate organisation membership.+7. Check that switching organisation refreshes projects and database config state.+8. Add or update tests for membership denial, selected project, cross-project denial, and invalid JSON.+9. Run:```bashcd src/clientdiff --git a/.cursor-rules/README.md b/.cursor-rules/README.mdindex 520a7632..4f09b165 100644--- a/.cursor-rules/README.md+++ b/.cursor-rules/README.md@@ -32,6 +32,8 @@ This directory contains organized cursor rules for different aspects of the Open**Key Features**:- Light and dark mode styling standards- Compact operational UI guidance+- CE/EE boundary expectations+- OSS-safe fallback guidance- Project hierarchy UI expectations- Message key requirements@@ -46,6 +48,7 @@ This directory contains organized cursor rules for different aspects of the Open**Key Features**:- Server-side authorization requirements- Invalid JSON handling+- OSS-safe extension fallback requirements- Secret redaction requirements- Project-scoped DB config test expectationsdiff --git a/.cursor-rules/frontend.md b/.cursor-rules/frontend.mdindex 543bb68f..802ac06d 100644--- a/.cursor-rules/frontend.md+++ b/.cursor-rules/frontend.md@@ -16,8 +16,15 @@ Use these rules for OpenLIT client UI work in `src/client/src`.- Do not hard-code user-facing strings.- Add strings to `src/client/src/constants/messages/en.ts`.+- Do not add enterprise-only strings here; those belong in `src/client/src/ee/constants/messages/en.ts` in `openlit-enterprise`.- Use existing message keys before adding new ones.+## Enterprise Boundary++- Do not add enterprise implementation to CE.+- CE may include OSS-safe no-op extension fallbacks used by shared code.+- Enterprise-only UI, providers, stores, selectors, types, and feature pages belong under `src/client/src/ee/` in `openlit-enterprise`.+## Project Hierarchy UI- Header should show organisation and project switching.@@ -28,6 +35,6 @@ Use these rules for OpenLIT client UI work in `src/client/src`.## Quality Checklist- [ ] Light and dark mode are both checked.-- [ ] Text uses `messages/en.ts`.+- [ ] Text uses CE `messages/en.ts`, with no enterprise-only copy added to CE.- [ ] Project-scoped UI refreshes after organisation or project changes.- [ ] Loading, empty, disabled, and error states are covered.diff --git a/.cursor-rules/security-testing.md b/.cursor-rules/security-testing.mdindex 34e75ec5..3c6f6d20 100644--- a/.cursor-rules/security-testing.md+++ b/.cursor-rules/security-testing.md@@ -8,8 +8,9 @@ Use these rules for API routes, auth checks, project hierarchy, billing, licensi- Server routes must enforce authorization. UI checks are not authorization.- Project routes must validate organisation membership.-- Enterprise routes must enforce entitlement or billing-admin checks on the server.+- Enterprise routes in the private repo must enforce entitlement or billing-admin checks on the server.- Database config selection must be scoped to the current project.+- CE must not contain enterprise audit, billing, licensing, or entitlement implementation beyond OSS-safe contracts and disabled/no-op fallbacks.## Input Handling@@ -17,12 +18,19 @@ Use these rules for API routes, auth checks, project hierarchy, billing, licensi- Malformed JSON should return `400`.- Validate names and identifiers before calling library mutation functions.- Use messages from `src/client/src/constants/messages/en.ts` for user-facing validation errors.+- Enterprise-only validation messages belong in the private repo's `src/client/src/ee/constants/messages/en.ts`.## Audit And Secrets- Do not persist raw passwords, tokens, cookies, API keys, license keys, authorization headers, or session values.- Audit metadata must redact sensitive request fields.+## Extension Points++- Shared code may import stable extension hooks only when CE provides an OSS-safe no-op fallback.+- Enterprise implementations for those hooks must live under `src/client/src/ee/**` in `openlit-enterprise`.+- Keep tests covering the CE fallback behavior when a shared hook is added.+## Tests- Add focused tests for every security boundary changed.diff --git a/.cursorrules b/.cursorrulesindex dd952c7f..f5a7dbcf 100644--- a/.cursorrules+++ b/.cursorrules@@ -13,14 +13,14 @@ For all documentation work including MDX files, guides, and API documentation.### Frontend RulesFor OpenLIT client UI work.- **File**: `.cursor-rules/frontend.md`-- **Applies to**: `src/client/src/**/*.tsx`, settings pages, telemetry-style pages, stores, selectors, and helpers-- **Purpose**: Keeps light/dark styling, compact page layout, project hierarchy UI, and message usage consistent+- **Applies to**: `src/client/src/**/*.tsx`, settings pages, telemetry-style pages, stores, selectors, helpers, and OSS-safe extension fallbacks+- **Purpose**: Keeps light/dark styling, compact page layout, project hierarchy UI, CE message usage, and CE/EE boundary placement consistent### Security And Testing RulesFor API routes, project hierarchy, auth, audit, billing, licensing, and tests.- **File**: `.cursor-rules/security-testing.md`- **Applies to**: `src/client/src/app/api/**`, `src/client/src/lib/**`, `src/client/src/ee/**`, `src/client/src/__tests__/**`-- **Purpose**: Ensures server-side authorization, invalid JSON handling, project scoping, redaction, and validation coverage+- **Purpose**: Ensures server-side authorization, invalid JSON handling, project scoping, OSS-safe fallback boundaries, redaction, and validation coverage## Usagediff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 00000000..c7a80cc3--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,25 @@+# OpenLIT Agent Rules++## CE/OSS Boundary++- This repository is the open-source CE/OSS codebase.+- Do not add enterprise implementation here.+- CE may contain shared contracts, empty feature lists, disabled feature placeholders, upgrade-required responses, and OSS-safe no-op extension fallbacks.+- Enterprise implementation belongs in `openlit-enterprise/src/client/src/ee/`.++## Extension Points++- Shared code may import a stable extension hook only when CE provides a no-op fallback.+- Do not import private enterprise modules from CE.+- Keep CE messages in `src/client/src/constants/messages/en.ts`; enterprise-only messages belong in `src/client/src/ee/constants/messages/en.ts` in the private repo.++## Project Hierarchy++- The hierarchy is `Organisation -> Project -> Database configuration`.+- Database config reads, writes, selection, and ping state must be scoped by current project.+- Billing, licensing, seats, and entitlements are organisation-scoped in enterprise.++## Validation++- Add tests for changed security boundaries.+- Run focused tests and `npm run lint` from `src/client` before handoff.diff --git a/CLAUDE.md b/CLAUDE.mdindex 1c072232..05746ec1 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -4,8 +4,10 @@- This repository is the open-source CE/OSS codebase.- Do not add enterprise implementation files here.-- CE may contain shared contracts, feature IDs, disabled feature placeholders, and upgrade-required responses.+- CE may contain shared contracts, feature IDs, empty feature lists, disabled feature placeholders, upgrade-required responses, and OSS-safe no-op extension fallbacks.- Enterprise-only implementation belongs in the private `openlit-enterprise` repository under `src/client/src/ee/`.+- If shared code needs an enterprise extension point, add a stable shared import with a CE no-op fallback here, then let `openlit-enterprise` override it from `src/client/src/ee/**`.+- Do not add enterprise-only libraries, stores, selectors, middleware behavior, feature rules, billing logic, license logic, audit implementation, or UI here.## Project Hierarchy@@ -26,7 +28,7 @@ Organisation## UI Rules- Follow the existing settings-page classes for light and dark mode.-- Do not hard-code user-facing strings in React, route handlers, or library errors. Add them to `src/client/src/constants/messages/en.ts`.+- Do not hard-code user-facing strings in React, route handlers, or library errors. Add CE strings to `src/client/src/constants/messages/en.ts`; enterprise-only strings belong in `src/client/src/ee/constants/messages/en.ts` in the private repo.- Use compact controls in settings and telemetry-style data pages.- Keep project and organisation switchers in the header; breadcrumbs belong below the header.diff --git a/src/client/src/__tests__/lib/platform/api-keys/api-keys.test.ts b/src/client/src/__tests__/lib/platform/api-keys/api-keys.test.tsindex 3aa5d466..40eae5bc 100644--- a/src/client/src/__tests__/lib/platform/api-keys/api-keys.test.ts+++ b/src/client/src/__tests__/lib/platform/api-keys/api-keys.test.ts@@ -16,6 +16,12 @@ jest.mock('@/lib/session', () => ({jest.mock('@/lib/db-config', () => ({getDBConfigByUser: jest.fn(),}));+jest.mock('@/lib/organisation', () => ({+ getCurrentOrganisation: jest.fn(),+}));+jest.mock('@/lib/billing/usage-recorder', () => ({+ recordOrganisationUsageEvent: jest.fn(),+}));jest.mock('@/utils/asaw', () => jest.fn());jest.mock('@/utils/error', () => ({throwIfError: jest.fn((condition: boolean, msg: string) => {@@ -33,11 +39,14 @@ jest.mock('@/constants/messages', () => ({import { deleteAPIKey, generateAPIKey, getAllAPIKeys, getAPIKeyInfo, hasAnyAPIKeys } from '@/lib/platform/api-keys/index';import { getCurrentUser } from '@/lib/session';import { getDBConfigByUser } from '@/lib/db-config';+import { getCurrentOrganisation } from '@/lib/organisation';+import { recordOrganisationUsageEvent } from '@/lib/billing/usage-recorder';import asaw from '@/utils/asaw';import prisma from '@/lib/prisma';beforeEach(() => {jest.clearAllMocks();+ (getCurrentOrganisation as jest.Mock).mockResolvedValue(null);});describe('generateAPIKey', () => {@@ -52,6 +61,23 @@ describe('generateAPIKey', () => {expect(result.databaseConfigId).toBe('db-1');});+ it('calls the usage recorder when a current organisation exists', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'user-1', email: '[email protected]' });+ (getCurrentOrganisation as jest.Mock).mockResolvedValue({ id: 'org1' });+ (asaw as jest.Mock).mockResolvedValue([null, { id: 'db-1' }]);+ (prisma.aPIKeys.create as jest.Mock).mockResolvedValue({});+ (recordOrganisationUsageEvent as jest.Mock).mockResolvedValue({});++ await generateAPIKey('my-key');++ expect(recordOrganisationUsageEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ organisationId: 'org1',+ featureId: 'platform.api-keys',+ })+ );+ });+it('throws when user is not authenticated', async () => {(getCurrentUser as jest.Mock).mockResolvedValue(null);await expect(generateAPIKey('key')).rejects.toThrow('Unauthorized');diff --git a/src/client/src/__tests__/lib/platform/vault/vault.test.ts b/src/client/src/__tests__/lib/platform/vault/vault.test.tsindex ed72180c..10be4127 100644--- a/src/client/src/__tests__/lib/platform/vault/vault.test.ts+++ b/src/client/src/__tests__/lib/platform/vault/vault.test.ts@@ -204,8 +204,16 @@ describe('upsertSecret', () => {const [insertParams, insertMode] = (dataCollector as jest.Mock).mock.calls[1];expect(insertMode).toBe('insert');expect(insertParams.table).toBe('openlit_vault');- expect(insertParams.values[0]).toMatchObject({ key: 'MY_SECRET', value: 'enc:v1:abc123' });- expect(result).toEqual({ data: {}, message: 'Secret saved!' });+ expect(insertParams.values[0]).toMatchObject({+ id: expect.any(String),+ key: 'MY_SECRET',+ value: 'enc:v1:abc123',+ });+ expect(result).toEqual({+ data: { id: insertParams.values[0].id },+ id: insertParams.values[0].id,+ message: 'Secret saved!',+ });});it('throws UNAUTHORIZED_USER when no user', async () => {diff --git a/src/client/src/__tests__/middleware/middleware.test.ts b/src/client/src/__tests__/middleware/middleware.test.tsindex cde55dee..419e0557 100644--- a/src/client/src/__tests__/middleware/middleware.test.ts+++ b/src/client/src/__tests__/middleware/middleware.test.ts@@ -43,4 +43,9 @@ describe('middleware', () => {it('matcher includes /login route', () => {expect(config.matcher).toContain('/login');});++ it('does not include enterprise-only routes in CE', () => {+ expect(config.matcher).not.toContain('/audit-logs');+ expect(config.matcher).not.toContain('/audit-logs/:path*');+ });});diff --git a/src/client/src/__tests__/utils/api.test.ts b/src/client/src/__tests__/utils/api.test.tsindex dfb38e70..5be5a8c1 100644--- a/src/client/src/__tests__/utils/api.test.ts+++ b/src/client/src/__tests__/utils/api.test.ts@@ -1,13 +1,43 @@import { getData, postData, deleteData } from '@/utils/api';+import { useRootStore } from '@/store';+import { OPENLIT_CONTEXT_HEADERS } from '@/constants/openlit-context';++jest.mock('@/store', () => ({+ useRootStore: {+ getState: jest.fn(),+ },+}));const makeFetchResponse = (ok: boolean, body: unknown) => ({ok,json: jest.fn().mockResolvedValue(body),});+const mockEmptyScope = () => {+ (useRootStore.getState as jest.Mock).mockReturnValue({+ organisation: {},+ project: {},+ databaseConfig: {},+ });+};++const mockSelectedScope = (databaseList = [+ { id: 'db-1', isCurrent: false },+ { id: 'db-2', isCurrent: true },+]) => {+ (useRootStore.getState as jest.Mock).mockReturnValue({+ organisation: { current: { id: 'org-1' } },+ project: { current: { id: 'project-1' } },+ databaseConfig: {+ list: databaseList,+ },+ });+};+describe('getData', () => {beforeEach(() => {global.fetch = jest.fn();+ mockEmptyScope();});it('makes a POST request by default', async () => {@@ -48,6 +78,30 @@ describe('getData', () => {expect(options.body).toBe(JSON.stringify({ key: 'value' }));});+ it('sends selected OpenLIT context headers when state has active scope', async () => {+ (global.fetch as jest.Mock).mockResolvedValue(makeFetchResponse(true, {}));+ mockSelectedScope();++ await getData({ url: '/api/test', method: 'GET' });++ const [, options] = (global.fetch as jest.Mock).mock.calls[0];+ expect(options.headers).toEqual({+ [OPENLIT_CONTEXT_HEADERS.organisationId]: 'org-1',+ [OPENLIT_CONTEXT_HEADERS.projectId]: 'project-1',+ [OPENLIT_CONTEXT_HEADERS.databaseConfigId]: 'db-2',+ });+ });++ it('falls back to first database config when no current config is marked', async () => {+ (global.fetch as jest.Mock).mockResolvedValue(makeFetchResponse(true, {}));+ mockSelectedScope([{ id: 'db-1' }, { id: 'db-2' }]);++ await getData({ url: '/api/test', method: 'GET' });++ const [, options] = (global.fetch as jest.Mock).mock.calls[0];+ expect(options.headers[OPENLIT_CONTEXT_HEADERS.databaseConfigId]).toBe('db-1');+ });+it('makes a PUT request when specified', async () => {(global.fetch as jest.Mock).mockResolvedValue(makeFetchResponse(true, {}));await getData({ url: '/api/test', method: 'PUT', data: { x: 1 } });@@ -58,6 +112,7 @@ describe('getData', () => {describe('postData', () => {beforeEach(() => {global.fetch = jest.fn();+ mockEmptyScope();});it('makes a POST request with JSON body', async () => {@@ -71,6 +126,21 @@ describe('postData', () => {expect(options.body).toBe(JSON.stringify(data));});+ it('merges JSON and OpenLIT context headers', async () => {+ (global.fetch as jest.Mock).mockResolvedValue(makeFetchResponse(true, { ok: true }));+ mockSelectedScope();++ await postData({ url: '/api/items', data: { name: 'test' } });++ const [, options] = (global.fetch as jest.Mock).mock.calls[0];+ expect(options.headers).toEqual({+ 'Content-Type': 'application/json',+ [OPENLIT_CONTEXT_HEADERS.organisationId]: 'org-1',+ [OPENLIT_CONTEXT_HEADERS.projectId]: 'project-1',+ [OPENLIT_CONTEXT_HEADERS.databaseConfigId]: 'db-2',+ });+ });+it('returns parsed JSON on success', async () => {const response = { created: true, id: '42' };(global.fetch as jest.Mock).mockResolvedValue(makeFetchResponse(true, response));@@ -87,12 +157,16 @@ describe('postData', () => {describe('deleteData', () => {beforeEach(() => {global.fetch = jest.fn();+ mockEmptyScope();});it('makes a DELETE request to the given URL', async () => {(global.fetch as jest.Mock).mockResolvedValue(makeFetchResponse(true, { deleted: true }));await deleteData({ url: '/api/items/1' });- expect(global.fetch).toHaveBeenCalledWith('/api/items/1', { method: 'DELETE' });+ expect(global.fetch).toHaveBeenCalledWith('/api/items/1', {+ method: 'DELETE',+ headers: {},+ });});it('returns parsed JSON on success', async () => {@@ -102,6 +176,22 @@ describe('deleteData', () => {expect(result).toEqual(response);});+ it('sends OpenLIT context headers with DELETE requests', async () => {+ (global.fetch as jest.Mock).mockResolvedValue(makeFetchResponse(true, { deleted: true }));+ mockSelectedScope();++ await deleteData({ url: '/api/items/1' });++ expect(global.fetch).toHaveBeenCalledWith('/api/items/1', {+ method: 'DELETE',+ headers: {+ [OPENLIT_CONTEXT_HEADERS.organisationId]: 'org-1',+ [OPENLIT_CONTEXT_HEADERS.projectId]: 'project-1',+ [OPENLIT_CONTEXT_HEADERS.databaseConfigId]: 'db-2',+ },+ });+ });+it('throws when response is not ok', async () => {(global.fetch as jest.Mock).mockResolvedValue(makeFetchResponse(false, 'Not Found'));await expect(deleteData({ url: '/api/items/1' })).rejects.toThrow();diff --git a/src/client/src/components/(playground)/filter/index.tsx b/src/client/src/components/(playground)/filter/index.tsxindex d18aede5..b76094fb 100644--- a/src/client/src/components/(playground)/filter/index.tsx+++ b/src/client/src/components/(playground)/filter/index.tsx@@ -34,7 +34,7 @@ const Filter = ({ className = "" }: { className?: string }) => {};return (- <div className={`flex grow gap-4 ${className}`}>+ <div className={`flex grow items-center gap-4 ${className}`}><Tabs value={filter.timeLimit.type} onValueChange={handleChange}><TabsList className="p-0 h-[30px] border border-stone-200 dark:border-stone-800">{TIME_RANGE_TABS.map(({ label, key }) => (diff --git a/src/client/src/components/(playground)/filter/refresh-rate.tsx b/src/client/src/components/(playground)/filter/refresh-rate.tsxindex 56ba4b5d..a4934bbf 100644--- a/src/client/src/components/(playground)/filter/refresh-rate.tsx+++ b/src/client/src/components/(playground)/filter/refresh-rate.tsx@@ -88,7 +88,7 @@ const RefreshRate = () => {return (<DropdownMenu><DropdownMenuTrigger asChild>- <Button variant="outline" className="flex gap-4 shrink-0 justify-start group-data-[state=close]:justify-center py-1 px-2 overflow-hidden font-normal h-auto w-auto ml-auto text-stone-500 hover:text-stone-600 dark:text-stone-400 dark:hover:text-stone-300 dark:bg-stone-800 dark:hover:bg-stone-900">+ <Button variant="outline" className="ml-auto flex h-[30px] w-auto shrink-0 justify-start gap-4 overflow-hidden px-2 py-1 font-normal text-stone-500 hover:text-stone-600 group-data-[state=close]:justify-center dark:bg-stone-800 dark:text-stone-400 dark:hover:bg-stone-900 dark:hover:text-stone-300"><TimerReset className={`size-3 shrink-0`} /><span className="block text-ellipsis overflow-hidden whitespace-nowrap grow text-xs">{filter.refreshRate}</span><ChevronsUpDown className={`size-3 block shrink-0`} />diff --git a/src/client/src/components/(playground)/header-project-switch.tsx b/src/client/src/components/(playground)/header-project-switch.tsxindex 072d2693..9ecb2c58 100644--- a/src/client/src/components/(playground)/header-project-switch.tsx+++ b/src/client/src/components/(playground)/header-project-switch.tsx@@ -69,11 +69,6 @@ export default function HeaderProjectSwitch() {className={cn(project.isDefault && "font-medium")}><span className="truncate">{project.name}</span>- {project.isDefault ? (- <span className="ml-2 text-xs text-muted-foreground">- {messages.DEFAULT_PROJECT}- </span>- ) : null}</DropdownMenuCheckboxItem>))}<DropdownMenuSeparator />diff --git a/src/client/src/components/(playground)/openground/provider-result-card.tsx b/src/client/src/components/(playground)/openground/provider-result-card.tsxindex b3dc22c5..d21dd0b5 100644--- a/src/client/src/components/(playground)/openground/provider-result-card.tsx+++ b/src/client/src/components/(playground)/openground/provider-result-card.tsx@@ -59,7 +59,7 @@ export default function ProviderResultCard({ result, index }: ProviderResultCard{/* Response/Error Content */}<div className="p-4">{result.error ? (- <div className="text-red-600 dark:text-red-400 text-sm font-mono whitespace-pre-wrap">+ <div className="text-red-600 dark:text-red-400 text-sm font-mono whitespace-pre-wrap break-all">{result.error}</div>) : (diff --git a/src/client/src/constants/openlit-context.ts b/src/client/src/constants/openlit-context.tsnew file mode 100644index 00000000..ed169cc0--- /dev/null+++ b/src/client/src/constants/openlit-context.ts@@ -0,0 +1,5 @@+export const OPENLIT_CONTEXT_HEADERS = {+ organisationId: "x-openlit-organisation-id",+ projectId: "x-openlit-project-id",+ databaseConfigId: "x-openlit-database-config-id",+} as const;diff --git a/src/client/src/lib/billing/usage-recorder.ts b/src/client/src/lib/billing/usage-recorder.tsnew file mode 100644index 00000000..c209f643--- /dev/null+++ b/src/client/src/lib/billing/usage-recorder.ts@@ -0,0 +1,14 @@+import { FeatureId } from "@/features";++export type UsageRecorderInput = {+ organisationId: string;+ projectId?: string | null;+ featureId: FeatureId;+ quantity?: number;+ periodStart: Date;+ periodEnd: Date;+};++export async function recordOrganisationUsageEvent(_input: UsageRecorderInput) {+ return null;+}diff --git a/src/client/src/lib/platform/api-keys/index.ts b/src/client/src/lib/platform/api-keys/index.tsindex aa43a671..f757d910 100644--- a/src/client/src/lib/platform/api-keys/index.ts+++ b/src/client/src/lib/platform/api-keys/index.ts@@ -5,6 +5,8 @@ import prisma from "@/lib/prisma";import { getCurrentUser } from "@/lib/session";import { throwIfError } from "@/utils/error";import getMessage from "@/constants/messages";+import { recordOrganisationUsageEvent } from "@/lib/billing/usage-recorder";+import { getCurrentOrganisation } from "@/lib/organisation";const APIKEY_PREFIX = "openlit-";@@ -37,6 +39,24 @@ export async function generateAPIKey(name: string) {},});+ const currentOrganisation = await getCurrentOrganisation();++ if (currentOrganisation?.id) {+ const periodStart = new Date();+ periodStart.setUTCDate(1);+ periodStart.setUTCHours(0, 0, 0, 0);++ const periodEnd = new Date(periodStart);+ periodEnd.setUTCMonth(periodEnd.getUTCMonth() + 1);++ await recordOrganisationUsageEvent({+ organisationId: currentOrganisation.id,+ featureId: "platform.api-keys",+ periodStart,+ periodEnd,+ });+ }+return {apiKey,databaseConfigId: dbConfig.id,diff --git a/src/client/src/lib/platform/vault/index.ts b/src/client/src/lib/platform/vault/index.tsindex 6476accc..f9e52f9f 100644--- a/src/client/src/lib/platform/vault/index.ts+++ b/src/client/src/lib/platform/vault/index.ts@@ -1,4 +1,5 @@import getMessage from "@/constants/messages";+import { randomUUID } from "crypto";import {SecretGetFilters,SecretGetFiltersWithApiKey,@@ -84,6 +85,7 @@ export async function upsertSecret(secretInputParams: Partial<SecretInput>) {: undefined;const ownerCondition = getOwnerEmailCondition(user!);const ownerEmail = escapeClickHouseString(user!.email || "");+ let createdSecretId: string | undefined;if (!secretInputParams.id) {const { isValid } = await checkNameValidity({@@ -129,11 +131,13 @@ export async function upsertSecret(secretInputParams: Partial<SecretInput>) {return getMessage().SECRET_SAVED;} else {+ createdSecretId = randomUUID();const { err } = await dataCollector({table: OPENLIT_VAULT_TABLE_NAME,values: [{+ id: createdSecretId,key: secretInput.key,value: encryptedValue || "",tags: secretInput.tags,@@ -151,7 +155,8 @@ export async function upsertSecret(secretInputParams: Partial<SecretInput>) {}return {- data: {},+ data: createdSecretId ? { id: createdSecretId } : {},+ id: createdSecretId,message: getMessage().SECRET_SAVED,};}diff --git a/src/client/src/middleware.ts b/src/client/src/middleware.tsindex 4ca78bb1..98c5e525 100644--- a/src/client/src/middleware.ts+++ b/src/client/src/middleware.ts@@ -2,6 +2,7 @@ import { chain } from "@/middleware/chain";import checkAuth from "@/middleware/check-auth";import checkCsrf from "@/middleware/check-csrf";import checkDemoAccount from "@/middleware/check-demo-account";+import { ENTERPRISE_MIDDLEWARE_MATCHERS } from "@/middleware/enterprise-matchers";export const middleware = chain([checkCsrf,@@ -19,6 +20,7 @@ export const config = {"/dashboard","/telemetry","/telemetry/:path*",+ ...ENTERPRISE_MIDDLEWARE_MATCHERS,"/observability","/observability/:path*","/requests",diff --git a/src/client/src/middleware/enterprise-matchers.ts b/src/client/src/middleware/enterprise-matchers.tsnew file mode 100644index 00000000..e1dcfe52--- /dev/null+++ b/src/client/src/middleware/enterprise-matchers.ts@@ -0,0 +1 @@+export const ENTERPRISE_MIDDLEWARE_MATCHERS: string[] = [];diff --git a/src/client/src/utils/api.ts b/src/client/src/utils/api.tsindex 8e03d4ec..9c01169a 100644--- a/src/client/src/utils/api.ts+++ b/src/client/src/utils/api.ts@@ -1,3 +1,6 @@+import { useRootStore } from "@/store";+import { OPENLIT_CONTEXT_HEADERS } from "@/constants/openlit-context";+type GET_DATA = {body?: string;method?: "GET" | "POST" | "PUT" | "PATCH";@@ -5,12 +8,45 @@ type GET_DATA = {data?: Record<string, unknown>;};+function getActiveDatabaseConfigId() {+ const databaseConfigList = useRootStore.getState().databaseConfig.list || [];+ return (+ databaseConfigList.find((item) => item.isCurrent)?.id ||+ databaseConfigList[0]?.id+ );+}++function getOpenLitContextHeaders() {+ if (typeof window === "undefined") return {};++ const state = useRootStore.getState();+ const headers: Record<string, string> = {};+ const organisationId = state.organisation.current?.id;+ const projectId = state.project.current?.id;+ const databaseConfigId = getActiveDatabaseConfigId();++ if (organisationId) headers[OPENLIT_CONTEXT_HEADERS.organisationId] = organisationId;+ if (projectId) headers[OPENLIT_CONTEXT_HEADERS.projectId] = projectId;+ if (databaseConfigId) headers[OPENLIT_CONTEXT_HEADERS.databaseConfigId] = databaseConfigId;++ return headers;+}++function getRequestHeaders(headers?: Record<string, string>) {+ return {+ ...getOpenLitContextHeaders(),+ ...(headers || {}),+ };+}+export async function getData({ body, method = "POST", url, data }: GET_DATA) {const hasBody = !!(body || data);const res = await fetch(url, {body: body || (data ? JSON.stringify(data) : undefined),method,- headers: hasBody ? { "Content-Type": "application/json" } : undefined,+ headers: getRequestHeaders(+ hasBody ? { "Content-Type": "application/json" } : undefined+ ),});if (!res.ok) {const error = await res.json();@@ -30,7 +66,7 @@ type POST_DATA = {export async function postData({ url, data }: POST_DATA) {const res = await fetch(url, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: getRequestHeaders({ "Content-Type": "application/json" }),body: JSON.stringify(data),});if (!res.ok) {@@ -48,7 +84,10 @@ type DELETE_DATA = {};export async function deleteData({ url }: DELETE_DATA) {- const res = await fetch(url, { method: "DELETE" });+ const res = await fetch(url, {+ method: "DELETE",+ headers: getRequestHeaders(),+ });if (!res.ok) {const error = await res.json();throw new Error(