Skip to content

Commit c552bb9

Browse files
authored
fix(elevenlabs): added internal auth helper for proxy routes (#1732)
* fix(elevenlabs): added internal auth helper for proxy routes * remove concurrent tests * build fix
1 parent ad7b791 commit c552bb9

File tree

8 files changed

+249
-171
lines changed

8 files changed

+249
-171
lines changed

apps/sim/app/api/proxy/image/route.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { type NextRequest, NextResponse } from 'next/server'
2+
import { checkHybridAuth } from '@/lib/auth/hybrid'
23
import { createLogger } from '@/lib/logs/console/logger'
34
import { validateImageUrl } from '@/lib/security/input-validation'
45
import { generateRequestId } from '@/lib/utils'
@@ -14,6 +15,12 @@ export async function GET(request: NextRequest) {
1415
const imageUrl = url.searchParams.get('url')
1516
const requestId = generateRequestId()
1617

18+
const authResult = await checkHybridAuth(request, { requireWorkflowId: false })
19+
if (!authResult.success) {
20+
logger.error(`[${requestId}] Authentication failed for image proxy:`, authResult.error)
21+
return new NextResponse('Unauthorized', { status: 401 })
22+
}
23+
1724
if (!imageUrl) {
1825
logger.error(`[${requestId}] Missing 'url' parameter`)
1926
return new NextResponse('Missing URL parameter', { status: 400 })

apps/sim/app/api/proxy/route.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
import type { NextRequest } from 'next/server'
12
import { NextResponse } from 'next/server'
3+
import { checkHybridAuth } from '@/lib/auth/hybrid'
24
import { generateInternalToken } from '@/lib/auth/internal'
35
import { isDev } from '@/lib/environment'
46
import { createLogger } from '@/lib/logs/console/logger'
@@ -242,12 +244,18 @@ export async function GET(request: Request) {
242244
}
243245
}
244246

245-
export async function POST(request: Request) {
247+
export async function POST(request: NextRequest) {
246248
const requestId = generateRequestId()
247249
const startTime = new Date()
248250
const startTimeISO = startTime.toISOString()
249251

250252
try {
253+
const authResult = await checkHybridAuth(request, { requireWorkflowId: false })
254+
if (!authResult.success) {
255+
logger.error(`[${requestId}] Authentication failed for proxy:`, authResult.error)
256+
return createErrorResponse('Unauthorized', 401)
257+
}
258+
251259
let requestBody
252260
try {
253261
requestBody = await request.json()
@@ -311,18 +319,15 @@ export async function POST(request: Request) {
311319
error: result.error || 'Unknown error',
312320
})
313321

314-
// Let the main executeTool handle error transformation to avoid double transformation
315322
throw new Error(result.error || 'Tool execution failed')
316323
}
317324

318325
const endTime = new Date()
319326
const endTimeISO = endTime.toISOString()
320327
const duration = endTime.getTime() - startTime.getTime()
321328

322-
// Add explicit timing information directly to the response
323329
const responseWithTimingData = {
324330
...result,
325-
// Add timing data both at root level and in nested timing object
326331
startTime: startTimeISO,
327332
endTime: endTimeISO,
328333
duration,
@@ -335,7 +340,6 @@ export async function POST(request: Request) {
335340

336341
logger.info(`[${requestId}] Tool executed successfully: ${toolId} (${duration}ms)`)
337342

338-
// Return the response with CORS headers
339343
return formatResponse(responseWithTimingData)
340344
} catch (error: any) {
341345
logger.error(`[${requestId}] Proxy request failed`, {
@@ -344,7 +348,6 @@ export async function POST(request: Request) {
344348
name: error instanceof Error ? error.name : undefined,
345349
})
346350

347-
// Add timing information even to error responses
348351
const endTime = new Date()
349352
const endTimeISO = endTime.toISOString()
350353
const duration = endTime.getTime() - startTime.getTime()

apps/sim/app/api/proxy/tts/route.ts

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,32 @@
1+
import type { NextRequest } from 'next/server'
12
import { NextResponse } from 'next/server'
3+
import { checkHybridAuth } from '@/lib/auth/hybrid'
24
import { createLogger } from '@/lib/logs/console/logger'
35
import { validateAlphanumericId } from '@/lib/security/input-validation'
46
import { uploadFile } from '@/lib/uploads/storage-client'
57
import { getBaseUrl } from '@/lib/urls/utils'
68

79
const logger = createLogger('ProxyTTSAPI')
810

9-
export async function POST(request: Request) {
11+
export async function POST(request: NextRequest) {
1012
try {
13+
const authResult = await checkHybridAuth(request, { requireWorkflowId: false })
14+
if (!authResult.success) {
15+
logger.error('Authentication failed for TTS proxy:', authResult.error)
16+
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
17+
}
18+
1119
const body = await request.json()
1220
const { text, voiceId, apiKey, modelId = 'eleven_monolingual_v1' } = body
1321

1422
if (!text || !voiceId || !apiKey) {
15-
return new NextResponse('Missing required parameters', { status: 400 })
23+
return NextResponse.json({ error: 'Missing required parameters' }, { status: 400 })
1624
}
1725

1826
const voiceIdValidation = validateAlphanumericId(voiceId, 'voiceId', 255)
1927
if (!voiceIdValidation.isValid) {
2028
logger.error(`Invalid voice ID: ${voiceIdValidation.error}`)
21-
return new NextResponse(voiceIdValidation.error, { status: 400 })
29+
return NextResponse.json({ error: voiceIdValidation.error }, { status: 400 })
2230
}
2331

2432
logger.info('Proxying TTS request for voice:', voiceId)
@@ -41,16 +49,17 @@ export async function POST(request: Request) {
4149

4250
if (!response.ok) {
4351
logger.error(`Failed to generate TTS: ${response.status} ${response.statusText}`)
44-
return new NextResponse(`Failed to generate TTS: ${response.status} ${response.statusText}`, {
45-
status: response.status,
46-
})
52+
return NextResponse.json(
53+
{ error: `Failed to generate TTS: ${response.status} ${response.statusText}` },
54+
{ status: response.status }
55+
)
4756
}
4857

4958
const audioBlob = await response.blob()
5059

5160
if (audioBlob.size === 0) {
5261
logger.error('Empty audio received from ElevenLabs')
53-
return new NextResponse('Empty audio received', { status: 422 })
62+
return NextResponse.json({ error: 'Empty audio received' }, { status: 422 })
5463
}
5564

5665
const audioBuffer = Buffer.from(await audioBlob.arrayBuffer())
@@ -67,11 +76,11 @@ export async function POST(request: Request) {
6776
} catch (error) {
6877
logger.error('Error proxying TTS:', error)
6978

70-
return new NextResponse(
71-
`Internal Server Error: ${error instanceof Error ? error.message : 'Unknown error'}`,
79+
return NextResponse.json(
7280
{
73-
status: 500,
74-
}
81+
error: `Internal Server Error: ${error instanceof Error ? error.message : 'Unknown error'}`,
82+
},
83+
{ status: 500 }
7584
)
7685
}
7786
}

apps/sim/app/api/proxy/tts/stream/route.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { NextRequest } from 'next/server'
2+
import { checkHybridAuth } from '@/lib/auth/hybrid'
23
import { env } from '@/lib/env'
34
import { createLogger } from '@/lib/logs/console/logger'
45
import { validateAlphanumericId } from '@/lib/security/input-validation'
@@ -7,6 +8,12 @@ const logger = createLogger('ProxyTTSStreamAPI')
78

89
export async function POST(request: NextRequest) {
910
try {
11+
const authResult = await checkHybridAuth(request, { requireWorkflowId: false })
12+
if (!authResult.success) {
13+
logger.error('Authentication failed for TTS stream proxy:', authResult.error)
14+
return new Response('Unauthorized', { status: 401 })
15+
}
16+
1017
const body = await request.json()
1118
const { text, voiceId, modelId = 'eleven_turbo_v2_5' } = body
1219

apps/sim/tools/elevenlabs/tts.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,16 @@ export const elevenLabsTtsTool: ToolConfig<ElevenLabsTtsParams, ElevenLabsTtsRes
5151
transformResponse: async (response: Response) => {
5252
const data = await response.json()
5353

54+
if (!response.ok || data.error) {
55+
return {
56+
success: false,
57+
error: data.error || 'Unknown error occurred',
58+
output: {
59+
audioUrl: '',
60+
},
61+
}
62+
}
63+
5464
return {
5565
success: true,
5666
output: {

0 commit comments

Comments
 (0)