Skip to content

Commit 8c9211f

Browse files
authored
Add relay disconnect UX: friendly errors, reconnect, cached identity (#1004)
1 parent 7983bf6 commit 8c9211f

23 files changed

Lines changed: 1553 additions & 51 deletions

‎desktop/playwright.config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ export default defineConfig({
3939
"**/workflows.spec.ts",
4040
"**/identity-archive.spec.ts",
4141
"**/identity-archive-hide.spec.ts",
42+
"**/relay-connectivity-screenshots.spec.ts",
4243
],
4344
use: {
4445
...devices["Desktop Chrome"],

‎desktop/src-tauri/src/commands/media.rs‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@ use sha2::{Digest, Sha256};
55
use tauri::State;
66

77
use crate::app_state::AppState;
8-
use crate::relay::relay_api_base_url_with_override;
8+
use crate::relay::{
9+
classify_request_error, parse_json_response, relay_api_base_url_with_override,
10+
relay_error_message,
11+
};
912

1013
use super::media_transcode::{is_video_file, transcode_and_extract_poster};
1114

@@ -246,17 +249,13 @@ async fn do_upload(
246249
} else {
247250
req.body(body).send().await
248251
}
249-
.map_err(|e| format!("upload failed: {e}"))?;
252+
.map_err(|e| classify_request_error(&e))?;
250253

251254
if !resp.status().is_success() {
252-
let status = resp.status();
253-
let text = resp.text().await.unwrap_or_default();
254-
return Err(format!("upload failed ({status}): {text}"));
255+
return Err(relay_error_message(resp).await);
255256
}
256257

257-
resp.json::<BlobDescriptor>()
258-
.await
259-
.map_err(|e| format!("parse failed: {e}"))
258+
parse_json_response::<BlobDescriptor>(resp).await
260259
}
261260

262261
// ── Commands ─────────────────────────────────────────────────────────────────

‎desktop/src-tauri/src/commands/media_download.rs‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use tauri::State;
33

44
use crate::app_state::AppState;
55
use crate::commands::export_util::save_bytes_with_dialog;
6-
use crate::relay::relay_api_base_url_with_override;
6+
use crate::relay::{classify_request_error, relay_api_base_url_with_override, relay_error_message};
77

88
use super::media::{detect_and_validate_mime, sanitize_filename};
99

@@ -140,12 +140,10 @@ async fn fetch_blob_bytes(url: &str, state: &State<'_, AppState>) -> Result<Vec<
140140
.timeout(DOWNLOAD_TIMEOUT)
141141
.send()
142142
.await
143-
.map_err(|e| format!("download failed: {e}"))?;
143+
.map_err(|e| classify_request_error(&e))?;
144144

145145
if !resp.status().is_success() {
146-
let status = resp.status();
147-
let text = resp.text().await.unwrap_or_default();
148-
return Err(format!("download failed ({status}): {text}"));
146+
return Err(relay_error_message(resp).await);
149147
}
150148

151149
// Check Content-Length header upfront if present.
@@ -164,7 +162,7 @@ async fn fetch_blob_bytes(url: &str, state: &State<'_, AppState>) -> Result<Vec<
164162
let mut bytes = Vec::new();
165163
let mut stream = resp.bytes_stream();
166164
while let Some(chunk) = stream.next().await {
167-
let chunk = chunk.map_err(|e| format!("download stream error: {e}"))?;
165+
let chunk = chunk.map_err(|e| classify_request_error(&e))?;
168166
if bytes.len() as u64 + chunk.len() as u64 > MAX_DOWNLOAD_BYTES {
169167
return Err(format!(
170168
"file too large (max {} MiB)",

‎desktop/src-tauri/src/relay.rs‎

Lines changed: 170 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
126207
pub 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)]
453541
mod 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)]

‎desktop/src/app/AppShell.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ import { useWorkspaces } from "@/features/workspaces/useWorkspaces";
6666
import { useApplyTemplate } from "@/features/channel-templates/useApplyTemplate";
6767
import { relayClient } from "@/shared/api/relayClient";
6868
import { useIdentityQuery } from "@/shared/api/hooks";
69+
import { useRelayAutoHeal } from "@/shared/api/useRelayAutoHeal";
6970
import { useDeferredStartup } from "@/shared/hooks/useDeferredStartup";
7071
import { joinChannel } from "@/shared/api/tauri";
7172
import type { Channel, RelayEvent, SearchHit } from "@/shared/api/types";
@@ -74,6 +75,7 @@ import { MainInsetProvider } from "@/shared/layout/MainInsetContext";
7475
import { chromeCssVarDefaults } from "@/shared/layout/chromeLayout";
7576
import { hasPrimaryShortcutModifier } from "@/shared/lib/platform";
7677
import { useMessageDeepLinks } from "@/shared/useMessageDeepLinks";
78+
import { ConnectionBanner } from "@/shared/ui/ConnectionBanner";
7779
import { SidebarInset, SidebarProvider } from "@/shared/ui/sidebar";
7880

7981
type AppView =
@@ -218,6 +220,7 @@ export function AppShell() {
218220
);
219221
const profileQuery = useProfileQuery();
220222
const deferredPubkey = startupReady ? identityQuery.data?.pubkey : undefined;
223+
useRelayAutoHeal();
221224
usePresenceSubscription();
222225
useUserStatusSubscription();
223226
useWorkspaceEmojiLiveUpdates();
@@ -938,6 +941,7 @@ export function AppShell() {
938941
className="min-h-0 min-w-0 overflow-hidden"
939942
style={chromeCssVarDefaults}
940943
>
944+
<ConnectionBanner />
941945
<Outlet />
942946
</SidebarInset>
943947
</MainInsetProvider>

‎desktop/src/features/channels/ui/ChannelCanvas.tsx‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ import { useChannelNavigation } from "@/shared/context/ChannelNavigationContext"
99
import { Button } from "@/shared/ui/button";
1010
import { Markdown } from "@/shared/ui/markdown";
1111
import { Textarea } from "@/shared/ui/textarea";
12+
import {
13+
isRelayUnreachableError,
14+
RELAY_UNREACHABLE_SHORT,
15+
} from "@/shared/lib/relayError";
1216

1317
type ChannelCanvasProps = {
1418
channelId: string | null;
@@ -55,7 +59,9 @@ export function ChannelCanvas({
5559
if (canvasQuery.error instanceof Error) {
5660
return (
5761
<p className="rounded-xl border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
58-
{canvasQuery.error.message}
62+
{isRelayUnreachableError(canvasQuery.error)
63+
? RELAY_UNREACHABLE_SHORT
64+
: canvasQuery.error.message}
5965
</p>
6066
);
6167
}

0 commit comments

Comments
 (0)