WIP working version

This commit is contained in:
Zebratic committed 2026-02-25 01:41:28 +01:00
1 parent 8b574e280f
commit b4396c6c1a
115 files changed
+17921 -3

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
# Database
DATABASE_URL=mongodb://localhost:27017/llm_proxy
# Redis
REDIS_URL=redis://localhost:6379
# Auth.js
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=generate-a-strong-random-secret-here
# Encryption (64 hex chars = 32 bytes for AES-256)
ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000
# App
NEXT_PUBLIC_APP_NAME=LLM Proxy
NEXT_PUBLIC_APP_URL=http://localhost:3000
+1 -1
View File
@@ -127,4 +127,4 @@ dist
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
.pnp.*
+8
View File
@@ -0,0 +1,8 @@
{
"semi": true,
"singleQuote": false,
"tabWidth": 2,
"trailingComma": "all",
"printWidth": 100,
"plugins": ["prettier-plugin-tailwindcss"]
}
+461
View File
@@ -0,0 +1,461 @@
# CLAUDE.md — Multi‑Provider OpenAI‑Compatible API SaaS
## 1. Mission & elevator pitch
Build a SaaS that exposes a **single OpenAI‑compatible API** (base URL + API key) which fans out to multiple LLM providers (OpenAI, Anthropic, Grok, DeepSeek, Perplexity, etc.).
Users get:
- One base URL and one key.
- Access to many models across providers.
- Centralized billing, limits, and analytics.
- A clean Next.js web app (dashboard + admin).
This repo should be structured so that adding a new AI provider requires **only a new adapter module and configuration**, not touching core routing logic.
---
## 2. High‑level requirements
### Core product
- OpenAI‑compatible API:
- `POST /v1/chat/completions`
- `POST /v1/completions`
- `POST /v1/embeddings`
- `GET /v1/models`
- (Optional later) `POST /v1/moderations`, file endpoints, etc.
- Single **base URL** and **single API key per user** (with ability for users to create multiple keys for their account, each with its own limits and metadata).
- Multi‑provider support from day one:
- OpenAI, Anthropic, Grok, DeepSeek, Perplexity.
- Additional providers must be pluggable via a standard adapter interface.
### Admin features
- Web admin panel with full CRUD for:
- Users and their status (active, banned, trial, etc.).
- Subscription plans, pricing, and usage limits per plan.
- Provider API keys (add/remove/enable/disable).
- Provider key ingestion system:
- Upload `.txt` with one raw key per line.
- System automatically:
- Detects which provider each key belongs to.
- Validates key via a lightweight test call or pattern.
- Fetches / stores basic metadata (rate limits, model access, etc.) where possible.
- Advanced usage stats panel:
- Per provider.
- Per provider API key.
- Per user and per user‑API‑key.
- Time‑series charts (e.g. daily/weekly usage) and breakdown by model.
### User features
- Authenticated user dashboard where users can:
- View and regenerate their own API keys (for this SaaS).
- Create multiple API keys with:
- Custom per‑key limits (requests/day, tokens/day, cost/day).
- Optional tags/labels (e.g. "staging", "prod‑service‑A").
- See usage statistics:
- Requests and tokens over time.
- By model, provider, and user key.
- View API request logs:
- Timestamp, model, provider, latency, tokens, cost, status (success/error).
- (Configurable) truncated prompt/response previews or hash IDs (for privacy).
- Delete logs for privacy/GDPR purposes (soft delete + optional hard delete jobs).
- Account billing section:
- Current plan, remaining quota.
- Upgrade/downgrade plan.
- Invoices and payment history.
---
## 3. Tech stack & major dependencies
**Frontend & backend framework**
- Next.js (App Router, latest stable).
- TypeScript everywhere.
- React Server Components where suitable; client components only where needed.
**UI**
- Tailwind CSS.
- shadcn/ui (or similar) for composable, good‑looking components.
- A design system matching a custom SaaS look (no raw boilerplate UI).
**Backend inside Next.js**
- Next.js Route Handlers for JSON API endpoints.
- Optionally a thin internal service layer (folder like `src/server/`) for domain logic.
**Database & data access**
- MongoDB
**Caching, rate limiting, queues**
- Redis:
- Per‑user/per‑key rate limiting counters.
- Short‑term request metadata caching as needed.
- Background work:
- Either:
- Next.js + cron jobs (e.g. Vercel Cron, or node‑cron in a long‑running environment), or
- A small worker process using BullMQ/Node + Redis.
**Auth**
- Auth.js (NextAuth) or similar:
- Email/password and OAuth (GitHub/Google) as nice‑to‑have.
- JWT sessions or database‑backed sessions.
**Billing**
- Stripe subscriptions:
- Plans aligned with DB `SubscriptionPlan` model.
- Webhooks to update user plan & limits.
**Logging & monitoring**
- Application logs via a standard logger (e.g. pino).
- Request/usage logs written to PostgreSQL (aggregations created via scheduled jobs).
---
## 4. Architecture overview
### Core components
1. **API Gateway Layer (OpenAI‑compatible)**
- Receives requests on `/v1/*`.
- Authenticates using the user’s SaaS API key.
- Normalizes input into an internal `UnifiedRequest` format.
- Selects provider + provider key based on model mapping and routing policies.
- Forwards the request to the appropriate provider adapter.
- Normalizes provider responses to `UnifiedResponse` matching OpenAI format.
2. **Provider Adapter Layer**
- Each provider gets its own module that implements a common interface, e.g.:
```ts
interface ProviderAdapter {
id: 'openai' | 'anthropic' | 'grok' | 'deepseek' | 'perplexity' | string;
// Used during ingestion to guess provider from raw key
matchesApiKeyPattern(key: string): boolean;
// Validate key and optionally fetch metadata
validateApiKey(key: string): Promise<ProviderKeyMetadata>;
// Core operations
chatCompletion(req: UnifiedChatRequest, ctx: ProviderKeyContext): Promise<UnifiedChatResponse>;
completion?(req: UnifiedCompletionRequest, ctx: ProviderKeyContext): Promise<UnifiedCompletionResponse>;
embeddings?(req: UnifiedEmbeddingRequest, ctx: ProviderKeyContext): Promise<UnifiedEmbeddingResponse>;
listModels?(ctx: ProviderKeyContext): Promise<ProviderModelInfo[]>;
}
```
- A registry maps provider IDs to adapters.
- Adding a new provider = new adapter file + config entry.
3. **Routing & Key Selection**
- Model map:
- Internal `model` names exactly match OpenAI naming where possible.
- Mapping table: `logical_model_id` → `{provider_id, provider_model_id}` or list for fallbacks.
- Provider key pool:
- Each provider has many keys, each with:
- Status (active/disabled).
- Remaining quota or soft usage limits.
- Health status (recent errors, last validated time).
- Routing policies:
- Default: round‑robin or least‑used key among active keys for chosen provider/model.
- Fallback:
- If provider returns rate‑limit/5xx, optionally try another provider/model in the mapping chain.
- Future: policies like “cheapest”, “fastest”, etc.
4. **Usage Logging & Analytics Pipeline**
- For each request:
- Synchronous write of a minimal log row (user_id, api_key_id, provider_id, model, tokens_in, tokens_out, success/error, latency).
- Async enrichment:
- Cost calculation from pricing table (per model).
- Aggregation into daily/weekly rollups by:
- User, API key, provider, model, plan.
- Dashboards query rollup tables for performance.
5. **Admin & User Web Apps**
- Same Next.js project, separated by route groups:
- `/dashboard/*` for users.
- `/admin/*` for admins (with role‑based access control).
---
## 5. Data model (high‑level)
Use MongoDB to define schemas similar to:
- `User`
- id, email, name, role (`user`, `admin`), createdAt, etc.
- `SubscriptionPlan`
- id, name, monthlyPrice, requestLimitPerMonth, tokenLimitPerMonth, overagePricePer1kTokens, features JSON, etc.
- `Subscription`
- id, userId, planId, status, currentPeriodStart, currentPeriodEnd, usage counters.
- `UserApiKey`
- id, userId, hashedKey, label, status, dailyRequestLimit, dailyTokenLimit, softCostLimit, createdAt, lastUsedAt.
- `Provider`
- id (openai, anthropic, grok, deepseek, perplexity, etc.), displayName, baseUrl, enabled, config JSON.
- `ProviderApiKey`
- id, providerId, encryptedKey, label, status, lastValidatedAt, errorCount, metadata JSON (rate limits, models, notes).
- `ModelMapping`
- id, logicalModelId (e.g. `gpt-4.1-mini`), providerId, providerModelId, priority, enabled.
- `RequestLog`
- id, userId, userApiKeyId, providerId, providerApiKeyId, logicalModelId, providerModelId, statusCode, errorCode, tokensIn, tokensOut, cost, latencyMs, createdAt.
- Optional fields for truncated prompt/response or hashes.
- `UsageAggregateDaily`
- date, userId, userApiKeyId, providerId, logicalModelId, totalRequests, totalTokensIn, totalTokensOut, totalCost.
- `IngestionBatch`
- id, providerId (optional at upload), status, totalKeys, successfulKeys, failedKeys, createdAt.
---
## 6. API surface (OpenAI‑compatible)
### Authentication
- Header: `Authorization: Bearer <user_api_key>` for this SaaS (not provider keys).
- Optional `X-Request-Id` header for correlation.
### Endpoints
1. `POST /v1/chat/completions`
- Accepts standard OpenAI chat schema: `model`, `messages`, `stream`, `temperature`, etc.
- `model` resolves through `ModelMapping`.
- Supports streaming responses with SSE (compatible with OpenAI clients).
2. `POST /v1/completions`
- Legacy support where needed.
3. `POST /v1/embeddings`
- Accepts OpenAI embeddings schema.
- Routes to providers that support embeddings.
4. `GET /v1/models`
- Returns merged set of logical models with metadata:
- id, owned_by (this SaaS), provider hints, capabilities.
5. (Later phases) `POST /v1/moderations`, image/audio endpoints as providers allow.
### Error format
- Mirror OpenAI’s error structure closely:
- `{"error": {"message": "...", "type": "...", "code": "...", ...}}`
- Include provider error info where safe, but never leak provider keys.
---
## 7. Provider key ingestion & management
### Ingestion flow
- Admin uploads a `.txt` file via `/admin/providers/ingest`:
- One raw API key per line.
- Optional prefix line for metadata, or UI‑provided `providerId` if known.
- Backend logic:
- For each line:
- Trim and ignore empty lines/comments.
- Run through adapter `matchesApiKeyPattern`.
- If ambiguous or none match:
- Try calling a lightweight “who am I” endpoint for providers (if such endpoints exist) or a low‑cost list‑models/completions test.
- Store as `ProviderApiKey` with:
- providerId.
- encryptedKey (use environment key).
- initial status (active or pending).
- metadata JSON with detection results and basic limits.
- Provide ingestion status UI showing:
- Total keys, success count, error reasons, and affected providers.
### Key lifecycle
- Admin can:
- Enable/disable keys.
- Tag keys (e.g. "low‑latency‑region‑EU", "backup").
- See basic health metrics per key: recent errors, last used, estimated remaining quota (where derivable).
---
## 8. Usage statistics & analytics
### Per provider and provider key
- Metrics:
- Requests, tokens, cost, errors, latency distribution.
- Views:
- Time series graphs (per day/week).
- Breakdowns by model.
### Per user and per user API key
- Metrics:
- Same as above, plus:
- % of plan used (requests, tokens, cost).
- Views:
- For users:
- Simple charts and tables.
- For admins:
- Global views, filters by plan, heavy users, etc.
### Data pipeline
- Real‑time counters in Redis can back UI for “today’s usage”.
- Nightly job aggregates logs into `UsageAggregateDaily`.
---
## 9. User dashboard
### Overview page
- Current plan and remaining quota.
- Sparkline or chart of recent usage (requests/tokens per day).
- Quick links to create API keys and view logs.
### API key management
- List of keys with:
- Label, createdAt, lastUsedAt, status.
- Daily limits and soft cost limits.
- Actions:
- Create new key.
- Regenerate key (invalidates old one).
- Edit limits and labels.
- Disable/enable key.
- Delete key (with confirmation).
### Request logs
- Paginated table:
- Time, model, provider, latency, tokens, cost, status.
- Filters:
- Date range, model, provider, status, API key.
- Log deletion:
- Single log or bulk within date range.
- UI warns about permanent deletion (or marks soft deletion with background purge).
### Billing
- Show:
- Current subscription plan and renewal date.
- Usage vs plan limits.
- Invoices & payment method.
- Actions:
- Upgrade/downgrade via Stripe Checkout/Customer Portal.
---
## 10. Admin panel
### Users
- Table of users:
- Email, role, plan, status, usage summary.
- Detail view:
- Reset password/email link.
- Force plan change.
- Suspend user.
- View user’s API keys and usage metrics.
### Subscription plans
- CRUD for plans:
- Name, description, price, limits, flags (e.g. “allow BYOK”, “priority routing”).
- Mark certain plans as public/hidden.
### Providers & keys
- Providers list:
- Enable/disable provider globally.
- Adjust base URLs, timeouts.
- Provider keys:
- List with status and usage.
- Ingestion batches management.
- Buttons to test a key and refresh metadata.
### System metrics
- Global charts:
- Requests/day across all users.
- Cost vs revenue estimation.
- Error rate and provider health.
---
## 11. Security, privacy & compliance
- Encrypt provider keys at rest with strong symmetric encryption (e.g. AES‑256‑GCM).
- Never log provider keys or user API keys in plain text.
- Allow users to:
- Opt out of prompt/response logging (store only metadata).
- Delete logs (with real deletion within a defined time frame).
- Rate limiting per user key to mitigate abuse.
- Store minimal PII; consider GDPR requirements for EU users.
---
## 12. Modularity & future providers
Design goal: **zero core changes to add a provider**.
- Provider adapter interface is the only place provider‑specific logic lives.
- Model mapping table decides which adapter is hit.
- Pricing, limits, and metadata are stored in DB, not hard‑coded.
- For future providers (e.g. local models, self‑hosted):
- Implement same adapter interface.
- Add models to `ModelMapping`.
---
## 13. Implementation phases
### ✅ Phase 1 — Functional MVP
- Implement:
- Core DB schema.
- User auth and basic dashboard.
- Single provider (e.g. OpenAI) through adapter.
- `/v1/chat/completions` + `/v1/models` only.
- Basic logs and per‑user API keys.
- Minimal admin UI for users and provider keys.
### ✅ Phase 2 — Multi‑provider & analytics
- Add:
- Anthropic, DeepSeek, Perplexity, Grok adapters.
- `ModelMapping`‑based routing.
- Provider key ingestion from `.txt` files.
- Full usage logging + daily aggregates.
- User dashboard charts and filters.
### ✅ Phase 3 — Competitive features
- Implement:
- Auto fallback routing, routing policies.
- Advanced plan system + Stripe billing.
- Fine‑grained per‑key limits & cost caps.
- Better admin dashboards and global analytics.
- Optional prompt/response logging controls.
---
## 14. Developer experience & quality
- Use strict TypeScript and ESLint + Prettier.
- Organize code by domain:
- `src/app` (Next routes).
- `src/server` (services, adapters, routing logic).
- `src/lib` (shared helpers).
- `src/components` (UI building blocks).
- Provide seed script to create:
- Default admin user.
- Example subscription plans.
- Example provider and model mappings.
- Include unit tests for:
- Provider adapters (mocking HTTP).
- Routing logic.
- Usage aggregation logic.
- Include end‑to‑end tests for:
- Basic API flow (chat completion).
- Dashboard and admin flows (Playwright or similar).
+114 -2
View File
@@ -1,2 +1,114 @@
# llm-proxy-api
A centralized OpenAI compatible API for all other major providers with rotating API keys support
# LLM Proxy API
OpenAI-compatible gateway with user auth, API key management, usage analytics, and admin controls.
## Quick Start
1. Install dependencies:
```bash
npm install
```
2. Create env file:
```bash
cp .env.example .env
```
3. Run services (MongoDB + Redis), then seed:
```bash
npm run db:seed
```
4. Start app:
```bash
npm run dev
```
App runs at `http://localhost:3000`.
## Getting Your User API Key
1. Register at `/register`
2. Login and open `/dashboard/api-keys`
3. Create a key and copy it (shown once)
4. Use it as:
```bash
Authorization: Bearer lp_...
```
## OpenAI-Compatible Endpoints
- `POST /v1/chat/completions`
- `GET /v1/models`
## cURL Examples
### List models
```bash
curl -s http://localhost:3000/v1/models \
-H "Authorization: Bearer $LLM_PROXY_API_KEY"
```
### Chat completion
```bash
curl -s http://localhost:3000/v1/chat/completions \
-H "Authorization: Bearer $LLM_PROXY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4.1-mini",
"messages": [
{ "role": "user", "content": "Say hello from LLM Proxy" }
]
}'
```
## Using With Claude Code
Claude Code can call any OpenAI-compatible endpoint. Point it to this proxy instead of a vendor URL.
### Option A: one-off command
```bash
claude \
--model gpt-4.1-mini \
--openai-api-base http://localhost:3000/v1 \
--openai-api-key "$LLM_PROXY_API_KEY"
```
### Option B: shell profile env vars
```bash
export OPENAI_API_BASE="http://localhost:3000/v1"
export OPENAI_API_KEY="$LLM_PROXY_API_KEY"
```
Then run:
```bash
claude --model gpt-4.1-mini
```
## Using With Other OpenAI-Compatible Tools
Any SDK/client that supports custom base URL works. Set:
- Base URL: `http://localhost:3000/v1`
- API key: your LLM Proxy user key
Example in JS:
```ts
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.LLM_PROXY_API_KEY,
baseURL: "http://localhost:3000/v1",
});
```
+20
View File
@@ -0,0 +1,20 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "tailwind.config.ts",
"css": "src/app/globals.css",
"baseColor": "zinc",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
}
}
+31
View File
@@ -0,0 +1,31 @@
module.exports = {
apps: [
{
name: "llm-proxy-api",
script: "npm",
args: "run start:pm2",
cwd: __dirname,
env_file: ".env",
watch: ["src", "scripts", "package.json", "next.config.ts", ".env"],
watch_delay: 1000,
watch_options: {
followSymlinks: false,
usePolling: true,
interval: 1000,
},
ignore_watch: [
"node_modules",
".next",
".git",
"logs",
"dist",
"build",
"coverage",
"public",
],
max_memory_restart: "1G",
instances: 1,
exec_mode: "fork",
},
],
};
+16
View File
@@ -0,0 +1,16 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
];
export default eslintConfig;
+6
View File
@@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
+7
View File
@@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
serverExternalPackages: ["pino", "pino-pretty"],
};
export default nextConfig;
+9048
View File
File diff suppressed because it is too large. Load diff
+63
View File
@@ -0,0 +1,63 @@
{
"name": "llm-proxy-api",
"version": "1.0.0",
"private": true,
"description": "A centralized OpenAI compatible API for all other major providers with rotating API keys support",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"start:pm2": "next build && next start -p 3000",
"lint": "next lint",
"typecheck": "tsc --noEmit",
"test:smoke": "tsx scripts/smoke-check.ts",
"format": "prettier --write .",
"db:seed": "tsx scripts/seed.ts"
},
"dependencies": {
"@radix-ui/react-dialog": "^1.1.14",
"@radix-ui/react-dropdown-menu": "^2.1.14",
"@radix-ui/react-label": "^2.1.6",
"@radix-ui/react-select": "^2.2.4",
"@radix-ui/react-separator": "^1.1.6",
"@radix-ui/react-slot": "^1.2.3",
"@radix-ui/react-switch": "^1.2.6",
"@radix-ui/react-tabs": "^1.1.11",
"@radix-ui/react-toast": "^1.2.14",
"bcryptjs": "^2.4.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
"dotenv": "^17.3.1",
"ioredis": "^5.6.1",
"lucide-react": "^0.513.0",
"mongodb": "^7.1.0",
"nanoid": "^5.1.5",
"next": "^15.3.3",
"next-auth": "^4.24.11",
"pino": "^9.7.0",
"pino-pretty": "^13.0.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"recharts": "^3.7.0",
"sonner": "^2.0.3",
"tailwind-merge": "^3.3.0",
"zod": "^3.25.20"
},
"devDependencies": {
"@eslint/eslintrc": "^3.3.4",
"@tailwindcss/postcss": "^4.1.8",
"@types/bcryptjs": "^2.4.6",
"@types/node": "^22.15.21",
"@types/react": "^19.1.4",
"@types/react-dom": "^19.1.5",
"eslint": "^9.27.0",
"eslint-config-next": "^15.3.3",
"postcss": "^8.5.4",
"prettier": "^3.5.3",
"prettier-plugin-tailwindcss": "^0.6.12",
"tailwindcss": "^4.1.8",
"tsx": "^4.19.4",
"typescript": "^5.8.3"
}
}
+7
View File
@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;
+238
View File
@@ -0,0 +1,238 @@
// @ts-nocheck
import "dotenv/config";
import { hash } from "bcryptjs";
import { MongoClient } from "mongodb";
function getDatabaseUrl() {
const url = process.env.DATABASE_URL;
if (!url) throw new Error("Missing DATABASE_URL.");
return url;
}
function getDatabaseNameFromUrl(urlString: string) {
const parsed = new URL(urlString);
const dbName = parsed.pathname.replace("/", "");
return dbName || "test";
}
async function main() {
console.log("Seeding database...");
const databaseUrl = getDatabaseUrl();
const client = new MongoClient(databaseUrl);
await client.connect();
const db = client.db(getDatabaseNameFromUrl(databaseUrl));
try {
const now = new Date();
const plans = [
{
name: "free",
displayName: "Free",
description: "Get started with basic access",
monthlyPriceCents: 0,
dailyRequestLimit: 100,
dailyTokenLimit: 100000,
requestLimitPerMonth: 3000,
tokenLimitPerMonth: 3000000,
maxApiKeys: 2,
sortOrder: 0,
isPublic: true,
},
{
name: "pro",
displayName: "Pro",
description: "For developers and small teams",
monthlyPriceCents: 2900,
dailyRequestLimit: 5000,
dailyTokenLimit: 2000000,
requestLimitPerMonth: 150000,
tokenLimitPerMonth: 60000000,
maxApiKeys: 10,
sortOrder: 1,
isPublic: true,
},
{
name: "enterprise",
displayName: "Enterprise",
description: "Unlimited access for large teams",
monthlyPriceCents: 9900,
dailyRequestLimit: null,
dailyTokenLimit: null,
requestLimitPerMonth: null,
tokenLimitPerMonth: null,
maxApiKeys: 50,
sortOrder: 2,
isPublic: true,
},
];
for (const plan of plans) {
await db.collection("subscription_plans").updateOne(
{ name: plan.name },
{
$setOnInsert: {
_id: crypto.randomUUID(),
createdAt: now,
},
$set: {
updatedAt: now,
...plan,
},
},
{ upsert: true },
);
}
console.log(" Plans created");
const proPlan = await db.collection<{ _id: string }>("subscription_plans").findOne({ name: "pro" });
if (!proPlan) throw new Error("Pro plan not found after upsert.");
const adminEmail = "[email protected]";
const adminPassword = await hash("admin123", 12);
const existingAdmin = await db.collection<{ _id: string }>("users").findOne({ email: adminEmail });
const adminId = existingAdmin?._id ?? crypto.randomUUID();
await db.collection("users").updateOne(
{ email: adminEmail },
{
$setOnInsert: {
_id: adminId,
email: adminEmail,
passwordHash: adminPassword,
name: "Admin",
role: "ADMIN",
status: "ACTIVE",
createdAt: now,
},
$set: {
updatedAt: now,
},
},
{ upsert: true },
);
await db.collection("subscriptions").updateOne(
{ userId: adminId },
{
$setOnInsert: {
_id: crypto.randomUUID(),
userId: adminId,
planId: proPlan._id,
status: "ACTIVE",
currentPeriodStart: now,
currentPeriodEnd: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000),
createdAt: now,
},
$set: {
updatedAt: now,
},
},
{ upsert: true },
);
console.log(` Admin user created: ${adminEmail} / admin123`);
const providers = [
{ id: "openai", displayName: "OpenAI", baseUrl: "https://api.openai.com" },
{ id: "anthropic", displayName: "Anthropic", baseUrl: "https://api.anthropic.com" },
{ id: "grok", displayName: "Grok (xAI)", baseUrl: "https://api.x.ai" },
{ id: "deepseek", displayName: "DeepSeek", baseUrl: "https://api.deepseek.com" },
{ id: "perplexity", displayName: "Perplexity", baseUrl: "https://api.perplexity.ai" },
];
for (const provider of providers) {
await db.collection("providers").updateOne(
{ _id: provider.id },
{
$setOnInsert: { createdAt: now },
$set: {
displayName: provider.displayName,
baseUrl: provider.baseUrl,
enabled: true,
updatedAt: now,
},
},
{ upsert: true },
);
}
console.log(" Providers created");
const mappings = [
{ logicalModelId: "gpt-4o", providerId: "openai", providerModelId: "gpt-4o", priority: 0 },
{ logicalModelId: "gpt-4o-mini", providerId: "openai", providerModelId: "gpt-4o-mini", priority: 0 },
{ logicalModelId: "gpt-4.1", providerId: "openai", providerModelId: "gpt-4.1", priority: 0 },
{ logicalModelId: "gpt-4.1-mini", providerId: "openai", providerModelId: "gpt-4.1-mini", priority: 0 },
{ logicalModelId: "gpt-4.1-nano", providerId: "openai", providerModelId: "gpt-4.1-nano", priority: 0 },
{ logicalModelId: "o3", providerId: "openai", providerModelId: "o3", priority: 0 },
{ logicalModelId: "o3-mini", providerId: "openai", providerModelId: "o3-mini", priority: 0 },
{ logicalModelId: "o4-mini", providerId: "openai", providerModelId: "o4-mini", priority: 0 },
{
logicalModelId: "claude-sonnet-4-20250514",
providerId: "anthropic",
providerModelId: "claude-sonnet-4-20250514",
priority: 0,
},
{
logicalModelId: "claude-haiku-4-20250414",
providerId: "anthropic",
providerModelId: "claude-haiku-4-20250414",
priority: 0,
},
{
logicalModelId: "claude-opus-4-20250514",
providerId: "anthropic",
providerModelId: "claude-opus-4-20250514",
priority: 0,
},
{ logicalModelId: "deepseek-chat", providerId: "deepseek", providerModelId: "deepseek-chat", priority: 0 },
{
logicalModelId: "deepseek-reasoner",
providerId: "deepseek",
providerModelId: "deepseek-reasoner",
priority: 0,
},
{ logicalModelId: "grok-3", providerId: "grok", providerModelId: "grok-3", priority: 0 },
{ logicalModelId: "grok-3-mini", providerId: "grok", providerModelId: "grok-3-mini", priority: 0 },
{ logicalModelId: "sonar", providerId: "perplexity", providerModelId: "sonar", priority: 0 },
{ logicalModelId: "sonar-pro", providerId: "perplexity", providerModelId: "sonar-pro", priority: 0 },
{
logicalModelId: "sonar-reasoning",
providerId: "perplexity",
providerModelId: "sonar-reasoning",
priority: 0,
},
{
logicalModelId: "sonar-reasoning-pro",
providerId: "perplexity",
providerModelId: "sonar-reasoning-pro",
priority: 0,
},
];
for (const mapping of mappings) {
await db.collection("model_mappings").updateOne(
{
logicalModelId: mapping.logicalModelId,
providerId: mapping.providerId,
providerModelId: mapping.providerModelId,
},
{
$setOnInsert: { _id: crypto.randomUUID(), createdAt: now },
$set: { ...mapping, enabled: true, updatedAt: now },
},
{ upsert: true },
);
}
console.log(` ${mappings.length} model mappings created`);
console.log("\nSeed complete!");
console.log(" Admin login: [email protected] / admin123");
} finally {
await client.close();
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
+33
View File
@@ -0,0 +1,33 @@
import { strict as assert } from "node:assert";
import { detectProvider, getAllAdapters } from "@/server/adapters";
import { completionSchema } from "@/lib/validations/completion";
import { embeddingsSchema } from "@/lib/validations/embeddings";
function runSmokeChecks() {
const adapters = getAllAdapters();
const ids = adapters.map((a) => a.id).sort();
assert(ids.includes("openai"));
assert(ids.includes("anthropic"));
assert(ids.includes("grok"));
assert(ids.includes("deepseek"));
assert(ids.includes("perplexity"));
assert.equal(detectProvider("sk-ant-abc123")?.id, "anthropic");
assert.equal(detectProvider("xai-abc123")?.id, "grok");
assert.equal(detectProvider("pplx-abc123")?.id, "perplexity");
const completion = completionSchema.safeParse({
model: "gpt-4.1-mini",
prompt: "hello",
});
assert.equal(completion.success, true);
const embeddings = embeddingsSchema.safeParse({
model: "text-embedding-3-small",
input: "hello",
});
assert.equal(embeddings.success, true);
}
runSmokeChecks();
console.log("Smoke checks passed");
+7
View File
@@ -0,0 +1,7 @@
export default function AuthLayout({ children }: { children: React.ReactNode }) {
return (
<div className="flex min-h-screen items-center justify-center bg-muted/40 p-4">
<div className="w-full max-w-md">{children}</div>
</div>
);
}
+107
View File
@@ -0,0 +1,107 @@
"use client";
import { signIn } from "next-auth/react";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useState } from "react";
import Link from "next/link";
export default function LoginPage() {
return (
<Suspense>
<LoginForm />
</Suspense>
);
}
function LoginForm() {
const router = useRouter();
const searchParams = useSearchParams();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const callbackUrl = searchParams.get("callbackUrl") ?? "/dashboard";
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError("");
setLoading(true);
const result = await signIn("credentials", {
email,
password,
redirect: false,
});
setLoading(false);
if (result?.error) {
setError("Invalid email or password.");
return;
}
router.push(callbackUrl);
router.refresh();
}
return (
<div className="rounded-lg border bg-card p-8 shadow-sm">
<div className="mb-6 text-center">
<h1 className="text-2xl font-bold">Sign In</h1>
<p className="mt-1 text-sm text-muted-foreground">Enter your credentials to continue</p>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">{error}</div>
)}
<div>
<label htmlFor="email" className="mb-1.5 block text-sm font-medium">
Email
</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
placeholder="[email protected]"
/>
</div>
<div>
<label htmlFor="password" className="mb-1.5 block text-sm font-medium">
Password
</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
placeholder="••••••••"
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
>
{loading ? "Signing in..." : "Sign In"}
</button>
</form>
<p className="mt-4 text-center text-sm text-muted-foreground">
Don&apos;t have an account?{" "}
<Link href="/register" className="text-primary hover:underline">
Register
</Link>
</p>
</div>
);
}
+150
View File
@@ -0,0 +1,150 @@
"use client";
import { signIn } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import Link from "next/link";
export default function RegisterPage() {
const router = useRouter();
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError("");
if (password !== confirmPassword) {
setError("Passwords do not match.");
return;
}
setLoading(true);
const res = await fetch("/api/auth/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, email, password, confirmPassword }),
});
setLoading(false);
if (!res.ok) {
const data = await res.json();
setError(data.error ?? "Registration failed.");
return;
}
const loginResult = await signIn("credentials", {
email,
password,
redirect: false,
});
if (loginResult?.error) {
setError("Account created, but auto-login failed. Please sign in manually.");
router.push("/login?registered=true");
return;
}
router.push("/dashboard");
router.refresh();
}
return (
<div className="rounded-lg border bg-card p-8 shadow-sm">
<div className="mb-6 text-center">
<h1 className="text-2xl font-bold">Create Account</h1>
<p className="mt-1 text-sm text-muted-foreground">Get started with LLM Proxy</p>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">{error}</div>
)}
<div>
<label htmlFor="username" className="mb-1.5 block text-sm font-medium">
Username
</label>
<input
id="username"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
minLength={3}
className="w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
placeholder="yourusername"
/>
</div>
<div>
<label htmlFor="email" className="mb-1.5 block text-sm font-medium">
Email
</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
placeholder="[email protected]"
/>
</div>
<div>
<label htmlFor="password" className="mb-1.5 block text-sm font-medium">
Password
</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={8}
className="w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
placeholder="••••••••"
/>
</div>
<div>
<label htmlFor="confirm-password" className="mb-1.5 block text-sm font-medium">
Confirm Password
</label>
<input
id="confirm-password"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
minLength={8}
className="w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
placeholder="••••••••"
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
>
{loading ? "Creating account..." : "Create Account"}
</button>
</form>
<p className="mt-4 text-center text-sm text-muted-foreground">
Already have an account?{" "}
<Link href="/login" className="text-primary hover:underline">
Sign in
</Link>
</p>
</div>
);
}
+114
View File
@@ -0,0 +1,114 @@
import { db } from "@/lib/db";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { AdminAnalyticsCharts } from "@/components/admin/admin-analytics-charts";
import { formatDateSafe } from "@/lib/date";
export default async function AdminAnalyticsPage() {
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
const [providerStats, daily] = await Promise.all([
db.requestLog.groupBy({
by: ["providerId"],
where: { createdAt: { gte: thirtyDaysAgo }, softDeleted: false },
_count: { _all: true },
_sum: { tokensIn: true, tokensOut: true, costCents: true },
orderBy: { providerId: "asc" },
take: 10,
}),
db.usageAggregateDaily.groupBy({
by: ["date"],
where: { date: { gte: thirtyDaysAgo }, userApiKeyId: null },
_sum: { totalRequests: true, totalTokensIn: true, totalTokensOut: true, totalCostCents: true, totalErrors: true },
orderBy: { date: "desc" },
take: 30,
}),
]);
const providerChart = providerStats.map((row) => ({
name: row.providerId,
requests: (row._count as { _all: number })._all,
cost: Number((((row._sum as { costCents?: number } | null)?.costCents ?? 0) / 100).toFixed(2)),
}));
const dailyChart = daily
.slice()
.reverse()
.map((row) => ({
date: formatDateSafe(row.date),
requests: (row._sum as { totalRequests?: number } | null)?.totalRequests ?? 0,
errors: (row._sum as { totalErrors?: number } | null)?.totalErrors ?? 0,
cost: Number(((((row._sum as { totalCostCents?: number } | null)?.totalCostCents ?? 0) / 100)).toFixed(2)),
}));
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">Analytics</h1>
<AdminAnalyticsCharts providers={providerChart} daily={dailyChart} />
<Card>
<CardHeader>
<CardTitle>Top Providers (30 days)</CardTitle>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Provider</TableHead>
<TableHead>Requests</TableHead>
<TableHead>Tokens In</TableHead>
<TableHead>Tokens Out</TableHead>
<TableHead>Cost</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{providerStats.map((row) => (
<TableRow key={row.providerId}>
<TableCell>{row.providerId}</TableCell>
<TableCell>{(row._count as { _all: number })._all}</TableCell>
<TableCell>{(((row._sum as { tokensIn?: number } | null)?.tokensIn ?? 0)).toLocaleString()}</TableCell>
<TableCell>{(((row._sum as { tokensOut?: number } | null)?.tokensOut ?? 0)).toLocaleString()}</TableCell>
<TableCell>${((((row._sum as { costCents?: number } | null)?.costCents ?? 0) / 100)).toFixed(2)}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Daily Totals (30 days)</CardTitle>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Date</TableHead>
<TableHead>Requests</TableHead>
<TableHead>Tokens In</TableHead>
<TableHead>Tokens Out</TableHead>
<TableHead>Errors</TableHead>
<TableHead>Cost</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{daily.map((row) => (
<TableRow key={String(row.date)}>
<TableCell>{formatDateSafe(row.date)}</TableCell>
<TableCell>{(((row._sum as { totalRequests?: number } | null)?.totalRequests ?? 0)).toLocaleString()}</TableCell>
<TableCell>{(((row._sum as { totalTokensIn?: number } | null)?.totalTokensIn ?? 0)).toLocaleString()}</TableCell>
<TableCell>{(((row._sum as { totalTokensOut?: number } | null)?.totalTokensOut ?? 0)).toLocaleString()}</TableCell>
<TableCell>{(((row._sum as { totalErrors?: number } | null)?.totalErrors ?? 0)).toLocaleString()}</TableCell>
<TableCell>${((((row._sum as { totalCostCents?: number } | null)?.totalCostCents ?? 0) / 100)).toFixed(2)}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
</div>
);
}
+20
View File
@@ -0,0 +1,20 @@
import { redirect } from "next/navigation";
import { getSession } from "@/lib/auth-helpers";
import { Sidebar } from "@/components/layout/sidebar";
import { Header } from "@/components/layout/header";
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
const session = await getSession();
if (!session) redirect("/login");
if (session.user.role !== "ADMIN") redirect("/dashboard");
return (
<div className="flex h-screen">
<Sidebar variant="admin" />
<div className="flex flex-1 flex-col overflow-hidden">
<Header />
<main className="flex-1 overflow-y-auto p-6">{children}</main>
</div>
</div>
);
}
+50
View File
@@ -0,0 +1,50 @@
import { db } from "@/lib/db";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
export default async function AdminModelMappingsPage() {
const mappings = await db.modelMapping.findMany({
include: { provider: { select: { displayName: true } } },
orderBy: [{ logicalModelId: "asc" }, { priority: "asc" }],
});
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">Model Mappings</h1>
<Card>
<CardHeader>
<CardTitle>All Mappings ({mappings.length})</CardTitle>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Logical Model</TableHead>
<TableHead>Provider</TableHead>
<TableHead>Provider Model</TableHead>
<TableHead>Priority</TableHead>
<TableHead>Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{mappings.map((mapping) => (
<TableRow key={mapping.id}>
<TableCell className="font-mono text-sm">{mapping.logicalModelId}</TableCell>
<TableCell>{mapping.provider.displayName}</TableCell>
<TableCell className="font-mono text-sm">{mapping.providerModelId}</TableCell>
<TableCell>{mapping.priority}</TableCell>
<TableCell>
<Badge variant={mapping.enabled ? "default" : "secondary"}>
{mapping.enabled ? "Enabled" : "Disabled"}
</Badge>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
</div>
);
}
+43
View File
@@ -0,0 +1,43 @@
import { db } from "@/lib/db";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Users, Server, Key, Activity } from "lucide-react";
export default async function AdminOverview() {
const [userCount, providerCount, providerKeyCount, todayLogs] = await Promise.all([
db.user.count(),
db.provider.count({ where: { enabled: true } }),
db.providerApiKey.count({ where: { status: "ACTIVE" } }),
db.requestLog.count({
where: {
createdAt: { gte: new Date(new Date().setUTCHours(0, 0, 0, 0)) },
softDeleted: false,
},
}),
]);
const stats = [
{ title: "Total Users", value: userCount, icon: Users },
{ title: "Active Providers", value: providerCount, icon: Server },
{ title: "Active Provider Keys", value: providerKeyCount, icon: Key },
{ title: "Requests Today", value: todayLogs, icon: Activity },
];
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">Admin Overview</h1>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{stats.map((stat) => (
<Card key={stat.title}>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">{stat.title}</CardTitle>
<stat.icon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stat.value}</div>
</CardContent>
</Card>
))}
</div>
</div>
);
}
+11
View File
@@ -0,0 +1,11 @@
import { db } from "@/lib/db";
import { PlanManagement, type PlanRow } from "@/components/admin/plan-management";
export default async function AdminPlansPage() {
const plans = (await db.subscriptionPlan.findMany({
include: { _count: { select: { subscriptions: true } } },
orderBy: { sortOrder: "asc" },
})) as unknown as PlanRow[];
return <PlanManagement initialPlans={plans} />;
}
@@ -0,0 +1,127 @@
import { notFound } from "next/navigation";
import { db } from "@/lib/db";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
export default async function AdminProviderDetailPage({ params }: { params: Promise<{ providerId: string }> }) {
const { providerId } = await params;
const provider = (await db.provider.findUnique({
where: { id: providerId },
include: {
modelMappings: { orderBy: [{ logicalModelId: "asc" }, { priority: "asc" }] },
apiKeys: {
select: {
id: true,
label: true,
status: true,
lastValidatedAt: true,
lastUsedAt: true,
errorCount: true,
createdAt: true,
},
orderBy: { createdAt: "desc" },
},
},
})) as
| {
id: string;
displayName: string;
baseUrl: string;
apiKeys: Array<{
id: string;
label: string | null;
status: string;
lastValidatedAt: string | Date | null;
lastUsedAt: string | Date | null;
errorCount: number;
createdAt: string | Date;
}>;
modelMappings: Array<{
id: string;
logicalModelId: string;
providerModelId: string;
priority: number;
enabled: boolean;
}>;
}
| null;
if (!provider) return notFound();
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold">{provider.displayName}</h1>
<p className="text-sm text-muted-foreground font-mono">{provider.baseUrl}</p>
</div>
<Card>
<CardHeader>
<CardTitle>Provider Keys ({provider.apiKeys.length})</CardTitle>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Label</TableHead>
<TableHead>Status</TableHead>
<TableHead>Errors</TableHead>
<TableHead>Last Validated</TableHead>
<TableHead>Last Used</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{provider.apiKeys.map((key) => (
<TableRow key={key.id}>
<TableCell className="font-mono text-xs">{key.id}</TableCell>
<TableCell>{key.label ?? "-"}</TableCell>
<TableCell>
<Badge variant={key.status === "ACTIVE" ? "default" : "secondary"}>{key.status}</Badge>
</TableCell>
<TableCell>{key.errorCount}</TableCell>
<TableCell>{key.lastValidatedAt ? new Date(key.lastValidatedAt).toLocaleString() : "-"}</TableCell>
<TableCell>{key.lastUsedAt ? new Date(key.lastUsedAt).toLocaleString() : "-"}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Model Mappings ({provider.modelMappings.length})</CardTitle>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Logical Model</TableHead>
<TableHead>Provider Model</TableHead>
<TableHead>Priority</TableHead>
<TableHead>Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{provider.modelMappings.map((mapping) => (
<TableRow key={mapping.id}>
<TableCell className="font-mono text-sm">{mapping.logicalModelId}</TableCell>
<TableCell className="font-mono text-sm">{mapping.providerModelId}</TableCell>
<TableCell>{mapping.priority}</TableCell>
<TableCell>
<Badge variant={mapping.enabled ? "default" : "secondary"}>
{mapping.enabled ? "Enabled" : "Disabled"}
</Badge>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
</div>
);
}
+5
View File
@@ -0,0 +1,5 @@
import { redirect } from "next/navigation";
export default function ProviderIngestionPage() {
redirect("/admin/providers?tab=ingestion");
}
+5
View File
@@ -0,0 +1,5 @@
import { ProviderManagement } from "@/components/admin/provider-management";
export default function AdminProvidersPage() {
return <ProviderManagement />;
}
+146
View File
@@ -0,0 +1,146 @@
import { notFound } from "next/navigation";
import { db } from "@/lib/db";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
export default async function AdminUserDetailPage({ params }: { params: Promise<{ userId: string }> }) {
const { userId } = await params;
const user = (await db.user.findUnique({
where: { id: userId },
include: {
subscription: { include: { plan: true } },
apiKeys: { orderBy: { createdAt: "desc" } },
requestLogs: {
where: { softDeleted: false },
orderBy: { createdAt: "desc" },
take: 20,
},
},
})) as
| {
id: string;
email: string;
role: "USER" | "ADMIN";
status: "ACTIVE" | "SUSPENDED" | "BANNED";
subscription: null | {
status: string;
currentPeriodEnd: string | Date;
plan: { displayName: string };
};
apiKeys: Array<{
id: string;
keyPrefix: string;
label: string | null;
status: string;
lastUsedAt: string | Date | null;
createdAt: string | Date;
}>;
requestLogs: Array<{
id: string;
createdAt: string | Date;
logicalModelId: string;
providerId: string;
statusCode: number;
tokensIn: number;
tokensOut: number;
costCents: number | null;
}>;
}
| null;
if (!user) return notFound();
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold">{user.email}</h1>
<div className="mt-2 flex items-center gap-2">
<Badge variant={user.role === "ADMIN" ? "default" : "secondary"}>{user.role}</Badge>
<Badge variant={user.status === "ACTIVE" ? "outline" : "destructive"}>{user.status}</Badge>
</div>
</div>
<Card>
<CardHeader>
<CardTitle>Subscription</CardTitle>
</CardHeader>
<CardContent className="text-sm">
{user.subscription ? (
<div className="space-y-1">
<p>Plan: {user.subscription.plan.displayName}</p>
<p>Status: {user.subscription.status}</p>
<p>Period Ends: {new Date(user.subscription.currentPeriodEnd).toLocaleDateString()}</p>
</div>
) : (
<p className="text-muted-foreground">No active subscription.</p>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>API Keys ({user.apiKeys.length})</CardTitle>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Prefix</TableHead>
<TableHead>Label</TableHead>
<TableHead>Status</TableHead>
<TableHead>Last Used</TableHead>
<TableHead>Created</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{user.apiKeys.map((key) => (
<TableRow key={key.id}>
<TableCell className="font-mono text-sm">{key.keyPrefix}</TableCell>
<TableCell>{key.label ?? "-"}</TableCell>
<TableCell>{key.status}</TableCell>
<TableCell>{key.lastUsedAt ? new Date(key.lastUsedAt).toLocaleString() : "-"}</TableCell>
<TableCell>{new Date(key.createdAt).toLocaleDateString()}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Recent Logs ({user.requestLogs.length})</CardTitle>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Time</TableHead>
<TableHead>Model</TableHead>
<TableHead>Provider</TableHead>
<TableHead>Status</TableHead>
<TableHead>Tokens</TableHead>
<TableHead>Cost</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{user.requestLogs.map((log) => (
<TableRow key={log.id}>
<TableCell>{new Date(log.createdAt).toLocaleString()}</TableCell>
<TableCell className="font-mono text-sm">{log.logicalModelId}</TableCell>
<TableCell>{log.providerId}</TableCell>
<TableCell>{log.statusCode}</TableCell>
<TableCell>
{log.tokensIn}/{log.tokensOut}
</TableCell>
<TableCell>{log.costCents != null ? `$${(log.costCents / 100).toFixed(4)}` : "-"}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
</div>
);
}
+20
View File
@@ -0,0 +1,20 @@
import { db } from "@/lib/db";
import { UserManagement, type AdminUserRow, type PlanOption } from "@/components/admin/user-management";
export default async function AdminUsersPage() {
const [users, plans] = (await Promise.all([
db.user.findMany({
include: {
subscription: { include: { plan: true } },
_count: { select: { apiKeys: true, requestLogs: true } },
},
orderBy: { createdAt: "desc" },
}),
db.subscriptionPlan.findMany({
select: { id: true, displayName: true },
orderBy: { sortOrder: "asc" },
}),
])) as unknown as [AdminUserRow[], PlanOption[]];
return <UserManagement initialUsers={users} plans={plans} />;
}
+43
View File
@@ -0,0 +1,43 @@
import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
export async function GET(req: Request) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const url = new URL(req.url);
const days = Math.max(1, Math.min(Number(url.searchParams.get("days") ?? "30"), 365));
const from = new Date();
from.setDate(from.getDate() - days);
const [topProviders, topUsers, daily] = await Promise.all([
db.requestLog.groupBy({
by: ["providerId"],
where: { createdAt: { gte: from }, softDeleted: false },
_count: { _all: true },
_sum: { tokensIn: true, tokensOut: true, costCents: true },
orderBy: { providerId: "asc" },
take: 10,
}),
db.requestLog.groupBy({
by: ["userId"],
where: { createdAt: { gte: from }, softDeleted: false },
_count: { _all: true },
_sum: { tokensIn: true, tokensOut: true, costCents: true },
orderBy: { userId: "asc" },
take: 10,
}),
db.usageAggregateDaily.groupBy({
by: ["date"],
where: { date: { gte: from }, userApiKeyId: null },
_sum: { totalRequests: true, totalTokensIn: true, totalTokensOut: true, totalCostCents: true, totalErrors: true },
orderBy: { date: "asc" },
}),
]);
return NextResponse.json({ data: { topProviders, topUsers, daily } });
}
@@ -0,0 +1,38 @@
import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { createModelMappingSchema } from "@/lib/validations/admin";
export async function PATCH(req: Request, { params }: { params: Promise<{ mappingId: string }> }) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { mappingId } = await params;
const body = await req.json();
const parsed = createModelMappingSchema.partial().safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input" }, { status: 400 });
}
const updated = await db.modelMapping.update({
where: { id: mappingId },
data: parsed.data,
});
return NextResponse.json({ data: updated });
}
export async function DELETE(_req: Request, { params }: { params: Promise<{ mappingId: string }> }) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { mappingId } = await params;
await db.modelMapping.delete({ where: { id: mappingId } });
return NextResponse.json({ success: true });
}
+36
View File
@@ -0,0 +1,36 @@
import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { createModelMappingSchema } from "@/lib/validations/admin";
export async function GET() {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const mappings = await db.modelMapping.findMany({
include: { provider: { select: { displayName: true } } },
orderBy: [{ logicalModelId: "asc" }, { priority: "asc" }],
});
return NextResponse.json({ data: mappings });
}
export async function POST(req: Request) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const body = await req.json();
const parsed = createModelMappingSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.errors[0]?.message }, { status: 400 });
}
const mapping = await db.modelMapping.create({ data: parsed.data });
return NextResponse.json(mapping, { status: 201 });
}
+58
View File
@@ -0,0 +1,58 @@
import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { createPlanSchema } from "@/lib/validations/admin";
export async function GET(_req: Request, { params }: { params: Promise<{ planId: string }> }) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { planId } = await params;
const plan = await db.subscriptionPlan.findUnique({
where: { id: planId },
include: { _count: { select: { subscriptions: true } } },
});
if (!plan) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json({ data: plan });
}
export async function PATCH(req: Request, { params }: { params: Promise<{ planId: string }> }) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { planId } = await params;
const body = await req.json();
const parsed = createPlanSchema.partial().safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input" }, { status: 400 });
}
const { features, ...rest } = parsed.data;
const updated = await db.subscriptionPlan.update({
where: { id: planId },
data: {
...rest,
...(features !== undefined ? { features: features } : {}),
},
});
return NextResponse.json({ data: updated });
}
export async function DELETE(_req: Request, { params }: { params: Promise<{ planId: string }> }) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { planId } = await params;
await db.subscriptionPlan.delete({ where: { id: planId } });
return NextResponse.json({ success: true });
}
+69
View File
@@ -0,0 +1,69 @@
import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { createPlanSchema, updatePlanSchema } from "@/lib/validations/admin";
export async function GET() {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const plans = await db.subscriptionPlan.findMany({
include: { _count: { select: { subscriptions: true } } },
orderBy: { sortOrder: "asc" },
});
return NextResponse.json({ data: plans });
}
export async function POST(req: Request) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const body = await req.json();
const parsed = createPlanSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.errors[0]?.message }, { status: 400 });
}
const { features, ...rest } = parsed.data;
const plan = await db.subscriptionPlan.create({
data: {
...rest,
features,
},
});
return NextResponse.json(plan, { status: 201 });
}
export async function PATCH(req: Request) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const body = await req.json();
const parsed = updatePlanSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input" }, { status: 400 });
}
const { id, ...updates } = parsed.data;
const data = Object.fromEntries(Object.entries(updates).filter(([, value]) => value !== undefined));
if (Object.keys(data).length === 0) {
return NextResponse.json({ error: "No fields to update" }, { status: 400 });
}
const plan = await db.subscriptionPlan.update({
where: { id },
data,
});
return NextResponse.json({ data: plan });
}
@@ -0,0 +1,67 @@
import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { z } from "zod";
const updateProviderKeySchema = z.object({
label: z.string().nullable().optional(),
status: z.enum(["ACTIVE", "DISABLED", "EXHAUSTED", "ERROR"]).optional(),
metadata: z.record(z.unknown()).nullable().optional(),
errorCount: z.number().int().min(0).optional(),
lastValidatedAt: z.coerce.date().nullable().optional(),
});
export async function PATCH(
req: Request,
{ params }: { params: Promise<{ providerId: string; keyId: string }> },
) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { providerId, keyId } = await params;
const body = await req.json();
const parsed = updateProviderKeySchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input" }, { status: 400 });
}
const key = await db.providerApiKey.findFirst({ where: { id: keyId, providerId } });
if (!key) return NextResponse.json({ error: "Not found" }, { status: 404 });
const updated = await db.providerApiKey.update({
where: { id: keyId },
data: {
...(parsed.data.label !== undefined ? { label: parsed.data.label } : {}),
...(parsed.data.status !== undefined ? { status: parsed.data.status } : {}),
...(parsed.data.errorCount !== undefined ? { errorCount: parsed.data.errorCount } : {}),
...(parsed.data.lastValidatedAt !== undefined ? { lastValidatedAt: parsed.data.lastValidatedAt } : {}),
...(parsed.data.metadata !== undefined
? {
metadata:
parsed.data.metadata === null ? null : (parsed.data.metadata),
}
: {}),
},
});
return NextResponse.json({ data: updated });
}
export async function DELETE(
_req: Request,
{ params }: { params: Promise<{ providerId: string; keyId: string }> },
) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { providerId, keyId } = await params;
const deleted = await db.providerApiKey.deleteMany({ where: { id: keyId, providerId } });
if (deleted.count === 0) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json({ success: true });
}
@@ -0,0 +1,97 @@
import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { encrypt } from "@/server/services/encryption";
import { createProviderKeySchema } from "@/lib/validations/admin";
import { decrypt } from "@/server/services/encryption";
function maskKey(raw: string) {
if (!raw) return "";
if (raw.length <= 10) return `${raw.slice(0, 4)}...`;
return `${raw.slice(0, 6)}...${raw.slice(-4)}`;
}
export async function GET(_req: Request, { params }: { params: Promise<{ providerId: string }> }) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { providerId } = await params;
const keys = await db.providerApiKey.findMany({
where: { providerId },
select: {
id: true,
providerId: true,
label: true,
status: true,
lastValidatedAt: true,
lastUsedAt: true,
errorCount: true,
metadata: true,
encryptedKey: true,
iv: true,
authTag: true,
createdAt: true,
},
orderBy: { createdAt: "desc" },
});
const withPreview = keys.map((key) => {
let keyPreview =
typeof (key.metadata as { keyPreview?: unknown } | null)?.keyPreview === "string"
? ((key.metadata as { keyPreview?: string }).keyPreview ?? "")
: "";
if (!keyPreview && key.encryptedKey && key.iv && key.authTag) {
try {
keyPreview = maskKey(decrypt(key.encryptedKey, key.iv, key.authTag));
} catch {
keyPreview = "unavailable";
}
}
return {
...key,
keyPreview,
encryptedKey: undefined,
iv: undefined,
authTag: undefined,
};
});
return NextResponse.json({ data: withPreview });
}
export async function POST(req: Request, { params }: { params: Promise<{ providerId: string }> }) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { providerId } = await params;
const body = await req.json();
const parsed = createProviderKeySchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.errors[0]?.message }, { status: 400 });
}
const { ciphertext, iv, authTag } = encrypt(parsed.data.rawKey);
const key = await db.providerApiKey.create({
data: {
providerId,
encryptedKey: ciphertext,
iv,
authTag,
label: parsed.data.label,
metadata: {
keyPreview: maskKey(parsed.data.rawKey),
},
},
});
return NextResponse.json({ id: key.id, status: key.status }, { status: 201 });
}
@@ -0,0 +1,75 @@
import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
export async function GET(_req: Request, { params }: { params: Promise<{ providerId: string }> }) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { providerId } = await params;
const provider = await db.provider.findUnique({
where: { id: providerId },
include: {
_count: { select: { apiKeys: true, modelMappings: true, requestLogs: true } },
apiKeys: {
select: {
id: true,
label: true,
status: true,
lastValidatedAt: true,
lastUsedAt: true,
errorCount: true,
createdAt: true,
},
orderBy: { createdAt: "desc" },
take: 20,
},
},
});
if (!provider) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json({ data: provider });
}
export async function PATCH(req: Request, { params }: { params: Promise<{ providerId: string }> }) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { providerId } = await params;
const body = (await req.json()) as {
displayName?: string;
baseUrl?: string;
enabled?: boolean;
config?: Record<string, unknown>;
};
const updated = await db.provider.update({
where: { id: providerId },
data: {
...(body.displayName !== undefined ? { displayName: body.displayName } : {}),
...(body.baseUrl !== undefined ? { baseUrl: body.baseUrl } : {}),
...(body.enabled !== undefined ? { enabled: body.enabled } : {}),
...(body.config !== undefined ? { config: body.config } : {}),
},
});
return NextResponse.json({ data: updated });
}
export async function DELETE(_req: Request, { params }: { params: Promise<{ providerId: string }> }) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { providerId } = await params;
await db.provider.delete({ where: { id: providerId } });
return NextResponse.json({ success: true });
}
+171
View File
@@ -0,0 +1,171 @@
import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { encrypt } from "@/server/services/encryption";
import { detectProvider, getAdapter } from "@/server/adapters";
function parseRawKeys(input: string): string[] {
return input
.split(/\r?\n/g)
.map((line) => line.trim())
.filter((line) => line.length > 0 && !line.startsWith("#"));
}
function maskKey(raw: string) {
if (!raw) return "";
if (raw.length <= 10) return `${raw.slice(0, 4)}...`;
return `${raw.slice(0, 6)}...${raw.slice(-4)}`;
}
export async function GET() {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const batches = await db.ingestionBatch.findMany({
orderBy: { createdAt: "desc" },
take: 30,
include: { providerApiKeys: { select: { id: true, providerId: true, status: true } } },
});
return NextResponse.json({ data: batches });
}
export async function POST(req: Request) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
let providerIdHint: string | undefined;
let rawPayload = "";
const contentType = req.headers.get("content-type") ?? "";
if (contentType.includes("multipart/form-data")) {
const formData = await req.formData();
providerIdHint = (formData.get("providerId")?.toString() || "").trim() || undefined;
const file = formData.get("file");
if (file instanceof File) {
rawPayload = await file.text();
} else {
rawPayload = (formData.get("rawKeys")?.toString() ?? "").trim();
}
} else {
const body = (await req.json()) as { providerId?: string; rawKeys?: string };
providerIdHint = body.providerId?.trim() || undefined;
rawPayload = (body.rawKeys ?? "").trim();
}
if (!rawPayload) {
return NextResponse.json({ error: "No keys provided" }, { status: 400 });
}
const keys = parseRawKeys(rawPayload);
if (keys.length === 0) {
return NextResponse.json({ error: "No valid keys found" }, { status: 400 });
}
const batch = await db.ingestionBatch.create({
data: {
providerId: providerIdHint,
status: "PROCESSING",
totalKeys: keys.length,
},
});
let successfulKeys = 0;
let failedKeys = 0;
const errors: Array<{ keyPreview: string; reason: string }> = [];
for (const rawKey of keys) {
const hintedAdapter = providerIdHint ? getAdapter(providerIdHint) : undefined;
const detectedAdapter = detectProvider(rawKey);
const adapter = hintedAdapter ?? detectedAdapter;
if (!adapter) {
failedKeys += 1;
errors.push({ keyPreview: rawKey.slice(0, 8), reason: "Could not detect provider" });
continue;
}
const metadata = await adapter.validateApiKey(rawKey);
if (!metadata.valid) {
failedKeys += 1;
errors.push({
keyPreview: rawKey.slice(0, 8),
reason: metadata.error ?? "Validation failed",
});
continue;
}
try {
const { ciphertext, iv, authTag } = encrypt(rawKey);
await db.providerApiKey.create({
data: {
providerId: adapter.id,
encryptedKey: ciphertext,
iv,
authTag,
status: "ACTIVE",
lastValidatedAt: new Date(),
metadata: {
keyPreview: maskKey(rawKey),
detectedByPattern: Boolean(detectedAdapter),
models: metadata.models ?? [],
rateLimits: metadata.rateLimits ?? {},
},
ingestionBatchId: batch.id,
},
});
// Auto-create passthrough model mappings for discovered models so newly ingested
// keys become usable immediately without extra manual setup.
for (const modelId of metadata.models ?? []) {
const existingMapping = await db.modelMapping.findFirst({
where: {
providerId: adapter.id,
logicalModelId: modelId,
providerModelId: modelId,
},
select: { id: true },
});
if (!existingMapping) {
await db.modelMapping.create({
data: {
logicalModelId: modelId,
providerId: adapter.id,
providerModelId: modelId,
priority: 100,
enabled: true,
},
});
}
}
successfulKeys += 1;
} catch (err) {
failedKeys += 1;
errors.push({
keyPreview: rawKey.slice(0, 8),
reason: `Store failed: ${String(err).slice(0, 160)}`,
});
}
}
const status = failedKeys === 0 ? "COMPLETED" : successfulKeys === 0 ? "FAILED" : "COMPLETED";
const updated = await db.ingestionBatch.update({
where: { id: batch.id },
data: {
status,
successfulKeys,
failedKeys,
errors,
},
include: { providerApiKeys: { select: { id: true, providerId: true, status: true } } },
});
return NextResponse.json({ data: updated });
}
+61
View File
@@ -0,0 +1,61 @@
import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { createProviderSchema } from "@/lib/validations/admin";
export async function GET() {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const providers = await db.provider.findMany({
include: { _count: { select: { apiKeys: true, modelMappings: true } } },
orderBy: { id: "asc" },
});
return NextResponse.json({ data: providers });
}
export async function POST(req: Request) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const body = await req.json();
const parsed = createProviderSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.errors[0]?.message }, { status: 400 });
}
const { config, ...rest } = parsed.data;
const provider = await db.provider.create({
data: {
...rest,
config,
},
});
return NextResponse.json(provider, { status: 201 });
}
export async function PATCH(req: Request) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const body = await req.json();
const { id, ...data } = body;
if (!id) return NextResponse.json({ error: "id required" }, { status: 400 });
const updated = await db.provider.update({
where: { id },
data,
});
return NextResponse.json(updated);
}
+59
View File
@@ -0,0 +1,59 @@
import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { updateUserSchema } from "@/lib/validations/admin";
export async function GET(_req: Request, { params }: { params: Promise<{ userId: string }> }) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { userId } = await params;
const user = await db.user.findUnique({
where: { id: userId },
include: {
subscription: { include: { plan: true } },
apiKeys: { orderBy: { createdAt: "desc" } },
_count: { select: { requestLogs: true } },
},
});
if (!user) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json({ data: user });
}
export async function PATCH(req: Request, { params }: { params: Promise<{ userId: string }> }) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { userId } = await params;
const body = await req.json();
const parsed = updateUserSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
}
const updated = await db.user.update({
where: { id: userId },
data: parsed.data,
});
return NextResponse.json({ data: updated });
}
export async function DELETE(_req: Request, { params }: { params: Promise<{ userId: string }> }) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { userId } = await params;
await db.user.delete({ where: { id: userId } });
return NextResponse.json({ success: true });
}
+156
View File
@@ -0,0 +1,156 @@
import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { updateUserSchema } from "@/lib/validations/admin";
import { hash } from "bcryptjs";
import { z } from "zod";
const createUserSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
name: z.string().optional(),
role: z.enum(["USER", "ADMIN"]).optional().default("USER"),
status: z.enum(["ACTIVE", "SUSPENDED", "BANNED"]).optional().default("ACTIVE"),
planId: z.string().optional(),
});
export async function GET() {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const users = await db.user.findMany({
include: {
subscription: { include: { plan: true } },
_count: { select: { apiKeys: true, requestLogs: true } },
},
orderBy: { createdAt: "desc" },
});
return NextResponse.json({ data: users });
}
export async function PATCH(req: Request) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const body = await req.json();
const { userId, ...updateData } = body;
if (!userId) {
return NextResponse.json({ error: "userId required" }, { status: 400 });
}
const parsed = updateUserSchema.safeParse(updateData);
if (!parsed.success) {
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
}
const { planId, subscriptionStatus, ...userData } = parsed.data;
const updated = await db.user.update({
where: { id: userId },
data: userData,
});
if (planId !== undefined || subscriptionStatus !== undefined) {
const existingSubscription = await db.subscription.findFirst({
where: { userId },
select: { id: true },
});
if (existingSubscription) {
if (planId === null) {
await db.subscription.delete({ where: { id: existingSubscription.id } });
} else {
const subscriptionUpdate: {
planId?: string;
status?: "ACTIVE" | "PAST_DUE" | "CANCELED" | "TRIALING";
} = {};
if (planId !== undefined && planId !== null) subscriptionUpdate.planId = planId;
if (subscriptionStatus !== undefined) subscriptionUpdate.status = subscriptionStatus;
if (Object.keys(subscriptionUpdate).length > 0) {
await db.subscription.update({
where: { id: existingSubscription.id },
data: subscriptionUpdate,
});
}
}
} else if (planId) {
await db.subscription.create({
data: {
userId,
planId,
status: subscriptionStatus ?? "ACTIVE",
currentPeriodStart: new Date(),
currentPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
},
});
}
}
const hydrated = await db.user.findUnique({
where: { id: userId },
include: {
subscription: { include: { plan: true } },
_count: { select: { apiKeys: true, requestLogs: true } },
},
});
return NextResponse.json({ data: hydrated ?? updated });
}
export async function POST(req: Request) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const body = await req.json();
const parsed = createUserSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input" }, { status: 400 });
}
const existing = await db.user.findUnique({ where: { email: parsed.data.email } });
if (existing) {
return NextResponse.json({ error: "User already exists" }, { status: 409 });
}
const passwordHash = await hash(parsed.data.password, 12);
const defaultPlan = parsed.data.planId
? await db.subscriptionPlan.findUnique({ where: { id: parsed.data.planId } })
: await db.subscriptionPlan.findFirst({ orderBy: { sortOrder: "asc" } });
const user = await db.user.create({
data: {
email: parsed.data.email,
name: parsed.data.name,
role: parsed.data.role,
status: parsed.data.status,
passwordHash,
...(defaultPlan
? {
subscription: {
create: {
planId: defaultPlan.id,
status: "ACTIVE",
currentPeriodStart: new Date(),
currentPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
},
},
}
: {}),
},
});
return NextResponse.json({ id: user.id, email: user.email }, { status: 201 });
}
+6
View File
@@ -0,0 +1,6 @@
import NextAuth from "next-auth";
import { authOptions } from "@/lib/auth";
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
+110
View File
@@ -0,0 +1,110 @@
import { NextResponse } from "next/server";
import { hash } from "bcryptjs";
import { getMongoDb } from "@/lib/mongo";
import { z } from "zod";
type UserDocument = {
_id: string;
email: string;
passwordHash: string;
name: string;
role: "USER";
status: "ACTIVE";
createdAt: Date;
updatedAt: Date;
};
type SubscriptionDocument = {
_id: string;
userId: string;
planId: string;
status: "ACTIVE";
currentPeriodStart: Date;
currentPeriodEnd: Date;
createdAt: Date;
updatedAt: Date;
};
type SubscriptionPlanDocument = {
_id: string;
isPublic: boolean;
sortOrder: number;
};
const registerSchema = z
.object({
username: z.string().trim().min(3),
email: z.string().trim().email(),
password: z.string().min(8),
confirmPassword: z.string().min(8),
})
.refine((data) => data.password === data.confirmPassword, {
message: "Passwords do not match.",
path: ["confirmPassword"],
});
export async function POST(req: Request) {
try {
const body = await req.json();
const parsed = registerSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: parsed.error.errors[0]?.message ?? "Invalid input." },
{ status: 400 },
);
}
const { username, email, password } = parsed.data;
const db = getMongoDb();
const existing = await db.collection<UserDocument>("users").findOne({ email });
if (existing) {
return NextResponse.json({ error: "An account with this email already exists." }, { status: 409 });
}
const passwordHash = await hash(password, 12);
// Find the default free plan
const freePlan = await db.collection<SubscriptionPlanDocument>("subscription_plans").findOne(
{ isPublic: true },
{ sort: { sortOrder: 1 } },
);
const userId = crypto.randomUUID();
const now = new Date();
await db.collection<UserDocument>("users").insertOne({
_id: userId,
email,
passwordHash,
name: username,
role: "USER",
status: "ACTIVE",
createdAt: now,
updatedAt: now,
});
if (freePlan) {
const periodStart = new Date();
await db.collection<SubscriptionDocument>("subscriptions").insertOne({
_id: crypto.randomUUID(),
userId,
planId: freePlan._id,
status: "ACTIVE",
currentPeriodStart: periodStart,
currentPeriodEnd: new Date(periodStart.getTime() + 30 * 24 * 60 * 60 * 1000),
createdAt: periodStart,
updatedAt: periodStart,
});
}
return NextResponse.json({ id: userId, email }, { status: 201 });
} catch (error) {
const message = error instanceof Error ? error.message : "";
if (message.includes("Unique constraint failed") || message.includes("E11000 duplicate key error")) {
return NextResponse.json({ error: "An account with this email already exists." }, { status: 409 });
}
return NextResponse.json({ error: "Registration failed." }, { status: 500 });
}
}
@@ -0,0 +1,55 @@
import { NextResponse } from "next/server";
import { getSession } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { z } from "zod";
const updateKeySchema = z.object({
label: z.string().optional(),
status: z.enum(["ACTIVE", "DISABLED"]).optional(),
dailyRequestLimit: z.number().int().positive().nullable().optional(),
dailyTokenLimit: z.number().int().positive().nullable().optional(),
});
export async function PATCH(req: Request, { params }: { params: Promise<{ keyId: string }> }) {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const { keyId } = await params;
const key = await db.userApiKey.findFirst({
where: { id: keyId, userId: session.user.id },
});
if (!key) return NextResponse.json({ error: "Not found" }, { status: 404 });
const body = await req.json();
const parsed = updateKeySchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
}
const updated = await db.userApiKey.update({
where: { id: keyId },
data: parsed.data,
});
return NextResponse.json(updated);
}
export async function DELETE(_req: Request, { params }: { params: Promise<{ keyId: string }> }) {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const { keyId } = await params;
const key = await db.userApiKey.findFirst({
where: { id: keyId, userId: session.user.id },
});
if (!key) return NextResponse.json({ error: "Not found" }, { status: 404 });
await db.userApiKey.update({
where: { id: keyId },
data: { status: "REVOKED" },
});
return NextResponse.json({ success: true });
}
+68
View File
@@ -0,0 +1,68 @@
import { NextResponse } from "next/server";
import { getSession } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { generateApiKey } from "@/lib/utils";
import { z } from "zod";
export async function GET() {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const keys = await db.userApiKey.findMany({
where: { userId: session.user.id },
select: {
id: true,
keyPrefix: true,
label: true,
status: true,
dailyRequestLimit: true,
dailyTokenLimit: true,
softCostLimitCents: true,
lastUsedAt: true,
createdAt: true,
},
orderBy: { createdAt: "desc" },
});
return NextResponse.json({ data: keys });
}
const createKeySchema = z.object({
label: z.string().optional(),
dailyRequestLimit: z.number().int().positive().optional(),
dailyTokenLimit: z.number().int().positive().optional(),
softCostLimitCents: z.number().int().positive().optional(),
});
export async function POST(req: Request) {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const body = await req.json();
const parsed = createKeySchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
}
const { raw, hashed, prefix } = generateApiKey();
const apiKey = await db.userApiKey.create({
data: {
userId: session.user.id,
hashedKey: hashed,
keyPrefix: prefix,
label: parsed.data.label,
status: "ACTIVE",
dailyRequestLimit: parsed.data.dailyRequestLimit,
dailyTokenLimit: parsed.data.dailyTokenLimit,
softCostLimitCents: parsed.data.softCostLimitCents,
},
});
return NextResponse.json({
id: apiKey.id,
key: raw,
prefix: apiKey.keyPrefix,
label: apiKey.label,
}, { status: 201 });
}
+203
View File
@@ -0,0 +1,203 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { getSession } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { logger } from "@/lib/logger";
import { checkRateLimit } from "@/server/services/rate-limiter";
import { resolveModelRouteCandidates } from "@/server/services/model-router";
import { logUsage } from "@/server/services/usage-logger";
import { ApiError, internalError, modelNotFound, rateLimitExceeded } from "@/lib/api-error";
import type { UnifiedChatRequest } from "@/types/unified-request";
const playgroundRequestSchema = z.object({
model: z.string().min(1),
message: z.string().trim().min(1),
systemPrompt: z.string().trim().optional(),
temperature: z.number().min(0).max(2).optional(),
max_tokens: z.number().int().positive().max(8192).optional(),
history: z
.array(
z.object({
role: z.enum(["user", "assistant"]),
content: z.string().trim().min(1),
}),
)
.max(40)
.optional(),
});
function shouldRetryProviderError(error: ApiError): boolean {
return error.statusCode === 429 || (error.statusCode >= 500 && error.statusCode < 600);
}
export async function GET() {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const mappings = (await db.modelMapping.findMany({
where: { enabled: true },
select: { logicalModelId: true, providerId: true, priority: true },
orderBy: [{ logicalModelId: "asc" }, { priority: "asc" }],
})) as Array<{ logicalModelId: string; providerId: string }>;
const byModel = new Map<string, string>();
for (const row of mappings) {
if (!byModel.has(row.logicalModelId)) {
byModel.set(row.logicalModelId, row.providerId);
}
}
return NextResponse.json({
data: [...byModel.entries()].map(([id, providerId]) => ({ id, providerId })),
});
}
export async function POST(req: Request) {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body." }, { status: 400 });
}
const parsed = playgroundRequestSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input." }, { status: 400 });
}
const payload = parsed.data;
const [apiKeys, subscription] = (await Promise.all([
db.userApiKey.findMany({
where: { userId: session.user.id },
orderBy: { createdAt: "asc" },
select: { id: true, status: true, dailyRequestLimit: true, dailyTokenLimit: true, softCostLimitCents: true },
}),
db.subscription.findUnique({
where: { userId: session.user.id },
include: { plan: true },
}),
])) as [
Array<{
id: string;
status?: "ACTIVE" | "DISABLED" | "REVOKED" | null;
dailyRequestLimit?: number | null;
dailyTokenLimit?: number | null;
softCostLimitCents?: number | null;
}>,
{ plan?: { dailyRequestLimit?: number | null; dailyTokenLimit?: number | null } } | null,
];
// Backward compatibility: treat missing status as ACTIVE.
const apiKey =
apiKeys.find((key) => !key.status || key.status === "ACTIVE") ??
null;
if (!apiKey) {
return NextResponse.json({ error: "Create a user API key first in Dashboard > API Keys." }, { status: 400 });
}
if (!subscription?.plan) {
return NextResponse.json({ error: "No active subscription plan found." }, { status: 403 });
}
const limits = {
dailyRequests: apiKey.dailyRequestLimit ?? subscription.plan.dailyRequestLimit ?? null,
dailyTokens: apiKey.dailyTokenLimit ?? subscription.plan.dailyTokenLimit ?? null,
dailyCostCents: apiKey.softCostLimitCents ?? null,
};
const rateLimit = await checkRateLimit(apiKey.id, limits);
if (!rateLimit.allowed) {
return rateLimitExceeded(rateLimit.reason!, rateLimit.retryAfter!);
}
const routes = await resolveModelRouteCandidates(payload.model);
if (routes.length === 0) {
return modelNotFound(payload.model).toResponse();
}
const messages: UnifiedChatRequest["messages"] = [];
if (payload.systemPrompt) {
messages.push({ role: "system", content: payload.systemPrompt });
}
for (const entry of payload.history ?? []) {
messages.push({ role: entry.role, content: entry.content });
}
messages.push({ role: "user", content: payload.message });
const unifiedReq: UnifiedChatRequest = {
model: payload.model,
messages,
temperature: payload.temperature,
max_tokens: payload.max_tokens,
stream: false,
};
const startedAt = Date.now();
let lastApiError: ApiError | null = null;
for (const route of routes) {
try {
const result = await route.adapter.chatCompletion(unifiedReq, route.ctx);
const latencyMs = Date.now() - startedAt;
const assistantText = result.choices[0]?.message.content ?? "";
logUsage({
userId: session.user.id,
userApiKeyId: apiKey.id,
providerId: route.providerId,
providerApiKeyId: route.providerApiKeyId,
logicalModelId: route.logicalModelId,
providerModelId: route.providerModelId,
statusCode: 200,
tokensIn: result.usage?.prompt_tokens ?? 0,
tokensOut: result.usage?.completion_tokens ?? 0,
latencyMs,
streamed: false,
promptText: messages.map((m) => `${m.role}: ${m.content ?? ""}`).join("\n"),
responseText: assistantText,
loggingMode: "preview",
}).catch((err) => logger.error(err, "Failed to log playground usage"));
return NextResponse.json({
providerId: route.providerId,
model: result.model,
content: assistantText,
usage: result.usage ?? null,
});
} catch (error) {
const latencyMs = Date.now() - startedAt;
if (error instanceof ApiError) {
lastApiError = error;
logUsage({
userId: session.user.id,
userApiKeyId: apiKey.id,
providerId: route.providerId,
providerApiKeyId: route.providerApiKeyId,
logicalModelId: route.logicalModelId,
providerModelId: route.providerModelId,
statusCode: error.statusCode,
errorCode: error.errorCode,
errorMessage: error.errorMessage,
tokensIn: 0,
tokensOut: 0,
latencyMs,
streamed: false,
promptText: messages.map((m) => `${m.role}: ${m.content ?? ""}`).join("\n"),
loggingMode: "hash_only",
}).catch(() => {});
if (shouldRetryProviderError(error)) {
continue;
}
return error.toResponse();
}
logger.error(error, "Unhandled playground chat error");
}
}
if (lastApiError) return lastApiError.toResponse();
return internalError().toResponse();
}
+33
View File
@@ -0,0 +1,33 @@
import { NextResponse } from "next/server";
import { getSession } from "@/lib/auth-helpers";
import { redis } from "@/lib/redis";
import { formatDate } from "@/lib/utils";
import { db } from "@/lib/db";
export async function GET() {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
// Get today's usage from Redis for all user keys
const keys = await db.userApiKey.findMany({
where: { userId: session.user.id, status: "ACTIVE" },
select: { id: true },
});
const date = formatDate(new Date());
let todayRequests = 0;
let todayTokens = 0;
for (const key of keys) {
const pipe = redis.pipeline();
pipe.get(`ratelimit:${key.id}:requests:${date}`);
pipe.get(`ratelimit:${key.id}:tokens:${date}`);
const results = await pipe.exec();
todayRequests += Number(results?.[0]?.[1] ?? 0);
todayTokens += Number(results?.[1]?.[1] ?? 0);
}
return NextResponse.json({
today: { requests: todayRequests, tokens: todayTokens },
});
}
+240
View File
@@ -0,0 +1,240 @@
"use client";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Plus, Copy, Trash2 } from "lucide-react";
interface ApiKey {
id: string;
keyPrefix: string;
label: string | null;
status: string;
dailyRequestLimit: number | null;
dailyTokenLimit: number | null;
lastUsedAt: string | null;
createdAt: string;
}
export default function ApiKeysPage() {
const [keys, setKeys] = useState<ApiKey[]>([]);
const [loading, setLoading] = useState(true);
const [createOpen, setCreateOpen] = useState(false);
const [newKeyLabel, setNewKeyLabel] = useState("");
const [newKeyDailyRequests, setNewKeyDailyRequests] = useState("");
const [newKeyDailyTokens, setNewKeyDailyTokens] = useState("");
const [createdKey, setCreatedKey] = useState<string | null>(null);
const [creating, setCreating] = useState(false);
async function fetchKeys() {
const res = await fetch("/api/dashboard/api-keys");
if (res.ok) {
const data = await res.json();
setKeys(data.data);
}
setLoading(false);
}
useEffect(() => {
fetchKeys();
}, []);
async function createKey() {
setCreating(true);
const res = await fetch("/api/dashboard/api-keys", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
label: newKeyLabel || undefined,
dailyRequestLimit: newKeyDailyRequests ? Number(newKeyDailyRequests) : undefined,
dailyTokenLimit: newKeyDailyTokens ? Number(newKeyDailyTokens) : undefined,
}),
});
setCreating(false);
if (res.ok) {
const data = await res.json();
setCreatedKey(data.key);
fetchKeys();
toast.success("API key created");
} else {
toast.error("Failed to create API key");
}
}
async function deleteKey(id: string) {
if (!confirm("Are you sure you want to delete this key?")) return;
const res = await fetch(`/api/dashboard/api-keys/${id}`, { method: "DELETE" });
if (res.ok) {
fetchKeys();
toast.success("Key deleted");
}
}
function copyToClipboard(text: string) {
navigator.clipboard.writeText(text);
toast.success("Copied to clipboard");
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold">API Keys</h1>
<p className="text-muted-foreground">Manage your API keys for accessing the LLM Proxy</p>
</div>
<Dialog
open={createOpen}
onOpenChange={(open) => {
setCreateOpen(open);
if (!open) {
setCreatedKey(null);
setNewKeyLabel("");
setNewKeyDailyRequests("");
setNewKeyDailyTokens("");
}
}}
>
<DialogTrigger asChild>
<Button>
<Plus className="h-4 w-4" />
Create Key
</Button>
</DialogTrigger>
<DialogContent>
{createdKey ? (
<>
<DialogHeader>
<DialogTitle>Key Created</DialogTitle>
<DialogDescription>
Copy this key now. You won&apos;t be able to see it again.
</DialogDescription>
</DialogHeader>
<div className="flex items-center gap-2">
<code className="flex-1 rounded-md bg-muted px-3 py-2 text-sm font-mono break-all">
{createdKey}
</code>
<Button size="icon" variant="outline" onClick={() => copyToClipboard(createdKey)}>
<Copy className="h-4 w-4" />
</Button>
</div>
</>
) : (
<>
<DialogHeader>
<DialogTitle>Create API Key</DialogTitle>
<DialogDescription>Create a new key with optional limits.</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="label">Label (optional)</Label>
<Input
id="label"
value={newKeyLabel}
onChange={(e) => setNewKeyLabel(e.target.value)}
placeholder="e.g. production, staging"
/>
</div>
<div>
<Label htmlFor="dailyRequests">Daily Request Limit (optional)</Label>
<Input
id="dailyRequests"
type="number"
value={newKeyDailyRequests}
onChange={(e) => setNewKeyDailyRequests(e.target.value)}
placeholder="Leave empty for plan default"
/>
</div>
<div>
<Label htmlFor="dailyTokens">Daily Token Limit (optional)</Label>
<Input
id="dailyTokens"
type="number"
value={newKeyDailyTokens}
onChange={(e) => setNewKeyDailyTokens(e.target.value)}
placeholder="Leave empty for plan default"
/>
</div>
</div>
<DialogFooter>
<Button onClick={createKey} disabled={creating}>
{creating ? "Creating..." : "Create Key"}
</Button>
</DialogFooter>
</>
)}
</DialogContent>
</Dialog>
</div>
<Card>
<CardHeader>
<CardTitle>Your Keys</CardTitle>
</CardHeader>
<CardContent>
{loading ? (
<p className="text-sm text-muted-foreground">Loading...</p>
) : keys.length === 0 ? (
<p className="text-sm text-muted-foreground">No API keys yet. Create one to get started.</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Key</TableHead>
<TableHead>Label</TableHead>
<TableHead>Status</TableHead>
<TableHead>Daily Limits</TableHead>
<TableHead>Last Used</TableHead>
<TableHead>Created</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
{keys.map((key) => (
<TableRow key={key.id}>
<TableCell className="font-mono text-sm">{key.keyPrefix}</TableCell>
<TableCell>{key.label ?? "-"}</TableCell>
<TableCell>
<Badge variant={key.status === "ACTIVE" ? "default" : "secondary"}>
{key.status}
</Badge>
</TableCell>
<TableCell className="text-sm">
{key.dailyRequestLimit ? `${key.dailyRequestLimit} req` : "Default"}
{key.dailyTokenLimit ? ` / ${key.dailyTokenLimit} tok` : ""}
</TableCell>
<TableCell className="text-sm">
{key.lastUsedAt ? new Date(key.lastUsedAt).toLocaleDateString() : "Never"}
</TableCell>
<TableCell className="text-sm">
{new Date(key.createdAt).toLocaleDateString()}
</TableCell>
<TableCell>
<Button size="icon" variant="ghost" onClick={() => deleteKey(key.id)}>
<Trash2 className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</div>
);
}
+83
View File
@@ -0,0 +1,83 @@
import { getSession } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
export default async function BillingPage() {
const session = await getSession();
if (!session) return null;
const subscription = await db.subscription.findUnique({
where: { userId: session.user.id },
include: { plan: true },
});
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold">Billing</h1>
<p className="text-muted-foreground">Manage your subscription and billing</p>
</div>
<Card>
<CardHeader>
<CardTitle>Current Plan</CardTitle>
<CardDescription>Your active subscription</CardDescription>
</CardHeader>
<CardContent>
{subscription ? (
<div className="space-y-4">
<div className="flex items-center gap-3">
<h3 className="text-xl font-bold">{subscription.plan.displayName}</h3>
<Badge>{subscription.status}</Badge>
</div>
{subscription.plan.description && (
<p className="text-sm text-muted-foreground">{subscription.plan.description}</p>
)}
<div className="grid gap-2 text-sm">
<div className="flex justify-between">
<span className="text-muted-foreground">Price</span>
<span>${(subscription.plan.monthlyPriceCents / 100).toFixed(2)}/month</span>
</div>
{subscription.plan.dailyRequestLimit && (
<div className="flex justify-between">
<span className="text-muted-foreground">Daily Request Limit</span>
<span>{subscription.plan.dailyRequestLimit.toLocaleString()}</span>
</div>
)}
{subscription.plan.dailyTokenLimit && (
<div className="flex justify-between">
<span className="text-muted-foreground">Daily Token Limit</span>
<span>{subscription.plan.dailyTokenLimit.toLocaleString()}</span>
</div>
)}
<div className="flex justify-between">
<span className="text-muted-foreground">Max API Keys</span>
<span>{subscription.plan.maxApiKeys}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Period End</span>
<span>{new Date(subscription.currentPeriodEnd).toLocaleDateString()}</span>
</div>
</div>
</div>
) : (
<p className="text-sm text-muted-foreground">No active subscription. Contact support.</p>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Stripe Billing</CardTitle>
<CardDescription>Payment management will be available in a future update</CardDescription>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
Stripe integration for plan upgrades, downgrades, and payment management is coming in Phase 3.
</p>
</CardContent>
</Card>
</div>
);
}
+19
View File
@@ -0,0 +1,19 @@
import { redirect } from "next/navigation";
import { getSession } from "@/lib/auth-helpers";
import { Sidebar } from "@/components/layout/sidebar";
import { Header } from "@/components/layout/header";
export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
const session = await getSession();
if (!session) redirect("/login");
return (
<div className="flex h-screen">
<Sidebar variant="dashboard" />
<div className="flex flex-1 flex-col overflow-hidden">
<Header />
<main className="flex-1 overflow-y-auto p-6">{children}</main>
</div>
</div>
);
}
+130
View File
@@ -0,0 +1,130 @@
import { getSession } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { DashboardUsageGraphs } from "@/components/dashboard/dashboard-usage-graphs";
import { Key, Activity, Coins, AlertCircle } from "lucide-react";
export default async function DashboardOverview() {
const session = await getSession();
if (!session) return null;
const [apiKeyCount, subscription, todayLogs] = await Promise.all([
db.userApiKey.count({
where: { userId: session.user.id, status: "ACTIVE" },
}),
db.subscription.findUnique({
where: { userId: session.user.id },
include: { plan: true },
}),
db.requestLog.aggregate({
where: {
userId: session.user.id,
createdAt: { gte: new Date(new Date().setUTCHours(0, 0, 0, 0)) },
softDeleted: false,
},
_count: true,
_sum: { tokensIn: true, tokensOut: true, costCents: true },
}),
]);
const fourteenDaysAgo = new Date();
fourteenDaysAgo.setDate(fourteenDaysAgo.getDate() - 14);
const [dailyUsage, providerUsage] = await Promise.all([
db.usageAggregateDaily.findMany({
where: {
userId: session.user.id,
date: { gte: fourteenDaysAgo },
userApiKeyId: null,
},
orderBy: { date: "asc" },
take: 14,
}),
db.requestLog.groupBy({
by: ["providerId"],
where: {
userId: session.user.id,
createdAt: { gte: fourteenDaysAgo },
softDeleted: false,
},
_count: { _all: true },
orderBy: { providerId: "asc" },
take: 6,
}),
]);
const trendData = dailyUsage.map((row) => ({
date: new Date(row.date).toLocaleDateString("en-US", { month: "short", day: "numeric" }),
requests: row.totalRequests,
tokens: row.totalTokensIn + row.totalTokensOut,
cost: row.totalCostCents / 100,
}));
const providerData = providerUsage.map((row) => ({
name: row.providerId,
requests: (row._count as { _all: number })._all,
}));
const stats = [
{
title: "Active API Keys",
value: apiKeyCount,
icon: Key,
},
{
title: "Requests Today",
value: todayLogs._count,
icon: Activity,
},
{
title: "Tokens Today",
value: ((todayLogs._sum.tokensIn ?? 0) + (todayLogs._sum.tokensOut ?? 0)).toLocaleString(),
icon: AlertCircle,
},
{
title: "Cost Today",
value: `$${((todayLogs._sum.costCents ?? 0) / 100).toFixed(4)}`,
icon: Coins,
},
];
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold">Dashboard</h1>
<p className="text-muted-foreground">
{subscription ? `${subscription.plan.displayName} plan` : "No active plan"}
</p>
</div>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{stats.map((stat) => (
<Card key={stat.title}>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">{stat.title}</CardTitle>
<stat.icon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stat.value}</div>
</CardContent>
</Card>
))}
</div>
{trendData.length === 0 ? (
<Card>
<CardHeader>
<CardTitle>Usage Trends</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
No usage data yet. Start making API requests to see beautiful charts here.
</p>
</CardContent>
</Card>
) : (
<DashboardUsageGraphs trend={trendData} providers={providerData} />
)}
</div>
);
}
+277
View File
@@ -0,0 +1,277 @@
"use client";
import { FormEvent, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Send, Sparkles } from "lucide-react";
interface ModelOption {
id: string;
providerId: string;
}
interface ChatMessage {
role: "user" | "assistant";
content: string;
providerId?: string;
usage?: {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
} | null;
}
export default function PlaygroundPage() {
const [models, setModels] = useState<ModelOption[]>([]);
const [loadingModels, setLoadingModels] = useState(true);
const [model, setModel] = useState("");
const [systemPrompt, setSystemPrompt] = useState("You are a helpful assistant.");
const [temperature, setTemperature] = useState("0.7");
const [maxTokens, setMaxTokens] = useState("1024");
const [input, setInput] = useState("");
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [submitting, setSubmitting] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => {
async function loadModels() {
setLoadingModels(true);
const res = await fetch("/api/dashboard/playground");
if (!res.ok) {
toast.error("Failed to load models for playground");
setLoadingModels(false);
return;
}
const data = (await res.json()) as { data: ModelOption[] };
const modelList = data.data ?? [];
setModels(modelList);
if (modelList.length > 0) {
setModel(modelList[0].id);
}
setLoadingModels(false);
}
loadModels().catch(() => {
toast.error("Failed to load models for playground");
setLoadingModels(false);
});
}, []);
useEffect(() => {
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
}, [messages, submitting]);
const modelProvider = useMemo(() => models.find((item) => item.id === model)?.providerId, [models, model]);
async function submitPrompt(event?: FormEvent) {
event?.preventDefault();
if (!input.trim() || !model || submitting) return;
const userContent = input.trim();
const history = messages.map((message) => ({
role: message.role,
content: message.content,
}));
setMessages((prev) => [...prev, { role: "user", content: userContent }]);
setInput("");
setSubmitting(true);
const res = await fetch("/api/dashboard/playground", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model,
message: userContent,
history,
systemPrompt: systemPrompt.trim() || undefined,
temperature: temperature.trim() ? Number(temperature) : undefined,
max_tokens: maxTokens.trim() ? Number(maxTokens) : undefined,
}),
});
setSubmitting(false);
if (!res.ok) {
const payload = (await res.json().catch(() => null)) as { error?: { message?: string } | string } | null;
const message =
typeof payload?.error === "string"
? payload.error
: payload?.error?.message ?? "Playground request failed.";
toast.error(message);
setMessages((prev) => prev.slice(0, -1));
setInput(userContent);
return;
}
const payload = (await res.json()) as {
content: string;
providerId: string;
usage: ChatMessage["usage"];
};
setMessages((prev) => [
...prev,
{
role: "assistant",
content: payload.content?.trim() || "(empty response)",
providerId: payload.providerId,
usage: payload.usage ?? null,
},
]);
}
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold">Playground</h1>
<p className="text-muted-foreground">Test any mapped model directly from your dashboard.</p>
</div>
<div className="grid gap-6 lg:grid-cols-[340px_minmax(0,1fr)]">
<Card className="h-fit">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Sparkles className="h-4 w-4" />
Settings
</CardTitle>
<CardDescription>Choose model and generation parameters.</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium">Model</label>
<select
value={model}
onChange={(e) => setModel(e.target.value)}
disabled={loadingModels || models.length === 0}
className="h-10 w-full rounded-md border bg-background px-3 text-sm"
>
{models.length === 0 && <option value="">No available models</option>}
{models.map((option) => (
<option key={option.id} value={option.id}>
{option.id}
</option>
))}
</select>
{modelProvider && <p className="text-xs text-muted-foreground">Primary provider: {modelProvider}</p>}
</div>
<div className="space-y-2">
<label className="text-sm font-medium">System Prompt</label>
<textarea
value={systemPrompt}
onChange={(e) => setSystemPrompt(e.target.value)}
rows={4}
className="w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring"
placeholder="Optional instructions for the assistant..."
/>
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-1">
<div className="space-y-2">
<label className="text-sm font-medium">Temperature</label>
<Input
value={temperature}
onChange={(e) => setTemperature(e.target.value)}
type="number"
min="0"
max="2"
step="0.1"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Max Tokens</label>
<Input
value={maxTokens}
onChange={(e) => setMaxTokens(e.target.value)}
type="number"
min="1"
max="8192"
step="1"
/>
</div>
</div>
<Button variant="outline" className="w-full" onClick={() => setMessages([])}>
Clear Conversation
</Button>
</CardContent>
</Card>
<Card className="flex min-h-[640px] flex-col">
<CardHeader>
<CardTitle>Chat</CardTitle>
<CardDescription>
Messages are processed through your configured routing and provider key pool.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-1 flex-col gap-4">
<div ref={scrollRef} className="flex-1 space-y-3 overflow-y-auto rounded-xl border bg-muted/20 p-4">
{messages.length === 0 && (
<p className="text-sm text-muted-foreground">Start chatting to test your configured models.</p>
)}
{messages.map((message, idx) => (
<div
key={`${message.role}-${idx}`}
className={message.role === "user" ? "ml-auto max-w-[85%]" : "mr-auto max-w-[90%]"}
>
<div
className={
message.role === "user"
? "rounded-2xl bg-primary px-4 py-3 text-sm text-primary-foreground"
: "rounded-2xl border bg-card px-4 py-3 text-sm"
}
>
<div className="whitespace-pre-wrap">{message.content}</div>
</div>
{message.role === "assistant" && (
<div className="mt-1 flex items-center gap-2 text-xs text-muted-foreground">
{message.providerId && <Badge variant="secondary">{message.providerId}</Badge>}
{message.usage && (
<span>
{message.usage.prompt_tokens + message.usage.completion_tokens} tokens
</span>
)}
</div>
)}
</div>
))}
{submitting && (
<div className="mr-auto max-w-[90%] rounded-2xl border bg-card px-4 py-3 text-sm text-muted-foreground">
Thinking...
</div>
)}
</div>
<form onSubmit={submitPrompt} className="space-y-2">
<textarea
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
submitPrompt();
}
}}
placeholder="Send a message... (Enter to send, Shift+Enter for newline)"
rows={4}
className="w-full rounded-xl border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring"
/>
<div className="flex items-center justify-between">
<p className="text-xs text-muted-foreground">Model: {model || "none selected"}</p>
<Button type="submit" disabled={submitting || !input.trim() || !model}>
<Send className="h-4 w-4" />
Send
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
</div>
);
}
+203
View File
@@ -0,0 +1,203 @@
import { getSession } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { UsageBreakdownCharts } from "@/components/dashboard/usage-breakdown-charts";
export default async function UsagePage() {
const session = await getSession();
if (!session) return null;
// Last 30 days aggregates
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
const aggregates = await db.usageAggregateDaily.findMany({
where: {
userId: session.user.id,
date: { gte: thirtyDaysAgo },
userApiKeyId: null, // user-level aggregates
},
orderBy: { date: "desc" },
take: 30,
});
const totals = aggregates.reduce(
(acc, row) => ({
requests: acc.requests + row.totalRequests,
tokensIn: acc.tokensIn + row.totalTokensIn,
tokensOut: acc.tokensOut + row.totalTokensOut,
cost: acc.cost + row.totalCostCents,
}),
{ requests: 0, tokensIn: 0, tokensOut: 0, cost: 0 },
);
const [providerStats, modelStats, apiKeyStats, apiKeys] = await Promise.all([
db.requestLog.groupBy({
by: ["providerId"],
where: {
userId: session.user.id,
createdAt: { gte: thirtyDaysAgo },
softDeleted: false,
},
_count: { _all: true },
_sum: { tokensIn: true, tokensOut: true, costCents: true },
orderBy: { providerId: "asc" },
take: 8,
}),
db.requestLog.groupBy({
by: ["logicalModelId"],
where: {
userId: session.user.id,
createdAt: { gte: thirtyDaysAgo },
softDeleted: false,
},
_count: { _all: true },
_sum: { tokensIn: true, tokensOut: true, costCents: true },
orderBy: { logicalModelId: "asc" },
take: 8,
}),
db.requestLog.groupBy({
by: ["userApiKeyId"],
where: {
userId: session.user.id,
createdAt: { gte: thirtyDaysAgo },
softDeleted: false,
},
_count: { _all: true },
_sum: { tokensIn: true, tokensOut: true, costCents: true },
orderBy: { userApiKeyId: "asc" },
take: 8,
}),
db.userApiKey.findMany({
where: { userId: session.user.id },
select: { id: true, keyPrefix: true },
}),
]);
const keyPrefixMap = new Map(apiKeys.map((k) => [k.id, k.keyPrefix]));
const chartDaily = aggregates
.slice()
.reverse()
.map((row) => ({
date: new Date(row.date).toLocaleDateString(),
requests: row.totalRequests,
tokensIn: row.totalTokensIn,
tokensOut: row.totalTokensOut,
cost: Number((row.totalCostCents / 100).toFixed(4)),
}));
const chartProviders = providerStats.map((row) => ({
name: row.providerId,
requests: (row._count as { _all: number })._all,
tokens:
((row._sum as { tokensIn?: number } | null)?.tokensIn ?? 0) +
((row._sum as { tokensOut?: number } | null)?.tokensOut ?? 0),
cost: Number(((((row._sum as { costCents?: number } | null)?.costCents ?? 0) / 100)).toFixed(4)),
}));
const chartModels = modelStats.map((row) => ({
name: row.logicalModelId,
requests: (row._count as { _all: number })._all,
tokens:
((row._sum as { tokensIn?: number } | null)?.tokensIn ?? 0) +
((row._sum as { tokensOut?: number } | null)?.tokensOut ?? 0),
cost: Number(((((row._sum as { costCents?: number } | null)?.costCents ?? 0) / 100)).toFixed(4)),
}));
const chartKeys = apiKeyStats.map((row) => ({
name: keyPrefixMap.get(row.userApiKeyId) ?? row.userApiKeyId.slice(0, 8),
requests: (row._count as { _all: number })._all,
tokens:
((row._sum as { tokensIn?: number } | null)?.tokensIn ?? 0) +
((row._sum as { tokensOut?: number } | null)?.tokensOut ?? 0),
cost: Number(((((row._sum as { costCents?: number } | null)?.costCents ?? 0) / 100)).toFixed(4)),
}));
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold">Usage</h1>
<p className="text-muted-foreground">Your API usage over the last 30 days</p>
</div>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Total Requests</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{totals.requests.toLocaleString()}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Input Tokens</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{totals.tokensIn.toLocaleString()}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Output Tokens</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{totals.tokensOut.toLocaleString()}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Total Cost</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">${(totals.cost / 100).toFixed(4)}</div>
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle>Daily Breakdown</CardTitle>
</CardHeader>
<CardContent>
{aggregates.length === 0 ? (
<p className="text-sm text-muted-foreground">No usage data yet.</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Date</TableHead>
<TableHead>Requests</TableHead>
<TableHead>Tokens In</TableHead>
<TableHead>Tokens Out</TableHead>
<TableHead>Cost</TableHead>
<TableHead>Errors</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{aggregates.map((row) => (
<TableRow key={row.id}>
<TableCell>{new Date(row.date).toLocaleDateString()}</TableCell>
<TableCell>{row.totalRequests.toLocaleString()}</TableCell>
<TableCell>{row.totalTokensIn.toLocaleString()}</TableCell>
<TableCell>{row.totalTokensOut.toLocaleString()}</TableCell>
<TableCell>${(row.totalCostCents / 100).toFixed(4)}</TableCell>
<TableCell>{row.totalErrors}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
<UsageBreakdownCharts
daily={chartDaily}
providers={chartProviders}
models={chartModels}
keys={chartKeys}
/>
</div>
);
}
+40
View File
@@ -0,0 +1,40 @@
@import "tailwindcss";
@theme inline {
--color-background: hsl(230 26% 8%);
--color-foreground: hsl(210 40% 96%);
--color-card: hsl(230 24% 11%);
--color-card-foreground: hsl(210 40% 96%);
--color-popover: hsl(230 24% 11%);
--color-popover-foreground: hsl(210 40% 96%);
--color-primary: hsl(188 100% 62%);
--color-primary-foreground: hsl(220 40% 8%);
--color-secondary: hsl(230 20% 17%);
--color-secondary-foreground: hsl(210 40% 96%);
--color-muted: hsl(230 18% 16%);
--color-muted-foreground: hsl(220 18% 72%);
--color-accent: hsl(230 20% 20%);
--color-accent-foreground: hsl(210 40% 96%);
--color-destructive: hsl(2 79% 60%);
--color-destructive-foreground: hsl(0 0% 98%);
--color-border: hsl(230 20% 24%);
--color-input: hsl(230 20% 24%);
--color-ring: hsl(188 100% 62%);
--radius: 0.5rem;
}
@layer base {
* {
border-color: var(--color-border);
}
html {
color-scheme: dark;
}
body {
min-height: 100vh;
background-color: var(--color-background);
color: var(--color-foreground);
background-image: radial-gradient(circle at 10% 10%, hsl(188 100% 62% / 0.08), transparent 25%),
radial-gradient(circle at 90% 20%, hsl(260 90% 65% / 0.08), transparent 30%);
}
}
+22
View File
@@ -0,0 +1,22 @@
import type { Metadata } from "next";
import { SessionProvider } from "@/components/layout/session-provider";
import { Toaster } from "sonner";
import "./globals.css";
export const metadata: Metadata = {
title: "LLM Proxy",
description: "Multi-provider OpenAI-compatible API gateway",
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning className="dark">
<body className="bg-background text-foreground antialiased font-[Inter,ui-sans-serif,system-ui,-apple-system,Segoe_UI,Roboto,Helvetica,Arial,sans-serif]">
<SessionProvider>
{children}
<Toaster richColors position="top-right" />
</SessionProvider>
</body>
</html>
);
}
+180
View File
@@ -0,0 +1,180 @@
import Link from "next/link";
import {
Activity,
ArrowRight,
Gauge,
Layers,
ShieldCheck,
Sparkles,
Wallet,
Zap,
} from "lucide-react";
import { getSession } from "@/lib/auth-helpers";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
const features = [
{
title: "One endpoint, every major model",
description:
"Plug into OpenAI, Anthropic, Grok, DeepSeek, and Perplexity with one base URL and one API format.",
icon: Layers,
},
{
title: "No workflow interruptions",
description:
"Use pooled provider capacity and automatic routing to avoid sudden lockouts and keep shipping continuously.",
icon: Zap,
},
{
title: "Built-in observability",
description:
"Track requests, token usage, latency, provider breakdowns, and cost from a clean real-time dashboard.",
icon: Activity,
},
{
title: "Smart cost controls",
description:
"Set per-key request, token, and spend limits with granular policy controls for teams and environments.",
icon: Wallet,
},
{
title: "Production-safe auth",
description:
"Use scoped user keys, encrypted provider credentials, and role-based admin controls for secure operations.",
icon: ShieldCheck,
},
{
title: "Fast model routing",
description:
"Route by model mapping with provider fallback support, high throughput behavior, and low response latency.",
icon: Gauge,
},
];
const stats = [
{ label: "Setup Time", value: "~30s" },
{ label: "Models Supported", value: "19+" },
{ label: "Provider Adapters", value: "5" },
{ label: "Streaming", value: "SSE Ready" },
];
const providers = ["OpenAI", "Anthropic", "Grok (xAI)", "DeepSeek", "Perplexity"];
export default async function Home() {
const session = await getSession();
return (
<main className="relative min-h-screen overflow-hidden bg-background text-foreground">
<div className="pointer-events-none absolute inset-0 opacity-70">
<div className="absolute -left-40 top-0 h-96 w-96 rounded-full bg-cyan-500/15 blur-3xl" />
<div className="absolute right-0 top-40 h-[28rem] w-[28rem] rounded-full bg-indigo-500/20 blur-3xl" />
<div className="absolute bottom-0 left-1/3 h-80 w-80 rounded-full bg-violet-500/15 blur-3xl" />
</div>
<div className="relative mx-auto flex w-full max-w-6xl flex-col px-6 pb-16 pt-8 md:px-10">
<header className="mb-16 flex items-center justify-between rounded-2xl border border-white/10 bg-black/30 px-5 py-3 backdrop-blur-xl">
<div className="flex items-center gap-2 text-sm font-medium">
<Sparkles className="h-4 w-4 text-cyan-300" />
<span className="tracking-wide">LLM Proxy</span>
</div>
<div className="flex items-center gap-2">
<Button asChild variant="ghost" className="text-muted-foreground hover:text-foreground">
<Link href="/login">Login</Link>
</Button>
<Button asChild className="bg-cyan-400 text-black hover:bg-cyan-300">
<Link href={session?.user ? "/dashboard" : "/register"}>
{session?.user ? "Open Dashboard" : "Get Started"}
</Link>
</Button>
</div>
</header>
<section className="mb-14">
<Badge className="mb-5 border-cyan-300/30 bg-cyan-300/10 text-cyan-200" variant="outline">
OpenAI-Compatible Multi-Provider Gateway
</Badge>
<h1 className="max-w-4xl text-4xl font-semibold leading-tight tracking-tight md:text-6xl">
One key. Every model. One clean API.
</h1>
<p className="mt-5 max-w-2xl text-base text-muted-foreground md:text-lg">
LLM Proxy unifies top model providers behind a single endpoint so your tools, SDKs, and teams can
ship faster without juggling multiple integrations.
</p>
<div className="mt-8 flex flex-wrap items-center gap-3">
<Button asChild size="lg" className="bg-cyan-400 text-black hover:bg-cyan-300">
<Link href={session?.user ? "/dashboard" : "/register"}>
Start Building
<ArrowRight className="h-4 w-4" />
</Link>
</Button>
<Button asChild size="lg" variant="outline" className="border-white/20 bg-white/5 hover:bg-white/10">
<Link href="/v1/models">View Models API</Link>
</Button>
</div>
</section>
<section className="mb-14 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{stats.map((item) => (
<Card key={item.label} className="border-white/10 bg-white/5 backdrop-blur-sm">
<CardContent className="p-5">
<p className="text-xs uppercase tracking-[0.18em] text-muted-foreground">{item.label}</p>
<p className="mt-2 text-2xl font-semibold">{item.value}</p>
</CardContent>
</Card>
))}
</section>
<section className="mb-14 rounded-3xl border border-white/10 bg-white/5 p-6 backdrop-blur-sm md:p-8">
<p className="mb-4 text-xs uppercase tracking-[0.2em] text-muted-foreground">Providers</p>
<div className="grid gap-3 sm:grid-cols-2 md:grid-cols-3">
{providers.map((provider) => (
<div
key={provider}
className="rounded-xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-foreground/90"
>
{provider}
</div>
))}
</div>
</section>
<section className="mb-14">
<div className="mb-6 flex items-center justify-between">
<h2 className="text-2xl font-semibold md:text-3xl">Everything you need to ship faster</h2>
<Badge variant="outline" className="border-white/15 bg-white/5 text-muted-foreground">
Modern API SaaS
</Badge>
</div>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{features.map((feature) => (
<Card key={feature.title} className="border-white/10 bg-black/25">
<CardContent className="p-6">
<feature.icon className="mb-4 h-5 w-5 text-cyan-300" />
<h3 className="mb-2 text-base font-semibold">{feature.title}</h3>
<p className="text-sm text-muted-foreground">{feature.description}</p>
</CardContent>
</Card>
))}
</div>
</section>
<section className="rounded-3xl border border-cyan-300/20 bg-gradient-to-r from-cyan-400/15 via-indigo-400/10 to-violet-400/15 p-8 text-center">
<h3 className="text-2xl font-semibold md:text-3xl">Stop fighting limits. Start shipping continuously.</h3>
<p className="mx-auto mt-3 max-w-2xl text-muted-foreground">
Connect once, route everywhere, and manage usage from a single dark-first control plane.
</p>
<div className="mt-6 flex justify-center gap-3">
<Button asChild size="lg" className="bg-cyan-400 text-black hover:bg-cyan-300">
<Link href={session?.user ? "/dashboard" : "/register"}>Launch Dashboard</Link>
</Button>
<Button asChild size="lg" variant="ghost" className="text-muted-foreground hover:text-foreground">
<Link href="/login">Sign In</Link>
</Button>
</div>
</section>
</div>
</main>
);
}
+8
View File
@@ -0,0 +1,8 @@
import { handleChatCompletion } from "@/server/services/request-handler";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function POST(request: Request): Promise<Response> {
return handleChatCompletion(request);
}
+8
View File
@@ -0,0 +1,8 @@
import { handleCompletion } from "@/server/services/request-handler";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function POST(request: Request): Promise<Response> {
return handleCompletion(request);
}
+8
View File
@@ -0,0 +1,8 @@
import { handleEmbeddings } from "@/server/services/request-handler";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function POST(request: Request): Promise<Response> {
return handleEmbeddings(request);
}
+61
View File
@@ -0,0 +1,61 @@
import { getMongoDb } from "@/lib/mongo";
import { authenticateApiKey } from "@/server/services/api-key-auth";
import { invalidApiKey } from "@/lib/api-error";
import type { OpenAIModelList } from "@/types/openai-compat";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function GET(request: Request): Promise<Response> {
const auth = await authenticateApiKey(request.headers.get("Authorization"));
if (!auth) {
return invalidApiKey().toResponse();
}
const mappings = await getMongoDb()
.collection<{ _id: string }>("model_mappings")
.aggregate([
{ $match: { enabled: true } },
{
$lookup: {
from: "providers",
localField: "providerId",
foreignField: "_id",
as: "provider",
},
},
{ $unwind: "$provider" },
{ $match: { "provider.enabled": true } },
{
$lookup: {
from: "provider_api_keys",
let: { providerId: "$providerId" },
pipeline: [
{
$match: {
$expr: { $eq: ["$providerId", "$$providerId"] },
status: "ACTIVE",
},
},
{ $limit: 1 },
],
as: "activeProviderKeys",
},
},
{ $match: { activeProviderKeys: { $ne: [] } } },
{ $group: { _id: "$logicalModelId" } },
])
.toArray();
const models: OpenAIModelList = {
object: "list",
data: mappings.map((m) => ({
id: m._id,
object: "model" as const,
created: Math.floor(Date.now() / 1000),
owned_by: "llm-proxy",
})),
};
return Response.json(models);
}
@@ -0,0 +1,125 @@
"use client";
import { Bar, BarChart, CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
interface ProviderRow {
name: string;
requests: number;
cost: number;
}
interface DailyRow {
date: string;
requests: number;
errors: number;
cost: number;
}
export function AdminAnalyticsCharts({
providers,
daily,
}: {
providers: ProviderRow[];
daily: DailyRow[];
}) {
const numberFormatter = new Intl.NumberFormat("en-US");
const currencyFormatter = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
minimumFractionDigits: 2,
});
const toNumber = (value: number | string | readonly (number | string)[] | undefined) => {
if (Array.isArray(value)) {
const first = value[0];
return typeof first === "number" ? first : Number(first ?? 0);
}
return typeof value === "number" ? value : Number(value ?? 0);
};
return (
<div className="grid gap-6 lg:grid-cols-2">
<div className="h-80 rounded-xl border bg-linear-to-b from-card to-card/30 p-4 shadow-sm">
<h3 className="mb-4 text-sm font-semibold tracking-tight">Requests by Provider</h3>
<ResponsiveContainer width="100%" height="90%">
<BarChart data={providers}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" vertical={false} />
<XAxis dataKey="name" tickLine={false} axisLine={false} />
<YAxis tickLine={false} axisLine={false} tickFormatter={(value) => numberFormatter.format(value)} />
<Tooltip
contentStyle={{
borderRadius: 10,
borderColor: "hsl(var(--border))",
backgroundColor: "hsl(var(--card))",
}}
formatter={(value, name) =>
name === "cost"
? [currencyFormatter.format(toNumber(value)), "Cost"]
: [numberFormatter.format(toNumber(value)), "Requests"]
}
/>
<Bar dataKey="requests" fill="hsl(var(--primary))" radius={[8, 8, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
<div className="h-80 rounded-xl border bg-linear-to-b from-card to-card/30 p-4 shadow-sm">
<h3 className="mb-4 text-sm font-semibold tracking-tight">Daily Requests / Errors / Cost</h3>
<ResponsiveContainer width="100%" height="90%">
<LineChart data={daily}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" vertical={false} />
<XAxis dataKey="date" tickLine={false} axisLine={false} />
<YAxis
yAxisId="left"
tickLine={false}
axisLine={false}
tickFormatter={(value) => numberFormatter.format(value)}
/>
<YAxis
yAxisId="right"
orientation="right"
tickLine={false}
axisLine={false}
tickFormatter={(value) => currencyFormatter.format(value)}
/>
<Tooltip
contentStyle={{
borderRadius: 10,
borderColor: "hsl(var(--border))",
backgroundColor: "hsl(var(--card))",
}}
formatter={(value, name) =>
name === "cost"
? [currencyFormatter.format(toNumber(value)), "Cost"]
: [numberFormatter.format(toNumber(value)), name === "errors" ? "Errors" : "Requests"]
}
/>
<Line
yAxisId="left"
type="monotone"
dataKey="requests"
stroke="hsl(var(--primary))"
strokeWidth={2}
dot={false}
/>
<Line
yAxisId="left"
type="monotone"
dataKey="errors"
stroke="#ef4444"
strokeWidth={2}
dot={false}
/>
<Line
yAxisId="right"
type="monotone"
dataKey="cost"
stroke="#22c55e"
strokeWidth={2}
dot={false}
/>
</LineChart>
</ResponsiveContainer>
</div>
</div>
);
}
+172
View File
@@ -0,0 +1,172 @@
"use client";
import { useState } from "react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
export interface PlanRow {
id: string;
name: string;
displayName: string;
monthlyPriceCents: number;
dailyRequestLimit?: number | null;
dailyTokenLimit?: number | null;
maxApiKeys: number;
isPublic: boolean;
sortOrder: number;
_count?: { subscriptions: number };
}
type EditablePlan = {
id: string;
displayName: string;
monthlyPriceDollars: string;
dailyRequestLimit: string;
dailyTokenLimit: string;
maxApiKeys: string;
isPublic: boolean;
sortOrder: string;
};
function toEditable(plan: PlanRow): EditablePlan {
return {
id: plan.id,
displayName: plan.displayName,
monthlyPriceDollars: (plan.monthlyPriceCents / 100).toString(),
dailyRequestLimit: plan.dailyRequestLimit == null ? "" : String(plan.dailyRequestLimit),
dailyTokenLimit: plan.dailyTokenLimit == null ? "" : String(plan.dailyTokenLimit),
maxApiKeys: String(plan.maxApiKeys),
isPublic: plan.isPublic,
sortOrder: String(plan.sortOrder),
};
}
export function PlanManagement({ initialPlans }: { initialPlans: PlanRow[] }) {
const [plans, setPlans] = useState<PlanRow[]>(initialPlans);
const [edited, setEdited] = useState<Record<string, EditablePlan>>(
() => Object.fromEntries(initialPlans.map((plan) => [plan.id, toEditable(plan)])) as Record<string, EditablePlan>,
);
const [savingId, setSavingId] = useState<string | null>(null);
function updateDraft(planId: string, updates: Partial<EditablePlan>) {
setEdited((current) => ({
...current,
[planId]: { ...current[planId], ...updates },
}));
}
async function savePlan(planId: string) {
const draft = edited[planId];
if (!draft) return;
setSavingId(planId);
const res = await fetch("/api/admin/plans", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
id: planId,
displayName: draft.displayName.trim(),
monthlyPriceCents: Math.round(Number(draft.monthlyPriceDollars || 0) * 100),
dailyRequestLimit: draft.dailyRequestLimit.trim() === "" ? null : Number(draft.dailyRequestLimit),
dailyTokenLimit: draft.dailyTokenLimit.trim() === "" ? null : Number(draft.dailyTokenLimit),
maxApiKeys: Number(draft.maxApiKeys),
isPublic: draft.isPublic,
sortOrder: Number(draft.sortOrder),
}),
});
setSavingId(null);
if (!res.ok) {
const payload = (await res.json().catch(() => null)) as { error?: string } | null;
toast.error(payload?.error ?? "Failed to update plan");
return;
}
const payload = (await res.json()) as { data?: PlanRow };
if (payload.data) {
setPlans((current) => current.map((plan) => (plan.id === planId ? { ...plan, ...payload.data } : plan)));
setEdited((current) => ({ ...current, [planId]: toEditable(payload.data as PlanRow) }));
}
toast.success("Plan updated");
}
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">Subscription Plans</h1>
<Card>
<CardHeader>
<CardTitle>All Plans</CardTitle>
</CardHeader>
<CardContent>
{plans.length === 0 ? (
<p className="text-sm text-muted-foreground">No plans configured. Run the seed script.</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Display Name</TableHead>
<TableHead>Price $/mo</TableHead>
<TableHead>Daily Requests</TableHead>
<TableHead>Daily Tokens</TableHead>
<TableHead>Max Keys</TableHead>
<TableHead>Visibility</TableHead>
<TableHead>Order</TableHead>
<TableHead>Subscribers</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
{plans.map((plan) => {
const draft = edited[plan.id] ?? toEditable(plan);
const busy = savingId === plan.id;
return (
<TableRow key={plan.id}>
<TableCell className="font-medium">{plan.name}</TableCell>
<TableCell className="min-w-[180px]">
<Input value={draft.displayName} onChange={(e) => updateDraft(plan.id, { displayName: e.target.value })} />
</TableCell>
<TableCell className="min-w-[120px]">
<Input type="number" min={0} step="0.01" value={draft.monthlyPriceDollars} onChange={(e) => updateDraft(plan.id, { monthlyPriceDollars: e.target.value })} />
</TableCell>
<TableCell className="min-w-[140px]">
<Input type="number" min={1} value={draft.dailyRequestLimit} onChange={(e) => updateDraft(plan.id, { dailyRequestLimit: e.target.value })} placeholder="Unlimited" />
</TableCell>
<TableCell className="min-w-[140px]">
<Input type="number" min={1} value={draft.dailyTokenLimit} onChange={(e) => updateDraft(plan.id, { dailyTokenLimit: e.target.value })} placeholder="Unlimited" />
</TableCell>
<TableCell className="w-[110px]">
<Input type="number" min={1} value={draft.maxApiKeys} onChange={(e) => updateDraft(plan.id, { maxApiKeys: e.target.value })} />
</TableCell>
<TableCell>
<button
type="button"
onClick={() => updateDraft(plan.id, { isPublic: !draft.isPublic })}
className="rounded-md border px-2 py-1 text-xs"
>
<Badge variant={draft.isPublic ? "default" : "secondary"}>
{draft.isPublic ? "Public" : "Hidden"}
</Badge>
</button>
</TableCell>
<TableCell className="w-[90px]">
<Input type="number" value={draft.sortOrder} onChange={(e) => updateDraft(plan.id, { sortOrder: e.target.value })} />
</TableCell>
<TableCell>{plan._count?.subscriptions ?? 0}</TableCell>
<TableCell>
<Button size="sm" onClick={() => savePlan(plan.id)} disabled={busy}>
{busy ? "Saving..." : "Save"}
</Button>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</div>
);
}
@@ -0,0 +1,398 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { formatDateTimeSafe } from "@/lib/date";
import { cn } from "@/lib/utils";
interface ProviderSummary {
id: string;
displayName: string;
baseUrl: string;
enabled: boolean;
_count: {
apiKeys: number;
modelMappings: number;
};
}
interface ProviderApiKey {
id: string;
label?: string | null;
keyPreview?: string;
status: "ACTIVE" | "DISABLED" | "EXHAUSTED" | "ERROR";
errorCount?: number;
lastValidatedAt?: string | null;
lastUsedAt?: string | null;
createdAt: string;
metadata?: {
models?: string[];
} | null;
}
interface IngestionBatch {
id: string;
providerId?: string | null;
status: string;
totalKeys: number;
successfulKeys: number;
failedKeys: number;
createdAt: string;
}
type AdminTab = "providers" | "ingestion";
export function ProviderManagement() {
const searchParams = useSearchParams();
const [tab, setTab] = useState<AdminTab>(searchParams.get("tab") === "ingestion" ? "ingestion" : "providers");
const [providers, setProviders] = useState<ProviderSummary[]>([]);
const [loadingProviders, setLoadingProviders] = useState(true);
const [selectedProviderId, setSelectedProviderId] = useState("");
const [providerKeys, setProviderKeys] = useState<ProviderApiKey[]>([]);
const [loadingKeys, setLoadingKeys] = useState(false);
const [providerIdHint, setProviderIdHint] = useState("");
const [rawKeys, setRawKeys] = useState("");
const [file, setFile] = useState<File | null>(null);
const [ingesting, setIngesting] = useState(false);
const [batches, setBatches] = useState<IngestionBatch[]>([]);
const selectedProvider = useMemo(
() => providers.find((provider) => provider.id === selectedProviderId),
[providers, selectedProviderId],
);
const loadProviders = useCallback(async () => {
setLoadingProviders(true);
const res = await fetch("/api/admin/providers");
if (!res.ok) {
toast.error("Failed to load providers");
setLoadingProviders(false);
return;
}
const data = (await res.json()) as { data: ProviderSummary[] };
const list = data.data ?? [];
setProviders(list);
if (!selectedProviderId && list.length > 0) {
setSelectedProviderId(list[0].id);
}
if (selectedProviderId && !list.some((provider) => provider.id === selectedProviderId)) {
setSelectedProviderId(list[0]?.id ?? "");
}
setLoadingProviders(false);
}, [selectedProviderId]);
async function loadProviderKeys(providerId: string) {
if (!providerId) {
setProviderKeys([]);
return;
}
setLoadingKeys(true);
const res = await fetch(`/api/admin/providers/${providerId}/keys`);
if (!res.ok) {
toast.error("Failed to load provider keys");
setLoadingKeys(false);
return;
}
const data = (await res.json()) as { data: ProviderApiKey[] };
setProviderKeys(data.data ?? []);
setLoadingKeys(false);
}
async function loadBatches() {
const res = await fetch("/api/admin/providers/ingest");
if (!res.ok) return;
const data = (await res.json()) as { data: IngestionBatch[] };
setBatches(data.data ?? []);
}
useEffect(() => {
loadProviders().catch(() => {});
loadBatches().catch(() => {});
}, [loadProviders]);
useEffect(() => {
if (!selectedProviderId) return;
loadProviderKeys(selectedProviderId).catch(() => {});
}, [selectedProviderId]);
async function toggleKeyStatus(key: ProviderApiKey) {
const nextStatus = key.status === "ACTIVE" ? "DISABLED" : "ACTIVE";
const res = await fetch(`/api/admin/providers/${selectedProviderId}/keys/${key.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ status: nextStatus }),
});
if (!res.ok) {
toast.error("Failed to update key status");
return;
}
toast.success(`Key ${nextStatus === "ACTIVE" ? "enabled" : "disabled"}`);
loadProviderKeys(selectedProviderId).catch(() => {});
loadProviders().catch(() => {});
}
async function deleteKey(key: ProviderApiKey) {
const confirmed = window.confirm("Delete this provider key permanently?");
if (!confirmed) return;
const res = await fetch(`/api/admin/providers/${selectedProviderId}/keys/${key.id}`, {
method: "DELETE",
});
if (!res.ok) {
toast.error("Failed to delete key");
return;
}
toast.success("Key deleted");
loadProviderKeys(selectedProviderId).catch(() => {});
loadProviders().catch(() => {});
}
async function submitIngestion() {
if (!rawKeys.trim() && !file) {
toast.error("Add raw keys text or upload a file.");
return;
}
setIngesting(true);
const formData = new FormData();
if (providerIdHint.trim()) formData.append("providerId", providerIdHint.trim());
if (file) formData.append("file", file);
if (rawKeys.trim()) formData.append("rawKeys", rawKeys.trim());
const res = await fetch("/api/admin/providers/ingest", {
method: "POST",
body: formData,
});
setIngesting(false);
if (!res.ok) {
const payload = (await res.json().catch(() => null)) as { error?: string } | null;
toast.error(payload?.error ?? "Ingestion failed");
return;
}
toast.success("Provider keys ingested");
setRawKeys("");
setFile(null);
loadProviders().catch(() => {});
loadBatches().catch(() => {});
if (selectedProviderId) {
loadProviderKeys(selectedProviderId).catch(() => {});
}
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold">Provider Management</h1>
<p className="text-muted-foreground">Manage ingested provider keys and routing readiness.</p>
</div>
<div className="flex items-center gap-2 rounded-lg border bg-muted/20 p-1">
<button
onClick={() => setTab("providers")}
className={cn(
"rounded-md px-3 py-1.5 text-sm font-medium",
tab === "providers" ? "bg-primary text-primary-foreground" : "text-muted-foreground",
)}
>
Providers & Keys
</button>
<button
onClick={() => setTab("ingestion")}
className={cn(
"rounded-md px-3 py-1.5 text-sm font-medium",
tab === "ingestion" ? "bg-primary text-primary-foreground" : "text-muted-foreground",
)}
>
Ingestion
</button>
</div>
</div>
{tab === "providers" ? (
<div className="grid gap-6 lg:grid-cols-[380px_minmax(0,1fr)]">
<Card>
<CardHeader>
<CardTitle>Providers</CardTitle>
</CardHeader>
<CardContent className="space-y-2">
{loadingProviders ? (
<p className="text-sm text-muted-foreground">Loading providers...</p>
) : providers.length === 0 ? (
<p className="text-sm text-muted-foreground">No providers found.</p>
) : (
providers.map((provider) => (
<button
key={provider.id}
onClick={() => setSelectedProviderId(provider.id)}
className={cn(
"w-full rounded-lg border p-3 text-left transition-colors",
selectedProviderId === provider.id ? "border-primary bg-primary/5" : "hover:bg-muted/30",
)}
>
<div className="flex items-center justify-between">
<p className="font-medium">{provider.displayName}</p>
<Badge variant={provider.enabled ? "default" : "secondary"}>
{provider.enabled ? "Enabled" : "Disabled"}
</Badge>
</div>
<p className="mt-1 font-mono text-xs text-muted-foreground">{provider.id}</p>
<div className="mt-2 flex items-center gap-4 text-xs text-muted-foreground">
<span>{provider._count.apiKeys} keys</span>
<span>{provider._count.modelMappings} mappings</span>
</div>
</button>
))
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>{selectedProvider ? `${selectedProvider.displayName} Keys` : "Provider Keys"}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{selectedProvider && (
<div className="rounded-md border bg-muted/20 p-3 text-sm">
<p>
<span className="font-medium">Routing status:</span>{" "}
{selectedProvider._count.apiKeys > 0 && selectedProvider._count.modelMappings > 0 && selectedProvider.enabled
? "Ready (keys + mappings + enabled)"
: "Not ready"}
</p>
<p className="mt-1 text-muted-foreground">
Needs: provider enabled, at least one ACTIVE key, and model mappings in `Model Mappings`.
</p>
</div>
)}
{loadingKeys ? (
<p className="text-sm text-muted-foreground">Loading provider keys...</p>
) : providerKeys.length === 0 ? (
<p className="text-sm text-muted-foreground">
No keys found for this provider. Use the Ingestion tab to add keys.
</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Status</TableHead>
<TableHead>Key</TableHead>
<TableHead>Label</TableHead>
<TableHead>Models</TableHead>
<TableHead>Last Used</TableHead>
<TableHead>Created</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
{providerKeys.map((key) => (
<TableRow key={key.id}>
<TableCell>
<Badge variant={key.status === "ACTIVE" ? "default" : "secondary"}>{key.status}</Badge>
</TableCell>
<TableCell className="font-mono text-xs">{key.keyPreview ?? "-"}</TableCell>
<TableCell>{key.label ?? "-"}</TableCell>
<TableCell className="text-sm text-muted-foreground">
{key.metadata?.models?.length ? key.metadata.models.slice(0, 3).join(", ") : "-"}
</TableCell>
<TableCell className="text-sm">
{key.lastUsedAt ? formatDateTimeSafe(key.lastUsedAt, "Never") : "Never"}
</TableCell>
<TableCell className="text-sm">{formatDateTimeSafe(key.createdAt)}</TableCell>
<TableCell className="space-x-2">
<Button size="sm" variant="outline" onClick={() => toggleKeyStatus(key)}>
{key.status === "ACTIVE" ? "Disable" : "Enable"}
</Button>
<Button size="sm" variant="destructive" onClick={() => deleteKey(key)}>
Delete
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</div>
) : (
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_420px]">
<Card>
<CardHeader>
<CardTitle>Ingest Provider Keys</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="providerIdHint">Provider ID (optional)</Label>
<Input
id="providerIdHint"
value={providerIdHint}
onChange={(event) => setProviderIdHint(event.target.value)}
placeholder="openai, anthropic, deepseek, perplexity..."
/>
</div>
<div className="space-y-2">
<Label htmlFor="providerFile">Upload .txt file</Label>
<Input
id="providerFile"
type="file"
accept=".txt"
onChange={(event) => setFile(event.target.files?.[0] ?? null)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="rawKeys">Or paste keys (one per line)</Label>
<textarea
id="rawKeys"
value={rawKeys}
onChange={(event) => setRawKeys(event.target.value)}
placeholder={"sk-...\nsk-..."}
className="min-h-48 w-full rounded-md border bg-background px-3 py-2 text-sm"
/>
</div>
<Button onClick={submitIngestion} disabled={ingesting}>
{ingesting ? "Ingesting..." : "Ingest Keys"}
</Button>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Recent Batches</CardTitle>
</CardHeader>
<CardContent>
{batches.length === 0 ? (
<p className="text-sm text-muted-foreground">No ingestion batches yet.</p>
) : (
<div className="space-y-2">
{batches.map((batch) => (
<div key={batch.id} className="rounded-md border p-3">
<div className="flex items-center justify-between">
<p className="font-mono text-xs text-muted-foreground">{batch.id.slice(0, 12)}</p>
<Badge variant={batch.failedKeys > 0 ? "secondary" : "default"}>{batch.status}</Badge>
</div>
<p className="mt-2 text-sm">
{batch.providerId ?? "auto-detect"} - {batch.successfulKeys}/{batch.totalKeys} success
</p>
<p className="text-xs text-muted-foreground">{formatDateTimeSafe(batch.createdAt)}</p>
</div>
))}
</div>
)}
</CardContent>
</Card>
</div>
)}
</div>
);
}
+234
View File
@@ -0,0 +1,234 @@
"use client";
import { useMemo, useState } from "react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
type UserRole = "USER" | "ADMIN";
type UserStatus = "ACTIVE" | "SUSPENDED" | "BANNED";
type SubscriptionStatus = "ACTIVE" | "PAST_DUE" | "CANCELED" | "TRIALING";
export interface PlanOption {
id: string;
displayName: string;
}
export interface AdminUserRow {
id: string;
email: string;
name?: string | null;
role: UserRole;
status: UserStatus;
createdAt: string;
_count: {
apiKeys: number;
requestLogs: number;
};
subscription?: {
id: string;
planId: string;
status: SubscriptionStatus;
plan?: {
id: string;
displayName: string;
} | null;
} | null;
}
interface EditableUser {
id: string;
name: string;
role: UserRole;
status: UserStatus;
planId: string;
subscriptionStatus: SubscriptionStatus;
}
function toEditable(user: AdminUserRow): EditableUser {
return {
id: user.id,
name: user.name ?? "",
role: user.role,
status: user.status,
planId: user.subscription?.planId ?? "",
subscriptionStatus: user.subscription?.status ?? "ACTIVE",
};
}
export function UserManagement({
initialUsers,
plans,
}: {
initialUsers: AdminUserRow[];
plans: PlanOption[];
}) {
const [users, setUsers] = useState<AdminUserRow[]>(initialUsers);
const [edited, setEdited] = useState<Record<string, EditableUser>>(
() => Object.fromEntries(initialUsers.map((user) => [user.id, toEditable(user)])) as Record<string, EditableUser>,
);
const [savingId, setSavingId] = useState<string | null>(null);
const hasUsers = useMemo(() => users.length > 0, [users.length]);
function updateDraft(userId: string, updates: Partial<EditableUser>) {
setEdited((current) => ({
...current,
[userId]: {
...current[userId],
...updates,
},
}));
}
async function saveUser(userId: string) {
const draft = edited[userId];
if (!draft) return;
setSavingId(userId);
const res = await fetch("/api/admin/users", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
userId,
name: draft.name.trim() || undefined,
role: draft.role,
status: draft.status,
planId: draft.planId === "" ? null : draft.planId,
subscriptionStatus: draft.subscriptionStatus,
}),
});
setSavingId(null);
if (!res.ok) {
const payload = (await res.json().catch(() => null)) as { error?: string } | null;
toast.error(payload?.error ?? "Failed to save user");
return;
}
const payload = (await res.json()) as { data?: AdminUserRow };
if (payload.data) {
const nextUser = payload.data;
setUsers((current) => current.map((user) => (user.id === userId ? nextUser : user)));
setEdited((current) => ({
...current,
[userId]: toEditable(nextUser),
}));
}
toast.success("User updated");
}
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">Users</h1>
<Card>
<CardHeader>
<CardTitle>All Users ({users.length})</CardTitle>
</CardHeader>
<CardContent>
{!hasUsers ? (
<p className="text-sm text-muted-foreground">No users found.</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Email</TableHead>
<TableHead>Name</TableHead>
<TableHead>Role</TableHead>
<TableHead>Status</TableHead>
<TableHead>Plan</TableHead>
<TableHead>Sub Status</TableHead>
<TableHead>API Keys</TableHead>
<TableHead>Requests</TableHead>
<TableHead>Joined</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
{users.map((user) => {
const draft = edited[user.id] ?? toEditable(user);
const busy = savingId === user.id;
return (
<TableRow key={user.id}>
<TableCell className="max-w-[220px] truncate">{user.email}</TableCell>
<TableCell className="min-w-[180px]">
<Input
value={draft.name}
onChange={(event) => updateDraft(user.id, { name: event.target.value })}
placeholder="Name"
/>
</TableCell>
<TableCell>
<select
className="h-9 rounded-md border bg-background px-2 text-sm"
value={draft.role}
onChange={(event) => updateDraft(user.id, { role: event.target.value as UserRole })}
>
<option value="USER">USER</option>
<option value="ADMIN">ADMIN</option>
</select>
</TableCell>
<TableCell>
<select
className="h-9 rounded-md border bg-background px-2 text-sm"
value={draft.status}
onChange={(event) => updateDraft(user.id, { status: event.target.value as UserStatus })}
>
<option value="ACTIVE">ACTIVE</option>
<option value="SUSPENDED">SUSPENDED</option>
<option value="BANNED">BANNED</option>
</select>
</TableCell>
<TableCell>
<select
className="h-9 rounded-md border bg-background px-2 text-sm"
value={draft.planId}
onChange={(event) => updateDraft(user.id, { planId: event.target.value })}
>
<option value="">No Plan</option>
{plans.map((plan) => (
<option key={plan.id} value={plan.id}>
{plan.displayName}
</option>
))}
</select>
</TableCell>
<TableCell>
<select
className="h-9 rounded-md border bg-background px-2 text-sm"
value={draft.subscriptionStatus}
onChange={(event) =>
updateDraft(user.id, { subscriptionStatus: event.target.value as SubscriptionStatus })
}
>
<option value="ACTIVE">ACTIVE</option>
<option value="PAST_DUE">PAST_DUE</option>
<option value="CANCELED">CANCELED</option>
<option value="TRIALING">TRIALING</option>
</select>
</TableCell>
<TableCell>
<Badge variant="secondary">{user._count.apiKeys}</Badge>
</TableCell>
<TableCell>{user._count.requestLogs}</TableCell>
<TableCell className="text-sm">{new Date(user.createdAt).toLocaleDateString()}</TableCell>
<TableCell>
<Button size="sm" onClick={() => saveUser(user.id)} disabled={busy}>
{busy ? "Saving..." : "Save"}
</Button>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</div>
);
}
@@ -0,0 +1,126 @@
"use client";
import {
Area,
AreaChart,
Bar,
BarChart,
CartesianGrid,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
type TrendPoint = {
date: string;
requests: number;
tokens: number;
cost: number;
};
type ProviderPoint = {
name: string;
requests: number;
};
export function DashboardUsageGraphs({
trend,
providers,
}: {
trend: TrendPoint[];
providers: ProviderPoint[];
}) {
const numberFormatter = new Intl.NumberFormat("en-US");
const currencyFormatter = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
return (
<div className="grid gap-4 xl:grid-cols-3">
<div className="xl:col-span-2 rounded-2xl border bg-linear-to-br from-card to-card/30 p-5 shadow-sm">
<div className="mb-4 flex items-center justify-between">
<div>
<p className="text-xs uppercase tracking-wider text-muted-foreground">Last 14 days</p>
<h3 className="text-base font-semibold">Usage Trend</h3>
</div>
<div className="text-right">
<p className="text-xs text-muted-foreground">Total Cost</p>
<p className="text-sm font-semibold">
{currencyFormatter.format(trend.reduce((acc, point) => acc + point.cost, 0))}
</p>
</div>
</div>
<div className="h-72">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={trend}>
<defs>
<linearGradient id="requestsFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="hsl(var(--primary))" stopOpacity={0.35} />
<stop offset="95%" stopColor="hsl(var(--primary))" stopOpacity={0.03} />
</linearGradient>
<linearGradient id="tokensFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#06b6d4" stopOpacity={0.2} />
<stop offset="95%" stopColor="#06b6d4" stopOpacity={0.03} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsl(var(--border))" />
<XAxis dataKey="date" tickLine={false} axisLine={false} />
<YAxis tickLine={false} axisLine={false} tickFormatter={(value) => numberFormatter.format(value)} />
<Tooltip
contentStyle={{
borderRadius: 12,
borderColor: "hsl(var(--border))",
backgroundColor: "hsl(var(--card))",
}}
formatter={(value, key) => {
const numeric = typeof value === "number" ? value : Number(value);
if (key === "cost") return [currencyFormatter.format(numeric), "Cost"];
return [numberFormatter.format(numeric), key === "requests" ? "Requests" : "Tokens"];
}}
/>
<Area
type="monotone"
dataKey="requests"
stroke="hsl(var(--primary))"
fill="url(#requestsFill)"
strokeWidth={2}
/>
<Area type="monotone" dataKey="tokens" stroke="#06b6d4" fill="url(#tokensFill)" strokeWidth={2} />
</AreaChart>
</ResponsiveContainer>
</div>
</div>
<div className="rounded-2xl border bg-linear-to-br from-card to-card/30 p-5 shadow-sm">
<div className="mb-4">
<p className="text-xs uppercase tracking-wider text-muted-foreground">Distribution</p>
<h3 className="text-base font-semibold">Requests by Provider</h3>
</div>
<div className="h-72">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={providers} layout="vertical" margin={{ left: 6, right: 10 }}>
<CartesianGrid strokeDasharray="3 3" horizontal={false} stroke="hsl(var(--border))" />
<XAxis type="number" tickLine={false} axisLine={false} tickFormatter={(value) => numberFormatter.format(value)} />
<YAxis dataKey="name" type="category" tickLine={false} axisLine={false} width={90} />
<Tooltip
contentStyle={{
borderRadius: 12,
borderColor: "hsl(var(--border))",
backgroundColor: "hsl(var(--card))",
}}
formatter={(value) => [numberFormatter.format(Number(value)), "Requests"]}
/>
<Bar dataKey="requests" fill="hsl(var(--primary))" radius={[0, 8, 8, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
</div>
</div>
);
}
@@ -0,0 +1,162 @@
"use client";
import { Bar, BarChart, CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
interface DailyPoint {
date: string;
requests: number;
tokensIn: number;
tokensOut: number;
cost: number;
}
interface BreakdownPoint {
name: string;
requests: number;
tokens: number;
cost: number;
}
export function UsageBreakdownCharts({
daily,
providers,
models,
keys,
}: {
daily: DailyPoint[];
providers: BreakdownPoint[];
models: BreakdownPoint[];
keys: BreakdownPoint[];
}) {
const numberFormatter = new Intl.NumberFormat("en-US");
const currencyFormatter = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
minimumFractionDigits: 2,
});
const toNumber = (value: number | string | readonly (number | string)[] | undefined) => {
if (Array.isArray(value)) {
const first = value[0];
return typeof first === "number" ? first : Number(first ?? 0);
}
return typeof value === "number" ? value : Number(value ?? 0);
};
return (
<div className="grid gap-6 lg:grid-cols-2">
<div className="h-80 rounded-xl border bg-linear-to-b from-card to-card/30 p-4 shadow-sm">
<h3 className="mb-4 text-sm font-semibold tracking-tight">Daily Requests & Cost</h3>
<ResponsiveContainer width="100%" height="90%">
<LineChart data={daily}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" vertical={false} />
<XAxis dataKey="date" tickLine={false} axisLine={false} />
<YAxis
yAxisId="left"
tickLine={false}
axisLine={false}
tickFormatter={(value) => numberFormatter.format(value)}
/>
<YAxis
yAxisId="right"
orientation="right"
tickLine={false}
axisLine={false}
tickFormatter={(value) => currencyFormatter.format(value)}
/>
<Tooltip
contentStyle={{
borderRadius: 10,
borderColor: "hsl(var(--border))",
backgroundColor: "hsl(var(--card))",
}}
formatter={(value, name) =>
name === "cost"
? [currencyFormatter.format(toNumber(value)), "Cost"]
: [numberFormatter.format(toNumber(value)), "Requests"]
}
/>
<Line
yAxisId="left"
type="monotone"
dataKey="requests"
stroke="hsl(var(--primary))"
strokeWidth={2}
dot={false}
/>
<Line
yAxisId="right"
type="monotone"
dataKey="cost"
stroke="#22c55e"
strokeWidth={2}
dot={false}
/>
</LineChart>
</ResponsiveContainer>
</div>
<div className="h-80 rounded-xl border bg-linear-to-b from-card to-card/30 p-4 shadow-sm">
<h3 className="mb-4 text-sm font-semibold tracking-tight">Top Providers</h3>
<ResponsiveContainer width="100%" height="90%">
<BarChart data={providers}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" vertical={false} />
<XAxis dataKey="name" tickLine={false} axisLine={false} />
<YAxis tickLine={false} axisLine={false} tickFormatter={(value) => numberFormatter.format(value)} />
<Tooltip
contentStyle={{
borderRadius: 10,
borderColor: "hsl(var(--border))",
backgroundColor: "hsl(var(--card))",
}}
formatter={(value, name) => [numberFormatter.format(toNumber(value)), name]}
/>
<Bar dataKey="requests" fill="hsl(var(--primary))" radius={[8, 8, 0, 0]} />
<Bar dataKey="tokens" fill="#8b5cf6" radius={[8, 8, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
<div className="h-80 rounded-xl border bg-linear-to-b from-card to-card/30 p-4 shadow-sm">
<h3 className="mb-4 text-sm font-semibold tracking-tight">Top Models</h3>
<ResponsiveContainer width="100%" height="90%">
<BarChart data={models}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" vertical={false} />
<XAxis dataKey="name" tickLine={false} axisLine={false} />
<YAxis tickLine={false} axisLine={false} tickFormatter={(value) => numberFormatter.format(value)} />
<Tooltip
contentStyle={{
borderRadius: 10,
borderColor: "hsl(var(--border))",
backgroundColor: "hsl(var(--card))",
}}
formatter={(value, name) => [numberFormatter.format(toNumber(value)), name]}
/>
<Bar dataKey="requests" fill="#06b6d4" radius={[8, 8, 0, 0]} />
<Bar dataKey="tokens" fill="#f97316" radius={[8, 8, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
<div className="h-80 rounded-xl border bg-linear-to-b from-card to-card/30 p-4 shadow-sm">
<h3 className="mb-4 text-sm font-semibold tracking-tight">Top API Keys</h3>
<ResponsiveContainer width="100%" height="90%">
<BarChart data={keys}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" vertical={false} />
<XAxis dataKey="name" tickLine={false} axisLine={false} />
<YAxis tickLine={false} axisLine={false} tickFormatter={(value) => numberFormatter.format(value)} />
<Tooltip
contentStyle={{
borderRadius: 10,
borderColor: "hsl(var(--border))",
backgroundColor: "hsl(var(--card))",
}}
formatter={(value, name) => [numberFormatter.format(toNumber(value)), name]}
/>
<Bar dataKey="requests" fill="#22c55e" radius={[8, 8, 0, 0]} />
<Bar dataKey="tokens" fill="#eab308" radius={[8, 8, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
</div>
);
}
+38
View File
@@ -0,0 +1,38 @@
"use client";
import { useSession, signOut } from "next-auth/react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { ArrowLeft, LogOut } from "lucide-react";
export function Header() {
const { data: session } = useSession();
const pathname = usePathname();
const isAdminArea = pathname.startsWith("/admin");
return (
<header className="flex h-14 items-center justify-between border-b bg-card px-6">
<div>
{isAdminArea && (
<Link
href="/dashboard"
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground"
>
<ArrowLeft className="h-4 w-4" />
Dashboard
</Link>
)}
</div>
<div className="flex items-center gap-4">
<span className="text-sm text-muted-foreground">{session?.user.email}</span>
<button
onClick={() => signOut({ callbackUrl: "/login" })}
className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground"
>
<LogOut className="h-4 w-4" />
Sign out
</button>
</div>
</header>
);
}
@@ -0,0 +1,7 @@
"use client";
import { SessionProvider as NextAuthSessionProvider } from "next-auth/react";
export function SessionProvider({ children }: { children: React.ReactNode }) {
return <NextAuthSessionProvider>{children}</NextAuthSessionProvider>;
}
+114
View File
@@ -0,0 +1,114 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useSession } from "next-auth/react";
import { cn } from "@/lib/utils";
import {
LayoutDashboard,
Key,
ScrollText,
BarChart3,
MessageSquare,
CreditCard,
Users,
Settings,
Server,
Layers,
TrendingUp,
Shield,
ArrowLeft,
} from "lucide-react";
interface NavItem {
label: string;
href: string;
icon: React.ComponentType<{ className?: string }>;
}
const dashboardNav: NavItem[] = [
{ label: "Overview", href: "/dashboard", icon: LayoutDashboard },
{ label: "Playground", href: "/dashboard/playground", icon: MessageSquare },
{ label: "API Keys", href: "/dashboard/api-keys", icon: Key },
{ label: "Usage", href: "/dashboard/usage", icon: BarChart3 },
{ label: "Logs", href: "/dashboard/logs", icon: ScrollText },
{ label: "Billing", href: "/dashboard/billing", icon: CreditCard },
];
const adminNav: NavItem[] = [
{ label: "Overview", href: "/admin", icon: LayoutDashboard },
{ label: "Users", href: "/admin/users", icon: Users },
{ label: "Plans", href: "/admin/plans", icon: Settings },
{ label: "Providers", href: "/admin/providers", icon: Server },
{ label: "Model Mappings", href: "/admin/model-mappings", icon: Layers },
{ label: "Analytics", href: "/admin/analytics", icon: TrendingUp },
];
export function Sidebar({ variant }: { variant: "dashboard" | "admin" }) {
const pathname = usePathname();
const { data: session } = useSession();
const items = variant === "admin" ? adminNav : dashboardNav;
const showAdminLink = variant === "dashboard" && session?.user.role === "ADMIN";
return (
<aside className="flex h-full w-64 flex-col border-r bg-card">
<div className="flex h-14 items-center border-b px-6">
<Link href="/" className="text-lg font-bold">
LLM Proxy
</Link>
</div>
<nav className="flex-1 space-y-1 p-3">
{variant === "admin" && (
<>
<Link
href="/dashboard"
className="mb-2 flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
>
<ArrowLeft className="h-4 w-4" />
Back to Dashboard
</Link>
<div className="mb-2 border-t" />
</>
)}
{items.map((item) => {
const isActive =
item.href === `/${variant === "admin" ? "admin" : "dashboard"}`
? pathname === item.href
: pathname.startsWith(item.href);
return (
<Link
key={item.href}
href={item.href}
className={cn(
"flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors",
isActive
? "bg-primary text-primary-foreground"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<item.icon className="h-4 w-4" />
{item.label}
</Link>
);
})}
{showAdminLink && (
<>
<div className="my-3 border-t" />
<Link
href="/admin"
className={cn(
"flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors",
pathname.startsWith("/admin")
? "bg-primary text-primary-foreground"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<Shield className="h-4 w-4" />
Admin Portal
</Link>
</>
)}
</nav>
</aside>
);
}
+26
View File
@@ -0,0 +1,26 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors",
{
variants: {
variant: {
default: "border-transparent bg-primary text-primary-foreground shadow",
secondary: "border-transparent bg-secondary text-secondary-foreground",
destructive: "border-transparent bg-destructive text-destructive-foreground shadow",
outline: "text-foreground",
},
},
defaultVariants: { variant: "default" },
},
);
export interface BadgeProps extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
}
export { Badge, badgeVariants };
+43
View File
@@ -0,0 +1,43 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8",
icon: "h-9 w-9",
},
},
defaultVariants: { variant: "default", size: "default" },
},
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />;
},
);
Button.displayName = "Button";
export { Button, buttonVariants };
+44
View File
@@ -0,0 +1,44 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("rounded-xl border bg-card text-card-foreground shadow", className)} {...props} />
),
);
Card.displayName = "Card";
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
),
);
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("font-semibold leading-none tracking-tight", className)} {...props} />
),
);
CardTitle.displayName = "CardTitle";
const CardDescription = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
),
);
CardDescription.displayName = "CardDescription";
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />,
);
CardContent.displayName = "CardContent";
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex items-center p-6 pt-0", className)} {...props} />
),
);
CardFooter.displayName = "CardFooter";
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
+72
View File
@@ -0,0 +1,72 @@
"use client";
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogClose = DialogPrimitive.Close;
const DialogPortal = DialogPrimitive.Portal;
const DialogOverlay = React.forwardRef<
React.ComponentRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", className)}
{...props}
/>
));
DialogOverlay.displayName = "DialogOverlay";
const DialogContent = React.forwardRef<
React.ComponentRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className,
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2">
<X className="h-4 w-4" />
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = "DialogContent";
function DialogHeader({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
return <div className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)} {...props} />;
}
function DialogFooter({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
return <div className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)} {...props} />;
}
const DialogTitle = React.forwardRef<
React.ComponentRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title ref={ref} className={cn("text-lg font-semibold leading-none tracking-tight", className)} {...props} />
));
DialogTitle.displayName = "DialogTitle";
const DialogDescription = React.forwardRef<
React.ComponentRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
));
DialogDescription.displayName = "DialogDescription";
export { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogDescription, DialogClose };
+19
View File
@@ -0,0 +1,19 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => (
<input
type={type}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className,
)}
ref={ref}
{...props}
/>
),
);
Input.displayName = "Input";
export { Input };
+19
View File
@@ -0,0 +1,19 @@
"use client";
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { cn } from "@/lib/utils";
const Label = React.forwardRef<
React.ComponentRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70", className)}
{...props}
/>
));
Label.displayName = "Label";
export { Label };
+21
View File
@@ -0,0 +1,21 @@
"use client";
import * as React from "react";
import * as SeparatorPrimitive from "@radix-ui/react-separator";
import { cn } from "@/lib/utils";
const Separator = React.forwardRef<
React.ComponentRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(({ className, orientation = "horizontal", decorative = true, ...props }, ref) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn("shrink-0 bg-border", orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]", className)}
{...props}
/>
));
Separator.displayName = "Separator";
export { Separator };
+7
View File
@@ -0,0 +1,7 @@
import { cn } from "@/lib/utils";
function Skeleton({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
return <div className={cn("animate-pulse rounded-md bg-muted", className)} {...props} />;
}
export { Skeleton };
+28
View File
@@ -0,0 +1,28 @@
"use client";
import * as React from "react";
import * as SwitchPrimitive from "@radix-ui/react-switch";
import { cn } from "@/lib/utils";
const Switch = React.forwardRef<
React.ComponentRef<typeof SwitchPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitive.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitive.Root
className={cn(
"peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
className,
)}
{...props}
ref={ref}
>
<SwitchPrimitive.Thumb
className={cn(
"pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0",
)}
/>
</SwitchPrimitive.Root>
));
Switch.displayName = "Switch";
export { Switch };
+49
View File
@@ -0,0 +1,49 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table ref={ref} className={cn("w-full caption-bottom text-sm", className)} {...props} />
</div>
),
);
Table.displayName = "Table";
const TableHeader = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => <thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />,
);
TableHeader.displayName = "TableHeader";
const TableBody = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => <tbody ref={ref} className={cn("[&_tr:last-child]:border-0", className)} {...props} />,
);
TableBody.displayName = "TableBody";
const TableFooter = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => (
<tfoot ref={ref} className={cn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", className)} {...props} />
),
);
TableFooter.displayName = "TableFooter";
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
({ className, ...props }, ref) => (
<tr ref={ref} className={cn("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted", className)} {...props} />
),
);
TableRow.displayName = "TableRow";
const TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement>>(
({ className, ...props }, ref) => (
<th ref={ref} className={cn("h-10 px-2 text-left align-middle font-medium text-muted-foreground", className)} {...props} />
),
);
TableHead.displayName = "TableHead";
const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement>>(
({ className, ...props }, ref) => <td ref={ref} className={cn("p-2 align-middle", className)} {...props} />,
);
TableCell.displayName = "TableCell";
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell };
+70
View File
@@ -0,0 +1,70 @@
export type ErrorType =
| "invalid_request_error"
| "authentication_error"
| "rate_limit_error"
| "not_found_error"
| "server_error";
export class ApiError extends Error {
constructor(
public readonly statusCode: number,
public readonly errorMessage: string,
public readonly errorType: ErrorType,
public readonly errorCode: string,
public readonly param?: string | null,
) {
super(errorMessage);
this.name = "ApiError";
}
toJSON() {
return {
error: {
message: this.errorMessage,
type: this.errorType,
code: this.errorCode,
param: this.param ?? null,
},
};
}
toResponse(): Response {
return Response.json(this.toJSON(), { status: this.statusCode });
}
}
export function invalidApiKey(): ApiError {
return new ApiError(401, "Invalid API key provided.", "authentication_error", "invalid_api_key");
}
export function rateLimitExceeded(reason: string, retryAfter: number): Response {
const error = new ApiError(429, reason, "rate_limit_error", "rate_limit_exceeded");
return new Response(JSON.stringify(error.toJSON()), {
status: 429,
headers: {
"Content-Type": "application/json",
"Retry-After": String(retryAfter),
},
});
}
export function modelNotFound(model: string): ApiError {
return new ApiError(
404,
`The model '${model}' does not exist or you do not have access to it.`,
"not_found_error",
"model_not_found",
);
}
export function invalidRequest(message: string, param?: string): ApiError {
return new ApiError(400, message, "invalid_request_error", "invalid_request", param);
}
export function providerError(message: string): ApiError {
return new ApiError(502, message, "server_error", "provider_error");
}
export function internalError(message = "An internal error occurred."): ApiError {
return new ApiError(500, message, "server_error", "internal_error");
}
+22
View File
@@ -0,0 +1,22 @@
import { getServerSession } from "next-auth";
import { authOptions } from "./auth";
export async function getSession() {
return getServerSession(authOptions);
}
export async function requireAuth() {
const session = await getSession();
if (!session?.user) {
throw new Error("Unauthorized");
}
return session;
}
export async function requireAdmin() {
const session = await requireAuth();
if (session.user.role !== "ADMIN") {
throw new Error("Forbidden");
}
return session;
}
+71
View File
@@ -0,0 +1,71 @@
import type { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { compare } from "bcryptjs";
import { getMongoDb } from "./mongo";
type UserDocument = {
_id: string;
email: string;
passwordHash: string;
name?: string;
role: "USER" | "ADMIN";
status: "ACTIVE" | "SUSPENDED" | "BANNED";
};
export const authOptions: NextAuthOptions = {
session: {
strategy: "jwt",
},
pages: {
signIn: "/login",
newUser: "/register",
},
providers: [
CredentialsProvider({
name: "credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) {
return null;
}
const user = await getMongoDb().collection<UserDocument>("users").findOne({
email: credentials.email,
});
if (!user || user.status !== "ACTIVE") {
return null;
}
const isValid = await compare(credentials.password, user.passwordHash);
if (!isValid) {
return null;
}
return {
id: user._id,
email: user.email,
name: user.name,
role: user.role,
};
},
}),
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id;
token.role = user.role;
}
return token;
},
async session({ session, token }) {
session.user.id = token.id;
session.user.role = token.role;
return session;
},
},
};
+6
View File
@@ -0,0 +1,6 @@
export const APP_NAME = process.env.NEXT_PUBLIC_APP_NAME ?? "LLM Proxy";
export const API_KEY_PREFIX = "sk-lp-";
export const API_KEY_BYTES = 32;
export const RATE_LIMIT_TTL_SECONDS = 172800; // 48 hours
export const DEFAULT_PROVIDER_TIMEOUT_MS = 30000;
export const MAX_STREAM_TIMEOUT_MS = 300000; // 5 minutes
+25
View File
@@ -0,0 +1,25 @@
export function toValidDate(value: Date | string | number | null | undefined): Date | null {
if (value == null) return null;
const date = value instanceof Date ? value : new Date(value);
return Number.isNaN(date.getTime()) ? null : date;
}
export function formatDateSafe(
value: Date | string | number | null | undefined,
fallback = "-",
locale?: string,
): string {
const date = toValidDate(value);
if (!date) return fallback;
return date.toLocaleDateString(locale);
}
export function formatDateTimeSafe(
value: Date | string | number | null | undefined,
fallback = "-",
locale?: string,
): string {
const date = toValidDate(value);
if (!date) return fallback;
return date.toLocaleString(locale);
}
+420
View File
@@ -0,0 +1,420 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { getMongoDb } from "./mongo";
type AnyRecord = Record<string, any>;
type PublicRecord = Record<string, any>;
type OrderBy = Record<string, "asc" | "desc"> | Array<Record<string, "asc" | "desc">>;
function toMongoField(field: string) {
return field === "id" ? "_id" : field;
}
function fromMongoField(field: string) {
return field === "_id" ? "id" : field;
}
function normalizeDocument<T = AnyRecord>(value: unknown): T {
if (Array.isArray(value)) return value.map((v) => normalizeDocument(v)) as T;
if (!value || typeof value !== "object") return value as T;
const source = value as AnyRecord;
const output: AnyRecord = {};
for (const [key, val] of Object.entries(source)) {
output[fromMongoField(key)] = normalizeDocument(val);
}
return output as T;
}
function denormalizeInput<T = AnyRecord>(value: unknown): T {
if (Array.isArray(value)) return value.map((v) => denormalizeInput(v)) as T;
if (!value || typeof value !== "object" || value instanceof Date) return value as T;
const source = value as AnyRecord;
const output: AnyRecord = {};
for (const [key, val] of Object.entries(source)) {
output[toMongoField(key)] = denormalizeInput(val);
}
return output as T;
}
function buildWhere(where?: AnyRecord): AnyRecord {
if (!where) return {};
const query: AnyRecord = {};
for (const [key, rawValue] of Object.entries(where)) {
const field = toMongoField(key);
if (
rawValue &&
typeof rawValue === "object" &&
!Array.isArray(rawValue) &&
!(rawValue instanceof Date)
) {
const source = rawValue as AnyRecord;
const op: AnyRecord = {};
if (source.gte !== undefined) op.$gte = source.gte;
if (source.lte !== undefined) op.$lte = source.lte;
if (source.gt !== undefined) op.$gt = source.gt;
if (source.lt !== undefined) op.$lt = source.lt;
if (source.in !== undefined) op.$in = source.in;
if (source.not !== undefined) op.$ne = source.not;
query[field] = Object.keys(op).length > 0 ? op : denormalizeInput(source);
} else {
query[field] = denormalizeInput(rawValue);
}
}
return query;
}
function buildSort(orderBy?: OrderBy): Record<string, 1 | -1> | undefined {
if (!orderBy) return undefined;
const sortEntries = Array.isArray(orderBy) ? orderBy : [orderBy];
const sort: Record<string, 1 | -1> = {};
for (const part of sortEntries) {
for (const [key, dir] of Object.entries(part)) {
sort[toMongoField(key)] = dir === "desc" ? -1 : 1;
}
}
return Object.keys(sort).length ? sort : undefined;
}
function buildProjection(select?: AnyRecord): AnyRecord | undefined {
if (!select) return undefined;
const projection: AnyRecord = {};
for (const [key, enabled] of Object.entries(select)) {
if (enabled) projection[toMongoField(key)] = 1;
}
return Object.keys(projection).length ? projection : undefined;
}
function applyTakeSkip<T>(items: T[], take?: number, skip?: number): T[] {
const start = skip ?? 0;
const afterSkip = start > 0 ? items.slice(start) : items;
return typeof take === "number" ? afterSkip.slice(0, take) : afterSkip;
}
async function withInclude(model: string, doc: AnyRecord, include?: AnyRecord) {
if (!include) return doc;
const db = getMongoDb();
if (model === "user") {
if (include.subscription) {
const subscription = await db.collection("subscriptions").findOne({ userId: doc.id });
doc.subscription = subscription ? normalizeDocument(subscription) : null;
if (doc.subscription && (include.subscription as AnyRecord).include?.plan) {
const planId = (doc.subscription as AnyRecord).planId;
const plan = await db.collection("subscription_plans").findOne({ _id: planId });
(doc.subscription as AnyRecord).plan = plan ? normalizeDocument(plan) : null;
}
}
if (include.apiKeys) {
const cfg = include.apiKeys as AnyRecord;
const keys = await db
.collection("user_api_keys")
.find({ userId: doc.id, ...buildWhere(cfg.where as AnyRecord | undefined) })
.sort(buildSort(cfg.orderBy as OrderBy) ?? {})
.toArray();
let rows = keys.map((k) => normalizeDocument(k));
if (cfg.select) {
rows = rows.map((row) => projectObject(row, cfg.select as AnyRecord));
}
doc.apiKeys = applyTakeSkip(rows, cfg.take as number | undefined, cfg.skip as number | undefined);
}
if (include.requestLogs) {
const cfg = include.requestLogs as AnyRecord;
const logs = await db
.collection("request_logs")
.find({ userId: doc.id, ...buildWhere(cfg.where as AnyRecord | undefined) })
.sort(buildSort(cfg.orderBy as OrderBy) ?? {})
.toArray();
doc.requestLogs = applyTakeSkip(
logs.map((log) => normalizeDocument(log)),
cfg.take as number | undefined,
cfg.skip as number | undefined,
);
}
if ((include as AnyRecord)._count?.select) {
const select = (include as AnyRecord)._count.select as AnyRecord;
const result: AnyRecord = {};
if (select.apiKeys) result.apiKeys = await db.collection("user_api_keys").countDocuments({ userId: doc.id });
if (select.requestLogs) {
result.requestLogs = await db.collection("request_logs").countDocuments({
userId: doc.id,
softDeleted: false,
});
}
doc._count = result;
}
}
if (model === "provider") {
if (include.modelMappings) {
const cfg = include.modelMappings as AnyRecord;
const rows = await db
.collection("model_mappings")
.find({ providerId: doc.id, ...buildWhere(cfg.where as AnyRecord | undefined) })
.sort(buildSort(cfg.orderBy as OrderBy) ?? {})
.toArray();
doc.modelMappings = applyTakeSkip(
rows.map((row) => normalizeDocument(row)),
cfg.take as number | undefined,
cfg.skip as number | undefined,
);
}
if (include.apiKeys) {
const cfg = include.apiKeys as AnyRecord;
const rows = await db
.collection("provider_api_keys")
.find({ providerId: doc.id, ...buildWhere(cfg.where as AnyRecord | undefined) })
.sort(buildSort(cfg.orderBy as OrderBy) ?? {})
.toArray();
let normalized = rows.map((row) => normalizeDocument(row));
if (cfg.select) {
normalized = normalized.map((row) => projectObject(row, cfg.select as AnyRecord));
}
doc.apiKeys = applyTakeSkip(
normalized,
cfg.take as number | undefined,
cfg.skip as number | undefined,
);
}
if ((include as AnyRecord)._count?.select) {
const select = (include as AnyRecord)._count.select as AnyRecord;
const result: AnyRecord = {};
if (select.apiKeys) result.apiKeys = await db.collection("provider_api_keys").countDocuments({ providerId: doc.id });
if (select.modelMappings) {
result.modelMappings = await db.collection("model_mappings").countDocuments({ providerId: doc.id });
}
if (select.requestLogs) {
result.requestLogs = await db.collection("request_logs").countDocuments({ providerId: doc.id });
}
doc._count = result;
}
}
if (model === "modelMapping" && include.provider) {
const provider = await db.collection("providers").findOne({ _id: doc.providerId });
doc.provider = provider
? projectObject(normalizeDocument(provider), (include.provider as AnyRecord).select as AnyRecord)
: null;
}
if (model === "subscription" && include.plan) {
const plan = await db.collection("subscription_plans").findOne({ _id: doc.planId });
doc.plan = plan ? normalizeDocument(plan) : null;
}
if (model === "subscriptionPlan" && (include as AnyRecord)._count?.select) {
const select = (include as AnyRecord)._count.select as AnyRecord;
const result: AnyRecord = {};
if (select.subscriptions) {
result.subscriptions = await db.collection("subscriptions").countDocuments({ planId: doc.id });
}
doc._count = result;
}
if (model === "ingestionBatch" && include.providerApiKeys) {
const cfg = include.providerApiKeys as AnyRecord;
const rows = await db
.collection("provider_api_keys")
.find({ ingestionBatchId: doc.id })
.sort(buildSort(cfg.orderBy as OrderBy) ?? {})
.toArray();
let normalized = rows.map((row) => normalizeDocument(row));
if (cfg.select) normalized = normalized.map((row) => projectObject(row, cfg.select as AnyRecord));
doc.providerApiKeys = normalized;
}
return doc;
}
function projectObject(obj: AnyRecord, select?: AnyRecord) {
if (!select) return obj;
const out: AnyRecord = {};
for (const [key, enabled] of Object.entries(select)) {
if (enabled) out[key] = obj[key];
}
return out;
}
function makeModel(model: string, collectionName: string) {
return {
async findMany(args: AnyRecord = {}): Promise<PublicRecord[]> {
const db = getMongoDb();
const cursor = db
.collection(collectionName)
.find(buildWhere(args.where as AnyRecord | undefined), {
projection: buildProjection(args.select as AnyRecord | undefined),
});
const sort = buildSort(args.orderBy as OrderBy | undefined);
if (sort) cursor.sort(sort);
if (typeof args.skip === "number") cursor.skip(args.skip);
if (typeof args.take === "number") cursor.limit(args.take);
const docs = (await cursor.toArray()).map((doc) => normalizeDocument<AnyRecord>(doc));
const withRelations = await Promise.all(
docs.map((doc) => withInclude(model, { ...doc }, args.include as AnyRecord | undefined)),
);
return withRelations as PublicRecord[];
},
async findUnique(args: AnyRecord): Promise<PublicRecord | null> {
const db = getMongoDb();
const doc = await db
.collection(collectionName)
.findOne(buildWhere(args.where as AnyRecord), {
projection: buildProjection(args.select as AnyRecord | undefined),
});
if (!doc) return null;
const normalized = normalizeDocument<AnyRecord>(doc);
return (await withInclude(model, normalized, args.include as AnyRecord | undefined)) as PublicRecord;
},
async findFirst(args: AnyRecord = {}): Promise<PublicRecord | null> {
const rows = await this.findMany({ ...args, take: 1 });
return rows[0] ?? null;
},
async create(args: AnyRecord): Promise<PublicRecord> {
const db = getMongoDb();
const data = { ...(args.data as AnyRecord) };
const nestedSubscription = model === "user" ? (data.subscription as AnyRecord | undefined) : undefined;
if (nestedSubscription) delete data.subscription;
const toInsert = denormalizeInput<AnyRecord>(data);
if (!toInsert._id) toInsert._id = crypto.randomUUID();
if (!toInsert.createdAt) toInsert.createdAt = new Date();
toInsert.updatedAt = new Date();
await db.collection(collectionName).insertOne(toInsert);
const created = normalizeDocument<AnyRecord>(toInsert);
if (model === "user" && nestedSubscription?.create) {
const subData = denormalizeInput<AnyRecord>(nestedSubscription.create);
if (!subData._id) subData._id = crypto.randomUUID();
subData.userId = created.id;
if (!subData.createdAt) subData.createdAt = new Date();
subData.updatedAt = new Date();
await db.collection("subscriptions").insertOne(subData);
}
return created as PublicRecord;
},
async update(args: AnyRecord): Promise<PublicRecord> {
const db = getMongoDb();
const where = buildWhere(args.where as AnyRecord);
const data = denormalizeInput<AnyRecord>(args.data as AnyRecord);
delete data._id;
data.updatedAt = new Date();
const result = await db.collection(collectionName).findOneAndUpdate(where, { $set: data }, { returnDocument: "after" });
if (!result) throw new Error(`${model} not found`);
return normalizeDocument(result) as PublicRecord;
},
async updateMany(args: AnyRecord): Promise<{ count: number }> {
const db = getMongoDb();
const where = buildWhere(args.where as AnyRecord);
const data = denormalizeInput<AnyRecord>(args.data as AnyRecord);
delete data._id;
data.updatedAt = new Date();
const result = await db.collection(collectionName).updateMany(where, { $set: data });
return { count: result.modifiedCount };
},
async delete(args: AnyRecord): Promise<PublicRecord> {
const db = getMongoDb();
const result = await db.collection(collectionName).findOneAndDelete(buildWhere(args.where as AnyRecord));
if (!result) throw new Error(`${model} not found`);
return normalizeDocument(result) as PublicRecord;
},
async deleteMany(args: AnyRecord) {
const db = getMongoDb();
const result = await db.collection(collectionName).deleteMany(buildWhere(args.where as AnyRecord));
return { count: result.deletedCount };
},
async count(args: AnyRecord = {}) {
const db = getMongoDb();
return db.collection(collectionName).countDocuments(buildWhere(args.where as AnyRecord | undefined));
},
async aggregate(args: AnyRecord = {}): Promise<PublicRecord> {
const db = getMongoDb();
const match = buildWhere(args.where as AnyRecord | undefined);
const docs = await db.collection(collectionName).find(match).toArray();
const normalized = docs.map((d) => normalizeDocument<AnyRecord>(d));
const out: AnyRecord = {};
if (args._count) out._count = normalized.length;
if (args._sum) {
const sumOut: AnyRecord = {};
for (const field of Object.keys(args._sum as AnyRecord)) {
sumOut[field] = normalized.reduce((acc, row) => acc + (Number(row[field] ?? 0) || 0), 0);
}
out._sum = sumOut;
}
return out as PublicRecord;
},
async groupBy(args: AnyRecord): Promise<PublicRecord[]> {
const db = getMongoDb();
const by = (args.by as string[]) ?? [];
const where = buildWhere(args.where as AnyRecord | undefined);
const docs = (await db.collection(collectionName).find(where).toArray()).map((d) =>
normalizeDocument<AnyRecord>(d),
);
const groups = new Map<string, AnyRecord[]>();
for (const row of docs) {
const keyObj = Object.fromEntries(by.map((field) => [field, row[field]]));
const key = JSON.stringify(keyObj);
if (!groups.has(key)) groups.set(key, []);
groups.get(key)!.push(row);
}
const out: AnyRecord[] = [];
for (const [key, rows] of groups.entries()) {
const keyObj = JSON.parse(key) as AnyRecord;
const groupRow: AnyRecord = { ...keyObj };
if (args._count) groupRow._count = { _all: rows.length };
if (args._sum) {
const sums: AnyRecord = {};
for (const field of Object.keys(args._sum as AnyRecord)) {
sums[field] = rows.reduce((acc, row) => acc + (Number(row[field] ?? 0) || 0), 0);
}
groupRow._sum = sums;
}
out.push(groupRow);
}
const sort = buildSort(args.orderBy as OrderBy | undefined);
if (sort) {
const sortKeys = Object.entries(sort);
out.sort((a, b) => {
for (const [field, dir] of sortKeys) {
const key = fromMongoField(field);
const av = a[key];
const bv = b[key];
if (av === bv) continue;
return av > bv ? dir : -dir;
}
return 0;
});
}
return applyTakeSkip(out, args.take as number | undefined, args.skip as number | undefined) as PublicRecord[];
},
};
}
export const db = {
user: makeModel("user", "users"),
subscriptionPlan: makeModel("subscriptionPlan", "subscription_plans"),
subscription: makeModel("subscription", "subscriptions"),
userApiKey: makeModel("userApiKey", "user_api_keys"),
provider: makeModel("provider", "providers"),
providerApiKey: makeModel("providerApiKey", "provider_api_keys"),
modelMapping: makeModel("modelMapping", "model_mappings"),
requestLog: makeModel("requestLog", "request_logs"),
usageAggregateDaily: makeModel("usageAggregateDaily", "usage_aggregates_daily"),
ingestionBatch: makeModel("ingestionBatch", "ingestion_batches"),
};
+9
View File
@@ -0,0 +1,9 @@
import pino from "pino";
export const logger = pino({
level: process.env.LOG_LEVEL ?? "info",
transport:
process.env.NODE_ENV === "development"
? { target: "pino-pretty", options: { colorize: true } }
: undefined,
});
+27
View File
@@ -0,0 +1,27 @@
import { MongoClient } from "mongodb";
function getDatabaseUrl() {
const url = process.env.DATABASE_URL;
if (!url) {
throw new Error("Missing DATABASE_URL.");
}
return url;
}
const globalForMongo = globalThis as unknown as { mongoClient?: MongoClient };
const client = globalForMongo.mongoClient ?? new MongoClient(getDatabaseUrl());
if (process.env.NODE_ENV !== "production") {
globalForMongo.mongoClient = client;
}
function getDatabaseNameFromUrl(urlString: string) {
const parsed = new URL(urlString);
const dbName = parsed.pathname.replace("/", "");
return dbName || "test";
}
export function getMongoDb() {
return client.db(getDatabaseNameFromUrl(getDatabaseUrl()));
}
+28
View File
@@ -0,0 +1,28 @@
import Redis from "ioredis";
import { logger } from "./logger";
const globalForRedis = globalThis as unknown as { redis: Redis };
let redisErrorLogged = false;
export const redis =
globalForRedis.redis ??
new Redis(process.env.REDIS_URL ?? "redis://localhost:6379", {
maxRetriesPerRequest: 1,
lazyConnect: true,
enableOfflineQueue: false,
retryStrategy: () => null,
});
redis.on("error", (err) => {
if (redisErrorLogged) return;
redisErrorLogged = true;
logger.warn({ err }, "Redis unavailable; continuing without Redis-backed features");
});
redis.on("ready", () => {
if (!redisErrorLogged) return;
redisErrorLogged = false;
logger.info("Redis connection restored");
});
if (process.env.NODE_ENV !== "production") globalForRedis.redis = redis;
+36
View File
@@ -0,0 +1,36 @@
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
import { randomBytes, createHash } from "crypto";
import { API_KEY_PREFIX, API_KEY_BYTES } from "./constants";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function formatDate(date: Date): string {
return date.toISOString().slice(0, 10); // "YYYY-MM-DD"
}
export function generateApiKey(): { raw: string; hashed: string; prefix: string } {
const bytes = randomBytes(API_KEY_BYTES);
const raw = `${API_KEY_PREFIX}${bytes.toString("base64url")}`;
const hashed = hashApiKey(raw);
const prefix = raw.slice(0, 12) + "...";
return { raw, hashed, prefix };
}
export function hashApiKey(key: string): string {
return createHash("sha256").update(key).digest("hex");
}
export function generateId(): string {
return randomBytes(12).toString("hex");
}
export function secondsUntilMidnightUTC(): number {
const now = new Date();
const midnight = new Date(now);
midnight.setUTCDate(midnight.getUTCDate() + 1);
midnight.setUTCHours(0, 0, 0, 0);
return Math.ceil((midnight.getTime() - now.getTime()) / 1000);
}
+49
View File
@@ -0,0 +1,49 @@
import { z } from "zod";
export const createPlanSchema = z.object({
name: z.string().min(1),
displayName: z.string().min(1),
description: z.string().optional(),
monthlyPriceCents: z.number().int().min(0),
requestLimitPerMonth: z.number().int().positive().nullable().optional(),
tokenLimitPerMonth: z.number().int().positive().nullable().optional(),
dailyRequestLimit: z.number().int().positive().nullable().optional(),
dailyTokenLimit: z.number().int().positive().nullable().optional(),
maxApiKeys: z.number().int().positive().optional().default(5),
features: z.record(z.unknown()).optional(),
isPublic: z.boolean().optional().default(true),
sortOrder: z.number().int().optional().default(0),
});
export const updateUserSchema = z.object({
name: z.string().optional(),
role: z.enum(["USER", "ADMIN"]).optional(),
status: z.enum(["ACTIVE", "SUSPENDED", "BANNED"]).optional(),
planId: z.string().nullable().optional(),
subscriptionStatus: z.enum(["ACTIVE", "PAST_DUE", "CANCELED", "TRIALING"]).optional(),
});
export const updatePlanSchema = createPlanSchema.partial().extend({
id: z.string().min(1),
});
export const createProviderSchema = z.object({
id: z.string().min(1),
displayName: z.string().min(1),
baseUrl: z.string().url(),
enabled: z.boolean().optional().default(true),
config: z.record(z.unknown()).optional(),
});
export const createProviderKeySchema = z.object({
rawKey: z.string().min(1),
label: z.string().optional(),
});
export const createModelMappingSchema = z.object({
logicalModelId: z.string().min(1),
providerId: z.string().min(1),
providerModelId: z.string().min(1),
priority: z.number().int().optional().default(0),
enabled: z.boolean().optional().default(true),
});
+52
View File
@@ -0,0 +1,52 @@
import { z } from "zod";
const chatMessageSchema = z.object({
role: z.enum(["system", "user", "assistant", "tool"]),
content: z.union([z.string(), z.null()]),
name: z.string().optional(),
tool_calls: z
.array(
z.object({
id: z.string(),
type: z.literal("function"),
function: z.object({
name: z.string(),
arguments: z.string(),
}),
}),
)
.optional(),
tool_call_id: z.string().optional(),
});
const toolDefinitionSchema = z.object({
type: z.literal("function"),
function: z.object({
name: z.string(),
description: z.string().optional(),
parameters: z.record(z.unknown()).optional(),
}),
});
export const chatCompletionSchema = z.object({
model: z.string().min(1),
messages: z.array(chatMessageSchema).min(1),
stream: z.boolean().optional().default(false),
temperature: z.number().min(0).max(2).optional(),
top_p: z.number().min(0).max(1).optional(),
max_tokens: z.number().int().positive().optional(),
stop: z.union([z.string(), z.array(z.string())]).optional(),
presence_penalty: z.number().min(-2).max(2).optional(),
frequency_penalty: z.number().min(-2).max(2).optional(),
n: z.number().int().positive().max(5).optional(),
user: z.string().optional(),
tools: z.array(toolDefinitionSchema).optional(),
tool_choice: z
.union([
z.enum(["auto", "none"]),
z.object({ type: z.literal("function"), function: z.object({ name: z.string() }) }),
])
.optional(),
});
export type ChatCompletionInput = z.infer<typeof chatCompletionSchema>;
+15
View File
@@ -0,0 +1,15 @@
import { z } from "zod";
export const completionSchema = z.object({
model: z.string().min(1),
prompt: z.union([z.string(), z.array(z.string())]),
stream: z.boolean().optional().default(false),
max_tokens: z.number().int().positive().optional(),
temperature: z.number().min(0).max(2).optional(),
top_p: z.number().min(0).max(1).optional(),
stop: z.union([z.string(), z.array(z.string())]).optional(),
n: z.number().int().positive().max(5).optional(),
user: z.string().optional(),
});
export type CompletionInput = z.infer<typeof completionSchema>;
+10
View File
@@ -0,0 +1,10 @@
import { z } from "zod";
export const embeddingsSchema = z.object({
model: z.string().min(1),
input: z.union([z.string(), z.array(z.string())]),
encoding_format: z.enum(["float", "base64"]).optional(),
user: z.string().optional(),
});
export type EmbeddingsInput = z.infer<typeof embeddingsSchema>;
+168
View File
@@ -0,0 +1,168 @@
import type { ProviderAdapter, ProviderKeyContext, ProviderKeyMetadata, ProviderModelInfo } from "@/types/provider";
import type { UnifiedChatRequest } from "@/types/unified-request";
import type { UnifiedChatResponse } from "@/types/unified-response";
import { ApiError } from "@/lib/api-error";
interface AnthropicMessagePart {
type: "text";
text: string;
}
interface AnthropicMessageResponse {
id: string;
content: AnthropicMessagePart[];
usage?: {
input_tokens?: number;
output_tokens?: number;
};
}
export class AnthropicAdapter implements ProviderAdapter {
id = "anthropic";
displayName = "Anthropic";
defaultBaseUrl = "https://api.anthropic.com";
matchesApiKeyPattern(key: string): boolean {
return key.startsWith("sk-ant-");
}
private buildHeaders(key: string): Record<string, string> {
return {
"x-api-key": key,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
};
}
private mapToAnthropicBody(req: UnifiedChatRequest, ctx: ProviderKeyContext): Record<string, unknown> {
const system = req.messages
.filter((m) => m.role === "system" && typeof m.content === "string")
.map((m) => m.content)
.join("\n");
const messages = req.messages
.filter((m) => m.role !== "system")
.map((m) => ({
role: m.role === "assistant" ? "assistant" : "user",
content: m.content ?? "",
}));
return {
model: ctx.providerModelId,
system: system || undefined,
messages,
max_tokens: req.max_tokens ?? 1024,
temperature: req.temperature,
top_p: req.top_p,
stop_sequences: Array.isArray(req.stop) ? req.stop : req.stop ? [req.stop] : undefined,
};
}
private mapToOpenAIResponse(data: AnthropicMessageResponse, model: string): UnifiedChatResponse {
const text = data.content.map((part) => part.text).join("");
const promptTokens = data.usage?.input_tokens ?? 0;
const completionTokens = data.usage?.output_tokens ?? 0;
return {
id: data.id,
object: "chat.completion",
created: Math.floor(Date.now() / 1000),
model,
choices: [
{
index: 0,
message: {
role: "assistant",
content: text,
},
finish_reason: "stop",
},
],
usage: {
prompt_tokens: promptTokens,
completion_tokens: completionTokens,
total_tokens: promptTokens + completionTokens,
},
};
}
async validateApiKey(key: string): Promise<ProviderKeyMetadata> {
try {
const res = await fetch(`${this.defaultBaseUrl}/v1/models`, {
method: "GET",
headers: this.buildHeaders(key),
signal: AbortSignal.timeout(10000),
});
if (!res.ok) return { valid: false, error: `HTTP ${res.status}` };
const json = (await res.json()) as { data?: Array<{ id: string }> };
return { valid: true, models: json.data?.map((m) => m.id) ?? [] };
} catch (err) {
return { valid: false, error: String(err) };
}
}
async chatCompletion(req: UnifiedChatRequest, ctx: ProviderKeyContext): Promise<UnifiedChatResponse> {
const res = await fetch(`${ctx.providerBaseUrl}/v1/messages`, {
method: "POST",
headers: this.buildHeaders(ctx.decryptedKey),
body: JSON.stringify(this.mapToAnthropicBody(req, ctx)),
signal: AbortSignal.timeout(ctx.timeout),
});
if (!res.ok) {
const err = await res.text().catch(() => "Unknown error");
throw new ApiError(
res.status,
`Provider anthropic returned ${res.status}: ${err.slice(0, 200)}`,
"server_error",
"provider_error",
);
}
const data = (await res.json()) as AnthropicMessageResponse;
return this.mapToOpenAIResponse(data, req.model);
}
async chatCompletionStream(req: UnifiedChatRequest, ctx: ProviderKeyContext): Promise<ReadableStream<Uint8Array>> {
const response = await this.chatCompletion(req, ctx);
const encoder = new TextEncoder();
return new ReadableStream<Uint8Array>({
start(controller) {
const chunk = {
id: response.id,
object: "chat.completion.chunk",
created: response.created,
model: response.model,
choices: [
{
index: 0,
delta: { role: "assistant", content: response.choices[0]?.message.content ?? "" },
finish_reason: "stop",
},
],
usage: response.usage,
};
controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
controller.close();
},
});
}
completion = undefined;
embeddings = undefined;
async listModels(ctx: ProviderKeyContext): Promise<ProviderModelInfo[]> {
const res = await fetch(`${ctx.providerBaseUrl}/v1/models`, {
method: "GET",
headers: this.buildHeaders(ctx.decryptedKey),
signal: AbortSignal.timeout(10000),
});
if (!res.ok) return [];
const json = (await res.json()) as { data?: Array<{ id: string }> };
return (json.data ?? []).map((m) => ({ id: m.id, ownedBy: this.id }));
}
}
+210
View File
@@ -0,0 +1,210 @@
import type {
ProviderAdapter,
ProviderKeyContext,
ProviderKeyMetadata,
ProviderModelInfo,
} from "@/types/provider";
import type { UnifiedChatRequest, UnifiedCompletionRequest, UnifiedEmbeddingRequest } from "@/types/unified-request";
import type { UnifiedChatResponse, UnifiedCompletionResponse, UnifiedEmbeddingResponse } from "@/types/unified-response";
import { ApiError, providerError } from "@/lib/api-error";
import { logger } from "@/lib/logger";
export abstract class OpenAICompatibleAdapter implements ProviderAdapter {
abstract id: string;
abstract displayName: string;
abstract defaultBaseUrl: string;
abstract matchesApiKeyPattern(key: string): boolean;
protected buildHeaders(ctx: ProviderKeyContext): Record<string, string> {
return {
Authorization: `Bearer ${ctx.decryptedKey}`,
"Content-Type": "application/json",
};
}
protected chatEndpoint(ctx: ProviderKeyContext): string {
return `${ctx.providerBaseUrl}/v1/chat/completions`;
}
protected completionEndpoint(ctx: ProviderKeyContext): string {
return `${ctx.providerBaseUrl}/v1/completions`;
}
protected embeddingEndpoint(ctx: ProviderKeyContext): string {
return `${ctx.providerBaseUrl}/v1/embeddings`;
}
protected modelsEndpoint(ctx: ProviderKeyContext): string {
return `${ctx.providerBaseUrl}/v1/models`;
}
protected buildChatBody(req: UnifiedChatRequest, ctx: ProviderKeyContext): Record<string, unknown> {
const body: Record<string, unknown> = {
model: ctx.providerModelId,
messages: req.messages,
};
if (req.temperature !== undefined) body.temperature = req.temperature;
if (req.top_p !== undefined) body.top_p = req.top_p;
if (req.max_tokens !== undefined) body.max_tokens = req.max_tokens;
if (req.stop !== undefined) body.stop = req.stop;
if (req.presence_penalty !== undefined) body.presence_penalty = req.presence_penalty;
if (req.frequency_penalty !== undefined) body.frequency_penalty = req.frequency_penalty;
if (req.n !== undefined) body.n = req.n;
if (req.user !== undefined) body.user = req.user;
if (req.tools !== undefined) body.tools = req.tools;
if (req.tool_choice !== undefined) body.tool_choice = req.tool_choice;
return body;
}
async chatCompletion(req: UnifiedChatRequest, ctx: ProviderKeyContext): Promise<UnifiedChatResponse> {
const body = this.buildChatBody(req, ctx);
body.stream = false;
const response = await fetch(this.chatEndpoint(ctx), {
method: "POST",
headers: this.buildHeaders(ctx),
body: JSON.stringify(body),
signal: AbortSignal.timeout(ctx.timeout),
});
if (!response.ok) {
const errorText = await response.text().catch(() => "Unknown error");
logger.error({ status: response.status, body: errorText, provider: this.id }, "Provider error");
throw new ApiError(
response.status,
`Provider ${this.id} returned ${response.status}: ${errorText.slice(0, 200)}`,
"server_error",
"provider_error",
);
}
return (await response.json()) as UnifiedChatResponse;
}
async chatCompletionStream(req: UnifiedChatRequest, ctx: ProviderKeyContext): Promise<ReadableStream<Uint8Array>> {
const body = this.buildChatBody(req, ctx);
body.stream = true;
body.stream_options = { include_usage: true };
const response = await fetch(this.chatEndpoint(ctx), {
method: "POST",
headers: this.buildHeaders(ctx),
body: JSON.stringify(body),
signal: AbortSignal.timeout(ctx.timeout),
});
if (!response.ok) {
const errorText = await response.text().catch(() => "Unknown error");
logger.error({ status: response.status, body: errorText, provider: this.id }, "Provider stream error");
throw new ApiError(
response.status,
`Provider ${this.id} returned ${response.status}: ${errorText.slice(0, 200)}`,
"server_error",
"provider_error",
);
}
if (!response.body) {
throw providerError(`Provider ${this.id} returned no stream body`);
}
return response.body;
}
async completion(req: UnifiedCompletionRequest, ctx: ProviderKeyContext): Promise<UnifiedCompletionResponse> {
const body: Record<string, unknown> = {
model: ctx.providerModelId,
prompt: req.prompt,
stream: false,
};
if (req.max_tokens !== undefined) body.max_tokens = req.max_tokens;
if (req.temperature !== undefined) body.temperature = req.temperature;
if (req.top_p !== undefined) body.top_p = req.top_p;
if (req.stop !== undefined) body.stop = req.stop;
if (req.n !== undefined) body.n = req.n;
const response = await fetch(this.completionEndpoint(ctx), {
method: "POST",
headers: this.buildHeaders(ctx),
body: JSON.stringify(body),
signal: AbortSignal.timeout(ctx.timeout),
});
if (!response.ok) {
const errorText = await response.text().catch(() => "Unknown error");
throw new ApiError(
response.status,
`Provider ${this.id} returned ${response.status}: ${errorText.slice(0, 200)}`,
"server_error",
"provider_error",
);
}
return (await response.json()) as UnifiedCompletionResponse;
}
async embeddings(req: UnifiedEmbeddingRequest, ctx: ProviderKeyContext): Promise<UnifiedEmbeddingResponse> {
const body: Record<string, unknown> = {
model: ctx.providerModelId,
input: req.input,
};
if (req.encoding_format !== undefined) body.encoding_format = req.encoding_format;
const response = await fetch(this.embeddingEndpoint(ctx), {
method: "POST",
headers: this.buildHeaders(ctx),
body: JSON.stringify(body),
signal: AbortSignal.timeout(ctx.timeout),
});
if (!response.ok) {
const errorText = await response.text().catch(() => "Unknown error");
throw new ApiError(
response.status,
`Provider ${this.id} returned ${response.status}: ${errorText.slice(0, 200)}`,
"server_error",
"provider_error",
);
}
return (await response.json()) as UnifiedEmbeddingResponse;
}
async validateApiKey(key: string): Promise<ProviderKeyMetadata> {
try {
const response = await fetch(`${this.defaultBaseUrl}/v1/models`, {
headers: { Authorization: `Bearer ${key}` },
signal: AbortSignal.timeout(10000),
});
if (!response.ok) {
return { valid: false, error: `HTTP ${response.status}` };
}
const data = (await response.json()) as { data?: Array<{ id: string }> };
const models = data.data?.map((m) => m.id) ?? [];
return { valid: true, models };
} catch (err) {
return { valid: false, error: String(err) };
}
}
async listModels(ctx: ProviderKeyContext): Promise<ProviderModelInfo[]> {
const response = await fetch(this.modelsEndpoint(ctx), {
headers: this.buildHeaders(ctx),
signal: AbortSignal.timeout(10000),
});
if (!response.ok) return [];
const data = (await response.json()) as { data?: Array<{ id: string; owned_by?: string }> };
return (
data.data?.map((m) => ({
id: m.id,
ownedBy: m.owned_by ?? this.id,
})) ?? []
);
}
}
+11
View File
@@ -0,0 +1,11 @@
import { OpenAICompatibleAdapter } from "./base";
export class DeepSeekAdapter extends OpenAICompatibleAdapter {
id = "deepseek";
displayName = "DeepSeek";
defaultBaseUrl = "https://api.deepseek.com";
matchesApiKeyPattern(key: string): boolean {
return key.startsWith("sk-deepseek-") || key.startsWith("dsk-");
}
}
+11
View File
@@ -0,0 +1,11 @@
import { OpenAICompatibleAdapter } from "./base";
export class GrokAdapter extends OpenAICompatibleAdapter {
id = "grok";
displayName = "Grok";
defaultBaseUrl = "https://api.x.ai";
matchesApiKeyPattern(key: string): boolean {
return key.startsWith("xai-");
}
}
+43
View File
@@ -0,0 +1,43 @@
import type { ProviderAdapter } from "@/types/provider";
import { AnthropicAdapter } from "./anthropic";
import { DeepSeekAdapter } from "./deepseek";
import { GrokAdapter } from "./grok";
import { OpenAIAdapter } from "./openai";
import { PerplexityAdapter } from "./perplexity";
const adapters = new Map<string, ProviderAdapter>();
function registerAdapter(adapter: ProviderAdapter): void {
adapters.set(adapter.id, adapter);
}
// Register built-in adapters
registerAdapter(new AnthropicAdapter());
registerAdapter(new GrokAdapter());
registerAdapter(new DeepSeekAdapter());
registerAdapter(new PerplexityAdapter());
registerAdapter(new OpenAIAdapter());
export function getAdapter(providerId: string): ProviderAdapter | undefined {
return adapters.get(providerId);
}
export function getAllAdapters(): ProviderAdapter[] {
return Array.from(adapters.values());
}
export function detectProvider(rawKey: string): ProviderAdapter | undefined {
let match: ProviderAdapter | undefined;
for (const adapter of adapters.values()) {
if (adapter.matchesApiKeyPattern(rawKey)) {
if (match) {
// Ambiguous pattern match; caller should validate with test call.
return undefined;
}
match = adapter;
}
}
return match;
}
+11
View File
@@ -0,0 +1,11 @@
import { OpenAICompatibleAdapter } from "./base";
export class OpenAIAdapter extends OpenAICompatibleAdapter {
id = "openai";
displayName = "OpenAI";
defaultBaseUrl = "https://api.openai.com";
matchesApiKeyPattern(key: string): boolean {
return (key.startsWith("sk-") && !key.startsWith("sk-ant-")) || key.startsWith("sk-proj-");
}
}
+11
View File
@@ -0,0 +1,11 @@
import { OpenAICompatibleAdapter } from "./base";
export class PerplexityAdapter extends OpenAICompatibleAdapter {
id = "perplexity";
displayName = "Perplexity";
defaultBaseUrl = "https://api.perplexity.ai";
matchesApiKeyPattern(key: string): boolean {
return key.startsWith("pplx-");
}
}
+128
View File
@@ -0,0 +1,128 @@
import { getMongoDb } from "@/lib/mongo";
import { hashApiKey } from "@/lib/utils";
type UserDocument = {
_id: string;
email: string;
name?: string;
role: "USER" | "ADMIN";
status: "ACTIVE" | "SUSPENDED" | "BANNED";
};
type UserApiKeyDocument = {
_id: string;
userId: string;
hashedKey: string;
status?: "ACTIVE" | "DISABLED" | "REVOKED";
expiresAt?: Date | null;
dailyRequestLimit?: number | null;
dailyTokenLimit?: number | null;
softCostLimitCents?: number | null;
};
type SubscriptionDocument = {
_id: string;
userId: string;
planId: string;
status: "ACTIVE" | "PAST_DUE" | "CANCELED" | "TRIALING";
};
type SubscriptionPlanDocument = {
_id: string;
dailyRequestLimit?: number | null;
dailyTokenLimit?: number | null;
};
type AuthUser = {
id: string;
email: string;
name?: string;
role: "USER" | "ADMIN";
status: "ACTIVE" | "SUSPENDED" | "BANNED";
};
type AuthApiKey = {
id: string;
userId: string;
dailyRequestLimit: number | null;
dailyTokenLimit: number | null;
softCostLimitCents: number | null;
};
type AuthSubscription = {
id: string;
userId: string;
status: "ACTIVE" | "PAST_DUE" | "CANCELED" | "TRIALING";
plan: {
id: string;
dailyRequestLimit: number | null;
dailyTokenLimit: number | null;
};
};
export interface AuthResult {
user: AuthUser;
apiKey: AuthApiKey;
subscription: AuthSubscription;
}
export async function authenticateApiKey(authHeader: string | null): Promise<AuthResult | null> {
if (!authHeader?.startsWith("Bearer ")) {
return null;
}
const rawKey = authHeader.slice(7);
if (!rawKey) return null;
const hashed = hashApiKey(rawKey);
const db = getMongoDb();
const apiKey = await db.collection<UserApiKeyDocument>("user_api_keys").findOne({
hashedKey: hashed,
});
if (!apiKey) return null;
// Backward compatibility: older keys may not have explicit status.
if (apiKey.status && apiKey.status !== "ACTIVE") return null;
if (apiKey.expiresAt && apiKey.expiresAt < new Date()) return null;
const user = await db.collection<UserDocument>("users").findOne({ _id: apiKey.userId });
if (!user || user.status !== "ACTIVE") return null;
const subscription = await db.collection<SubscriptionDocument>("subscriptions").findOne({
userId: user._id,
});
if (!subscription) return null;
const plan = await db.collection<SubscriptionPlanDocument>("subscription_plans").findOne({
_id: subscription.planId,
});
if (!plan) return null;
return {
user: {
id: user._id,
email: user.email,
name: user.name,
role: user.role,
status: user.status,
},
apiKey: {
id: apiKey._id,
userId: apiKey.userId,
dailyRequestLimit: apiKey.dailyRequestLimit ?? null,
dailyTokenLimit: apiKey.dailyTokenLimit ?? null,
softCostLimitCents: apiKey.softCostLimitCents ?? null,
},
subscription: {
id: subscription._id,
userId: subscription.userId,
status: subscription.status,
plan: {
id: plan._id,
dailyRequestLimit: plan.dailyRequestLimit ?? null,
dailyTokenLimit: plan.dailyTokenLimit ?? null,
},
},
};
}
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff. Show more