Skip to content

Commit 9d4c1db

Browse files
fix(desktop): fetch join policies through native networking (#2862)
## Context Adding an existing community by relay URL could fail with `Community rejected: Load failed` even when its WebSocket endpoint was reachable. The Add Community flow fetched `/api/join-policy` from the WebView, so a relay without a matching CORS allowance blocked the policy request before the app could join it. ## Summary This bug fix fetches join policies through Tauri's native networking layer for direct URL joins. Invite-code discovery, policy acceptance, and signed invite claims remain on the WebView path so those operations can migrate together later. ## Changes - Uses native networking for Add Community and first-community direct URL join-policy requests. - Validates relay schemes, rejects URLs containing credentials, and refuses redirects. - Bounds declared and chunked native responses before JSON parsing. - Preserves existing `404`, non-success status, malformed JSON, and absent-policy behavior. - Requires every join-policy caller to choose its transport explicitly. Public relays using Buzz's default permissive CORS configuration are not known to be affected. ### Related issue Related to #2872. ### Testing #### Reviewer-reproducible examples End-to-end red/green requires a relay with restrictive CORS and a Buzz identity authorized to join it. ##### Red: `main` From a clean checkout of `main`: ```bash . ./bin/activate-hermit just staging ``` In Buzz Desktop: 1. Add another community so the restrictive-CORS relay can be removed. 2. Remove that relay. 3. Open Add Community and enter the relay's WebSocket URL. 4. Select Add Community. Observed result: ```text Community rejected: Load failed ``` ##### Green: this PR From a clean checkout of this branch: ```bash . ./bin/activate-hermit just staging ``` Repeat the same steps above. Observed result: ```text The community rejoins successfully. ``` Supporting checks: - Six native join-policy tests, including oversized declared and chunked responses. - Four TypeScript API tests, including the native command contract. - E2E build and four focused onboarding and sidebar Playwright tests. - Full `just ci` and pre-push suites. - Builderbot, Kalvin, and minimize-diff review fanout found no actionable issues after the final rebase.
1 parent 0b3ff0c commit 9d4c1db

11 files changed

Lines changed: 292 additions & 62 deletions

File tree

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
use futures_util::StreamExt;
2+
use serde_json::Value;
3+
use std::time::Duration;
4+
use url::Url;
5+
6+
// Each relay policy document is capped at 256 KiB before JSON encoding. Four
7+
// MiB covers two maximally escaped documents plus the response envelope.
8+
const MAX_JOIN_POLICY_RESPONSE_BYTES: usize = 4 * 1024 * 1024;
9+
const JOIN_POLICY_REQUEST_TIMEOUT: Duration = Duration::from_secs(15);
10+
11+
fn join_policy_url(relay_url: &str) -> Result<Url, String> {
12+
let mut url = Url::parse(relay_url.trim()).map_err(|_| "invalid relay URL".to_string())?;
13+
let http_scheme = match url.scheme() {
14+
"wss" => "https",
15+
"ws" => "http",
16+
_ => return Err("relay URL must use ws:// or wss://".to_string()),
17+
};
18+
url.set_scheme(http_scheme)
19+
.map_err(|_| "invalid relay URL scheme".to_string())?;
20+
21+
if !url.username().is_empty() || url.password().is_some() {
22+
return Err("relay URL must not contain credentials".to_string());
23+
}
24+
25+
let base_path = url.path().trim_end_matches('/');
26+
url.set_path(&format!("{base_path}/api/join-policy"));
27+
url.set_query(None);
28+
url.set_fragment(None);
29+
Ok(url)
30+
}
31+
32+
/// Fetch an arbitrary relay's optional join policy through native networking.
33+
#[tauri::command]
34+
pub async fn fetch_join_policy(relay_url: String) -> Result<Option<Value>, String> {
35+
let url = join_policy_url(&relay_url)?;
36+
let client = reqwest::Client::builder()
37+
.redirect(reqwest::redirect::Policy::none())
38+
.build()
39+
.map_err(|error| format!("failed to build join policy client: {error}"))?;
40+
let response = client
41+
.get(url)
42+
.timeout(JOIN_POLICY_REQUEST_TIMEOUT)
43+
.send()
44+
.await
45+
.map_err(|error| format!("join policy request failed: {error}"))?;
46+
47+
if response.status() == reqwest::StatusCode::NOT_FOUND {
48+
return Ok(None);
49+
}
50+
if !response.status().is_success() {
51+
return Err(format!("HTTP {}", response.status().as_u16()));
52+
}
53+
54+
let body = read_join_policy_json(response).await?;
55+
Ok(body
56+
.get("policy")
57+
.filter(|policy| !policy.is_null())
58+
.cloned())
59+
}
60+
61+
async fn read_join_policy_json(response: reqwest::Response) -> Result<Value, String> {
62+
if response
63+
.content_length()
64+
.is_some_and(|length| length > MAX_JOIN_POLICY_RESPONSE_BYTES as u64)
65+
{
66+
return Err("relay returned oversized join policy".to_string());
67+
}
68+
69+
let mut stream = response.bytes_stream();
70+
let mut bytes = Vec::new();
71+
while let Some(chunk) = stream.next().await {
72+
let chunk = chunk.map_err(|error| format!("reading join policy failed: {error}"))?;
73+
if bytes.len().saturating_add(chunk.len()) > MAX_JOIN_POLICY_RESPONSE_BYTES {
74+
return Err("relay returned oversized join policy".to_string());
75+
}
76+
bytes.extend_from_slice(&chunk);
77+
}
78+
79+
serde_json::from_slice(&bytes).map_err(|_| "relay returned malformed join policy".to_string())
80+
}
81+
82+
#[cfg(test)]
83+
mod tests {
84+
use super::*;
85+
use axum::{
86+
body::{Body, Bytes},
87+
http::Response,
88+
response::Redirect,
89+
routing::get,
90+
Json, Router,
91+
};
92+
use std::convert::Infallible;
93+
94+
async fn test_relay(router: Router) -> String {
95+
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
96+
let address = listener.local_addr().unwrap();
97+
tokio::spawn(async move {
98+
axum::serve(listener, router).await.unwrap();
99+
});
100+
format!("ws://{address}")
101+
}
102+
103+
#[test]
104+
fn converts_relay_urls_to_join_policy_urls() {
105+
assert_eq!(
106+
join_policy_url("wss://relay.example.com/")
107+
.unwrap()
108+
.as_str(),
109+
"https://relay.example.com/api/join-policy"
110+
);
111+
assert_eq!(
112+
join_policy_url("ws://localhost:3000/base")
113+
.unwrap()
114+
.as_str(),
115+
"http://localhost:3000/base/api/join-policy"
116+
);
117+
}
118+
119+
#[test]
120+
fn rejects_non_relay_schemes_and_credentials() {
121+
assert!(join_policy_url("https://relay.example.com").is_err());
122+
assert!(join_policy_url("wss://user:[email protected]").is_err());
123+
}
124+
125+
#[tokio::test]
126+
async fn reads_an_optional_policy_without_webview_cors() {
127+
let relay_url = test_relay(Router::new().route(
128+
"/api/join-policy",
129+
get(|| async {
130+
Json(serde_json::json!({
131+
"policy": {
132+
"terms_markdown": "# Terms",
133+
"age_attestation_required": true,
134+
"version": "v1"
135+
}
136+
}))
137+
}),
138+
))
139+
.await;
140+
141+
let policy = fetch_join_policy(relay_url).await.unwrap().unwrap();
142+
assert_eq!(policy["version"], "v1");
143+
assert_eq!(policy["age_attestation_required"], true);
144+
}
145+
146+
#[tokio::test]
147+
async fn refuses_join_policy_redirects() {
148+
let relay_url = test_relay(Router::new().route(
149+
"/api/join-policy",
150+
get(|| async { Redirect::temporary("http://127.0.0.1:1/private") }),
151+
))
152+
.await;
153+
154+
assert_eq!(fetch_join_policy(relay_url).await.unwrap_err(), "HTTP 307");
155+
}
156+
157+
#[tokio::test]
158+
async fn rejects_declared_oversized_join_policy() {
159+
let relay_url = test_relay(Router::new().route(
160+
"/api/join-policy",
161+
get(|| async {
162+
Response::builder()
163+
.body(Body::from(vec![b'x'; MAX_JOIN_POLICY_RESPONSE_BYTES + 1]))
164+
.unwrap()
165+
}),
166+
))
167+
.await;
168+
169+
assert_eq!(
170+
fetch_join_policy(relay_url).await.unwrap_err(),
171+
"relay returned oversized join policy"
172+
);
173+
}
174+
175+
#[tokio::test]
176+
async fn rejects_chunked_oversized_join_policy() {
177+
let relay_url = test_relay(Router::new().route(
178+
"/api/join-policy",
179+
get(|| async {
180+
let chunk = Bytes::from(vec![b'x'; MAX_JOIN_POLICY_RESPONSE_BYTES + 1]);
181+
Body::from_stream(futures_util::stream::once(async move {
182+
Ok::<_, Infallible>(chunk)
183+
}))
184+
}),
185+
))
186+
.await;
187+
188+
assert_eq!(
189+
fetch_join_policy(relay_url).await.unwrap_err(),
190+
"relay returned oversized join policy"
191+
);
192+
}
193+
}

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ mod export_util;
2121
mod global_agent_config;
2222
mod identity;
2323
mod identity_archive;
24+
mod join_policy;
2425
mod legacy_storage;
2526
mod link_preview;
2627
pub(crate) mod media;
@@ -78,6 +79,7 @@ pub use engrams::*;
7879
pub use global_agent_config::*;
7980
pub use identity::*;
8081
pub use identity_archive::*;
82+
pub use join_policy::*;
8183
pub use legacy_storage::*;
8284
pub use link_preview::*;
8385
pub use media::*;

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -895,6 +895,7 @@ pub fn run() {
895895
validate_repos_dir,
896896
get_active_workspace,
897897
fetch_workspace_icon,
898+
fetch_join_policy,
898899
set_prevent_sleep_active,
899900
get_agent_memory,
900901
relay_reconnect_hook,

‎desktop/src/features/communities/ui/CommunityEditForm.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ export function CommunityEditForm({
6868

6969
let cancelled = false;
7070
const timeoutId = window.setTimeout(() => {
71-
void getJoinPolicy(normalizedUrl)
71+
void getJoinPolicy(normalizedUrl, "native")
7272
.then((policy) => {
7373
if (cancelled || !policy) return;
7474
setJoinPolicy(policy);
@@ -105,7 +105,7 @@ export function CommunityEditForm({
105105

106106
if (joinPolicyRequired) {
107107
try {
108-
const policy = await getJoinPolicy(normalizedUrl);
108+
const policy = await getJoinPolicy(normalizedUrl, "native");
109109
if (!policy) {
110110
onSubmit(trimmedName, normalizedUrl);
111111
return;

‎desktop/src/features/onboarding/ui/InviteRedeemForm.tsx‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ export function InviteRedeemForm({
118118
const code = parsedInvite?.code;
119119
let cancelled = false;
120120
const timeoutId = window.setTimeout(() => {
121-
void getJoinPolicy(relayWsUrl)
121+
void getJoinPolicy(relayWsUrl, code ? "webview" : "native")
122122
.then((policy) => {
123123
if (cancelled || !policy) return;
124124
setJoinPolicy(policy);
@@ -156,7 +156,7 @@ export function InviteRedeemForm({
156156
setPolicyError(null);
157157
setIsLoadingPolicy(true);
158158
try {
159-
const policy = await getJoinPolicy(normalizedRelayUrl);
159+
const policy = await getJoinPolicy(normalizedRelayUrl, "native");
160160
if (!policy) {
161161
onConnect?.(normalizedRelayUrl, apiToken.trim() || undefined);
162162
return;
@@ -205,7 +205,7 @@ export function InviteRedeemForm({
205205
setPolicyError(null);
206206
setIsLoadingPolicy(true);
207207
try {
208-
const policy = await getJoinPolicy(relayWsUrl);
208+
const policy = await getJoinPolicy(relayWsUrl, "webview");
209209
if (!policy) {
210210
onRedeem(relayWsUrl, parsedInvite.code);
211211
return;

‎desktop/src/shared/api/invites.test.mjs‎

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ test("getJoinPolicy maps relay-hosted Markdown and age requirements", async () =
2828
{ status: 200 },
2929
),
3030
async () => {
31-
assert.deepEqual(await getJoinPolicy("wss://relay.example"), {
31+
assert.deepEqual(await getJoinPolicy("wss://relay.example", "webview"), {
3232
termsMarkdown: "# Terms",
3333
privacyMarkdown: "# Privacy",
3434
ageAttestationRequired: true,
@@ -40,15 +40,44 @@ test("getJoinPolicy maps relay-hosted Markdown and age requirements", async () =
4040

4141
test("getJoinPolicy preserves opt-in behavior for unconfigured and older relays", async () => {
4242
await withFetch(new Response(JSON.stringify({}), { status: 200 }), async () =>
43-
assert.equal(await getJoinPolicy("wss://relay.example"), null),
43+
assert.equal(await getJoinPolicy("wss://relay.example", "webview"), null),
4444
);
4545
await withFetch(new Response(null, { status: 404 }), async () =>
46-
assert.equal(await getJoinPolicy("wss://relay.example"), null),
46+
assert.equal(await getJoinPolicy("wss://relay.example", "webview"), null),
4747
);
4848
});
4949

5050
test("getJoinPolicy fails closed on a policy endpoint error", async () => {
5151
await withFetch(new Response(null, { status: 503 }), async () =>
52-
assert.rejects(getJoinPolicy("wss://relay.example"), /HTTP 503/),
52+
assert.rejects(getJoinPolicy("wss://relay.example", "webview"), /HTTP 503/),
5353
);
5454
});
55+
56+
test("getJoinPolicy maps the native command response", async () => {
57+
const previousWindow = globalThis.window;
58+
globalThis.window = {
59+
__TAURI_INTERNALS__: {
60+
invoke(command, args) {
61+
assert.equal(command, "fetch_join_policy");
62+
assert.deepEqual(args, { relayUrl: "wss://relay.example" });
63+
return Promise.resolve({
64+
terms_markdown: "# Terms",
65+
privacy_markdown: "# Privacy",
66+
age_attestation_required: true,
67+
version: "policy-v1",
68+
});
69+
},
70+
},
71+
};
72+
73+
try {
74+
assert.deepEqual(await getJoinPolicy("wss://relay.example", "native"), {
75+
termsMarkdown: "# Terms",
76+
privacyMarkdown: "# Privacy",
77+
ageAttestationRequired: true,
78+
version: "policy-v1",
79+
});
80+
} finally {
81+
globalThis.window = previousWindow;
82+
}
83+
});

‎desktop/src/shared/api/invites.ts‎

Lines changed: 34 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import { relayHttpFromWs } from "@/shared/api/inviteHelpers";
2-
import { getRelayHttpUrl, signRelayEvent } from "@/shared/api/tauri";
2+
import {
3+
getRelayHttpUrl,
4+
invokeTauri,
5+
signRelayEvent,
6+
} from "@/shared/api/tauri";
37

48
// Relay invite data layer. Both endpoints are NIP-98-authed HTTP POSTs
59
// (mirrors the read path in moderation.ts, plus the payload tag the relay
@@ -124,26 +128,38 @@ export function isJoinPolicyDiscoveryCandidate(relayWsUrl: string): boolean {
124128
/** Fetch relay-hosted policy content for any join surface. */
125129
export async function getJoinPolicy(
126130
relayWsUrl: string,
131+
transport: "native" | "webview",
127132
): Promise<JoinPolicy | null> {
128-
const base = relayHttpFromWs(relayWsUrl);
129-
const response = await fetch(`${base.replace(/\/+$/, "")}/api/join-policy`);
130-
// Relays predating join-policy support have no configured policy.
131-
if (response.status === 404) return null;
132-
if (!response.ok) throw new Error(`HTTP ${response.status}`);
133-
const raw = (await response.json()) as {
134-
policy?: {
135-
terms_markdown?: string;
136-
privacy_markdown?: string;
137-
age_attestation_required: boolean;
138-
version: string;
139-
};
133+
type RawJoinPolicy = {
134+
terms_markdown?: string;
135+
privacy_markdown?: string;
136+
age_attestation_required: boolean;
137+
version: string;
140138
};
141-
return raw.policy
139+
let raw: RawJoinPolicy | null;
140+
if (transport === "native") {
141+
raw = await invokeTauri<RawJoinPolicy | null>("fetch_join_policy", {
142+
relayUrl: relayWsUrl,
143+
});
144+
} else {
145+
const base = relayHttpFromWs(relayWsUrl);
146+
const response = await fetch(`${base.replace(/\/+$/, "")}/api/join-policy`);
147+
// Relays predating join-policy support have no configured policy.
148+
if (response.status === 404) return null;
149+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
150+
raw =
151+
(
152+
(await response.json()) as {
153+
policy?: RawJoinPolicy;
154+
}
155+
).policy ?? null;
156+
}
157+
return raw
142158
? {
143-
termsMarkdown: raw.policy.terms_markdown,
144-
privacyMarkdown: raw.policy.privacy_markdown,
145-
ageAttestationRequired: raw.policy.age_attestation_required,
146-
version: raw.policy.version,
159+
termsMarkdown: raw.terms_markdown,
160+
privacyMarkdown: raw.privacy_markdown,
161+
ageAttestationRequired: raw.age_attestation_required,
162+
version: raw.version,
147163
}
148164
: null;
149165
}

0 commit comments

Comments
 (0)