diff --git a/browser-host/relay-broker-api.test.mjs b/browser-host/relay-broker-api.test.mjs index 2d8483ce02..d94abe1c6f 100644 --- a/browser-host/relay-broker-api.test.mjs +++ b/browser-host/relay-broker-api.test.mjs @@ -89,6 +89,7 @@ async function harness( } const call = { url: upstreamUrl, + method: init?.method ?? "GET", body: init?.body ? JSON.parse(init.body) : undefined, signal: init?.signal, headers: init?.headers, @@ -3132,6 +3133,75 @@ test("invite mint forwards only bounded ttl/max_uses and returns the relay invit } }); +test("invite list and revoke sign their exact relay routes and never echo a code", async () => { + const cursor = "1795049564000000_0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f"; + const page = { invites: [], next_before: null }; + const { h, post } = await communityAdmin((call) => + call.url.endsWith("/api/invites/revoke") + ? call.body.code === "v2.leak" + ? Response.json({ error: "v2.leak not found" }, { status: 404 }) + : Response.json({ id: "x", revoked_at: 1 }) + : Response.json(page), + ); + try { + for (const [body, url] of [ + [{}, `${fixtureRelayUrl}/api/invites`], + [{ before: cursor }, `${fixtureRelayUrl}/api/invites?before=${cursor}`], + ]) { + const response = await post("invites", body); + expect(response.status).toBe(200); + expect(await response.json()).toEqual(page); + const sent = h.calls.at(-1); + expect(sent.url).toBe(url); + expect(sent.method).toBe("GET"); + expect(sent.body).toBeUndefined(); + expect(sent.auth.tags).toContainEqual(["u", url]); + expect(sent.auth.tags).toContainEqual(["method", "GET"]); + expect(sent.auth.tags.some(([name]) => name === "payload")).toBe(false); + } + const revoked = await post("invite-revoke", { code: "v2.abc" }); + expect(revoked.status).toBe(200); + const sent = h.calls.at(-1); + expect(sent.url).toBe(`${fixtureRelayUrl}/api/invites/revoke`); + expect(sent.method).toBe("POST"); + expect(sent.body).toEqual({ code: "v2.abc" }); + expect(sent.auth.tags).toContainEqual([ + "u", + `${fixtureRelayUrl}/api/invites/revoke`, + ]); + expect(sent.auth.tags).toContainEqual(["method", "POST"]); + expect(sent.auth.tags).toContainEqual([ + "payload", + createHash("sha256") + .update(JSON.stringify({ code: "v2.abc" })) + .digest("hex"), + ]); + + const calls = h.calls.length; + for (const body of [ + { before: "1&limit=200" }, + { before: `${cursor}&limit=1` }, + { before: "1795049564000000_0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2fx" }, + { limit: 200 }, + ]) + expect((await post("invites", body)).status).toBe(400); + for (const body of [ + {}, + { id: "x" }, + { id: "a", code: "v2.a" }, + { code: "a b" }, + ]) + expect((await post("invite-revoke", body)).status).toBe(400); + expect(h.calls).toHaveLength(calls); + + const refused = await post("invite-revoke", { code: "v2.leak" }); + expect(refused.status).toBe(404); + expect(await refused.text()).not.toContain("v2.leak"); + } finally { + await h.close(); + } +}); + test("member changes sign exact NIP-43 admin kinds and reject malformed changes locally", async () => { const { h, post } = await communityAdmin((call) => Response.json({ accepted: true, event_id: call.body.id, message: "" }), diff --git a/browser-host/relay-broker.mjs b/browser-host/relay-broker.mjs index c06f05862e..babf77f4c6 100644 --- a/browser-host/relay-broker.mjs +++ b/browser-host/relay-broker.mjs @@ -50,8 +50,10 @@ import { validChannelCommand } from "./channel-commands.mjs"; import { adminReason, claimReason, + inviteListPath, inviteRequest, memberCommand, + revokeRequest, } from "../src/features/communities/admin-protocol.ts"; import { leaveRefusal, @@ -2523,6 +2525,8 @@ export function relayBrokerPlugin({ "/api/relay/claim", "/api/relay/accept-policy", "/api/relay/invite", + "/api/relay/invites", + "/api/relay/invite-revoke", "/api/relay/member", "/api/relay/leave", "/api/relay/gifs", @@ -2837,13 +2841,15 @@ export function relayBrokerPlugin({ const claim = route === "/api/relay/claim"; const policy = route === "/api/relay/accept-policy"; const invite = route === "/api/relay/invite"; + const inviteList = route === "/api/relay/invites"; + const revoke = route === "/api/relay/invite-revoke"; const member = route === "/api/relay/member"; const leave = route === "/api/relay/leave"; const gifs = route === "/api/relay/gifs"; const profileSearch = route === "/api/relay/profile-search"; // Only these routes may surface an exact, allowed relay refusal. const refusal = - invite || member + invite || inviteList || revoke || member ? adminReason : claim ? claimReason @@ -2856,18 +2862,24 @@ export function relayBrokerPlugin({ body?.error, ) : undefined; - if (invite || member || leave) { + let invitePath; + if (invite || inviteList || revoke || member || leave) { // Community-bound only; the relay remains the authority for roles. if (!scoped) return json(res, 400, { error: "Select a community first" }); try { // The viewer's own leave request has one shape; the body carries nothing. + if (inviteList) invitePath = inviteListPath(filters); filters = invite ? inviteRequest(filters) - : finalizeEvent( - leave ? leaveRequestTemplate() : memberCommand(filters), - key, - ); + : revoke + ? revokeRequest(filters) + : inviteList + ? undefined + : finalizeEvent( + leave ? leaveRequestTemplate() : memberCommand(filters), + key, + ); } catch (error) { return json(res, 400, { error: error.message, sent: false }); } @@ -3225,6 +3237,8 @@ export function relayBrokerPlugin({ !claim && !policy && !invite && + !inviteList && + !revoke && !member && !leave && !gifs && @@ -3308,6 +3322,7 @@ export function relayBrokerPlugin({ return json(res, 404, { error: "GIF search is unavailable" }); const upstreamPath = workflowPath ?? + invitePath ?? (gifs ? gifSearchPath : profileSearch @@ -3320,8 +3335,10 @@ export function relayBrokerPlugin({ ? "/api/invites/accept-policy" : invite ? "/api/invites" - : "/query"); - const method = workflowPath ? "GET" : "POST"; + : revoke + ? "/api/invites/revoke" + : "/query"); + const method = workflowPath || invitePath ? "GET" : "POST"; const lane = admissions(relay, viewer).api; let releasePresence; if (presence) { @@ -3339,7 +3356,8 @@ export function relayBrokerPlugin({ }); if (!presence) inflight.set(relay, (inflight.get(relay) ?? 0) + 1); try { - const body = workflowPath ? undefined : JSON.stringify(filters); + const body = + workflowPath || invitePath ? undefined : JSON.stringify(filters); const admissionStart = performance.now(); let connectsBefore, upstreamStart; let response; diff --git a/docs/buzz-help.md b/docs/buzz-help.md index dbc82c18b9..e5dfe65949 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -279,6 +279,9 @@ In a Codex agent’s settings, open **Huddle voice** in the **Settings** tab to **Copy link**, and shared expiry and use limits. On macOS, hover over the QR or focus its action with the keyboard to reveal **Share**, which opens the system share menu with a QR image and the invite link. + **Links** lists the community's invite links with their status, uses and + expiry; **Revoke** on a row, or paste a link into **Revoke a link**, stops + anyone new from joining with it. People who already joined stay in. - To use Buzz on your phone, open Settings → **Mobile app** (**Pair mobile** in builds without Builderlab). When you're signed in with Builderlab and your account holds this identity's backup, it says to install the app (with store diff --git a/src-tauri/src/relay.rs b/src-tauri/src/relay.rs index 2dbd8f6f7c..ace406cb1a 100644 --- a/src-tauri/src/relay.rs +++ b/src-tauri/src/relay.rs @@ -81,12 +81,13 @@ pub(crate) fn origin(value: &str) -> Result { fn request_url(community: &str, path: &str, method: &str) -> Result { let allowed = match method { - "GET" => matches!(path, "/" | "/api/join-policy"), + "GET" => matches!(path, "/" | "/api/join-policy") || invite_list(path), "POST" => matches!( path, "/query" | "/events" | "/api/invites" + | "/api/invites/revoke" | "/api/invites/claim" | "/api/invites/accept-policy" | "/gifs/search" @@ -102,6 +103,27 @@ fn request_url(community: &str, path: &str, method: &str) -> Result { .map_err(|_| "Invalid relay path".into()) } +/// `GET /api/invites`, optionally with the relay's `_` cursor. +fn invite_list(path: &str) -> bool { + let Some(rest) = path.strip_prefix("/api/invites") else { + return false; + }; + let Some(cursor) = rest.strip_prefix("?before=") else { + return rest.is_empty(); + }; + cursor.split_once('_').is_some_and(|(micros, id)| { + (1..=20).contains(µs.len()) + && micros.bytes().all(|b| b.is_ascii_digit()) + && workflow_uuid(id) + }) +} + +/// Whether `relay_http` signs a request: every write, and the invite list, +/// which is an owner/admin-only read. +fn signed_http(method: &str, path: &str) -> bool { + method == "POST" || invite_list(path) +} + fn workflow_uuid(value: &str) -> bool { uuid::Uuid::parse_str(value).is_ok() && value.len() == 36 @@ -1021,7 +1043,7 @@ pub(crate) async fn relay_http( url, &method, body, - method == "POST", + signed_http(&method, &path), MAX_RESPONSE, ); cancellable(id.as_deref(), &method, &path, request).await diff --git a/src-tauri/src/relay/tests.rs b/src-tauri/src/relay/tests.rs index a6c2ff1855..6d03ca0dbc 100644 --- a/src-tauri/src/relay/tests.rs +++ b/src-tauri/src/relay/tests.rs @@ -22,10 +22,23 @@ fn routes_cannot_retarget_credentials_or_expand_http_access() { ] { assert!(request_url("https://relay.test", path, "POST").is_err()); } - for path in ["/api/invites", "/gifs/search", "/profiles/search"] { + for path in ["/gifs/search", "/profiles/search", "/api/invites/revoke"] { assert!(request_url("https://relay.test", path, "POST").is_ok()); assert!(request_url("https://relay.test", path, "GET").is_err()); } + let cursor = "/api/invites?before=1795049564000000_0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f"; + for path in ["/api/invites", cursor] { + assert!(request_url("https://relay.test", path, "GET").is_ok()); + } + assert!(request_url("https://relay.test", "/api/invites", "POST").is_ok()); + for path in [ + "/api/invites?limit=200", + "/api/invites?before=1_x", + "/api/invites?before=1795049564000000_0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f&limit=1", + "/api/invites/claim", + ] { + assert!(request_url("https://relay.test", path, "GET").is_err()); + } assert!(request_url("https://relay.test", "/gifs/other", "POST").is_err()); assert!(request_url("https://relay.test", "/profiles/other", "POST").is_err()); assert!(request_url("https://relay.test", "/events", "GET").is_err()); @@ -4660,6 +4673,85 @@ mod federated_header { ); community.assert_carried(head); } + /// The invite list and revoke go through `relay_http` itself: both list + /// forms are signed GETs over their full URL, revoke binds its body. + #[tokio::test] + async fn relay_http_signs_invite_list_and_revoke() { + use tauri::Manager; + let community = community(false).await; + let app = tauri::test::mock_builder() + .manage(community.host.clone()) + .manage(community.fi.clone()) + .build(crate::app_context()) + .unwrap(); + let cursor = "?before=1795049564000000_0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f"; + let revoke = r#"{"code":"v2.abc"}"#; + let routes = [ + ("GET", "/api/invites".to_owned(), None), + ("GET", format!("/api/invites{cursor}"), None), + ("POST", "/api/invites/revoke".to_owned(), Some(revoke)), + ]; + let server = community.serve(routes.iter().map(|_| reply("200 OK", "{}")).collect()); + for (method, path, body) in &routes { + let response = relay_http( + app.state(), + app.state(), + community.origin.to_string(), + path.clone(), + (*method).into(), + body.map(str::to_owned), + None, + ) + .await + .unwrap(); + assert_eq!(response.status, 200); + } + let heads = server.heads().await; + for ((method, path, body), head) in routes.iter().zip(&heads) { + assert!(head.starts_with(&format!("{method} {path} ")), "{head}"); + let encoded = head + .lines() + .find_map(|line| line.strip_prefix("authorization: Nostr ")) + .unwrap_or_else(|| panic!("unsigned: {head}")); + let event: serde_json::Value = + serde_json::from_slice(&STANDARD.decode(encoded).unwrap()).unwrap(); + verify(&event); + let url = community.origin.join(path).unwrap(); + assert_eq!(event["tags"][0], serde_json::json!(["u", url.as_str()])); + assert_eq!(event["tags"][1], serde_json::json!(["method", method])); + let payload = event["tags"] + .as_array() + .unwrap() + .iter() + .find(|tag| tag[0] == "payload"); + match body { + Some(body) => assert_eq!( + payload.unwrap()[1], + format!("{:x}", Sha256::digest(body.as_bytes())) + ), + None => assert!(payload.is_none()), + } + } + // No other invite path or query is reachable through the command. + for path in [ + "/api/invites?limit=200", + "/api/invites?before=1_x", + &format!("/api/invites{cursor}&limit=1"), + "/api/invites/revoke", + ] { + assert!(relay_http( + app.state(), + app.state(), + community.origin.to_string(), + path.into(), + "GET".into(), + None, + None, + ) + .await + .is_err()); + } + } #[tokio::test] async fn http_attaches_for_required_discovery() { http(true).await; diff --git a/src/bundled/moderation/CommunityAdmin.test.tsx b/src/bundled/moderation/CommunityAdmin.test.tsx index 1c0f4b51c9..0fef04afb4 100644 --- a/src/bundled/moderation/CommunityAdmin.test.tsx +++ b/src/bundled/moderation/CommunityAdmin.test.tsx @@ -707,3 +707,492 @@ it("ignores a late mint from a previous Invite visit", async () => { screen.queryByDisplayValue("https://primary.example/invite/old"), ).toBeNull(); }); + +it("lists invite links and revokes one by row or by pasted link", async () => { + const user = userEvent.setup(); + const permanent = "0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f"; + let revoked = false; + const calls = broker({ + invites: () => + Response.json({ + invites: [ + { + id: permanent, + created_by: owner, + created_at: 1700000000, + expires_at: 4102444800, + max_uses: null, + use_count: 2, + revoked_at: revoked ? 1700000100 : null, + status: revoked ? "revoked" : "active", + }, + { + id: "1b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f", + created_by: admin, + created_at: 1690000000, + expires_at: 1690003600, + max_uses: 5, + use_count: 5, + revoked_at: null, + status: "exhausted", + }, + ], + next_before: null, + }), + "invite-revoke": (body) => { + revoked = true; + return Response.json({ + id: (body as { id?: string }).id ?? permanent, + revoked_at: 1700000100, + }); + }, + }); + const { relay: data } = relay(owner); + render( true} />); + await user.click(await screen.findByRole("tab", { name: "Links" })); + const list = await screen.findByRole("list", { name: "Invite links" }); + expect(list).toHaveTextContent("Active · 2 uses · Expires"); + expect(list).toHaveTextContent("Used up · 5 of 5 uses · Expired"); + expect(calls.find((c) => c.route === "invites")?.body).toEqual({}); + + const [rowRevoke] = screen.getAllByRole("button", { name: /^Revoke Link/ }); + await user.click(rowRevoke as HTMLElement); + const dialog = await screen.findByRole("alertdialog"); + expect(dialog).toHaveTextContent(/Link 0b9c8f7e by .+, created /); + await user.click( + within(dialog).getByRole("button", { + name: "Revoke", + }), + ); + await waitFor(() => + expect(list).toHaveTextContent("Revoked · 2 uses · Expires"), + ); + expect(calls.filter((c) => c.route === "invite-revoke")).toEqual([ + { route: "invite-revoke", body: { id: permanent } }, + ]); + + const field = screen.getByRole("textbox", { name: "Revoke a link" }); + await user.type(field, "https://other.example/invite/abc"); + expect(field).toHaveAccessibleDescription( + "This invite link is for a different community.", + ); + expect(field).toHaveAttribute("aria-invalid", "true"); + await user.clear(field); + await user.type(field, "https://primary.example/invite/abc"); + await user.click(screen.getByRole("button", { name: "Revoke" })); + await user.click( + within(await screen.findByRole("alertdialog")).getByRole("button", { + name: "Revoke", + }), + ); + await waitFor(() => + expect( + calls.filter((c) => c.route === "invite-revoke").at(-1)?.body, + ).toEqual({ code: "abc" }), + ); +}); + +const linkId = (n: number) => `${n}b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f`; +const link = (n: number, extra: Record = {}) => ({ + id: linkId(n), + created_by: owner, + created_at: 1700000000 - n, + expires_at: 4102444800, + max_uses: null, + use_count: 0, + revoked_at: null, + status: "active", + ...extra, +}); +const unavailable = () => + Response.json( + { error: "community writes are temporarily unavailable" }, + { status: 503 }, + ); + +it("shows a revoke from its receipt and keeps older pages on refresh", async () => { + const user = userEvent.setup(); + let reads = 0; + const calls = broker({ + invites: (body) => { + reads++; + if ((body as { before?: string }).before) + return Response.json({ invites: [link(2)], next_before: null }); + // The read after the first page fails; the receipt alone shows the revoke. + if (reads === 3) return unavailable(); + return Response.json({ + invites: [link(1)], + next_before: `1699999999_${linkId(1)}`, + }); + }, + "invite-revoke": (body) => + Response.json({ + id: (body as { id: string }).id, + revoked_at: 1700000100, + }), + }); + const { relay: data } = relay(owner); + render( true} />); + await user.click(await screen.findByRole("tab", { name: "Links" })); + const list = await screen.findByRole("list", { name: "Invite links" }); + await user.click(screen.getByRole("button", { name: "Show more" })); + await waitFor(() => + expect(calls.filter((c) => c.route === "invites").at(-1)?.body).toEqual({ + before: `1699999999_${linkId(1)}`, + }), + ); + await waitFor(() => + expect(within(list).getAllByRole("listitem")).toHaveLength(2), + ); + + await user.click( + screen.getAllByRole("button", { + name: /^Revoke Link 1b9c8f7e/, + })[0] as HTMLElement, + ); + await user.click( + within(await screen.findByRole("alertdialog")).getByRole("button", { + name: "Revoke", + }), + ); + await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull()); + await waitFor(() => expect(list).toHaveFocus()); + const [first] = within(list).getAllByRole("listitem"); + expect(first).toHaveTextContent("Revoked"); + expect(within(first as HTMLElement).queryByRole("button")).toBeNull(); + + await user.click(screen.getByRole("button", { name: "Refresh" })); + expect(await screen.findByRole("alert")).toHaveTextContent( + "community writes are temporarily unavailable", + ); + // The receipt still wins, and Retry works with the list loaded. + expect(within(list).getAllByRole("listitem")[0]).toHaveTextContent("Revoked"); + await user.click(screen.getByRole("button", { name: "Retry" })); + await waitFor(() => expect(screen.queryByRole("alert")).toBeNull()); + expect(within(list).getAllByRole("listitem")).toHaveLength(2); + expect(within(list).getAllByRole("listitem")[0]).toHaveTextContent("Revoked"); + expect(screen.queryByRole("button", { name: "Show more" })).toBeNull(); +}); + +it("lands a held revoke after Back and Forward", async () => { + const user = userEvent.setup(); + let finish!: (response: Response) => void; + const held = new Promise((resolve) => { + finish = resolve; + }); + broker({ + invites: () => Response.json({ invites: [link(1)], next_before: null }), + "invite-revoke": () => held, + }); + const { relay: data } = relay(owner); + const active = () => true; + const view = render( + , + ); + await user.click(await screen.findByRole("button", { name: /^Revoke Link/ })); + await user.click( + within(await screen.findByRole("alertdialog")).getByRole("button", { + name: "Revoke", + }), + ); + view.rerender( + , + ); + expect(screen.queryByRole("alertdialog")).toBeNull(); + view.rerender( + , + ); + await act(async () => { + finish(Response.json({ id: linkId(1), revoked_at: 1700000100 })); + await held; + }); + const list = await screen.findByRole("list", { name: "Invite links" }); + await waitFor(() => expect(list).toHaveTextContent("Revoked")); + expect(screen.queryByRole("button", { name: /^Revoke Link/ })).toBeNull(); +}); + +it("keeps the confirmation open with a retry when revoke fails", async () => { + const user = userEvent.setup(); + let attempts = 0; + const calls = broker({ + invites: () => Response.json({ invites: [link(1)], next_before: null }), + "invite-revoke": () => + ++attempts === 1 + ? Response.json({ error: "invite_not_found" }, { status: 404 }) + : Response.json({ id: linkId(1), revoked_at: 1700000100 }), + }); + const { relay: data } = relay(owner); + render( + true} selectedMethod="links" />, + ); + await user.click(await screen.findByRole("button", { name: /^Revoke Link/ })); + const dialog = await screen.findByRole("alertdialog"); + await user.click(within(dialog).getByRole("button", { name: "Revoke" })); + expect(await within(dialog).findByRole("alert")).toHaveTextContent( + "No invite link in this community matches that link.", + ); + expect(dialog).not.toHaveTextContent("invite_not_found"); + expect(dialog).toHaveTextContent(/Link 1b9c8f7e/); + await user.click(within(dialog).getByRole("button", { name: "Retry" })); + await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull()); + expect( + calls.filter((c) => c.route === "invite-revoke").map((c) => c.body), + ).toEqual([{ id: linkId(1) }, { id: linkId(1) }]); + expect(screen.getByRole("list", { name: "Invite links" })).toHaveTextContent( + "Revoked", + ); +}); + +it("shows a listed link without an expiry as never expiring", async () => { + broker({ + invites: () => + Response.json({ + invites: [link(1, { expires_at: null })], + next_before: null, + }), + }); + const { relay: data } = relay(owner); + render( + true} selectedMethod="links" />, + ); + expect( + await screen.findByRole("list", { name: "Invite links" }), + ).toHaveTextContent("Active · 0 uses · Never expires"); +}); + +it("refresh re-reads loaded pages and resolves a lost page-two receipt", async () => { + const user = userEvent.setup(); + let committed = false; + // Same creation second, UUIDs in the opposite order to the relay's cursor order. + const later = link(1, { created_at: 1700000000 }); + const earlier = link(9, { created_at: 1700000000 }); + const calls = broker({ + invites: (body) => + (body as { before?: string }).before + ? Response.json({ + invites: [ + { + ...earlier, + ...(committed && { status: "revoked", revoked_at: 1700000100 }), + }, + ], + next_before: null, + }) + : Response.json({ + invites: [later], + next_before: `1700000000000001_${linkId(1)}`, + }), + "invite-revoke": () => { + committed = true; + return unavailable(); + }, + }); + const { relay: data } = relay(owner); + render( + true} selectedMethod="links" />, + ); + const list = await screen.findByRole("list", { name: "Invite links" }); + await user.click(screen.getByRole("button", { name: "Show more" })); + await waitFor(() => + expect(within(list).getAllByRole("listitem")).toHaveLength(2), + ); + await user.click( + screen.getByRole("button", { name: /^Revoke Link 9b9c8f7e/ }), + ); + const dialog = await screen.findByRole("alertdialog"); + await user.click(within(dialog).getByRole("button", { name: "Revoke" })); + await within(dialog).findByRole("alert"); + await user.click(within(dialog).getByRole("button", { name: "Cancel" })); + + await user.click(screen.getByRole("button", { name: "Refresh" })); + await waitFor(() => + expect(within(list).getAllByRole("listitem")[1]).toHaveTextContent( + "Revoked", + ), + ); + const rows = within(list).getAllByRole("listitem"); + expect(rows).toHaveLength(2); + expect(rows[0]).toHaveTextContent("Link 1b9c8f7e"); + expect(rows[0]).toHaveTextContent("Active"); + expect( + calls + .filter((c) => c.route === "invites") + .slice(-2) + .map((c) => c.body), + ).toEqual([{}, { before: `1700000000000001_${linkId(1)}` }]); +}); + +it("keeps the shown list when a refresh read fails partway", async () => { + const user = userEvent.setup(); + let failOlder = false; + broker({ + invites: (body) => + (body as { before?: string }).before + ? failOlder + ? unavailable() + : Response.json({ invites: [link(2)], next_before: null }) + : Response.json({ + invites: [link(1, { use_count: failOlder ? 7 : 0 })], + next_before: `1699999999_${linkId(1)}`, + }), + }); + const { relay: data } = relay(owner); + render( + true} selectedMethod="links" />, + ); + const list = await screen.findByRole("list", { name: "Invite links" }); + await user.click(screen.getByRole("button", { name: "Show more" })); + await waitFor(() => + expect(within(list).getAllByRole("listitem")).toHaveLength(2), + ); + failOlder = true; + await user.click(screen.getByRole("button", { name: "Refresh" })); + await screen.findByRole("alert"); + const rows = within(list).getAllByRole("listitem"); + expect(rows).toHaveLength(2); + expect(rows[0]).toHaveTextContent("0 uses"); + expect(screen.getByRole("button", { name: "Retry" })).toBeEnabled(); +}); + +it("ignores an older list response that arrives after a newer one", async () => { + let finish!: (response: Response) => void; + const held = new Promise((resolve) => { + finish = resolve; + }); + let reads = 0; + broker({ + invites: () => + ++reads === 1 + ? held + : Response.json({ invites: [link(2)], next_before: null }), + }); + const { relay: data } = relay(owner); + const active = () => true; + const view = render( + , + ); + await waitFor(() => expect(reads).toBe(1)); + view.rerender( + , + ); + view.rerender( + , + ); + const list = await screen.findByRole("list", { name: "Invite links" }); + await waitFor(() => expect(list).toHaveTextContent("Link 2b9c8f7e")); + await act(async () => { + finish(Response.json({ invites: [link(1)], next_before: null })); + await held; + }); + expect(list).toHaveTextContent("Link 2b9c8f7e"); + expect(list).not.toHaveTextContent("Link 1b9c8f7e"); +}); + +it("keeps Links hidden on Members and drops only an unsent confirmation", async () => { + const user = userEvent.setup(); + const calls = broker({ + invites: () => Response.json({ invites: [link(1)], next_before: null }), + }); + const { relay: data } = relay(owner); + const active = () => true; + const view = render( + , + ); + await user.click(await screen.findByRole("button", { name: /^Revoke Link/ })); + expect(await screen.findByRole("alertdialog")).toBeVisible(); + view.rerender( + , + ); + expect( + screen.getByRole("list", { name: "Invite links", hidden: true }), + ).not.toBeVisible(); + await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull()); + view.rerender( + , + ); + expect( + await screen.findByRole("list", { name: "Invite links" }), + ).toBeVisible(); + expect(screen.queryByRole("alertdialog")).toBeNull(); + expect(calls.some((c) => c.route === "invite-revoke")).toBe(false); +}); + +it("shows a revoke failure that arrived while Links was hidden", async () => { + const user = userEvent.setup(); + let finish!: (response: Response) => void; + const held = new Promise((resolve) => { + finish = resolve; + }); + broker({ + invites: () => Response.json({ invites: [link(1)], next_before: null }), + "invite-revoke": () => held, + }); + const { relay: data } = relay(owner); + const active = () => true; + const view = render( + , + ); + await user.click(await screen.findByRole("button", { name: /^Revoke Link/ })); + await user.click( + within(await screen.findByRole("alertdialog")).getByRole("button", { + name: "Revoke", + }), + ); + view.rerender( + , + ); + await act(async () => { + finish(unavailable()); + await held.catch(() => {}); + }); + view.rerender( + , + ); + const dialog = await screen.findByRole("alertdialog"); + expect(within(dialog).getByRole("alert")).toHaveTextContent( + "community writes are temporarily unavailable", + ); + expect(within(dialog).getByRole("button", { name: "Retry" })).toBeEnabled(); + // The open modal hides the list from the accessibility tree. + expect( + screen.getByRole("list", { name: "Invite links", hidden: true }), + ).toHaveTextContent("Active"); +}); + +it("keeps focus on the confirm action after a refused revoke", async () => { + const user = userEvent.setup(); + let finish!: (response: Response) => void; + const held = new Promise((resolve) => { + finish = resolve; + }); + const calls = broker({ + invites: () => Response.json({ invites: [link(1)], next_before: null }), + "invite-revoke": () => held, + }); + const { relay: data } = relay(owner); + render( + true} selectedMethod="links" />, + ); + await user.click(await screen.findByRole("button", { name: /^Revoke Link/ })); + const dialog = await screen.findByRole("alertdialog"); + const action = within(dialog).getByRole("button", { name: "Revoke" }); + action.focus(); + await user.keyboard("{Enter}"); + const revokes = () => calls.filter((c) => c.route === "invite-revoke"); + await waitFor(() => expect(revokes()).toHaveLength(1)); + // A second Enter and a click on the busy action send nothing more. + await user.keyboard("{Enter}"); + await user.click(action); + expect(revokes()).toHaveLength(1); + // While loading, the action stays focusable (a disabled button drops focus to + // the body in browsers) and blocks a second submit. + await waitFor(() => expect(action).toHaveAttribute("aria-busy", "true")); + expect(action).not.toHaveAttribute("disabled"); + await act(async () => { + finish(unavailable()); + await held; + }); + await within(dialog).findByRole("alert"); + expect(action).toHaveFocus(); + expect(action).toHaveTextContent("Retry"); +}); diff --git a/src/bundled/moderation/CommunityAdmin.tsx b/src/bundled/moderation/CommunityAdmin.tsx index 15ac4de547..8c4bb2cce1 100644 --- a/src/bundled/moderation/CommunityAdmin.tsx +++ b/src/bundled/moderation/CommunityAdmin.tsx @@ -67,6 +67,7 @@ import { import styles from "./CommunityAdmin.module.css"; import { DIRECT_MEMBER_ADD_ENABLED } from "./features"; import { canShareInvite, shareInvite } from "./shareInvite"; +import { InviteLinks } from "./InviteLinks"; const DAY = 24 * 60 * 60; const EXPIRY = [1, 3, 7, 30].map((days) => ({ @@ -84,7 +85,7 @@ const message = (reason: unknown) => reason instanceof Error ? reason.message : String(reason); const STALE = "The member list is out of date. Retry before making changes."; -export type MembershipMethod = "members" | "invite" | "direct"; +export type MembershipMethod = "members" | "invite" | "links" | "direct"; type MembershipSelection = { selectedMethod?: MembershipMethod | undefined; onMethodChange?: ((method: MembershipMethod) => void) | undefined; @@ -306,6 +307,7 @@ function Members({ busy={busy || !!pending} community={community} members={members} + name={name} owner={role === "owner"} stale={stale} refreshing={refreshing} @@ -523,6 +525,7 @@ function MembershipContent({ busy, community, members, + name, owner, stale, refreshing, @@ -536,6 +539,7 @@ function MembershipContent({ busy: boolean; community: string; members: readonly Member[]; + name(pubkey: string): string; owner: boolean; stale: boolean; refreshing: boolean; @@ -550,6 +554,8 @@ function MembershipContent({ ? "members" : requestedMethod; const open = method === "invite"; + const [linksVisited, setLinksVisited] = useState(false); + if (method === "links" && !linksVisited) setLinksVisited(true); const [ttl, setTtl] = useState(String(3 * DAY)); const [uses, setUses] = useState(""); const [identity, setIdentity] = useState(""); @@ -685,6 +691,12 @@ function MembershipContent({ panelId: "invite-share-panel", disabled: adding || busy, }, + { + value: "links", + label: "Links", + panelId: "invite-links-panel", + disabled: adding || busy, + }, ...(DIRECT_MEMBER_ADD_ENABLED ? [ { @@ -826,6 +838,23 @@ function MembershipContent({ )} + {/* Mounted from the first visit so a revoke in flight survives Back/Forward. */} + {(method === "links" || linksVisited) && ( + + )} {DIRECT_MEMBER_ADD_ENABLED && method === "direct" && (
+ reason instanceof Error ? reason.message : String(reason); +// Exact relay revoke refusal codes, forwarded unchanged by the broker. +const REVOKE_REFUSALS: Record = { + invite_not_found: "No invite link in this community matches that link.", + invite_not_revocable: + "This link can’t be revoked. It stops working when it expires or reaches its use limit.", + invite_restricted: + "You can’t revoke invite links while you’re restricted in this community.", +}; +const revokeMessage = (reason: unknown) => { + const text = message(reason); + return Object.hasOwn(REVOKE_REFUSALS, text) ? REVOKE_REFUSALS[text] : text; +}; +const STATUS: Record = { + active: "Active", + revoked: "Revoked", + expired: "Expired", + exhausted: "Used up", +}; + +/** How a link's expiry reads wherever it is shown. */ +export function inviteExpiry(expiresAt: number | null) { + if (expiresAt === null) return "Never expires"; + const date = new Date(expiresAt * 1000).toLocaleString(undefined, { + dateStyle: "medium", + timeStyle: "short", + }); + return expiresAt * 1000 <= Date.now() ? `Expired ${date}` : `Expires ${date}`; +} + +const created = (at: number) => + new Date(at * 1000).toLocaleString(undefined, { + dateStyle: "medium", + timeStyle: "short", + }); + +const uses = (invite: InviteSummary) => + invite.max_uses === null + ? `${invite.use_count} ${invite.use_count === 1 ? "use" : "uses"}` + : `${invite.use_count} of ${invite.max_uses} uses`; + +/** The community's invite links, with revoking by row or by pasted link. */ +export function InviteLinks({ + community, + name, + locked, + active, + visible, +}: { + community: string; + name(pubkey: string): string; + locked: boolean; + active(): boolean; + /** Hidden while another tab shows; the list stays mounted so a revoke in flight lands here. */ + visible: boolean; +}) { + const [list, setList] = useState<{ + invites: InviteSummary[]; + next: string | null; + } | null>(null); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(""); + const [notice, setNotice] = useState(""); + const [pasted, setPasted] = useState(""); + const [pending, setPending] = useState< + { id: string; label: string } | { code: string; label: string } | null + >(null); + const [revoking, setRevoking] = useState(false); + const [revokeError, setRevokeError] = useState(""); + // Confirmed revocations by id; they win over any list read that raced them. + const [revoked, setRevoked] = useState>({}); + const reads = useRef(0); + // Pages on screen, so a refresh re-reads the same range. + const loaded = useRef(0); + const listRef = useRef(null); + // A revoked row loses its Revoke button, so focus moves to the list instead. + const [focusList, setFocusList] = useState(0); + useEffect(() => { + if (focusList) listRef.current?.focus(); + }, [focusList]); + + const load = useCallback( + async (before?: string) => { + const read = ++reads.current; + setLoading(true); + setError(""); + try { + // Show more appends one page; a refresh re-reads every page already + // loaded along the relay's cursors, and replaces the list only once all succeed. + const pages = before ? 1 : Math.max(1, loaded.current); + const rows: InviteSummary[] = []; + let cursor = before; + let next: string | null = null; + let fetched = 0; + do { + const page = await listInvites(community, cursor); + if (read !== reads.current) return; + rows.push(...page.invites); + next = page.next_before; + cursor = next ?? undefined; + } while (++fetched < pages && next); + loaded.current = (before ? loaded.current : 0) + fetched; + setList((shown) => { + const invites = before ? [...(shown?.invites ?? []), ...rows] : rows; + // One row per id, even if a link moved across a page boundary. + const byId = new Map(invites.map((invite) => [invite.id, invite])); + return { invites: [...byId.values()], next }; + }); + } catch (reason) { + if (read === reads.current) setError(message(reason)); + } finally { + if (read === reads.current) setLoading(false); + } + }, + [community], + ); + useEffect(() => { + if (visible) void load(); + }, [load, visible]); + useEffect( + () => () => { + ++reads.current; + }, + [], + ); + // Leaving the tab drops an unsent confirmation, as Members does; a sent + // attempt stays, so its failure shows on return. + useEffect(() => { + if (!visible && !revoking && !revokeError) setPending(null); + }, [visible, revoking, revokeError]); + + const pastedCode = pasted.trim() ? pastedInviteCode(community, pasted) : null; + const pastedError = + pastedCode && "error" in pastedCode ? pastedCode.error : ""; + + function close() { + setPending(null); + setRevokeError(""); + } + + async function revoke() { + if (!pending || !active() || locked || revoking) return; + setRevoking(true); + setRevokeError(""); + setNotice(""); + try { + const receipt = await revokeInvite( + community, + "id" in pending ? { id: pending.id } : { code: pending.code }, + ); + setRevoked((shown) => ({ ...shown, [receipt.id]: receipt.revoked_at })); + if ("code" in pending) setPasted(""); + else setFocusList((n) => n + 1); + setPending(null); + setNotice("Invite link revoked. People who already joined stay in."); + } catch (reason) { + // The outcome may be unknown after a timeout; Refresh shows what the relay holds. + setRevokeError(revokeMessage(reason) ?? ""); + } finally { + setRevoking(false); + } + } + + const shown = list?.invites.map((invite) => + revoked[invite.id] === undefined + ? invite + : { + ...invite, + revoked_at: revoked[invite.id] ?? null, + status: "revoked" as const, + }, + ); + + return ( +
+
{ + event.preventDefault(); + if (pastedCode && "code" in pastedCode) + setPending({ code: pastedCode.code, label: "this link" }); + }} + > + +
+
+ + setPasted(event.currentTarget.value)} + autoComplete="off" + spellCheck={false} + disabled={revoking} + /> + + {pastedError && ( + + )} +
+ +
+
+
+
+

