|
| 1 | +import { db } from '@sim/db' |
| 2 | +import { chat } from '@sim/db/schema' |
| 3 | +import { createLogger } from '@sim/logger' |
| 4 | +import { eq } from 'drizzle-orm' |
| 5 | +import { type NextRequest, NextResponse } from 'next/server' |
| 6 | +import { getSession } from '@/lib/auth' |
| 7 | +import { hasExceededCostLimit } from '@/lib/billing/core/subscription' |
| 8 | +import { recordUsage } from '@/lib/billing/core/usage-log' |
| 9 | +import { env } from '@/lib/core/config/env' |
| 10 | +import { getCostMultiplier, isBillingEnabled } from '@/lib/core/config/feature-flags' |
| 11 | +import { RateLimiter } from '@/lib/core/rate-limiter' |
| 12 | +import { validateAuthToken } from '@/lib/core/security/deployment' |
| 13 | +import { getClientIp } from '@/lib/core/utils/request' |
| 14 | + |
| 15 | +const logger = createLogger('SpeechTokenAPI') |
| 16 | + |
| 17 | +export const dynamic = 'force-dynamic' |
| 18 | + |
| 19 | +const ELEVENLABS_TOKEN_URL = 'https://api.elevenlabs.io/v1/single-use-token/realtime_scribe' |
| 20 | + |
| 21 | +const VOICE_SESSION_COST_PER_MIN = 0.008 |
| 22 | +const WORKSPACE_SESSION_MAX_MINUTES = 3 |
| 23 | +const CHAT_SESSION_MAX_MINUTES = 1 |
| 24 | + |
| 25 | +const STT_TOKEN_RATE_LIMIT = { |
| 26 | + maxTokens: 30, |
| 27 | + refillRate: 3, |
| 28 | + refillIntervalMs: 72 * 1000, |
| 29 | +} as const |
| 30 | + |
| 31 | +const rateLimiter = new RateLimiter() |
| 32 | + |
| 33 | +async function validateChatAuth( |
| 34 | + request: NextRequest, |
| 35 | + chatId: string |
| 36 | +): Promise<{ valid: boolean; ownerId?: string }> { |
| 37 | + try { |
| 38 | + const chatResult = await db |
| 39 | + .select({ |
| 40 | + id: chat.id, |
| 41 | + userId: chat.userId, |
| 42 | + isActive: chat.isActive, |
| 43 | + authType: chat.authType, |
| 44 | + password: chat.password, |
| 45 | + }) |
| 46 | + .from(chat) |
| 47 | + .where(eq(chat.id, chatId)) |
| 48 | + .limit(1) |
| 49 | + |
| 50 | + if (chatResult.length === 0 || !chatResult[0].isActive) { |
| 51 | + return { valid: false } |
| 52 | + } |
| 53 | + |
| 54 | + const chatData = chatResult[0] |
| 55 | + |
| 56 | + if (chatData.authType === 'public') { |
| 57 | + return { valid: true, ownerId: chatData.userId } |
| 58 | + } |
| 59 | + |
| 60 | + const cookieName = `chat_auth_${chatId}` |
| 61 | + const authCookie = request.cookies.get(cookieName) |
| 62 | + if (authCookie && validateAuthToken(authCookie.value, chatId, chatData.password)) { |
| 63 | + return { valid: true, ownerId: chatData.userId } |
| 64 | + } |
| 65 | + |
| 66 | + return { valid: false } |
| 67 | + } catch (error) { |
| 68 | + logger.error('Error validating chat auth for STT:', error) |
| 69 | + return { valid: false } |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +export async function POST(request: NextRequest) { |
| 74 | + try { |
| 75 | + const body = await request.json().catch(() => ({})) |
| 76 | + const chatId = body?.chatId as string | undefined |
| 77 | + |
| 78 | + let billingUserId: string | undefined |
| 79 | + |
| 80 | + if (chatId) { |
| 81 | + const chatAuth = await validateChatAuth(request, chatId) |
| 82 | + if (!chatAuth.valid) { |
| 83 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 84 | + } |
| 85 | + billingUserId = chatAuth.ownerId |
| 86 | + } else { |
| 87 | + const session = await getSession() |
| 88 | + if (!session?.user?.id) { |
| 89 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 90 | + } |
| 91 | + billingUserId = session.user.id |
| 92 | + } |
| 93 | + |
| 94 | + if (isBillingEnabled) { |
| 95 | + const rateLimitKey = chatId |
| 96 | + ? `stt-token:chat:${chatId}:${getClientIp(request)}` |
| 97 | + : `stt-token:user:${billingUserId}` |
| 98 | + |
| 99 | + const rateCheck = await rateLimiter.checkRateLimitDirect(rateLimitKey, STT_TOKEN_RATE_LIMIT) |
| 100 | + if (!rateCheck.allowed) { |
| 101 | + return NextResponse.json( |
| 102 | + { error: 'Voice input rate limit exceeded. Please try again later.' }, |
| 103 | + { |
| 104 | + status: 429, |
| 105 | + headers: { |
| 106 | + 'Retry-After': String(Math.ceil((rateCheck.retryAfterMs ?? 60000) / 1000)), |
| 107 | + }, |
| 108 | + } |
| 109 | + ) |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + if (billingUserId && isBillingEnabled) { |
| 114 | + const exceeded = await hasExceededCostLimit(billingUserId) |
| 115 | + if (exceeded) { |
| 116 | + return NextResponse.json( |
| 117 | + { error: 'Usage limit exceeded. Please upgrade your plan to continue.' }, |
| 118 | + { status: 402 } |
| 119 | + ) |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + const apiKey = env.ELEVENLABS_API_KEY |
| 124 | + if (!apiKey?.trim()) { |
| 125 | + return NextResponse.json( |
| 126 | + { error: 'Speech-to-text service is not configured' }, |
| 127 | + { status: 503 } |
| 128 | + ) |
| 129 | + } |
| 130 | + |
| 131 | + const response = await fetch(ELEVENLABS_TOKEN_URL, { |
| 132 | + method: 'POST', |
| 133 | + headers: { 'xi-api-key': apiKey }, |
| 134 | + }) |
| 135 | + |
| 136 | + if (!response.ok) { |
| 137 | + const errBody = await response.json().catch(() => ({})) |
| 138 | + const message = |
| 139 | + errBody.detail || errBody.message || `Token request failed (${response.status})` |
| 140 | + logger.error('ElevenLabs token request failed', { status: response.status, message }) |
| 141 | + return NextResponse.json({ error: message }, { status: 502 }) |
| 142 | + } |
| 143 | + |
| 144 | + const data = await response.json() |
| 145 | + |
| 146 | + if (billingUserId) { |
| 147 | + const maxMinutes = chatId ? CHAT_SESSION_MAX_MINUTES : WORKSPACE_SESSION_MAX_MINUTES |
| 148 | + const sessionCost = VOICE_SESSION_COST_PER_MIN * maxMinutes |
| 149 | + |
| 150 | + await recordUsage({ |
| 151 | + userId: billingUserId, |
| 152 | + entries: [ |
| 153 | + { |
| 154 | + category: 'fixed', |
| 155 | + source: 'voice-input', |
| 156 | + description: `Voice input session (${maxMinutes} min)`, |
| 157 | + cost: sessionCost * getCostMultiplier(), |
| 158 | + }, |
| 159 | + ], |
| 160 | + }).catch((err) => { |
| 161 | + logger.warn('Failed to record voice input usage, continuing:', err) |
| 162 | + }) |
| 163 | + } |
| 164 | + |
| 165 | + return NextResponse.json({ token: data.token }) |
| 166 | + } catch (error) { |
| 167 | + const message = error instanceof Error ? error.message : 'Failed to generate speech token' |
| 168 | + logger.error('Speech token error:', error) |
| 169 | + return NextResponse.json({ error: message }, { status: 500 }) |
| 170 | + } |
| 171 | +} |
0 commit comments