@@ -231,6 +231,17 @@ pub(crate) async fn parse_json_response<T: DeserializeOwned>(
231231 . map_err ( |_| MALFORMED_RESPONSE_MESSAGE . to_string ( ) )
232232}
233233
234+ /// Extract the `retry in Ns` hint from a rate-limit error string.
235+ ///
236+ /// Matches the canonical format emitted by the relay in both HTTP 429 bodies
237+ /// and CLOSED/NOTICE messages: `quota exceeded; retry in 4s`.
238+ fn extract_retry_in_hint ( body : & str ) -> Option < u64 > {
239+ let re_match = body. find ( "retry in " ) ?;
240+ let after = & body[ re_match + "retry in " . len ( ) ..] ;
241+ let digits: String = after. chars ( ) . take_while ( |c| c. is_ascii_digit ( ) ) . collect ( ) ;
242+ digits. parse :: < u64 > ( ) . ok ( )
243+ }
244+
234245pub async fn relay_error_message ( response : reqwest:: Response ) -> String {
235246 let status = response. status ( ) ;
236247
@@ -250,6 +261,27 @@ pub async fn relay_error_message(response: reqwest::Response) -> String {
250261 // Real relay error: extract the structured message field if available.
251262 let body = response. text ( ) . await . unwrap_or_default ( ) ;
252263
264+ // 429 Too Many Requests → typed `relay rate-limited:` prefix so the TS
265+ // client can activate the rate-limit gate without confusing it with a
266+ // connectivity failure (`relay unreachable:`). Also arm the Rust-side
267+ // admission gate here — the one place every relay HTTP error funnels
268+ // through — so the next relay-backed command waits out the quota window
269+ // instead of burning it (see `relay_admission`).
270+ if status == reqwest:: StatusCode :: TOO_MANY_REQUESTS {
271+ let hint = extract_retry_in_hint ( & body) ;
272+ // Clamp the hint to MAX_HINT_SECONDS before arming the Rust gate AND
273+ // before embedding it in the returned string. Every consumer (Rust gate
274+ // via `activate_rate_limit` and TS gate via `applyTauriRateLimitIfNeeded`)
275+ // must see the same capped value — a single policy point prevents the TS
276+ // gate from receiving an uncapped hint from an untrusted relay.
277+ let capped_hint = hint. map ( |s| s. min ( crate :: relay_admission:: MAX_HINT_SECONDS ) ) ;
278+ crate :: relay_admission:: activate_rate_limit ( capped_hint) ;
279+ if let Some ( secs) = capped_hint {
280+ return format ! ( "relay rate-limited: retry in {secs}s" ) ;
281+ }
282+ return "relay rate-limited: quota exceeded" . to_string ( ) ;
283+ }
284+
253285 if let Ok ( value) = serde_json:: from_str :: < serde_json:: Value > ( & body) {
254286 if let Some ( message) = value. get ( "message" ) . and_then ( serde_json:: Value :: as_str) {
255287 return format ! ( "relay returned {status}: {message}" ) ;
@@ -286,6 +318,7 @@ pub async fn query_relay_at(
286318 api_base_url : & str ,
287319 filters : & [ serde_json:: Value ] ,
288320) -> Result < Vec < nostr:: Event > , String > {
321+ crate :: relay_admission:: wait_for_rate_limit ( ) . await ;
289322 let url = format ! ( "{}/query" , api_base_url) ;
290323 let body_bytes =
291324 serde_json:: to_vec ( filters) . map_err ( |e| format ! ( "filter serialization failed: {e}" ) ) ?;
@@ -382,6 +415,7 @@ pub async fn sync_managed_agent_profile(
382415 avatar_url : Option < & str > ,
383416 auth_tag : Option < & str > , // NIP-OA auth tag JSON
384417) -> Result < ( ) , String > {
418+ crate :: relay_admission:: wait_for_rate_limit ( ) . await ;
385419 // Build a signed kind:0 profile event (with optional NIP-OA auth tag).
386420 let event = build_profile_event ( agent_keys, display_name, avatar_url, auth_tag) ?;
387421 let event_json = event. as_json ( ) ;
@@ -482,6 +516,7 @@ pub async fn submit_event(
482516 builder : nostr:: EventBuilder ,
483517 state : & AppState ,
484518) -> Result < SubmitEventResponse , String > {
519+ crate :: relay_admission:: wait_for_rate_limit ( ) . await ;
485520 // All synchronous work (signing) must complete before any .await
486521 // so the MutexGuard is dropped and the future remains Send.
487522 let url = format ! ( "{}/events" , relay_api_base_url_with_override( state) ) ;
@@ -529,6 +564,7 @@ pub async fn submit_signed_event(
529564 event : & nostr:: Event ,
530565 state : & AppState ,
531566) -> Result < SubmitEventResponse , String > {
567+ crate :: relay_admission:: wait_for_rate_limit ( ) . await ;
532568 let url = format ! ( "{}/events" , relay_api_base_url_with_override( state) ) ;
533569 let body_bytes = event. as_json ( ) . into_bytes ( ) ;
534570 let auth_header = {
@@ -586,6 +622,7 @@ pub async fn submit_signed_event_with_keys(
586622 if event. pubkey != keys. public_key ( ) {
587623 return Err ( "signed event does not match the publishing identity" . to_string ( ) ) ;
588624 }
625+ crate :: relay_admission:: wait_for_rate_limit ( ) . await ;
589626 let url = format ! ( "{}/events" , relay_api_base_url_with_override( state) ) ;
590627 let body_bytes = event. as_json ( ) . into_bytes ( ) ;
591628 let auth_header = build_nip98_auth_header_for_keys ( keys, & Method :: POST , & url, & body_bytes) ?;
@@ -624,10 +661,106 @@ pub async fn submit_signed_event_with_keys(
624661mod tests {
625662 use super :: {
626663 build_profile_event, classify_intercepted_response, effective_agent_relay_url,
627- parse_command_response, relay_http_base_url, MALFORMED_RESPONSE_MESSAGE ,
664+ extract_retry_in_hint, parse_command_response, relay_http_base_url,
665+ MALFORMED_RESPONSE_MESSAGE ,
628666 } ;
629667 use serde:: Deserialize ;
630668
669+ // ── extract_retry_in_hint ────────────────────────────────────────────────
670+
671+ #[ test]
672+ fn extracts_hint_from_429_body ( ) {
673+ assert_eq ! (
674+ extract_retry_in_hint( r#"{"error":"rate-limited: quota exceeded; retry in 4s"}"# ) ,
675+ Some ( 4 )
676+ ) ;
677+ }
678+
679+ #[ test]
680+ fn extracts_hint_when_no_json_wrapper ( ) {
681+ assert_eq ! ( extract_retry_in_hint( "retry in 30s" ) , Some ( 30 ) ) ;
682+ }
683+
684+ #[ test]
685+ fn returns_none_when_no_hint_present ( ) {
686+ assert_eq ! (
687+ extract_retry_in_hint( r#"{"error":"rate-limited: quota exceeded"}"# ) ,
688+ None
689+ ) ;
690+ assert_eq ! ( extract_retry_in_hint( "" ) , None ) ;
691+ }
692+
693+ #[ test]
694+ fn overlong_digit_string_returns_none ( ) {
695+ // A digit sequence that exceeds u64::MAX cannot be parsed; the function
696+ // must return None (→ caller uses the default) rather than panicking.
697+ assert_eq ! (
698+ extract_retry_in_hint( "retry in 99999999999999999999999s" ) ,
699+ None
700+ ) ;
701+ }
702+
703+ // ── relay_error_message: hint capping ────────────────────────────────────
704+ //
705+ // Verify that an oversized relay hint is capped in the returned message
706+ // string, not just inside `activate_rate_limit()`. This guarantees every
707+ // consumer — including the TS gate via `applyTauriRateLimitIfNeeded` —
708+ // receives the capped value rather than the raw untrusted relay value.
709+
710+ #[ tokio:: test]
711+ async fn oversized_hint_is_capped_in_relay_error_message_string ( ) {
712+ use crate :: relay_admission:: MAX_HINT_SECONDS ;
713+ use std:: io:: { Read as _, Write as _} ;
714+
715+ // Use a std::net listener on a std::thread — the same pattern as the
716+ // relay_admission loopback tests. This avoids two races that cause CI
717+ // failures with tokio::net + into_std():
718+ // 1. No request read: the client is still sending when the response
719+ // arrives → hyper `UnexpectedMessage`/`Canceled` under load.
720+ // 2. into_std() leaves the socket in nonblocking mode → write_all
721+ // may return WouldBlock and silently drop the response.
722+ let listener = std:: net:: TcpListener :: bind ( "127.0.0.1:0" ) . unwrap ( ) ;
723+ let addr = listener. local_addr ( ) . unwrap ( ) ;
724+
725+ // Serve a 429 with a hint far exceeding MAX_HINT_SECONDS (300).
726+ let oversized = 1_000_000u64 ;
727+ let body = format ! ( r#"{{"error":"rate-limited: quota exceeded; retry in {oversized}s"}}"# ) ;
728+ let body_len = body. len ( ) ;
729+ std:: thread:: spawn ( move || {
730+ if let Ok ( ( mut stream, _) ) = listener. accept ( ) {
731+ // Read the request first so the client finishes sending before
732+ // we write the response — mirrors relay_admission.rs pattern.
733+ let mut buf = [ 0u8 ; 4096 ] ;
734+ let _ = stream. read ( & mut buf) ;
735+ let response = format ! (
736+ "HTTP/1.1 429 Too Many Requests\r \n Content-Type: application/json\r \n Content-Length: {body_len}\r \n Connection: close\r \n \r \n {body}"
737+ ) ;
738+ let _ = stream. write_all ( response. as_bytes ( ) ) ;
739+ let _ = stream. flush ( ) ;
740+ }
741+ } ) ;
742+
743+ let client = reqwest:: Client :: new ( ) ;
744+ let response = client
745+ . get ( format ! ( "http://{addr}/" ) )
746+ . send ( )
747+ . await
748+ . expect ( "request must succeed" ) ;
749+
750+ let msg = super :: relay_error_message ( response) . await ;
751+
752+ // The message must embed the CAPPED hint, not the raw 1 000 000.
753+ assert_eq ! (
754+ msg,
755+ format!( "relay rate-limited: retry in {MAX_HINT_SECONDS}s" ) ,
756+ "relay_error_message must embed the capped hint, not the raw untrusted value"
757+ ) ;
758+ assert ! (
759+ !msg. contains( & oversized. to_string( ) ) ,
760+ "raw oversized hint must not appear in the message string"
761+ ) ;
762+ }
763+
631764 // ── effective_agent_relay_url: per-agent override precedence ─────────────
632765
633766 #[ test]
0 commit comments