77//! Both endpoints require NIP-98 auth (same as `/events`, `/query`, `/count`).
88
99use std:: sync:: Arc ;
10+ use std:: time:: { Duration , Instant } ;
1011
1112use axum:: {
1213 extract:: State ,
@@ -22,7 +23,9 @@ use super::api_error;
2223
2324const OPENAI_REALTIME_CLIENT_SECRETS_URL : & str =
2425 "https://api.openai.com/v1/realtime/client_secrets" ;
25- const DEFAULT_TRANSCRIPTION_MODEL : & str = "whisper-1" ;
26+
27+ /// Rate-limit window for transcription session minting.
28+ const TRANSCRIBE_RATE_WINDOW : Duration = Duration :: from_secs ( 60 ) ;
2629
2730/// Response for `GET /transcribe/status`.
2831#[ derive( Serialize ) ]
@@ -47,11 +50,11 @@ pub async fn transcribe_status(
4750 State ( state) : State < Arc < AppState > > ,
4851 headers : HeaderMap ,
4952) -> Result < Json < TranscribeStatus > , ( StatusCode , Json < Value > ) > {
50- authenticate ( & state, & headers, "/transcribe/status" , "GET" ) . await ?;
53+ let _pubkey = authenticate ( & state, & headers, "/transcribe/status" , "GET" ) . await ?;
5154
5255 Ok ( Json ( TranscribeStatus {
5356 configured : state. config . openai_api_key . is_some ( ) ,
54- model : transcription_model ( ) ,
57+ model : state . config . transcription_model . clone ( ) ,
5558 } ) )
5659}
5760
@@ -64,7 +67,18 @@ pub async fn create_transcribe_session(
6467 State ( state) : State < Arc < AppState > > ,
6568 headers : HeaderMap ,
6669) -> Result < Json < TranscribeSession > , ( StatusCode , Json < Value > ) > {
67- authenticate ( & state, & headers, "/transcribe/session" , "POST" ) . await ?;
70+ let pubkey = authenticate ( & state, & headers, "/transcribe/session" , "POST" ) . await ?;
71+
72+ // Per-pubkey rate limit — each session mints a metered OpenAI Realtime
73+ // connection on the operator's bill.
74+ if transcribe_rate_limited ( & state, & pubkey) {
75+ metrics:: counter!( "buzz_transcribe_session_rejections_total" , "reason" => "rate_limit" )
76+ . increment ( 1 ) ;
77+ return Err ( api_error (
78+ StatusCode :: TOO_MANY_REQUESTS ,
79+ "transcription session rate limit exceeded — try again shortly" ,
80+ ) ) ;
81+ }
6882
6983 let api_key = state. config . openai_api_key . as_deref ( ) . ok_or_else ( || {
7084 api_error (
@@ -73,10 +87,9 @@ pub async fn create_transcribe_session(
7387 )
7488 } ) ?;
7589
76- let model = transcription_model ( ) ;
90+ let model = state . config . transcription_model . clone ( ) ;
7791
78- let client = reqwest:: Client :: new ( ) ;
79- let response = client
92+ let response = openai_client ( )
8093 . post ( OPENAI_REALTIME_CLIENT_SECRETS_URL )
8194 . header ( "Authorization" , format ! ( "Bearer {api_key}" ) )
8295 . header ( "Content-Type" , "application/json" )
@@ -95,7 +108,6 @@ pub async fn create_transcribe_session(
95108 }
96109 }
97110 } ) )
98- . timeout ( std:: time:: Duration :: from_secs ( 10 ) )
99111 . send ( )
100112 . await
101113 . map_err ( |e| {
@@ -142,12 +154,13 @@ pub async fn create_transcribe_session(
142154
143155/// Authenticate the request using the same NIP-98 / X-Pubkey pattern as the
144156/// bridge endpoints, plus replay detection and relay membership enforcement.
157+ /// Returns the authenticated pubkey on success.
145158async fn authenticate (
146159 state : & AppState ,
147160 headers : & HeaderMap ,
148161 path : & str ,
149162 method : & str ,
150- ) -> Result < ( ) , ( StatusCode , Json < Value > ) > {
163+ ) -> Result < nostr :: PublicKey , ( StatusCode , Json < Value > ) > {
151164 let raw_host = headers
152165 . get ( "host" )
153166 . and_then ( |v| v. to_str ( ) . ok ( ) )
@@ -182,14 +195,37 @@ async fn authenticate(
182195 )
183196 . await ?;
184197
185- Ok ( ( ) )
198+ Ok ( pubkey)
199+ }
200+
201+ /// Per-pubkey sliding-window rate limiter for transcription session minting.
202+ fn transcribe_rate_limited ( state : & AppState , pubkey : & nostr:: PublicKey ) -> bool {
203+ let key: [ u8 ; 32 ] = pubkey. to_bytes ( ) ;
204+ let now = Instant :: now ( ) ;
205+ let limit = state. config . transcribe_sessions_per_minute ;
206+ let mut entry = state. transcribe_rate_limiter . entry ( key) . or_insert ( ( 0 , now) ) ;
207+ let ( count, window_start) = entry. value_mut ( ) ;
208+ if now. duration_since ( * window_start) >= TRANSCRIBE_RATE_WINDOW {
209+ * count = 1 ;
210+ * window_start = now;
211+ return false ;
212+ }
213+ if * count >= limit {
214+ return true ;
215+ }
216+ * count += 1 ;
217+ false
186218}
187219
188- fn transcription_model ( ) -> String {
189- std:: env:: var ( "BUZZ_TRANSCRIPTION_MODEL" )
190- . ok ( )
191- . filter ( |s| !s. is_empty ( ) )
192- . unwrap_or_else ( || DEFAULT_TRANSCRIPTION_MODEL . to_string ( ) )
220+ /// Shared HTTP client for OpenAI requests (connection pooling).
221+ fn openai_client ( ) -> & ' static reqwest:: Client {
222+ static CLIENT : std:: sync:: OnceLock < reqwest:: Client > = std:: sync:: OnceLock :: new ( ) ;
223+ CLIENT . get_or_init ( || {
224+ reqwest:: Client :: builder ( )
225+ . timeout ( Duration :: from_secs ( 10 ) )
226+ . build ( )
227+ . expect ( "failed to build reqwest client" )
228+ } )
193229}
194230
195231fn extract_client_secret ( value : & Value ) -> Option < String > {
0 commit comments