diff --git a/desktop/src/features/communities/communitySwitchRelaySocket.test.mjs b/desktop/src/features/communities/communitySwitchRelaySocket.test.mjs new file mode 100644 index 00000000000..992b2cb6f6f --- /dev/null +++ b/desktop/src/features/communities/communitySwitchRelaySocket.test.mjs @@ -0,0 +1,162 @@ +// A community switch must not leave the relay client on the previous +// community's relay. +// +// History: Settings → Invite to community published a kind:9030 admin add to +// a self-hosted community while a hosted community was selected. The relay +// client read its URL from the backend's process-global override. A relay call +// landing after `disconnect()` but before `apply_workspace` installed the new +// override connected to the OLD relay, and that socket survived as the current +// connection, so every later publish (relay admin events included) went to the +// old community. +import assert from "node:assert/strict"; +import { after, before, test } from "node:test"; +import { JSDOM } from "jsdom"; + +const dom = new JSDOM("", { + url: "http://localhost", +}); +const selfHosted = { + id: "self-hosted", + relayUrl: "wss://self-hosted.example", + name: "Self-hosted", +}; +const hosted = { + id: "hosted", + relayUrl: "wss://hosted.example", + name: "Hosted", +}; + +let renderHook, waitFor, cleanup, act, useCommunityInit, relayClient; +let backendRelayOverride = null; +let heldApply = null; +let applyCalls = 0; +let heldUrlLookup = null; +const socketOpens = []; + +function deferred() { + let resolve; + const promise = new Promise((promiseResolve) => { + resolve = promiseResolve; + }); + return { promise, resolve }; +} + +before(async () => { + Object.assign(globalThis, { + window: dom.window, + document: dom.window.document, + localStorage: dom.window.localStorage, + IS_REACT_ACT_ENVIRONMENT: true, + }); + dom.window.__TAURI_INTERNALS__ = { + invoke: async (command, args) => { + switch (command) { + case "get_identity": + return { pubkey: "a".repeat(64) }; + case "apply_workspace": + applyCalls += 1; + if (heldApply) await heldApply.promise; + backendRelayOverride = args.relayUrl; + return undefined; + case "get_relay_ws_url": { + const url = backendRelayOverride; + if (heldUrlLookup) await heldUrlLookup.promise; + return url; + } + case "plugin:websocket|connect": { + // The test only needs to know which relay each socket was opened + // to; the handshake never completes. + const open = { url: args.url, ...deferred() }; + socketOpens.push(open); + return open.promise; + } + default: + return undefined; + } + }, + transformCallback: () => 1, + }; + globalThis.__TAURI_INTERNALS__ = dom.window.__TAURI_INTERNALS__; + ({ renderHook, waitFor, cleanup, act } = await import( + "@testing-library/react" + )); + ({ useCommunityInit } = await import("./useCommunityInit.ts")); + ({ relayClient } = await import("@/shared/api/relayClient")); +}); + +after(() => { + cleanup(); + relayClient.disconnect(); + dom.window.close(); +}); + +test("a relay call during a community switch does not leave the client on the old relay", async () => { + const { result, rerender } = renderHook( + ({ community }) => useCommunityInit(community, community.id, false), + { initialProps: { community: selfHosted } }, + ); + await waitFor(() => assert.equal(result.current.isReady, true)); + assert.equal(backendRelayOverride, selfHosted.relayUrl); + + // Switch to the hosted community, holding the backend apply open so a relay + // call lands between disconnect() and the new override. + heldApply = deferred(); + rerender({ community: hosted }); + await waitFor(() => assert.equal(applyCalls, 2)); + void relayClient.preconnect().catch(() => {}); + await waitFor(() => assert.equal(socketOpens.length, 1)); + assert.equal( + socketOpens[0].url, + selfHosted.relayUrl, + "precondition: the gap connect reads the not-yet-replaced override", + ); + + await act(async () => heldApply.resolve()); + heldApply = null; + await waitFor(() => assert.equal(result.current.isReady, true)); + // The stale attempt finishes opening its socket after the switch. + await act(async () => socketOpens[0].resolve(1)); + + assert.equal( + relayClient.relayUrl, + hosted.relayUrl, + "after the switch the relay client must target the selected community", + ); + assert.equal( + relayClient.wsId, + null, + "the socket opened to the previous community must not survive the switch", + ); +}); + +test("a relay URL lookup that outlives a community switch does not overwrite the new relay", async () => { + cleanup(); + relayClient.disconnect(); + socketOpens.length = 0; + applyCalls = 0; + const { result, rerender } = renderHook( + ({ community }) => useCommunityInit(community, community.id, false), + { initialProps: { community: selfHosted } }, + ); + await waitFor(() => assert.equal(result.current.isReady, true)); + + heldApply = deferred(); + rerender({ community: hosted }); + await waitFor(() => assert.equal(applyCalls, 2)); + // The gap connect reads the outgoing override, but its answer only arrives + // after the switch has finished. + heldUrlLookup = deferred(); + void relayClient.preconnect().catch(() => {}); + await act(async () => heldApply.resolve()); + heldApply = null; + await waitFor(() => assert.equal(result.current.isReady, true)); + await act(async () => heldUrlLookup.resolve()); + heldUrlLookup = null; + + assert.equal(relayClient.relayUrl, hosted.relayUrl); + assert.equal( + socketOpens.length, + 0, + "no socket may be opened to the previous community's relay", + ); +}); diff --git a/desktop/src/features/communities/useCommunityInit.ts b/desktop/src/features/communities/useCommunityInit.ts index 64ce9ab09d9..e3dc0f77936 100644 --- a/desktop/src/features/communities/useCommunityInit.ts +++ b/desktop/src/features/communities/useCommunityInit.ts @@ -388,6 +388,9 @@ export function useCommunityInit( } if (!cancelled) { + // A relay call between resetCommunityState() and this point read the + // previous override and may have connected to the outgoing relay. + relayClient.bindRelayUrl(activeCommunity.relayUrl); // Refresh relay-derived media state only after the backend has installed // this community's relay override. On cold launch, mediaUrl.ts may have // eagerly cached the default relay origin before applyCommunity ran; diff --git a/desktop/src/features/community-members/hooks.ts b/desktop/src/features/community-members/hooks.ts index bb63a888d98..1aa50a66c85 100644 --- a/desktop/src/features/community-members/hooks.ts +++ b/desktop/src/features/community-members/hooks.ts @@ -1,5 +1,6 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useCommunities } from "@/features/communities/useCommunities"; import { addRelayMember, changeRelayMemberRole, @@ -43,10 +44,11 @@ export function useMyRelayMembershipLookupQuery() { export function useAddRelayMemberMutation() { const queryClient = useQueryClient(); + const relayUrl = useCommunities().activeCommunity?.relayUrl; return useMutation({ mutationFn: ({ pubkey, role }: { pubkey: string; role: string }) => - addRelayMember(pubkey, role), + addRelayMember(pubkey, role, relayUrl), onMutate: async ({ pubkey, role }) => { await queryClient.cancelQueries({ queryKey: relayMembersQueryKey }); const previous = @@ -83,9 +85,10 @@ export function useAddRelayMemberMutation() { export function useRemoveRelayMemberMutation() { const queryClient = useQueryClient(); + const relayUrl = useCommunities().activeCommunity?.relayUrl; return useMutation({ - mutationFn: (pubkey: string) => removeRelayMember(pubkey), + mutationFn: (pubkey: string) => removeRelayMember(pubkey, relayUrl), onMutate: async (pubkey) => { await queryClient.cancelQueries({ queryKey: relayMembersQueryKey }); const previous = @@ -116,6 +119,7 @@ export function useRemoveRelayMemberMutation() { export function useChangeRelayMemberRoleMutation() { const queryClient = useQueryClient(); + const relayUrl = useCommunities().activeCommunity?.relayUrl; return useMutation({ mutationFn: ({ @@ -126,7 +130,7 @@ export function useChangeRelayMemberRoleMutation() { pubkey: string; role?: string; newRole?: string; - }) => changeRelayMemberRole(pubkey, role ?? newRole ?? "member"), + }) => changeRelayMemberRole(pubkey, role ?? newRole ?? "member", relayUrl), onMutate: async ({ pubkey, role, newRole }) => { const nextRole = (role ?? newRole ?? "member") as RelayMember["role"]; await queryClient.cancelQueries({ queryKey: relayMembersQueryKey }); diff --git a/desktop/src/features/community-members/ui/AddMemberDialog.tsx b/desktop/src/features/community-members/ui/AddMemberDialog.tsx index bc97a68b182..99b578e963d 100644 --- a/desktop/src/features/community-members/ui/AddMemberDialog.tsx +++ b/desktop/src/features/community-members/ui/AddMemberDialog.tsx @@ -3,6 +3,7 @@ import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import * as React from "react"; import { toast } from "sonner"; +import { useCommunities } from "@/features/communities/useCommunities"; import { useAddRelayMemberMutation, useRelayMembersQuery, @@ -423,6 +424,8 @@ export function AddMemberDialog({ open: boolean; onOpenChange: (open: boolean) => void; }) { + const communityName = useCommunities().activeCommunity?.name; + return ( Add member - Add a person to this community by their public key. + Add a person to{" "} + + {communityName ?? "this community"} + {" "} + by their public key.
diff --git a/desktop/src/features/community-members/ui/CommunityInviteDialog.tsx b/desktop/src/features/community-members/ui/CommunityInviteDialog.tsx index 95500dd8a6f..b33f8439fd1 100644 --- a/desktop/src/features/community-members/ui/CommunityInviteDialog.tsx +++ b/desktop/src/features/community-members/ui/CommunityInviteDialog.tsx @@ -1,5 +1,6 @@ import * as React from "react"; +import { useCommunities } from "@/features/communities/useCommunities"; import { Dialog, DialogContent, @@ -24,6 +25,7 @@ export function CommunityInviteDialog({ open: boolean; }) { const [ttlSecs, setTtlSecs] = React.useState(DEFAULT_INVITE_TTL_SECS); + const communityName = useCommunities().activeCommunity?.name; React.useEffect(() => { // Reset after the link section has unmounted so reopening never mints an @@ -40,7 +42,11 @@ export function CommunityInviteDialog({ Invite to community - Add someone directly or share a link they can use to join. + Add someone to{" "} + + {communityName ?? "this community"} + {" "} + directly or share a link they can use to join. diff --git a/desktop/src/shared/api/relayChannelFilters.ts b/desktop/src/shared/api/relayChannelFilters.ts index b9a6cb11508..349966ac58f 100644 --- a/desktop/src/shared/api/relayChannelFilters.ts +++ b/desktop/src/shared/api/relayChannelFilters.ts @@ -8,6 +8,7 @@ import { KIND_STREAM_MESSAGE, KIND_STREAM_MESSAGE_V2, KIND_STREAM_MESSAGE_EDIT, + KIND_TYPING_INDICATOR, } from "@/shared/constants/kinds"; import type { RelaySubscriptionFilter } from "@/shared/api/relayClientShared"; @@ -41,6 +42,25 @@ export function buildChannelFilter( return filter; } +/** Huddle lifecycle events (kinds 48100–48103) for one channel. */ +export function buildHuddleEventsFilter( + channelId: string, +): RelaySubscriptionFilter { + return { kinds: [48100, 48101, 48102, 48103], "#h": [channelId], limit: 100 }; +} + +/** Typing indicators for one channel from the last 10 seconds onward. */ +export function buildTypingIndicatorFilter( + channelId: string, +): RelaySubscriptionFilter { + return { + kinds: [KIND_TYPING_INDICATOR], + "#h": [channelId], + limit: 10, + since: Math.floor(Date.now() / 1_000) - 10, + }; +} + /** * Huddle TTS message filter with a bounded startup replay window. * diff --git a/desktop/src/shared/api/relayClientSession.ts b/desktop/src/shared/api/relayClientSession.ts index ce640375709..b81525739d1 100644 --- a/desktop/src/shared/api/relayClientSession.ts +++ b/desktop/src/shared/api/relayClientSession.ts @@ -27,6 +27,8 @@ import { buildChannelFilter, buildChannelHistoryFilter, buildGlobalStreamFilter, + buildHuddleEventsFilter, + buildTypingIndicatorFilter, } from "@/shared/api/relayChannelFilters"; import { clearClosedRetry, @@ -112,6 +114,21 @@ export class RelayClient { this.resetConnection(error); }, }); + /** The relay this client connects to, or `null` before one is known. */ + getRelayUrl(): string | null { + return this.relayUrl; + } + /** + * Pins the relay just applied to the backend. A socket or attempt on any + * other relay is the previous community's, so it is torn down. + */ + bindRelayUrl(relayUrl: string) { + if (this.relayUrl === relayUrl) return; + if (this.relayUrl || this.wsId !== null || this.connectPromise) + this.disconnect(); + this.relayUrl = relayUrl; + } + setVisibleChannelId(id: string | null) { this.visibleChannelId = id; } @@ -361,29 +378,14 @@ export class RelayClient { channelId: string, onEvent: (event: RelayEvent) => void, ) { - return this.subscribe( - { - kinds: [48100, 48101, 48102, 48103], - "#h": [channelId], - limit: 100, - }, - onEvent, - ); + return this.subscribe(buildHuddleEventsFilter(channelId), onEvent); } async subscribeToTypingIndicators( channelId: string, onEvent: (event: RelayEvent) => void, ) { - return this.subscribe( - { - kinds: [KIND_TYPING_INDICATOR], - "#h": [channelId], - limit: 10, - since: Math.floor(Date.now() / 1_000) - 10, - }, - onEvent, - ); + return this.subscribe(buildTypingIndicatorFilter(channelId), onEvent); } async publishUserStatus(status: UserStatusInput): Promise { await this.ensureConnected(); @@ -564,9 +566,11 @@ export class RelayClient { inbound.receive(delivery), ); try { - if (!this.relayUrl) { - this.relayUrl = await getRelayWsUrl(); - } + const relayUrl = this.relayUrl ?? (await getRelayWsUrl()); + // A switch during the lookup makes this the previous community's relay. + if (generation !== this.connectionGeneration) + throw new Error("Relay connection attempt was superseded."); + this.relayUrl = relayUrl; const wsId = await invoke("plugin:websocket|connect", { url: this.relayUrl, onMessage: this.onMessageChannel, @@ -947,13 +951,9 @@ export class RelayClient { } private async handleAuthChallenge(challenge: string, generation: number) { - if (!this.relayUrl) { - this.relayUrl = await getRelayWsUrl(); - } - const event = await createAuthEvent({ challenge, - relayUrl: this.relayUrl, + relayUrl: this.relayUrl ?? (await getRelayWsUrl()), }); if (generation !== this.connectionGeneration || !this.authRequest) { diff --git a/desktop/src/shared/api/relayMembers.test.mjs b/desktop/src/shared/api/relayMembers.test.mjs index 50e4d715fe6..c60d5646d6a 100644 --- a/desktop/src/shared/api/relayMembers.test.mjs +++ b/desktop/src/shared/api/relayMembers.test.mjs @@ -1,8 +1,12 @@ import assert from "node:assert/strict"; import test from "node:test"; +import { relayClient } from "./relayClient.ts"; import { + addRelayMember, canManageCommunityMembers, + changeRelayMemberRole, + removeRelayMember, loadRelayMembershipLookup, shouldWarnMissingMembershipSnapshot, } from "./relayMembers.ts"; @@ -112,3 +116,50 @@ test("an available snapshot never warns", () => { false, ); }); + +function installRecordingTauri(t) { + const invoked = []; + const previousWindow = globalThis.window; + globalThis.window = { + ...previousWindow, + __TAURI_INTERNALS__: { + invoke: async (command) => { + invoked.push(command); + throw new Error(`unexpected ${command}`); + }, + }, + }; + t.after(() => { + relayClient.disconnect(); + globalThis.window = previousWindow; + }); + return invoked; +} + +test("relay admin events refuse a connection to another community's relay", async (t) => { + const invoked = installRecordingTauri(t); + relayClient.bindRelayUrl("wss://self-hosted.example"); + const target = "b".repeat(64); + const selected = "wss://hosted.example"; + + for (const publish of [ + () => addRelayMember(target, "admin", selected), + () => removeRelayMember(target, selected), + () => changeRelayMemberRole(target, "member", selected), + () => addRelayMember(target, "admin", undefined), + ]) { + await assert.rejects(publish, /is not the selected community/); + } + assert.deepEqual(invoked, [], "nothing may be signed or sent"); +}); + +test("relay admin events for the connected community proceed to signing", async (t) => { + const invoked = installRecordingTauri(t); + relayClient.bindRelayUrl("wss://hosted.example"); + + await assert.rejects( + () => addRelayMember("b".repeat(64), "admin", "wss://hosted.example"), + /unexpected sign_event/, + ); + assert.deepEqual(invoked, ["sign_event"]); +}); diff --git a/desktop/src/shared/api/relayMembers.ts b/desktop/src/shared/api/relayMembers.ts index bc2a473a33f..d67b1d186fb 100644 --- a/desktop/src/shared/api/relayMembers.ts +++ b/desktop/src/shared/api/relayMembers.ts @@ -148,8 +148,18 @@ export async function getMyRelayMembership(): Promise { async function publishRelayAdminEvent( kind: number, targetPubkey: string, + relayUrl: string | undefined, role?: string, ): Promise { + // The receiving relay applies the change to its own community, so an admin + // event sent over a socket left on another community changes that one. + const connectedRelayUrl = relayClient.getRelayUrl(); + if (!relayUrl || connectedRelayUrl !== relayUrl) { + throw new Error( + `Relay access was not changed: the relay connection (${connectedRelayUrl ?? "none"}) is not the selected community (${relayUrl ?? "none"}).`, + ); + } + const tags = [["p", normalizePubkey(targetPubkey)]]; if (role) { tags.push(["role", role]); @@ -161,31 +171,60 @@ async function publishRelayAdminEvent( tags, }); + // Re-checked before every send, so a switch during signing cancels it. await relayClient.publishEvent( event, "Timed out while updating relay access.", "Failed to update relay access.", + () => relayClient.getRelayUrl() === relayUrl, ); } +/** + * Adds `targetPubkey` to the community on `relayUrl`. Refuses to publish when + * the relay connection is to any other relay. + */ export async function addRelayMember( targetPubkey: string, role: string, + relayUrl: string | undefined, ): Promise { - await publishRelayAdminEvent(KIND_RELAY_ADMIN_ADD_MEMBER, targetPubkey, role); + await publishRelayAdminEvent( + KIND_RELAY_ADMIN_ADD_MEMBER, + targetPubkey, + relayUrl, + role, + ); } -export async function removeRelayMember(targetPubkey: string): Promise { - await publishRelayAdminEvent(KIND_RELAY_ADMIN_REMOVE_MEMBER, targetPubkey); +/** + * Removes `targetPubkey` from the community on `relayUrl`. Refuses to publish + * when the relay connection is to any other relay. + */ +export async function removeRelayMember( + targetPubkey: string, + relayUrl: string | undefined, +): Promise { + await publishRelayAdminEvent( + KIND_RELAY_ADMIN_REMOVE_MEMBER, + targetPubkey, + relayUrl, + ); } +/** + * Changes the role of `targetPubkey` in the community on `relayUrl`. Refuses + * to publish when the relay connection is to any other relay. + */ export async function changeRelayMemberRole( targetPubkey: string, newRole: string, + relayUrl: string | undefined, ): Promise { await publishRelayAdminEvent( KIND_RELAY_ADMIN_CHANGE_ROLE, targetPubkey, + relayUrl, newRole, ); } diff --git a/desktop/tests/e2e/invites-settings-screenshots.spec.ts b/desktop/tests/e2e/invites-settings-screenshots.spec.ts index 5421fa64282..71fbab24a3a 100644 --- a/desktop/tests/e2e/invites-settings-screenshots.spec.ts +++ b/desktop/tests/e2e/invites-settings-screenshots.spec.ts @@ -98,7 +98,7 @@ test("capture: share-style community invite dialog", async ({ page }) => { await expect(page.getByPlaceholder("Type an email address")).toHaveCount(0); await expect( dialog.getByText( - "Add someone directly or share a link they can use to join.", + /^Add someone to .+ directly or share a link they can use to join\.$/, ), ).toBeVisible(); await expect(