Skip to content

Commit aeb35c6

Browse files
vijaythecoderclaude
andcommitted
Implement proper ephemeral key generation for OpenAI Realtime API
- Replace direct API key exposure with secure ephemeral key generation - Make server-side POST request to OpenAI /v1/realtime/sessions endpoint - Return temporary ephemeral key that expires after 1-2 hours - Keep API key secure on server, never expose to frontend - Return session ID and expiration timestamp with ephemeral key This follows OpenAI's security best practices for client-side applications Co-Authored-By: Claude <[email protected]>
1 parent 3793306 commit aeb35c6

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

app/Http/Controllers/RealtimeController.php

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use App\Services\ApiKeyService;
66
use Illuminate\Http\Request;
7+
use Illuminate\Support\Facades\Http;
78
use Illuminate\Support\Facades\Log;
89

910
class RealtimeController extends Controller
@@ -30,13 +31,29 @@ public function generateEphemeralKey(Request $request)
3031
], 422);
3132
}
3233

33-
// Return the actual API key for now
34-
// OpenAI Realtime API uses the API key directly in WebSocket connection
34+
// Generate ephemeral key from OpenAI Realtime API
35+
$response = Http::withHeaders([
36+
'Authorization' => 'Bearer ' . $apiKey,
37+
'Content-Type' => 'application/json',
38+
])->post('https://api.openai.com/v1/realtime/sessions', [
39+
'model' => 'gpt-4o-realtime-preview-2024-12-17',
40+
'voice' => $request->input('voice', 'alloy'),
41+
]);
42+
43+
if (!$response->successful()) {
44+
Log::error('OpenAI API error: ' . $response->body());
45+
throw new \Exception('Failed to generate ephemeral key from OpenAI: ' . $response->status());
46+
}
47+
48+
$data = $response->json();
49+
50+
// Return ephemeral key data
3551
return response()->json([
3652
'status' => 'success',
37-
'ephemeralKey' => $apiKey, // Use actual API key
38-
'expiresAt' => now()->addMinutes(60)->toIso8601String(),
39-
'model' => 'gpt-4o-realtime-preview-2024-12-17',
53+
'ephemeralKey' => $data['client_secret']['value'],
54+
'expiresAt' => $data['client_secret']['expires_at'],
55+
'sessionId' => $data['id'],
56+
'model' => $data['model'],
4057
]);
4158

4259
} catch (\Exception $e) {

0 commit comments

Comments
 (0)