feat: design system overhaul — sidebar, AI chats, settings, brainstorm, color cleanup
All checks were successful
Deploy to Production / Build and Deploy (push) Successful in 12s

- Sidebar: dynamic brand-accent colors, brainstorm section restyled
- AI chat general: popup panel with expand/collapse, hides when contextual AI open
- AI chat contextual: tabs reordered (Actions first), X close button, height fix
- Settings: all tabs restyled, 6 new color presets (sage, terracotta, iron, etc.)
- Global color cleanup: emerald/orange hardcoded → brand-accent dynamic
- Brainstorm page: orange → brand-accent throughout
- PageEntry animation component added to key pages
- Floating AI button: bg-brand-accent instead of hardcoded black
- i18n: all 15 locales updated with new AI/billing keys
- Billing: freemium quota tracking, BYOK, stripe subscription scaffolding
- Admin: integrated into new design
- AGENTS.md + CLAUDE.md project rules added
This commit is contained in:
Antigravity
2026-05-16 12:59:30 +00:00
parent 1fcea6ed7d
commit bd495be965
2284 changed files with 395285 additions and 2327 deletions

View File

@@ -1,9 +1,10 @@
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import { contextualAutoTagService } from '@/lib/ai/services/contextual-auto-tag.service';
import { getTagsProvider } from '@/lib/ai/factory';
import { runLaneWithBillingUser, willUseByokForLane } from '@/lib/ai/provider-for-user';
import { getSystemConfig } from '@/lib/config';
import { z } from 'zod';
import { checkEntitlementOrThrow, QuotaExceededError, incrementUsageAsync } from '@/lib/entitlements';
import { getAISettings } from '@/app/actions/ai-settings';
@@ -25,6 +26,18 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ tags: [] });
}
try {
const config = await getSystemConfig();
const { usedByok: willUseByok } = await willUseByokForLane('tags', config, session.user.id);
if (!willUseByok) {
await checkEntitlementOrThrow(session.user.id, 'auto_tag');
}
} catch (err) {
if (err instanceof QuotaExceededError) {
return NextResponse.json(err.toJSON(), { status: 402 });
}
console.error('[/api/ai/tags] Quota check error (fail-open):', err);
}
const body = await req.json();
const { content, notebookId, language } = requestSchema.parse(body);
@@ -58,8 +71,13 @@ export async function POST(req: NextRequest) {
// Otherwise, use legacy auto-tagging (generates new tags)
try {
const config = await getSystemConfig();
const provider = getTagsProvider(config);
const tags = await provider.generateTags(content, language);
const { result: tags, usedByok } = await runLaneWithBillingUser(
'tags',
config,
session.user.id,
(provider) => provider.generateTags(content, language),
);
if (!usedByok) incrementUsageAsync(session.user.id, 'auto_tag');
return NextResponse.json({ tags });
} catch (err) {
console.error('[/api/ai/tags] legacy tagging failed:', err)

View File

@@ -1,8 +1,9 @@
import { NextRequest, NextResponse } from 'next/server'
import { getTagsProvider } from '@/lib/ai/factory'
import { runLaneWithBillingUser, willUseByokForLane } from '@/lib/ai/provider-for-user'
import { getSystemConfig } from '@/lib/config'
import { auth } from '@/auth'
import { getAISettings } from '@/app/actions/ai-settings'
import { checkEntitlementOrThrow, QuotaExceededError, incrementUsageAsync } from '@/lib/entitlements'
import { z } from 'zod'
const requestSchema = z.object({
@@ -13,14 +14,27 @@ export async function POST(req: NextRequest) {
try {
// Check authentication and user setting
const session = await auth()
if (session?.user?.id) {
const settings = await getAISettings(session.user.id)
if (settings.titleSuggestions === false) {
return NextResponse.json({ suggestions: [] })
}
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const settings = await getAISettings(session.user.id)
if (settings.titleSuggestions === false) {
return NextResponse.json({ suggestions: [] })
}
try {
const config = await getSystemConfig()
const { usedByok: willUseByok } = await willUseByokForLane('tags', config, session.user.id);
if (!willUseByok) {
await checkEntitlementOrThrow(session.user.id, 'auto_title');
}
} catch (err) {
if (err instanceof QuotaExceededError) {
return NextResponse.json(err.toJSON(), { status: 402 });
}
console.error('[/api/ai/title-suggestions] Quota check error (fail-open):', err);
}
const body = await req.json()
const { content } = requestSchema.parse(body)
@@ -35,7 +49,6 @@ export async function POST(req: NextRequest) {
}
const config = await getSystemConfig()
const provider = getTagsProvider(config)
// Détecter la langue du contenu (simple détection basée sur les caractères et mots)
const hasNonLatinChars = /[\u0400-\u04FF\u0600-\u06FF\u4E00-\u9FFF\u0E00-\u0E7F]/.test(content)
@@ -95,7 +108,13 @@ CONTENT_START: ${content.substring(0, 500)} CONTENT_END
Réponds SEULEMENT avec un tableau JSON: [{"title": "titre1", "confidence": 0.95}, {"title": "titre2", "confidence": 0.85}, {"title": "titre3", "confidence": 0.75}]`
const titles = await provider.generateTitles(titlePrompt)
const { result: titles, usedByok } = await runLaneWithBillingUser(
'tags',
config,
session.user.id,
(provider) => provider.generateTitles(titlePrompt),
)
if (!usedByok) incrementUsageAsync(session.user.id, 'auto_title')
// Créer les suggestions
const suggestions = titles.map((t: any) => ({

View File

@@ -0,0 +1,68 @@
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import { stripe } from '@/lib/stripe';
import { resolvePriceId } from '@/lib/billing/stripe-prices';
import { prisma } from '@/lib/prisma';
import { z } from 'zod';
const bodySchema = z.object({
tier: z.enum(['PRO', 'BUSINESS']),
interval: z.enum(['month', 'year']),
});
export async function POST(req: NextRequest) {
const session = await auth();
if (!session?.user?.id || !session.user.email) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const parsed = bodySchema.safeParse(await req.json());
if (!parsed.success) {
return NextResponse.json({ error: 'Invalid request body' }, { status: 400 });
}
const { tier, interval } = parsed.data;
const userId = session.user.id;
const userEmail = session.user.email;
try {
const priceId = resolvePriceId(tier, interval);
const subscription = await prisma.subscription.findUnique({ where: { userId } });
let customerId = subscription?.stripeCustomerId ?? undefined;
if (!customerId) {
const customer = await stripe.customers.create({
email: userEmail,
metadata: { userId },
});
customerId = customer.id;
}
const origin = req.headers.get('origin') ?? process.env.NEXTAUTH_URL ?? 'http://localhost:3000';
const sessionParams = {
customer: customerId,
mode: 'subscription' as const,
line_items: [{ price: priceId, quantity: 1 }],
ui_mode: 'embedded',
return_url: `${origin}/settings/billing?session_id={CHECKOUT_SESSION_ID}`,
metadata: { userId, tier },
subscription_data: { metadata: { userId, tier } },
customer_update: { address: 'auto' },
};
const checkoutSession = await stripe.checkout.sessions.create(sessionParams as any);
if (checkoutSession.client_secret) {
return NextResponse.json({
clientSecret: checkoutSession.client_secret,
sessionId: checkoutSession.id,
});
}
return NextResponse.json({ url: checkoutSession.url });
} catch (error) {
console.error('[billing/create-checkout]', error);
return NextResponse.json({ error: 'Failed to create checkout session' }, { status: 500 });
}
}

View File

@@ -0,0 +1,32 @@
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import { stripe } from '@/lib/stripe';
import { prisma } from '@/lib/prisma';
export async function POST(req: NextRequest) {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const userId = session.user.id;
try {
const subscription = await prisma.subscription.findUnique({ where: { userId } });
if (!subscription?.stripeCustomerId) {
return NextResponse.json({ error: 'No active subscription found' }, { status: 404 });
}
const origin = req.headers.get('origin') ?? process.env.NEXTAUTH_URL ?? 'http://localhost:3000';
const portalSession = await stripe.billingPortal.sessions.create({
customer: subscription.stripeCustomerId,
return_url: `${origin}/settings/billing`,
});
return NextResponse.json({ url: portalSession.url });
} catch (error) {
console.error('[billing/portal]', error);
return NextResponse.json({ error: 'Failed to create portal session' }, { status: 500 });
}
}

View File

@@ -0,0 +1,32 @@
import { NextResponse } from 'next/server';
import { auth } from '@/auth';
import { getUserInfo, getEffectiveTier } from '@/lib/entitlements';
export async function GET() {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const userId = session.user.id;
try {
const { tier, status, currentPeriodEnd } = await getUserInfo(userId);
const effectiveTier = await getEffectiveTier(userId);
const { prisma } = await import('@/lib/prisma');
const subscription = await prisma.subscription.findUnique({ where: { userId } });
return NextResponse.json({
tier,
effectiveTier,
status,
currentPeriodEnd: currentPeriodEnd ?? null,
cancelAtPeriodEnd: subscription?.cancelAtPeriodEnd ?? false,
hasStripeSubscription: !!subscription?.stripeSubscriptionId,
});
} catch (error) {
console.error('[billing/status]', error);
return NextResponse.json({ error: 'Failed to fetch billing status' }, { status: 500 });
}
}

View File

@@ -0,0 +1,98 @@
import { headers } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';
import { stripe } from '@/lib/stripe';
import {
syncSubscriptionFromStripe,
handleSubscriptionDeleted,
resolveUserIdFromStripeEvent,
} from '@/lib/billing/sync-subscription-from-stripe';
import { prisma } from '@/lib/prisma';
import type Stripe from 'stripe';
export const runtime = 'nodejs';
export async function POST(req: NextRequest) {
const body = await req.text();
const headersList = await headers();
const sig = headersList.get('stripe-signature');
if (!sig) {
return NextResponse.json({ error: 'Missing stripe-signature header' }, { status: 400 });
}
if (!process.env.STRIPE_WEBHOOK_SECRET) {
console.error('[billing/webhook] STRIPE_WEBHOOK_SECRET not configured');
return NextResponse.json({ error: 'Webhook not configured' }, { status: 500 });
}
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(body, sig, process.env.STRIPE_WEBHOOK_SECRET);
} catch (err) {
console.error('[billing/webhook] Signature verification failed:', err);
return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
}
try {
switch (event.type) {
case 'checkout.session.completed': {
const session = event.data.object as Stripe.Checkout.Session;
if (session.mode === 'subscription' && session.subscription) {
const subscriptionId = typeof session.subscription === 'string'
? session.subscription
: session.subscription.id;
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
const userId = (session.metadata?.userId as string | undefined)
?? (subscription.metadata?.userId as string | undefined);
if (userId) {
await syncSubscriptionFromStripe(subscription, userId);
} else {
console.warn('[billing/webhook] checkout.session.completed: no userId in metadata', session.id);
}
}
break;
}
case 'customer.subscription.created':
case 'customer.subscription.updated': {
const subscription = event.data.object as Stripe.Subscription;
const userId = await resolveUserIdFromStripeEvent(subscription);
if (userId) {
await syncSubscriptionFromStripe(subscription, userId);
} else {
console.warn('[billing/webhook] subscription event: no userId found', subscription.id);
}
break;
}
case 'customer.subscription.deleted': {
const subscription = event.data.object as Stripe.Subscription;
await handleSubscriptionDeleted(subscription);
break;
}
case 'invoice.payment_failed': {
const invoice = event.data.object as Stripe.Invoice & { subscription?: string | { id: string } };
if (invoice.subscription) {
const subscriptionId = typeof invoice.subscription === 'string'
? invoice.subscription
: invoice.subscription.id;
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
const userId = await resolveUserIdFromStripeEvent(subscription);
if (userId) {
await syncSubscriptionFromStripe(subscription, userId);
}
}
break;
}
default:
break;
}
return NextResponse.json({ received: true });
} catch (error) {
console.error('[billing/webhook] Handler error:', error);
return NextResponse.json({ error: 'Webhook handler failed' }, { status: 500 });
}
}

View File

@@ -2,10 +2,15 @@ import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { auth } from '@/auth'
import { z } from 'zod'
import { getTagsProvider } from '@/lib/ai/factory'
import { runLaneWithBillingUser, willUseByokForLane } from '@/lib/ai/provider-for-user'
import { getSystemConfig } from '@/lib/config'
import { embeddingService } from '@/lib/ai/services/embedding.service'
import {
checkSessionEntitlementOrThrow,
QuotaExceededError,
} from '@/lib/entitlements'
import {
billingOwnerFromSession,
verifyParticipant,
resolveAiContextUserId,
sanitizeNotesForGuest,
@@ -182,7 +187,23 @@ export async function POST(
return NextResponse.json({ error: 'Session not found' }, { status: 404 })
}
const parentIdea = brainstormSession.ideas.find(i => i.id === ideaId)
const { billingOwnerId, isGuestActor } = billingOwnerFromSession(
brainstormSession.userId,
session.user.id,
)
// Story 3.5: per-provider BYOK bypass
const earlyConfig = await getSystemConfig()
const { usedByok: willUseByok } = await willUseByokForLane('tags', earlyConfig, billingOwnerId)
if (!willUseByok) {
await checkSessionEntitlementOrThrow(
billingOwnerId,
session.user.id,
isGuestActor,
'brainstorm_expand',
)
}
const parentIdea = (brainstormSession.ideas || []).find(i => i.id === ideaId)
if (!parentIdea) {
return NextResponse.json({ error: 'Idea not found' }, { status: 404 })
}
@@ -205,7 +226,6 @@ export async function POST(
}
const config = await getSystemConfig()
const provider = getTagsProvider(config)
const prompt = buildExpandPromptV2(
parentIdea.title,
@@ -216,7 +236,12 @@ export async function POST(
locale
)
const llmResponse = await provider.generateText(prompt)
const { result: llmResponse } = await runLaneWithBillingUser(
'tags',
config,
billingOwnerId,
(provider) => provider.generateText(prompt),
)
let newIdeas: any[]
try {
@@ -311,6 +336,9 @@ export async function POST(
return NextResponse.json({ success: true, data: updatedSession })
} catch (error: any) {
if (error instanceof QuotaExceededError) {
return NextResponse.json(error.toJSON(), { status: 402 })
}
if (error instanceof z.ZodError) {
return NextResponse.json({ error: error.issues }, { status: 400 })
}

View File

@@ -2,10 +2,20 @@ import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { auth } from '@/auth'
import { z } from 'zod'
import { verifyParticipant, logActivity, resolveAiContextUserId, captureSnapshot } from '@/lib/brainstorm-collab'
import {
billingOwnerFromSession,
verifyParticipant,
logActivity,
resolveAiContextUserId,
captureSnapshot,
} from '@/lib/brainstorm-collab'
import { embeddingService } from '@/lib/ai/services/embedding.service'
import { getTagsProvider } from '@/lib/ai/factory'
import { runLaneWithBillingUser, willUseByokForLane } from '@/lib/ai/provider-for-user'
import { getSystemConfig } from '@/lib/config'
import {
reserveUsageOrThrow,
QuotaExceededError,
} from '@/lib/entitlements'
import { emitToSession } from '@/lib/socket-emit'
const manualSchema = z.object({
@@ -43,6 +53,11 @@ export async function POST(
return NextResponse.json({ error: 'Session not found' }, { status: 404 })
}
const { billingOwnerId, isGuestActor } = billingOwnerFromSession(
brainstormSession.userId,
session.user.id,
)
let wave = 1
let parentIdea: any = null
if (parentIdeaId) {
@@ -78,8 +93,25 @@ export async function POST(
},
})
// [UPDATE - SÉCURITÉ] Recherche vectorielle guest-safe
// Story 3.5: per-provider BYOK bypass for enrich
let enrichBlocked = false
try {
const config = await getSystemConfig()
const { usedByok: willUseByok } = await willUseByokForLane('tags', config, billingOwnerId)
if (!willUseByok) {
await reserveUsageOrThrow(billingOwnerId, 'brainstorm_enrich')
}
} catch (err) {
if (err instanceof QuotaExceededError) {
enrichBlocked = true
} else {
console.error('[manual-idea] reserveUsage error:', err)
}
}
// [UPDATE - SÉCURITÉ] Recherche vectorielle guest-safe (skipped when host quota exhausted)
let relatedNoteIds: string[] = []
if (!enrichBlocked) {
try {
const { isGuest, publicNoteIds, aiUserId } = await resolveAiContextUserId(sessionId, session.user.id)
@@ -117,7 +149,10 @@ export async function POST(
}
relatedNoteIds = results.map((r: any) => r.id)
}
} catch {}
} catch (vectorErr) {
console.error('[manual-idea] vector context search failed:', vectorErr)
}
}
if (relatedNoteIds.length > 0) {
const notes = await prisma.note.findMany({
@@ -155,6 +190,16 @@ export async function POST(
const requestingUserId = session.user!.id
const enrichAsync = async () => {
if (enrichBlocked) {
await emitToSession(sessionId, 'idea:ai_failed', {
ideaId: idea.id,
reason: 'quota_exceeded',
isGuestActor,
billingOwnerId,
})
return
}
try {
// Notifier le room que l'IA traite ce nœud (bordure pulsante violet)
await emitToSession(sessionId, 'idea:ai_processing', {
@@ -163,7 +208,6 @@ export async function POST(
})
const config = await getSystemConfig()
const provider = getTagsProvider(config)
const lang = locale === 'fr' ? 'French' : locale === 'es' ? 'Spanish' : locale === 'de' ? 'German' : locale === 'it' ? 'Italian' : locale === 'pt' ? 'Portuguese' : locale === 'ja' ? 'Japanese' : locale === 'ko' ? 'Korean' : locale === 'zh' ? 'Chinese' : locale === 'ar' ? 'Arabic' : "the user's language"
const enrichPrompt = `You are an idea enrichment assistant. Given a user's raw brainstorm idea and context, produce a JSON object with:
@@ -181,7 +225,12 @@ User's raw description: "${description || 'none provided'}"
Respond ONLY with the JSON object, no markdown.`
const raw = await provider.generateText(enrichPrompt)
const { result: raw } = await runLaneWithBillingUser(
'tags',
config,
billingOwnerId,
(provider) => provider.generateText(enrichPrompt),
)
const cleaned = raw.replace(/```json\n?/g, '').replace(/```\n?/g, '').trim()
const enriched = JSON.parse(cleaned)
@@ -195,7 +244,6 @@ Respond ONLY with the JSON object, no markdown.`
data: { title: enrichedTitle, description: enrichedDescription, connectionToSeed, noveltyScore },
})
// [UPDATE - TEMPS RÉEL] Notifier la complétion avec les données enrichies
await emitToSession(sessionId, 'idea:ai_completed', {
ideaId: idea.id,
title: enrichedTitle,

View File

@@ -2,9 +2,14 @@ import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { auth } from '@/auth'
import { z } from 'zod'
import { getTagsProvider } from '@/lib/ai/factory'
import { runLaneWithBillingUser, willUseByokForLane } from '@/lib/ai/provider-for-user'
import { getSystemConfig } from '@/lib/config'
import { embeddingService } from '@/lib/ai/services/embedding.service'
import {
checkEntitlementOrThrow,
QuotaExceededError,
incrementUsageAsync,
} from '@/lib/entitlements'
import { logActivity, captureSnapshot } from '@/lib/brainstorm-collab'
const waveSchema = z.object({
@@ -64,11 +69,7 @@ async function autoContextSearch(
snippet: (n.content || '').slice(0, 300),
}))
try {
const config = await getSystemConfig()
const provider = getTagsProvider(config)
const classifyPrompt = `Given the seed idea: "${seedIdea}"
const classifyPrompt = `Given the seed idea: "${seedIdea}"
Classify each note as SUPPORT (confirms/reinforces the seed), TENSION (contradicts/questions the seed), or EXTENSION (extends the seed into an adjacent domain).
@@ -78,7 +79,14 @@ ${notesForLLM.map(n => `[${n.id}] "${n.title}": ${n.snippet}`).join('\n')}
Respond ONLY with a valid JSON array of objects:
{ "noteId": string, "category": "SUPPORT" | "TENSION" | "EXTENSION" }`
const raw = await provider.generateText(classifyPrompt)
try {
const config = await getSystemConfig()
const { result: raw } = await runLaneWithBillingUser(
'tags',
config,
userId,
(provider) => provider.generateText(classifyPrompt),
)
const cleaned = raw.replace(/```json\n?/g, '').replace(/```\n?/g, '').trim()
const classifications: { noteId: string; category: 'SUPPORT' | 'TENSION' | 'EXTENSION' }[] = JSON.parse(cleaned)
@@ -199,13 +207,23 @@ export async function POST(request: NextRequest) {
const body = await request.json()
const { seedIdea, sourceNoteId, contextNoteIds, locale } = waveSchema.parse(body)
// Story 3.5: per-provider BYOK bypass
const config = await getSystemConfig()
const { usedByok: willUseByok } = await willUseByokForLane('tags', config, userId)
if (!willUseByok) {
await checkEntitlementOrThrow(userId, 'brainstorm_create')
}
const classifiedNotes = await autoContextSearch(userId, seedIdea, contextNoteIds)
const config = await getSystemConfig()
const provider = getTagsProvider(config)
const prompt = buildPromptV2(seedIdea, classifiedNotes, locale)
const llmResponse = await provider.generateText(prompt)
const { result: llmResponse, usedByok } = await runLaneWithBillingUser(
'tags',
config,
userId,
(provider) => provider.generateText(prompt),
)
if (!usedByok) incrementUsageAsync(userId, 'brainstorm_create')
let ideas: any[]
try {
@@ -312,6 +330,9 @@ export async function POST(request: NextRequest) {
},
}, { status: 201 })
} catch (error: any) {
if (error instanceof QuotaExceededError) {
return NextResponse.json(error.toJSON(), { status: 402 })
}
if (error instanceof z.ZodError) {
return NextResponse.json({ error: error.issues }, { status: 400 })
}

View File

@@ -1,11 +1,14 @@
import { streamText, UIMessage, stepCountIs } from 'ai'
import { getChatProvider } from '@/lib/ai/factory'
import { resolveAiRouteWithTiming, formatAiRouteDebug } from '@/lib/ai/router'
import { runLaneWithBillingUser, willUseByokForLane } from '@/lib/ai/provider-for-user'
import { getSystemConfig } from '@/lib/config'
import { semanticSearchService } from '@/lib/ai/services/semantic-search.service'
import { prisma } from '@/lib/prisma'
import { auth } from '@/auth'
import { loadTranslations, getTranslationValue, SupportedLanguage } from '@/lib/i18n'
import { toolRegistry } from '@/lib/ai/tools'
import { checkEntitlementOrThrow, QuotaExceededError, incrementUsageAsync } from '@/lib/entitlements'
import { trackFeatureUsage } from '@/lib/usage-tracker'
import { readFile } from 'fs/promises'
import path from 'path'
@@ -46,6 +49,20 @@ export async function POST(req: Request) {
}
const userId = session.user.id
// 1.5 Quota check (per-provider BYOK bypass — only when BYOK will be used for resolved provider)
try {
const sysConfigEarly = await getSystemConfig()
const { usedByok: willUseByok } = await willUseByokForLane('chat', sysConfigEarly, userId)
if (!willUseByok) {
await checkEntitlementOrThrow(userId, 'chat')
}
} catch (err) {
if (err instanceof QuotaExceededError) {
return Response.json(err.toJSON(), { status: 402 })
}
console.error('[chat] Quota check error (fail-open):', err)
}
// 2. Parse request body
const body = await req.json()
const { messages: rawMessages, conversationId, notebookId, language, webSearch, noteContext, format, noteId } = body as {
@@ -323,27 +340,43 @@ Focus ONLY on this note unless asked otherwise.`
// 6. Execute stream
const sysConfig = await getSystemConfig()
const routeDebug =
process.env.NODE_ENV !== 'production' || process.env.MEMENTO_AI_ROUTE_DEBUG === '1'
if (routeDebug) {
console.debug('[ai-route]', formatAiRouteDebug(resolveAiRouteWithTiming('chat', sysConfig)))
}
const chatTools = noteContext
? toolRegistry.buildToolsForChat({ userId, config: sysConfig, webSearch, notebookId: notebookId || undefined })
: toolRegistry.buildToolsForChat({ userId, config: sysConfig, webSearch, notebookId: notebookId || undefined })
const provider = getChatProvider(sysConfig)
const result = await streamText({
model: provider.getModel(),
system: systemPrompt,
messages: incomingMessages,
tools: chatTools,
stopWhen: stepCountIs(5),
onFinish: async (final) => {
const userContent = incomingMessages[incomingMessages.length - 1].content
await prisma.chatMessage.create({
data: { conversationId: conversation.id, role: 'user', content: userContent }
})
await prisma.chatMessage.create({
data: { conversationId: conversation.id, role: 'assistant', content: final.text }
})
}
})
const { result, usedByok } = await runLaneWithBillingUser(
'chat',
sysConfig,
userId,
async (provider) =>
streamText({
model: provider.getModel(),
system: systemPrompt,
messages: incomingMessages,
tools: chatTools,
stopWhen: stepCountIs(5),
onFinish: async (final) => {
const userContent = incomingMessages[incomingMessages.length - 1].content
await prisma.chatMessage.create({
data: { conversationId: conversation.id, role: 'user', content: userContent },
})
await prisma.chatMessage.create({
data: { conversationId: conversation.id, role: 'assistant', content: final.text },
})
if (!usedByok) {
trackFeatureUsage(userId, 'chat', final.usage?.totalTokens ?? 0)
incrementUsageAsync(userId, 'chat')
}
},
}),
)
return result.toUIMessageStreamResponse()
}

View File

@@ -0,0 +1,122 @@
import { NextRequest, NextResponse } from 'next/server';
import { redis } from '@/lib/redis';
import { prisma } from '@/lib/prisma';
import { parseRedisInt, getCurrentPeriodKey } from '@/lib/quota-utils';
function verifyCronAuth(req: NextRequest): boolean {
const cronSecret = process.env.CRON_SECRET;
if (!cronSecret) {
console.error('[sync-usage] CRON_SECRET env var is required but not set');
return false;
}
const authHeader = req.headers.get('authorization');
return authHeader === `Bearer ${cronSecret}`;
}
async function scanKeys(pattern: string): Promise<string[]> {
const keys: string[] = [];
let cursor = '0';
do {
const [nextCursor, batch] = await redis.scan(
cursor,
'MATCH',
pattern,
'COUNT',
200,
);
cursor = nextCursor;
keys.push(...batch);
} while (cursor !== '0');
return keys;
}
function parseUsageKey(key: string, period: string): { userId: string; feature: string } | null {
const suffix = `:${period}`;
if (!key.endsWith(suffix)) return null;
if (key.endsWith(':tokens')) return null;
const prefix = key.slice(0, key.length - suffix.length);
const firstColon = prefix.indexOf(':');
if (firstColon === -1) return null;
const afterPrefix = prefix.slice(firstColon + 1);
const lastColon = afterPrefix.lastIndexOf(':');
if (lastColon === -1) return null;
const userId = afterPrefix.slice(0, lastColon);
const feature = afterPrefix.slice(lastColon + 1);
if (!userId || !feature) return null;
return { userId, feature };
}
export async function POST(req: NextRequest) {
if (!verifyCronAuth(req)) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
try {
const period = getCurrentPeriodKey();
const pattern = `usage:*:${period}`;
const keys = await scanKeys(pattern);
let synced = 0;
let errors = 0;
for (const key of keys) {
if (key.endsWith(':tokens')) continue;
try {
const parsed = parseUsageKey(key, period);
if (!parsed) continue;
const { userId, feature } = parsed;
const [counter, tokens] = await Promise.all([
redis.get(key),
redis.get(`${key}:tokens`),
]);
const periodStart = new Date(`${period}-01`);
const periodEnd = new Date(
periodStart.getFullYear(),
periodStart.getMonth() + 1,
1,
);
await prisma.usageLog.upsert({
where: {
userId_feature_periodStart: {
userId,
feature,
periodStart,
},
},
create: {
userId,
feature,
periodStart,
periodEnd,
requestsCount: parseRedisInt(counter),
tokensUsed: parseRedisInt(tokens),
},
update: {
requestsCount: parseRedisInt(counter),
tokensUsed: parseRedisInt(tokens),
syncedAt: new Date(),
},
});
synced++;
} catch (err) {
errors++;
console.error(`[sync-usage] Failed to sync key ${key}:`, err);
}
}
return NextResponse.json({ synced, errors, total: keys.length });
} catch (error) {
console.error('[sync-usage] Error:', error);
return NextResponse.json({ error: 'Sync failed' }, { status: 500 });
}
}

View File

@@ -28,7 +28,7 @@ export async function PATCH(
try {
const { id } = await params
const body = await request.json()
const { name, icon, color, order, trashedAt } = body
const { name, icon, color, order, trashedAt, parentId } = body
const existing = await prisma.notebook.findUnique({
where: { id },
@@ -49,12 +49,40 @@ export async function PATCH(
)
}
if (parentId !== undefined) {
if (parentId !== null) {
if (parentId === id) {
return NextResponse.json(
{ success: false, error: 'A notebook cannot be its own parent' },
{ status: 400 }
)
}
const target = await prisma.notebook.findFirst({
where: { id: parentId, userId: session.user.id }
})
if (!target) {
return NextResponse.json(
{ success: false, error: 'Parent notebook not found' },
{ status: 404 }
)
}
const descendants = await getDescendantIds(id)
if (descendants.includes(parentId)) {
return NextResponse.json(
{ success: false, error: 'Cannot move a notebook into its own descendant' },
{ status: 400 }
)
}
}
}
const updateData: any = {}
if (name !== undefined) updateData.name = name.trim()
if (icon !== undefined) updateData.icon = icon
if (color !== undefined) updateData.color = color
if (order !== undefined) updateData.order = order
if (trashedAt !== undefined) updateData.trashedAt = trashedAt
if (parentId !== undefined) updateData.parentId = parentId
if (trashedAt !== undefined) {
const descendantIds = await getDescendantIds(id)

View File

@@ -4,124 +4,103 @@ import { prisma } from '@/lib/prisma'
export async function GET(req: NextRequest) {
try {
// Check authentication
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json(
{ success: false, error: 'Unauthorized' },
{ status: 401 }
)
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
}
// Fetch all notes with related data
const notes = await prisma.note.findMany({
where: {
userId: session.user.id,
trashedAt: null
},
include: {
labelRelations: {
select: {
id: true,
name: true
}
},
notebook: {
select: {
id: true,
name: true
}
}
},
orderBy: {
createdAt: 'desc'
}
})
const userId = session.user.id
// Fetch labels separately
const labels = await prisma.label.findMany({
where: {
userId: session.user.id
},
include: {
notes: {
select: {
id: true
}
}
}
})
const [allNotes, labels, notebooks] = await Promise.all([
prisma.note.findMany({
where: { userId },
orderBy: { createdAt: 'asc' },
}),
prisma.label.findMany({
where: { userId },
include: { notes: { select: { id: true } } },
}),
prisma.notebook.findMany({
where: { userId },
include: { notes: { select: { id: true } } },
}),
])
// Fetch notebooks
const notebooks = await prisma.notebook.findMany({
where: {
userId: session.user.id
},
include: {
notes: {
select: {
id: true
}
}
const noteLabelMap = new Map<string, string[]>()
for (const label of labels) {
for (const note of label.notes) {
const arr = noteLabelMap.get(note.id) || []
arr.push(label.id)
noteLabelMap.set(note.id, arr)
}
})
}
// Create export object
const exportData = {
version: '1.0.0',
version: '2.0.0',
exportDate: new Date().toISOString(),
user: {
id: session.user.id,
email: session.user.email,
name: session.user.name
id: userId,
email: session.user.email ?? '',
name: session.user.name ?? '',
},
data: {
labels: labels.map(label => ({
id: label.id,
name: label.name,
color: label.color,
noteCount: label.notes.length
notebooks: notebooks.map(nb => ({
id: nb.id,
name: nb.name,
icon: nb.icon,
color: nb.color,
order: nb.order,
parentId: nb.parentId,
trashedAt: nb.trashedAt?.toISOString() ?? null,
createdAt: nb.createdAt.toISOString(),
updatedAt: nb.updatedAt.toISOString(),
noteIds: nb.notes.map(n => n.id),
})),
notebooks: notebooks.map(notebook => ({
id: notebook.id,
name: notebook.name,
noteCount: notebook.notes.length
labels: labels.map(lb => ({
id: lb.id,
name: lb.name,
color: lb.color,
notebookId: lb.notebookId,
type: lb.type,
createdAt: lb.createdAt.toISOString(),
updatedAt: lb.updatedAt.toISOString(),
noteIds: lb.notes.map(n => n.id),
})),
notes: notes.map(note => ({
id: note.id,
title: note.title,
content: note.content,
color: note.color,
isPinned: note.isPinned,
isArchived: note.isArchived,
type: note.type,
checkItems: note.checkItems,
images: note.images,
links: note.links,
createdAt: note.createdAt,
updatedAt: note.updatedAt,
notebookId: note.notebookId,
labelRelations: note.labelRelations.map(label => ({
id: label.id,
name: label.name
}))
}))
}
notes: allNotes.map(n => ({
id: n.id,
title: n.title,
content: n.content,
color: n.color,
isPinned: n.isPinned,
isArchived: n.isArchived,
type: n.type,
order: n.order,
isMarkdown: n.isMarkdown,
size: n.size,
autoGenerated: n.autoGenerated,
historyEnabled: n.historyEnabled,
checkItems: n.checkItems,
images: n.images,
links: n.links,
trashedAt: n.trashedAt?.toISOString() ?? null,
notebookId: n.notebookId,
createdAt: n.createdAt.toISOString(),
updatedAt: n.updatedAt.toISOString(),
contentUpdatedAt: n.contentUpdatedAt?.toISOString() ?? null,
labelIds: noteLabelMap.get(n.id) || [],
})),
},
}
// Return as JSON file
const jsonString = JSON.stringify(exportData, null, 2)
return new NextResponse(jsonString, {
headers: {
'Content-Type': 'application/json',
'Content-Disposition': `attachment; filename="memento-export-${new Date().toISOString().split('T')[0]}.json"`
}
'Content-Disposition': `attachment; filename="memento-export-${new Date().toISOString().split('T')[0]}.json"`,
},
})
} catch (error) {
console.error('Export error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to export notes' },
{ status: 500 }
)
return NextResponse.json({ success: false, error: 'Failed to export notes' }, { status: 500 })
}
}

View File

@@ -3,162 +3,231 @@ import { auth } from '@/auth'
import { prisma } from '@/lib/prisma'
import { revalidatePath } from 'next/cache'
function parseDate(v: unknown): Date | null {
if (!v) return null
const d = new Date(v as string)
return isNaN(d.getTime()) ? null : d
}
export async function POST(req: NextRequest) {
try {
// Check authentication
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json(
{ success: false, error: 'Unauthorized' },
{ status: 401 }
)
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
}
// Parse form data
const userId = session.user.id
const formData = await req.formData()
const file = formData.get('file') as File
if (!file) {
return NextResponse.json(
{ success: false, error: 'No file provided' },
{ status: 400 }
)
return NextResponse.json({ success: false, error: 'No file provided' }, { status: 400 })
}
// Parse JSON file
const text = await file.text()
let importData: any
try {
importData = JSON.parse(text)
} catch (error) {
return NextResponse.json(
{ success: false, error: 'Invalid JSON file' },
{ status: 400 }
)
} catch {
return NextResponse.json({ success: false, error: 'Invalid JSON file' }, { status: 400 })
}
// Validate import data structure
if (!importData.data || !importData.data.notes) {
return NextResponse.json(
{ success: false, error: 'Invalid import format' },
{ status: 400 }
)
return NextResponse.json({ success: false, error: 'Invalid import format' }, { status: 400 })
}
let importedNotes = 0
let importedLabels = 0
let importedNotebooks = 0
const stats = { notes: 0, labels: 0, notebooks: 0, skipped: 0 }
// Import labels first
if (importData.data.labels && Array.isArray(importData.data.labels)) {
for (const label of importData.data.labels) {
// Check if label already exists
const existing = await prisma.label.findFirst({
where: {
userId: session.user.id,
name: label.name
}
})
// 1. Notebooks — parents first, preserve original IDs
if (importData.data.notebooks?.length) {
const sorted = [...importData.data.notebooks].sort((a: any, b: any) => {
if (!a.parentId && b.parentId) return -1
if (a.parentId && !b.parentId) return 1
return 0
})
if (!existing) {
await prisma.label.create({
data: {
userId: session.user.id,
name: label.name,
color: label.color
}
for (const nb of sorted) {
try {
await prisma.notebook.upsert({
where: { id: nb.id },
update: {
name: nb.name,
icon: nb.icon ?? null,
color: nb.color ?? null,
order: nb.order ?? 0,
parentId: nb.parentId ?? null,
trashedAt: parseDate(nb.trashedAt),
updatedAt: new Date(),
},
create: {
id: nb.id,
name: nb.name,
icon: nb.icon ?? null,
color: nb.color ?? null,
order: nb.order ?? 0,
parentId: nb.parentId ?? null,
trashedAt: parseDate(nb.trashedAt),
userId,
createdAt: parseDate(nb.createdAt) ?? new Date(),
updatedAt: parseDate(nb.updatedAt) ?? new Date(),
},
})
importedLabels++
stats.notebooks++
} catch (e: any) {
if (e.code === 'P2002') {
// unique constraint — try with new ID
const parentId = nb.parentId ?? null
await prisma.notebook.create({
data: {
name: nb.name,
icon: nb.icon ?? null,
color: nb.color ?? null,
order: nb.order ?? 0,
parentId,
trashedAt: parseDate(nb.trashedAt),
userId,
createdAt: parseDate(nb.createdAt) ?? new Date(),
updatedAt: parseDate(nb.updatedAt) ?? new Date(),
},
})
stats.notebooks++
} else {
stats.skipped++
}
}
}
}
// Import notebooks
const notebookIdMap = new Map<string, string>()
if (importData.data.notebooks && Array.isArray(importData.data.notebooks)) {
for (const notebook of importData.data.notebooks) {
// Check if notebook already exists
const existing = await prisma.notebook.findFirst({
where: {
userId: session.user.id,
name: notebook.name
}
})
let newNotebookId
if (!existing) {
const created = await prisma.notebook.create({
data: {
userId: session.user.id,
name: notebook.name,
order: 0
}
// 2. Labels — preserve original IDs
if (importData.data.labels?.length) {
for (const lb of importData.data.labels) {
try {
await prisma.label.upsert({
where: { id: lb.id },
update: {
name: lb.name,
color: lb.color ?? null,
notebookId: lb.notebookId ?? null,
type: lb.type ?? 'user',
},
create: {
id: lb.id,
name: lb.name,
color: lb.color ?? null,
notebookId: lb.notebookId ?? null,
type: lb.type ?? 'user',
userId,
createdAt: parseDate(lb.createdAt) ?? new Date(),
updatedAt: parseDate(lb.updatedAt) ?? new Date(),
},
})
newNotebookId = created.id
notebookIdMap.set(notebook.id, newNotebookId)
importedNotebooks++
} else {
notebookIdMap.set(notebook.id, existing.id)
stats.labels++
} catch {
stats.skipped++
}
}
}
// Import notes
if (importData.data.notes && Array.isArray(importData.data.notes)) {
for (const note of importData.data.notes) {
// Map notebook ID
const mappedNotebookId = notebookIdMap.get(note.notebookId) || null
// 3. Notes — preserve original IDs
if (importData.data.notes?.length) {
for (const n of importData.data.notes) {
try {
const labelIds: string[] = n.labelIds || []
const validLabelIds = labelIds.length
? await prisma.label.findMany({
where: { id: { in: labelIds }, userId },
select: { id: true },
}).then(ls => ls.map(l => l.id))
: []
// Get label IDs
const labelNames = (note.labels || note.labelRelations || []).map((l: any) => l.name).filter(Boolean)
const labels = await prisma.label.findMany({
where: {
userId: session.user.id,
name: {
in: labelNames
}
await prisma.note.upsert({
where: { id: n.id },
update: {
title: n.title || 'Untitled',
content: n.content || '',
color: n.color || 'default',
isPinned: n.isPinned ?? false,
isArchived: n.isArchived ?? false,
type: n.type || 'richtext',
order: n.order ?? 0,
isMarkdown: n.isMarkdown ?? false,
size: n.size || 'small',
autoGenerated: n.autoGenerated ?? false,
historyEnabled: n.historyEnabled ?? true,
checkItems: n.checkItems ?? undefined,
images: n.images ?? undefined,
links: n.links ?? undefined,
trashedAt: parseDate(n.trashedAt),
notebookId: n.notebookId ?? null,
contentUpdatedAt: parseDate(n.contentUpdatedAt),
updatedAt: new Date(),
labelRelations: {
set: validLabelIds.map(id => ({ id })),
},
},
create: {
id: n.id,
title: n.title || 'Untitled',
content: n.content || '',
color: n.color || 'default',
isPinned: n.isPinned ?? false,
isArchived: n.isArchived ?? false,
type: n.type || 'richtext',
order: n.order ?? 0,
isMarkdown: n.isMarkdown ?? false,
size: n.size || 'small',
autoGenerated: n.autoGenerated ?? false,
historyEnabled: n.historyEnabled ?? true,
checkItems: n.checkItems ?? undefined,
images: n.images ?? undefined,
links: n.links ?? undefined,
trashedAt: parseDate(n.trashedAt),
notebookId: n.notebookId ?? null,
userId,
createdAt: parseDate(n.createdAt) ?? new Date(),
updatedAt: parseDate(n.updatedAt) ?? new Date(),
contentUpdatedAt: parseDate(n.contentUpdatedAt),
labelRelations: {
connect: validLabelIds.map(id => ({ id })),
},
},
})
stats.notes++
} catch (e: any) {
if (e.code === 'P2002') {
await prisma.note.create({
data: {
title: n.title || 'Untitled',
content: n.content || '',
color: n.color || 'default',
isPinned: n.isPinned ?? false,
isArchived: n.isArchived ?? false,
type: n.type || 'richtext',
order: n.order ?? 0,
isMarkdown: n.isMarkdown ?? false,
size: n.size || 'small',
notebookId: n.notebookId ?? null,
userId,
createdAt: parseDate(n.createdAt) ?? new Date(),
updatedAt: parseDate(n.updatedAt) ?? new Date(),
contentUpdatedAt: parseDate(n.contentUpdatedAt),
},
})
stats.notes++
} else {
stats.skipped++
}
})
// Create note
await prisma.note.create({
data: {
userId: session.user.id,
title: note.title || 'Untitled',
content: note.content || '',
color: note.color || 'default',
isPinned: note.isPinned || false,
isArchived: note.isArchived || false,
type: note.type || 'richtext',
checkItems: note.checkItems || null,
images: note.images || null,
links: note.links || null,
notebookId: mappedNotebookId,
labelRelations: {
connect: labels.map(label => ({ id: label.id }))
}
}
})
importedNotes++
}
}
}
// Revalidate paths
revalidatePath('/')
revalidatePath('/settings/data')
return NextResponse.json({
success: true,
count: importedNotes,
labels: importedLabels,
notebooks: importedNotebooks
})
return NextResponse.json({ success: true, ...stats })
} catch (error) {
console.error('Import error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to import notes' },
{ status: 500 }
)
return NextResponse.json({ success: false, error: 'Failed to import notes' }, { status: 500 })
}
}

View File

@@ -0,0 +1,22 @@
import { NextResponse } from 'next/server';
import { auth } from '@/auth';
import { getUserQuotas } from '@/lib/entitlements';
export async function GET() {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
try {
const quotas = await getUserQuotas(session.user.id);
return NextResponse.json({ quotas });
} catch (error) {
console.error('[usage/current] Failed to fetch quotas:', error);
return NextResponse.json(
{ error: 'Failed to fetch usage data' },
{ status: 503 },
);
}
}

View File

@@ -0,0 +1,56 @@
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import { prisma } from '@/lib/prisma';
import { VALID_PROVIDERS } from '@/lib/ai/router';
type RouteContext = { params: Promise<{ provider: string }> };
export async function PATCH(req: NextRequest, context: RouteContext) {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { provider } = await context.params;
if (!VALID_PROVIDERS.has(provider)) {
return NextResponse.json({ error: 'Unknown provider' }, { status: 400 });
}
const body = (await req.json().catch(() => ({}))) as { isActive?: boolean };
if (typeof body.isActive !== 'boolean') {
return NextResponse.json({ error: 'isActive boolean required' }, { status: 400 });
}
const updated = await prisma.userAPIKey.updateMany({
where: { userId: session.user.id, provider },
data: { isActive: body.isActive },
});
if (updated.count === 0) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
return NextResponse.json({ ok: true });
}
export async function DELETE(_req: NextRequest, context: RouteContext) {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { provider } = await context.params;
if (!VALID_PROVIDERS.has(provider)) {
return NextResponse.json({ error: 'Unknown provider' }, { status: 400 });
}
const deleted = await prisma.userAPIKey.deleteMany({
where: { userId: session.user.id, provider },
});
if (deleted.count === 0) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
return NextResponse.json({ ok: true });
}

View File

@@ -0,0 +1,99 @@
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auth } from '@/auth';
import { getEffectiveTier } from '@/lib/entitlements';
import {
getAllowedByokProviders,
isByokProviderAllowed,
} from '@/lib/byok';
import {
upsertUserApiKey,
toPublicApiKey,
} from '@/lib/byok';
import { validateProviderApiKey } from '@/lib/byok/validate-key';
import { VALID_PROVIDERS, type AiGatewayProvider } from '@/lib/ai/router';
import { prisma } from '@/lib/prisma';
const createSchema = z.object({
provider: z.string().min(1),
apiKey: z.string().min(8),
alias: z.string().max(120).optional(),
model: z.string().max(120).optional(),
baseUrl: z.string().url().optional(),
});
export async function GET() {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const keys = await prisma.userAPIKey.findMany({
where: { userId: session.user.id },
orderBy: { provider: 'asc' },
});
return NextResponse.json({
keys: keys.map(toPublicApiKey),
allowedProviders: getAllowedByokProviders(await getEffectiveTier(session.user.id)),
});
}
export async function POST(req: NextRequest) {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const tier = await getEffectiveTier(session.user.id);
if (tier === 'BASIC') {
return NextResponse.json(
{ error: 'TIER_LIMITED', message: 'BYOK requires a Pro plan or higher' },
{ status: 403 },
);
}
let body: z.infer<typeof createSchema>;
try {
body = createSchema.parse(await req.json());
} catch {
return NextResponse.json({ error: 'Invalid request body' }, { status: 400 });
}
const provider = body.provider as AiGatewayProvider;
if (!VALID_PROVIDERS.has(provider)) {
return NextResponse.json({ error: 'Unknown provider' }, { status: 400 });
}
if (!isByokProviderAllowed(tier, provider)) {
return NextResponse.json(
{ error: 'TIER_LIMITED', message: `Provider "${provider}" is not available on your plan` },
{ status: 403 },
);
}
const effectiveBaseUrl = provider === 'custom' ? body.baseUrl : undefined;
if (provider !== 'custom' && body.baseUrl) {
return NextResponse.json(
{ error: 'INVALID_REQUEST', message: 'baseUrl is only allowed for custom providers' },
{ status: 400 },
);
}
try {
await validateProviderApiKey(provider, body.apiKey, effectiveBaseUrl);
} catch (err) {
const message = err instanceof Error ? err.message : 'Invalid API key';
return NextResponse.json({ error: 'INVALID_API_KEY', message }, { status: 400 });
}
const row = await upsertUserApiKey({
userId: session.user.id,
provider,
plaintext: body.apiKey,
alias: body.alias,
model: body.model,
});
return NextResponse.json({ key: toPublicApiKey(row) });
}