Invite links

+ +
+ {shown === undefined ? ( + !error &&

Loading invite links…

+ ) : shown.length === 0 ? ( +

+ No invite links yet. +

+ ) : ( +
    + {shown.map((invite) => { + // Creation time and a short id tell one creator's links apart. + const label = `Link ${invite.id.slice(0, 8)} by ${name(invite.created_by)}, created ${created(invite.created_at)}`; + return ( +
  • +
    +

    {label}

    +

    + {STATUS[invite.status]} · {uses(invite)} ·{" "} + {inviteExpiry(invite.expires_at)} +

    +
    + {invite.status !== "revoked" && ( + + )} +
  • + ); + })} +
+ )} + {list?.next && ( +
+ +
+ )} +
+
+ {error && ( +

+ {error} +

+ )} + {notice && ( +

+ {notice} +

+ )} +
+ {pending && visible && ( + + + + + } + > + {revokeError && ( +

+ {revokeError} +

+ )} +
+ )} +
+ ); +} diff --git a/src/bundled/moderation/api.ts b/src/bundled/moderation/api.ts index fe00fae294..be31fe44da 100644 --- a/src/bundled/moderation/api.ts +++ b/src/bundled/moderation/api.ts @@ -1,6 +1,11 @@ // Owner/admin requests through the selected community adapter. Roles come from // the shared roster reader; the relay decides every change. import { communityRequest } from "../../features/communities/api"; +import { communityDestination } from "../../features/communities/destination"; +import { + parsePastedInvite, + pastedInviteError, +} from "../../features/communities/invite-link"; import type { Member, Role } from "../../features/communities/roster"; export { @@ -11,12 +16,28 @@ export { } from "../../features/communities/roster"; export type Invite = { + invite_id: string; code: string; url: string; expires_at: number; max_uses: number | null; uses_remaining: number | null; }; +/** A listed invite; the relay never returns its code. */ +export type InviteSummary = { + id: string; + created_by: string; + created_at: number; + expires_at: number | null; + max_uses: number | null; + use_count: number; + revoked_at: number | null; + status: "active" | "revoked" | "expired" | "exhausted"; +}; +export type InvitePage = { + invites: InviteSummary[]; + next_before: string | null; +}; export type MemberChange = | { action: "add" | "role"; pubkey: string; role: "admin" | "member" } | { action: "remove"; pubkey: string }; @@ -40,6 +61,33 @@ export const mintInvite = ( max_uses: number | null, ) => communityRequest(community, "invite", { ttl_secs, max_uses }); +/** One page of the community's invites, newest first. */ +export const listInvites = (community: string, before?: string) => + communityRequest(community, "invites", before ? { before } : {}); + +export const revokeInvite = ( + community: string, + target: { id: string } | { code: string }, +) => + communityRequest<{ id: string; revoked_at: number }>( + community, + "invite-revoke", + target, + ); + +/** The code in a pasted link to this community, or why it can't be revoked here. */ +export function pastedInviteCode( + community: string, + input: string, +): { code: string } | { error: string } { + const link = parsePastedInvite(input); + if (!link?.code) + return { error: pastedInviteError(input.trim(), "Paste an invite link.") }; + if (link.community !== communityDestination(community).url) + return { error: "This invite link is for a different community." }; + return { code: link.code }; +} + export async function changeMember(community: string, change: MemberChange) { const receipt = await communityRequest<{ accepted?: boolean; diff --git a/src/bundled/moderation/index.tsx b/src/bundled/moderation/index.tsx index d7e6055cc1..73bcf9467e 100644 --- a/src/bundled/moderation/index.tsx +++ b/src/bundled/moderation/index.tsx @@ -45,6 +45,7 @@ export const apply: PluginModule["apply"] = (ctx) => { navigation?.target.kind === "settings" && navigation.target.route?.version === 1 && (navigation.target.route.params === "invite" || + navigation.target.route.params === "links" || navigation.target.route.params === "direct") ? navigation.target.route.params : "members" diff --git a/src/features/communities/admin-protocol.test.ts b/src/features/communities/admin-protocol.test.ts new file mode 100644 index 0000000000..4a69bc2e81 --- /dev/null +++ b/src/features/communities/admin-protocol.test.ts @@ -0,0 +1,35 @@ +import { expect, it } from "vitest"; +import { adminReason, inviteListPath, revokeRequest } from "./admin-protocol"; + +const id = "0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f"; + +it("pages the invite list only by the relay's cursor", () => { + expect(inviteListPath({})).toBe("/api/invites"); + expect(inviteListPath({ before: `1795049564000000_${id}` })).toBe( + `/api/invites?before=1795049564000000_${id}`, + ); + for (const body of [ + { before: "1&limit=200" }, + { before: `x_${id}` }, + { limit: 200 }, + ]) + expect(() => inviteListPath(body)).toThrow("Invalid invite list request"); +}); + +it("revokes by exactly one of id or code", () => { + expect(revokeRequest({ id })).toEqual({ id }); + expect(revokeRequest({ code: "v2.abc_-" })).toEqual({ code: "v2.abc_-" }); + for (const body of [ + {}, + { id, code: "v2.abc" }, + { id: "nope" }, + { code: "a b" }, + { code: "v2.abc", extra: 1 }, + ]) + expect(() => revokeRequest(body)).toThrow("Invalid revoke request"); +}); + +it("shows only allowlisted relay refusals, never one carrying a code", () => { + expect(adminReason({ error: "invite_not_found" })).toBe("invite_not_found"); + expect(adminReason({ error: "v2.leak not found" })).toBeUndefined(); +}); diff --git a/src/features/communities/admin-protocol.ts b/src/features/communities/admin-protocol.ts index 17471950bb..6ece5b877f 100644 --- a/src/features/communities/admin-protocol.ts +++ b/src/features/communities/admin-protocol.ts @@ -5,6 +5,7 @@ const MIN_TTL = 60; const MAX_TTL = 30 * 24 * 60 * 60; const MAX_USES = 10_000; const ROLES = ["admin", "member"]; +const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"; const KINDS: Record = { add: 9030, remove: 9031, role: 9032 }; /** Normalized `POST /api/invites` body; unknown fields are dropped. */ @@ -31,6 +32,44 @@ export function inviteRequest(value: unknown) { return { ttl_secs: ttl, max_uses: uses }; } +/** `GET /api/invites` path for one page; `before` is the relay's opaque cursor. */ +export function inviteListPath(value: unknown) { + const { before, ...rest } = (value ?? {}) as { before?: unknown }; + if ( + Object.keys(rest).length || + (before !== undefined && + (typeof before !== "string" || + !new RegExp(`^\\d{1,20}_${UUID}$`).test(before))) + ) + throw new Error("Invalid invite list request"); + return before === undefined + ? "/api/invites" + : `/api/invites?before=${before}`; +} + +/** Normalized `POST /api/invites/revoke` body: exactly one of `id` or `code`. */ +export function revokeRequest(value: unknown) { + const { id, code, ...rest } = (value ?? {}) as { + id?: unknown; + code?: unknown; + }; + if (Object.keys(rest).length === 0) { + if ( + typeof id === "string" && + code === undefined && + new RegExp(`^${UUID}$`).test(id) + ) + return { id }; + if ( + typeof code === "string" && + id === undefined && + /^[a-zA-Z0-9._-]{1,256}$/.test(code) + ) + return { code }; + } + throw new Error("Invalid revoke request"); +} + /** Unsigned NIP-43 add/remove/role command for one member. */ export function memberCommand( value: unknown, @@ -78,6 +117,11 @@ const REASONS = new Set([ "invalid: cannot set role to owner", "blocked: you are banned from this community", "only relay owners and admins can create invites", + "only relay owners and admins can list invites", + "only relay owners, admins or the invite's creator can revoke it", + "invite_not_revocable", + "invite_not_found", + "invite_restricted", "community writes are temporarily unavailable", ]); diff --git a/src/features/communities/native-api.ts b/src/features/communities/native-api.ts index a42f5f9c7a..22bd1ce1cd 100644 --- a/src/features/communities/native-api.ts +++ b/src/features/communities/native-api.ts @@ -9,7 +9,13 @@ import { } from "../relay/native"; import { joinPolicy as readJoinPolicy } from "./join-policy"; import { leaveRefusal, leaveRequestTemplate } from "./leave-protocol"; -import { adminReason, memberCommand } from "./admin-protocol"; +import { + adminReason, + inviteListPath, + inviteRequest, + memberCommand, + revokeRequest, +} from "./admin-protocol"; import { readRelayLibrary } from "../agents/relay-library"; import { eventDto } from "../relay/events"; import { readApiFailure } from "../relay/http-admission"; @@ -135,31 +141,37 @@ export async function nativeCommunityRequest( }); } if (route === "invite") { - const input = body as - | { ttl_secs?: unknown; max_uses?: unknown } - | undefined; - const ttl = input?.ttl_secs; - const uses = input?.max_uses ?? null; - if ( - !Number.isSafeInteger(ttl) || - (ttl as number) < 60 || - (ttl as number) > 2_592_000 - ) - throw new Error("Invalid invite expiry"); - if ( - uses !== null && - (!Number.isSafeInteger(uses) || - (uses as number) < 1 || - (uses as number) > 10_000) - ) - throw new Error("Invalid invite use limit"); return readResponse( await nativeRelayRequest( community, "/api/invites", - { ttl_secs: ttl, max_uses: uses }, + inviteRequest(body), + signal, + ), + adminReason, + ); + } + if (route === "invites") { + // The native host signs this owner/admin read; the cursor is the relay's. + return readResponse( + await nativeRelayRequest( + community, + inviteListPath(body), + undefined, + signal, + ), + adminReason, + ); + } + if (route === "invite-revoke") { + return readResponse( + await nativeRelayRequest( + community, + "/api/invites/revoke", + revokeRequest(body), signal, ), + adminReason, ); } if (route === "profile") {