@@ -123,8 +123,104 @@ pub fn build_nip98_auth_header_for_keys(
123123
124124// ── Error handling ──────────────────────────────────────────────────────────
125125
126+ /// Classify a `send()` failure into a stable, URL-free error string.
127+ ///
128+ /// The returned string always starts with `"relay unreachable:"` so the
129+ /// frontend connectivity classifier can detect it with a simple prefix check.
130+ pub ( crate ) fn classify_request_error ( e : & reqwest:: Error ) -> String {
131+ let display = e. to_string ( ) . to_lowercase ( ) ;
132+ if e. is_timeout ( ) {
133+ "relay unreachable: request timed out" . to_string ( )
134+ } else if e. is_connect ( ) {
135+ "relay unreachable: could not connect to relay" . to_string ( )
136+ } else if display. contains ( "dns" ) || display. contains ( "failed to lookup" ) {
137+ "relay unreachable: relay host not found" . to_string ( )
138+ } else {
139+ "relay unreachable: network error" . to_string ( )
140+ }
141+ }
142+
143+ /// Detect responses that were intercepted by a captive portal or auth proxy.
144+ ///
145+ /// Returns `Some(msg)` when the response clearly did not come from the relay:
146+ /// - Cloudflare Access redirect (final URL on `*.cloudflareaccess.com`)
147+ /// - Any other HTML response (proxy login page, captive portal, etc.)
148+ ///
149+ /// Pure function: takes the already-extracted host and content-type strings so
150+ /// it can be unit-tested without constructing a real `reqwest::Response`.
151+ fn classify_intercepted_response ( final_host : & str , content_type : & str ) -> Option < String > {
152+ let host = final_host. to_lowercase ( ) ;
153+ let ct = content_type. to_lowercase ( ) ;
154+
155+ // Cloudflare Access intercepts requests and redirects to its own domain.
156+ // Label-boundary check prevents `notcloudflareaccess.com.evil.example` from
157+ // matching.
158+ if host == "cloudflareaccess.com" || host. ends_with ( ".cloudflareaccess.com" ) {
159+ return Some (
160+ "relay unreachable: network sign-in required (Cloudflare Access / VPN) \
161+ — re-authenticate and reconnect"
162+ . to_string ( ) ,
163+ ) ;
164+ }
165+
166+ // Generic HTML body from any other proxy or captive portal.
167+ if ct. contains ( "text/html" ) {
168+ return Some (
169+ "relay unreachable: relay returned an unexpected HTML page \
170+ (VPN or proxy sign-in?)"
171+ . to_string ( ) ,
172+ ) ;
173+ }
174+
175+ None
176+ }
177+
178+ /// Deserialize a successful response as JSON, guarding against intercepted pages.
179+ ///
180+ /// Extracts the final URL host and `Content-Type` header before consuming the
181+ /// response body. If the response looks like a captive-portal page, returns the
182+ /// appropriate `"relay unreachable:"` message instead of attempting JSON parsing.
183+ /// URL details are deliberately omitted from error strings so raw URLs are never
184+ /// surfaced in the UI.
185+ pub ( crate ) async fn parse_json_response < T : DeserializeOwned > (
186+ response : reqwest:: Response ,
187+ ) -> Result < T , String > {
188+ let final_host = response. url ( ) . host_str ( ) . unwrap_or ( "" ) . to_string ( ) ;
189+ let content_type = response
190+ . headers ( )
191+ . get ( reqwest:: header:: CONTENT_TYPE )
192+ . and_then ( |v| v. to_str ( ) . ok ( ) )
193+ . unwrap_or ( "" )
194+ . to_string ( ) ;
195+
196+ if let Some ( msg) = classify_intercepted_response ( & final_host, & content_type) {
197+ return Err ( msg) ;
198+ }
199+
200+ // Drop the reqwest error detail — it contains the raw URL.
201+ response
202+ . json :: < T > ( )
203+ . await
204+ . map_err ( |_| "relay unreachable: response was not valid JSON" . to_string ( ) )
205+ }
206+
126207pub async fn relay_error_message ( response : reqwest:: Response ) -> String {
127208 let status = response. status ( ) ;
209+
210+ // Check for intercepted/proxy responses before reading the body.
211+ let final_host = response. url ( ) . host_str ( ) . unwrap_or ( "" ) . to_string ( ) ;
212+ let content_type = response
213+ . headers ( )
214+ . get ( reqwest:: header:: CONTENT_TYPE )
215+ . and_then ( |v| v. to_str ( ) . ok ( ) )
216+ . unwrap_or ( "" )
217+ . to_string ( ) ;
218+
219+ if let Some ( msg) = classify_intercepted_response ( & final_host, & content_type) {
220+ return msg;
221+ }
222+
223+ // Real relay error: extract the structured message field if available.
128224 let body = response. text ( ) . await . unwrap_or_default ( ) ;
129225
130226 if let Ok ( value) = serde_json:: from_str :: < serde_json:: Value > ( & body) {
@@ -137,7 +233,8 @@ pub async fn relay_error_message(response: reqwest::Response) -> String {
137233 }
138234 }
139235
140- format ! ( "relay returned {status}: {body}" )
236+ // Non-JSON, non-HTML body: emit status only — no raw body in the UI.
237+ format ! ( "relay returned {status}" )
141238}
142239
143240// ── HTTP bridge: POST /query ────────────────────────────────────────────────
@@ -175,16 +272,13 @@ pub async fn query_relay_at(
175272 . body ( body_bytes)
176273 . send ( )
177274 . await
178- . map_err ( |e| format ! ( "request failed: {e}" ) ) ?;
275+ . map_err ( |e| classify_request_error ( & e ) ) ?;
179276
180277 if !response. status ( ) . is_success ( ) {
181278 return Err ( relay_error_message ( response) . await ) ;
182279 }
183280
184- response
185- . json :: < Vec < nostr:: Event > > ( )
186- . await
187- . map_err ( |e| format ! ( "failed to parse query response: {e}" ) )
281+ parse_json_response ( response) . await
188282}
189283
190284// ── Command response parsing ────────────────────────────────────────────────
@@ -281,7 +375,7 @@ pub async fn sync_managed_agent_profile(
281375 . body ( body_bytes)
282376 . send ( )
283377 . await
284- . map_err ( |e| format ! ( "request failed: {e}" ) ) ?;
378+ . map_err ( |e| classify_request_error ( & e ) ) ?;
285379
286380 if !response. status ( ) . is_success ( ) {
287381 let msg = relay_error_message ( response) . await ;
@@ -380,16 +474,13 @@ pub async fn submit_event(
380474 . body ( body_bytes)
381475 . send ( )
382476 . await
383- . map_err ( |e| format ! ( "request failed: {e}" ) ) ?;
477+ . map_err ( |e| classify_request_error ( & e ) ) ?;
384478
385479 if !response. status ( ) . is_success ( ) {
386480 return Err ( relay_error_message ( response) . await ) ;
387481 }
388482
389- let result: SubmitEventResponse = response
390- . json ( )
391- . await
392- . map_err ( |e| format ! ( "failed to parse response: {e}" ) ) ?;
483+ let result: SubmitEventResponse = parse_json_response ( response) . await ?;
393484
394485 if !result. accepted {
395486 return Err ( format ! ( "relay rejected event: {}" , result. message) ) ;
@@ -429,16 +520,13 @@ pub async fn submit_event_with_keys(
429520 . body ( body_bytes)
430521 . send ( )
431522 . await
432- . map_err ( |e| format ! ( "request failed: {e}" ) ) ?;
523+ . map_err ( |e| classify_request_error ( & e ) ) ?;
433524
434525 if !response. status ( ) . is_success ( ) {
435526 return Err ( relay_error_message ( response) . await ) ;
436527 }
437528
438- let result: SubmitEventResponse = response
439- . json ( )
440- . await
441- . map_err ( |e| format ! ( "failed to parse response: {e}" ) ) ?;
529+ let result: SubmitEventResponse = parse_json_response ( response) . await ?;
442530
443531 if !result. accepted {
444532 return Err ( format ! ( "relay rejected event: {}" , result. message) ) ;
@@ -451,9 +539,73 @@ pub async fn submit_event_with_keys(
451539
452540#[ cfg( test) ]
453541mod tests {
454- use super :: { build_profile_event, parse_command_response} ;
542+ use super :: { build_profile_event, classify_intercepted_response , parse_command_response} ;
455543 use serde:: Deserialize ;
456544
545+ // ── classify_intercepted_response ────────────────────────────────────────
546+
547+ #[ test]
548+ fn intercepted_cloudflare_host_returns_some ( ) {
549+ let result = classify_intercepted_response ( "sqprod.cloudflareaccess.com" , "text/html" ) ;
550+ assert ! ( result. is_some( ) ) ;
551+ let msg = result. unwrap ( ) ;
552+ assert ! (
553+ msg. starts_with( "relay unreachable:" ) ,
554+ "should have unreachable prefix"
555+ ) ;
556+ assert ! ( msg. contains( "Cloudflare" ) , "should mention Cloudflare" ) ;
557+ }
558+
559+ #[ test]
560+ fn intercepted_cloudflare_apex_host_returns_some ( ) {
561+ // The apex domain itself should also match.
562+ let result = classify_intercepted_response ( "cloudflareaccess.com" , "application/json" ) ;
563+ assert ! ( result. is_some( ) ) ;
564+ let msg = result. unwrap ( ) ;
565+ assert ! ( msg. starts_with( "relay unreachable:" ) ) ;
566+ assert ! ( msg. contains( "Cloudflare" ) ) ;
567+ }
568+
569+ #[ test]
570+ fn intercepted_non_cloudflare_html_returns_some ( ) {
571+ let result =
572+ classify_intercepted_response ( "proxy.corporate.example" , "text/html; charset=utf-8" ) ;
573+ assert ! ( result. is_some( ) ) ;
574+ let msg = result. unwrap ( ) ;
575+ assert ! ( msg. starts_with( "relay unreachable:" ) ) ;
576+ }
577+
578+ #[ test]
579+ fn normal_relay_json_returns_none ( ) {
580+ let result = classify_intercepted_response ( "relay.myapp.example.com" , "application/json" ) ;
581+ assert ! ( result. is_none( ) ) ;
582+ }
583+
584+ #[ test]
585+ fn content_type_case_insensitive ( ) {
586+ // Uppercase content-type must still be detected.
587+ let result = classify_intercepted_response ( "proxy.example.com" , "TEXT/HTML" ) ;
588+ assert ! ( result. is_some( ) ) ;
589+ assert ! ( result. unwrap( ) . starts_with( "relay unreachable:" ) ) ;
590+ }
591+
592+ #[ test]
593+ fn evil_suffix_does_not_match_cloudflare ( ) {
594+ // A host whose suffix happens to contain the Cloudflare string but is
595+ // not actually a subdomain must NOT match.
596+ let result = classify_intercepted_response (
597+ "notcloudflareaccess.com.evil.example" ,
598+ "application/json" ,
599+ ) ;
600+ assert ! (
601+ result. is_none( ) ,
602+ "false suffix match should not trigger Cloudflare branch"
603+ ) ;
604+ }
605+
606+ // classify_request_error requires a real reqwest::Error (not publicly
607+ // constructable) — tested indirectly through integration; skipped here.
608+
457609 // ── parse_command_response ───────────────────────────────────────────────
458610
459611 #[ derive( Debug , Deserialize , PartialEq ) ]
0 commit comments