From ed1c77794115d8b4894f263e198461c7e583d24e Mon Sep 17 00:00:00 2001 From: Will Pfleger Date: Wed, 18 Nov 2026 20:04:38 -0500 Subject: [PATCH 01/10] feat(moderation): list and revoke invite links, mint never-expiring links Adds a Links tab to community Membership settings for owners and admins: the community's invite links with status, uses and expiry, a Revoke button per row, and a field that revokes a pasted link by its code. The Invite tab gains a Never expires option that mints with never_expires: true, and a never-expiring link reads Never expires. Both hosts gain the relay's new routes: GET /api/invites (signed, with only the relay's opaque before cursor) and POST /api/invites/revoke, through shared request normalizers in admin-protocol.ts. Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Signed-off-by: Will Pfleger --- browser-host/relay-broker.mjs | 36 ++- docs/buzz-help.md | 4 + src-tauri/src/relay.rs | 21 +- src-tauri/src/relay/tests.rs | 15 +- .../moderation/CommunityAdmin.test.tsx | 112 ++++++++ src/bundled/moderation/CommunityAdmin.tsx | 44 +++- src/bundled/moderation/InviteLinks.tsx | 249 ++++++++++++++++++ src/bundled/moderation/api.ts | 63 ++++- src/bundled/moderation/index.tsx | 1 + .../communities/admin-protocol.test.ts | 48 ++++ src/features/communities/admin-protocol.ts | 64 ++++- src/features/communities/native-api.ts | 52 ++-- 12 files changed, 662 insertions(+), 47 deletions(-) create mode 100644 src/bundled/moderation/InviteLinks.tsx create mode 100644 src/features/communities/admin-protocol.test.ts 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..500a265b59 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -279,6 +279,10 @@ 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. + An invite's expiry can be **Never expires** on relays that support it. + **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..d2512814b8 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,21 @@ 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) + }) +} + fn workflow_uuid(value: &str) -> bool { uuid::Uuid::parse_str(value).is_ok() && value.len() == 36 @@ -1021,7 +1037,8 @@ pub(crate) async fn relay_http( url, &method, body, - method == "POST", + // The invite list is owner/admin-only, so its read is signed too. + method == "POST" || invite_list(&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..aa0cba011c 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()); diff --git a/src/bundled/moderation/CommunityAdmin.test.tsx b/src/bundled/moderation/CommunityAdmin.test.tsx index 1c0f4b51c9..3e05e9d2e9 100644 --- a/src/bundled/moderation/CommunityAdmin.test.tsx +++ b/src/bundled/moderation/CommunityAdmin.test.tsx @@ -707,3 +707,115 @@ it("ignores a late mint from a previous Invite visit", async () => { screen.queryByDisplayValue("https://primary.example/invite/old"), ).toBeNull(); }); + +it("mints a link that never expires", async () => { + const user = userEvent.setup(); + const calls = broker({ + invite: () => + Response.json({ + invite_id: "0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f", + code: "abc", + url: "https://primary.example/invite/abc", + expires_at: null, + max_uses: null, + uses_remaining: null, + }), + }); + const { relay: data } = relay(owner); + render( true} />); + await user.click(await screen.findByRole("tab", { name: "Invite" })); + await screen.findByDisplayValue("https://primary.example/invite/abc"); + await user.click( + screen.getByRole("button", { name: "Choose invite expiry" }), + ); + await user.click( + await screen.findByRole("menuitemradio", { name: "Never expires" }), + ); + await waitFor(() => + expect(calls.filter((c) => c.route === "invite").at(-1)?.body).toEqual({ + never_expires: true, + max_uses: null, + }), + ); +}); + +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: null, + 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 · Never 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); + await user.click( + within(await screen.findByRole("alertdialog")).getByRole("button", { + name: "Revoke", + }), + ); + await waitFor(() => + expect(list).toHaveTextContent("Revoked · 2 uses · Never 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(screen.getByRole("alert")).toHaveTextContent( + "This invite link is for a different community.", + ); + 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" }), + ); +}); diff --git a/src/bundled/moderation/CommunityAdmin.tsx b/src/bundled/moderation/CommunityAdmin.tsx index 15ac4de547..7d762bb0e1 100644 --- a/src/bundled/moderation/CommunityAdmin.tsx +++ b/src/bundled/moderation/CommunityAdmin.tsx @@ -67,12 +67,17 @@ 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) => ({ - value: String(days * DAY), - label: days === 1 ? "1 day" : `${days} days`, -})); +const NEVER = "never"; +const EXPIRY = [ + ...[1, 3, 7, 30].map((days) => ({ + value: String(days * DAY), + label: days === 1 ? "1 day" : `${days} days`, + })), + { value: NEVER, label: "Never expires" }, +]; const USES = [ { value: "", label: "No limit" }, ...[1, 5, 10, 25].map((uses) => ({ @@ -84,7 +89,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 +311,7 @@ function Members({ busy={busy || !!pending} community={community} members={members} + name={name} owner={role === "owner"} stale={stale} refreshing={refreshing} @@ -523,6 +529,7 @@ function MembershipContent({ busy, community, members, + name, owner, stale, refreshing, @@ -536,6 +543,7 @@ function MembershipContent({ busy: boolean; community: string; members: readonly Member[]; + name(pubkey: string): string; owner: boolean; stale: boolean; refreshing: boolean; @@ -597,7 +605,11 @@ function MembershipContent({ setLink({ settings }); setCopied(false); setError(""); - mintInvite(community, Number(ttl), uses ? Number(uses) : null).then( + mintInvite( + community, + ttl === NEVER ? null : Number(ttl), + uses ? Number(uses) : null, + ).then( (invite) => { if (minting.current === request) setLink({ settings, url: invite.url }); }, @@ -685,6 +697,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 +844,20 @@ function MembershipContent({ )} + {method === "links" && ( + + )} {DIRECT_MEMBER_ADD_ENABLED && method === "direct" && (
+ reason instanceof Error ? reason.message : String(reason); +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 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, +}: { + community: string; + name(pubkey: string): string; + locked: boolean; + active(): boolean; +}) { + const [invites, setInvites] = useState(null); + const [next, setNext] = useState(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 reads = useRef(0); + + const load = useCallback( + async (before?: string) => { + const read = ++reads.current; + setLoading(true); + setError(""); + try { + const page = await listInvites(community, before); + if (read !== reads.current) return; + setInvites((shown) => + before ? [...(shown ?? []), ...page.invites] : page.invites, + ); + setNext(page.next_before); + } catch (reason) { + if (read === reads.current) setError(message(reason)); + } finally { + if (read === reads.current) setLoading(false); + } + }, + [community], + ); + useEffect(() => { + void load(); + return () => { + ++reads.current; + }; + }, [load]); + + const pastedCode = pasted.trim() ? pastedInviteCode(community, pasted) : null; + + async function revoke() { + if (!pending || !active() || locked || revoking) return; + setRevoking(true); + setError(""); + setNotice(""); + try { + await revokeInvite( + community, + "id" in pending ? { id: pending.id } : { code: pending.code }, + ); + if ("code" in pending) setPasted(""); + setNotice("Invite link revoked. People who already joined stay in."); + await load(); + } catch (reason) { + setError(message(reason)); + } finally { + setRevoking(false); + setPending(null); + } + } + + 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} + /> + + {pastedCode && "error" in pastedCode && ( +

+ {pastedCode.error} +

+ )} +
+ +
+
+
+

Invite links

+ {invites === null ? ( + !error &&

Loading invite links…

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

+ No invite links yet. +

+ ) : ( +
    + {invites.map((invite) => { + const label = `Link by ${name(invite.created_by)}`; + return ( +
  • +
    +

    {label}

    +

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

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

+ {error} +

+ {invites === null && ( + + )} +
+ )} + {notice && ( +

+ {notice} +

+ )} +
+ {pending && ( + setPending(null)} + actions={ + <> + + + + } + /> + )} +
+ ); +} diff --git a/src/bundled/moderation/api.ts b/src/bundled/moderation/api.ts index fe00fae294..b336f96752 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,29 @@ export { } from "../../features/communities/roster"; export type Invite = { + invite_id: string; code: string; url: string; - expires_at: number; + /** Unix seconds, or null for a link that never expires. */ + expires_at: number | null; 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 }; @@ -34,11 +56,46 @@ export function allowedActions( return [target.role === "admin" ? "demote" : "promote", "remove"]; } +/** Mints a link; a null `ttl_secs` makes one that never expires. */ export const mintInvite = ( community: string, - ttl_secs: number, + ttl_secs: number | null, max_uses: number | null, -) => communityRequest(community, "invite", { ttl_secs, max_uses }); +) => + communityRequest( + community, + "invite", + ttl_secs === null + ? { never_expires: true, max_uses } + : { 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<{ 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..8a080c14b4 --- /dev/null +++ b/src/features/communities/admin-protocol.test.ts @@ -0,0 +1,48 @@ +import { expect, it } from "vitest"; +import { inviteListPath, inviteRequest, revokeRequest } from "./admin-protocol"; + +const id = "0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f"; + +it("mints either a bounded expiry or one that never expires", () => { + expect(inviteRequest({ ttl_secs: 60, max_uses: 2, extra: 1 })).toEqual({ + ttl_secs: 60, + max_uses: 2, + }); + expect(inviteRequest({ never_expires: true })).toEqual({ + never_expires: true, + max_uses: null, + }); + for (const body of [ + { never_expires: true, ttl_secs: 60 }, + { never_expires: false, ttl_secs: 60 }, + { never_expires: "true" }, + {}, + ]) + expect(() => inviteRequest(body)).toThrow("Invalid invite expiry"); +}); + +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"); +}); diff --git a/src/features/communities/admin-protocol.ts b/src/features/communities/admin-protocol.ts index 17471950bb..12cf9432e7 100644 --- a/src/features/communities/admin-protocol.ts +++ b/src/features/communities/admin-protocol.ts @@ -9,15 +9,23 @@ const KINDS: Record = { add: 9030, remove: 9031, role: 9032 }; /** Normalized `POST /api/invites` body; unknown fields are dropped. */ export function inviteRequest(value: unknown) { - const { ttl_secs: ttl, max_uses: uses = null } = (value ?? {}) as { + const { + ttl_secs: ttl, + max_uses: uses = null, + never_expires: never, + } = (value ?? {}) as { ttl_secs?: unknown; max_uses?: unknown; + never_expires?: unknown; }; + if (never !== undefined && (never !== true || ttl !== undefined)) + throw new Error("Invalid invite expiry"); if ( - typeof ttl !== "number" || - !Number.isSafeInteger(ttl) || - ttl < MIN_TTL || - ttl > MAX_TTL + never !== true && + (typeof ttl !== "number" || + !Number.isSafeInteger(ttl) || + ttl < MIN_TTL || + ttl > MAX_TTL) ) throw new Error("Invalid invite expiry"); if ( @@ -28,7 +36,46 @@ export function inviteRequest(value: unknown) { uses > MAX_USES) ) throw new Error("Invalid invite use limit"); - return { ttl_secs: ttl, max_uses: uses }; + return never === true + ? { never_expires: true, max_uses: uses } + : { ttl_secs: ttl as number, 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" || !/^\d{1,20}_[0-9a-f-]{36}$/.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 && + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.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. */ @@ -78,6 +125,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") { From 1f4d827d02a8f5854ea948f49631c6980e82841e Mon Sep 17 00:00:00 2001 From: Will Pfleger Date: Wed, 18 Nov 2026 20:28:11 -0500 Subject: [PATCH 02/10] test(moderation): cover invite list/revoke host wiring; tell links apart - Broker and native tests drive list and revoke through the production dispatch: method, full URL with before, NIP-98 u/method binding, no payload on the GET, payload binding on revoke, rejected paths/queries, and a code-bearing refusal that is not echoed. - Native relay_http's signing decision is a named fn the test exercises. - The list cursor uses the canonical UUID pattern revoke ids use. - Rows and the revoke confirmation show a short id and creation time. - The paste field's error is tied to the input (aria-describedby/invalid). Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Signed-off-by: Will Pfleger --- browser-host/relay-broker-api.test.mjs | 63 ++++++++++++++++++ src-tauri/src/relay.rs | 9 ++- src-tauri/src/relay/tests.rs | 64 +++++++++++++++++++ .../moderation/CommunityAdmin.test.tsx | 7 +- src/bundled/moderation/InviteLinks.tsx | 25 ++++++-- .../communities/admin-protocol.test.ts | 12 +++- src/features/communities/admin-protocol.ts | 6 +- 7 files changed, 175 insertions(+), 11 deletions(-) diff --git a/browser-host/relay-broker-api.test.mjs b/browser-host/relay-broker-api.test.mjs index 2d8483ce02..40f6e48297 100644 --- a/browser-host/relay-broker-api.test.mjs +++ b/browser-host/relay-broker-api.test.mjs @@ -3132,6 +3132,69 @@ 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.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.body).toEqual({ code: "v2.abc" }); + 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/src-tauri/src/relay.rs b/src-tauri/src/relay.rs index d2512814b8..ace406cb1a 100644 --- a/src-tauri/src/relay.rs +++ b/src-tauri/src/relay.rs @@ -118,6 +118,12 @@ fn invite_list(path: &str) -> bool { }) } +/// 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 @@ -1037,8 +1043,7 @@ pub(crate) async fn relay_http( url, &method, body, - // The invite list is owner/admin-only, so its read is signed too. - method == "POST" || invite_list(&path), + 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 aa0cba011c..fa5b37e76c 100644 --- a/src-tauri/src/relay/tests.rs +++ b/src-tauri/src/relay/tests.rs @@ -295,6 +295,70 @@ async fn native_http_signs_exact_bytes_and_never_follows_redirects() { verify(&event); } +#[tokio::test] +async fn native_http_signs_the_invite_list_query_and_revoke_payload() { + let cursor = "?before=1795049564000000_0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f"; + let revoke = r#"{"code":"v2.abc"}"#; + for (method, path, body) in [ + ("GET", "/api/invites".to_owned(), None), + ("GET", format!("/api/invites{cursor}"), None), + ("POST", "/api/invites/revoke".to_owned(), Some(revoke)), + ] { + // The command's own allowlist and signing decision for this route. + assert!(request_url("https://relay.test", &path, method).is_ok()); + assert!(signed_http(method, &path)); + let (base, task) = fixture_server( + "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}".into(), + ); + let url = base.join(&path).unwrap(); + send( + &IdentityHost::fixture(), + None, + url.clone(), + method, + body.map(str::to_owned), + signed_http(method, &path), + MAX_RESPONSE, + ) + .await + .unwrap(); + let (headers, sent) = task.join().unwrap(); + assert!(headers.starts_with(&format!("{method} {path} "))); + assert_eq!(sent, body.unwrap_or("")); + let encoded = headers + .lines() + .find_map(|line| line.strip_prefix("authorization: Nostr ")) + .unwrap(); + let event: serde_json::Value = + serde_json::from_slice(&STANDARD.decode(encoded).unwrap()).unwrap(); + verify(&event); + 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()), + } + } + // Other reads stay unsigned, and no other invite path or query is reachable. + assert!(!signed_http("GET", "/api/join-policy")); + for path in [ + "/api/invites?limit=200", + "/api/invites?before=1_x", + &format!("/api/invites{cursor}&limit=1"), + "/api/invites/revoke", + ] { + assert!(request_url("https://relay.test", path, "GET").is_err()); + } +} + #[tokio::test] async fn memory_response_limit_rejects_before_generic_transport_budget() { // The advertised size alone must be rejected. A multi-megabyte server write diff --git a/src/bundled/moderation/CommunityAdmin.test.tsx b/src/bundled/moderation/CommunityAdmin.test.tsx index 3e05e9d2e9..1245ed3ab5 100644 --- a/src/bundled/moderation/CommunityAdmin.test.tsx +++ b/src/bundled/moderation/CommunityAdmin.test.tsx @@ -788,8 +788,10 @@ it("lists invite links and revokes one by row or by pasted link", async () => { 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(await screen.findByRole("alertdialog")).getByRole("button", { + within(dialog).getByRole("button", { name: "Revoke", }), ); @@ -802,9 +804,10 @@ it("lists invite links and revokes one by row or by pasted link", async () => { const field = screen.getByRole("textbox", { name: "Revoke a link" }); await user.type(field, "https://other.example/invite/abc"); - expect(screen.getByRole("alert")).toHaveTextContent( + 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" })); diff --git a/src/bundled/moderation/InviteLinks.tsx b/src/bundled/moderation/InviteLinks.tsx index 22ace36bb9..a336cd3ff0 100644 --- a/src/bundled/moderation/InviteLinks.tsx +++ b/src/bundled/moderation/InviteLinks.tsx @@ -30,6 +30,12 @@ export function inviteExpiry(expiresAt: number | null) { 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"}` @@ -87,6 +93,8 @@ export function InviteLinks({ }, [load]); const pastedCode = pasted.trim() ? pastedInviteCode(community, pasted) : null; + const pastedError = + pastedCode && "error" in pastedCode ? pastedCode.error : ""; async function revoke() { if (!pending || !active() || locked || revoking) return; @@ -127,6 +135,10 @@ export function InviteLinks({ setPasted(event.currentTarget.value)} @@ -135,9 +147,13 @@ export function InviteLinks({ disabled={revoking} /> - {pastedCode && "error" in pastedCode && ( -

- {pastedCode.error} + {pastedError && ( +

)} @@ -163,7 +179,8 @@ export function InviteLinks({ ) : (
    {invites.map((invite) => { - const label = `Link by ${name(invite.created_by)}`; + // 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 (
  • diff --git a/src/features/communities/admin-protocol.test.ts b/src/features/communities/admin-protocol.test.ts index 8a080c14b4..9b3c7cf53b 100644 --- a/src/features/communities/admin-protocol.test.ts +++ b/src/features/communities/admin-protocol.test.ts @@ -1,5 +1,10 @@ import { expect, it } from "vitest"; -import { inviteListPath, inviteRequest, revokeRequest } from "./admin-protocol"; +import { + adminReason, + inviteListPath, + inviteRequest, + revokeRequest, +} from "./admin-protocol"; const id = "0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f"; @@ -46,3 +51,8 @@ it("revokes by exactly one of id or code", () => { ]) 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 12cf9432e7..102a70b8ee 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. */ @@ -47,7 +48,8 @@ export function inviteListPath(value: unknown) { if ( Object.keys(rest).length || (before !== undefined && - (typeof before !== "string" || !/^\d{1,20}_[0-9a-f-]{36}$/.test(before))) + (typeof before !== "string" || + !new RegExp(`^\\d{1,20}_${UUID}$`).test(before))) ) throw new Error("Invalid invite list request"); return before === undefined @@ -65,7 +67,7 @@ export function revokeRequest(value: unknown) { if ( typeof id === "string" && code === undefined && - /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id) + new RegExp(`^${UUID}$`).test(id) ) return { id }; if ( From 1ffa7af60edc1b5f1a170e9d44d222a535e711f4 Mon Sep 17 00:00:00 2001 From: Will Pfleger Date: Wed, 18 Nov 2026 20:36:35 -0500 Subject: [PATCH 03/10] test(moderation): drive invite list/revoke through relay_http and record broker method Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Signed-off-by: Will Pfleger --- browser-host/relay-broker-api.test.mjs | 7 ++ src-tauri/src/relay/tests.rs | 143 ++++++++++++++----------- 2 files changed, 86 insertions(+), 64 deletions(-) diff --git a/browser-host/relay-broker-api.test.mjs b/browser-host/relay-broker-api.test.mjs index 40f6e48297..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, @@ -3152,6 +3153,7 @@ test("invite list and revoke sign their exact relay routes and never echo a code 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"]); @@ -3161,7 +3163,12 @@ test("invite list and revoke sign their exact relay routes and never echo a code 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", diff --git a/src-tauri/src/relay/tests.rs b/src-tauri/src/relay/tests.rs index fa5b37e76c..6d03ca0dbc 100644 --- a/src-tauri/src/relay/tests.rs +++ b/src-tauri/src/relay/tests.rs @@ -295,70 +295,6 @@ async fn native_http_signs_exact_bytes_and_never_follows_redirects() { verify(&event); } -#[tokio::test] -async fn native_http_signs_the_invite_list_query_and_revoke_payload() { - let cursor = "?before=1795049564000000_0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f"; - let revoke = r#"{"code":"v2.abc"}"#; - for (method, path, body) in [ - ("GET", "/api/invites".to_owned(), None), - ("GET", format!("/api/invites{cursor}"), None), - ("POST", "/api/invites/revoke".to_owned(), Some(revoke)), - ] { - // The command's own allowlist and signing decision for this route. - assert!(request_url("https://relay.test", &path, method).is_ok()); - assert!(signed_http(method, &path)); - let (base, task) = fixture_server( - "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}".into(), - ); - let url = base.join(&path).unwrap(); - send( - &IdentityHost::fixture(), - None, - url.clone(), - method, - body.map(str::to_owned), - signed_http(method, &path), - MAX_RESPONSE, - ) - .await - .unwrap(); - let (headers, sent) = task.join().unwrap(); - assert!(headers.starts_with(&format!("{method} {path} "))); - assert_eq!(sent, body.unwrap_or("")); - let encoded = headers - .lines() - .find_map(|line| line.strip_prefix("authorization: Nostr ")) - .unwrap(); - let event: serde_json::Value = - serde_json::from_slice(&STANDARD.decode(encoded).unwrap()).unwrap(); - verify(&event); - 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()), - } - } - // Other reads stay unsigned, and no other invite path or query is reachable. - assert!(!signed_http("GET", "/api/join-policy")); - for path in [ - "/api/invites?limit=200", - "/api/invites?before=1_x", - &format!("/api/invites{cursor}&limit=1"), - "/api/invites/revoke", - ] { - assert!(request_url("https://relay.test", path, "GET").is_err()); - } -} - #[tokio::test] async fn memory_response_limit_rejects_before_generic_transport_budget() { // The advertised size alone must be rejected. A multi-megabyte server write @@ -4737,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; From f137114828090b156ec0b9fa4672f60c3b63a940 Mon Sep 17 00:00:00 2001 From: Will Pfleger Date: Fri, 20 Nov 2026 14:36:16 -0500 Subject: [PATCH 04/10] refactor(moderation): leave never-expiring links to the stacked PR Mint UI and request validation match main again; the Links list shows only finite expiries. Signed-off-by: Will Pfleger --- docs/buzz-help.md | 1 - .../moderation/CommunityAdmin.test.tsx | 37 ++----------------- src/bundled/moderation/CommunityAdmin.tsx | 18 +++------ src/bundled/moderation/InviteLinks.tsx | 3 +- src/bundled/moderation/api.ts | 17 ++------- .../communities/admin-protocol.test.ts | 25 +------------ src/features/communities/admin-protocol.ts | 22 +++-------- 7 files changed, 20 insertions(+), 103 deletions(-) diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 500a265b59..e5dfe65949 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -279,7 +279,6 @@ 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. - An invite's expiry can be **Never expires** on relays that support it. **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. diff --git a/src/bundled/moderation/CommunityAdmin.test.tsx b/src/bundled/moderation/CommunityAdmin.test.tsx index 1245ed3ab5..bcb0addbd6 100644 --- a/src/bundled/moderation/CommunityAdmin.test.tsx +++ b/src/bundled/moderation/CommunityAdmin.test.tsx @@ -708,37 +708,6 @@ it("ignores a late mint from a previous Invite visit", async () => { ).toBeNull(); }); -it("mints a link that never expires", async () => { - const user = userEvent.setup(); - const calls = broker({ - invite: () => - Response.json({ - invite_id: "0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f", - code: "abc", - url: "https://primary.example/invite/abc", - expires_at: null, - max_uses: null, - uses_remaining: null, - }), - }); - const { relay: data } = relay(owner); - render( true} />); - await user.click(await screen.findByRole("tab", { name: "Invite" })); - await screen.findByDisplayValue("https://primary.example/invite/abc"); - await user.click( - screen.getByRole("button", { name: "Choose invite expiry" }), - ); - await user.click( - await screen.findByRole("menuitemradio", { name: "Never expires" }), - ); - await waitFor(() => - expect(calls.filter((c) => c.route === "invite").at(-1)?.body).toEqual({ - never_expires: true, - max_uses: null, - }), - ); -}); - 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"; @@ -751,7 +720,7 @@ it("lists invite links and revokes one by row or by pasted link", async () => { id: permanent, created_by: owner, created_at: 1700000000, - expires_at: null, + expires_at: 4102444800, max_uses: null, use_count: 2, revoked_at: revoked ? 1700000100 : null, @@ -782,7 +751,7 @@ it("lists invite links and revokes one by row or by pasted link", async () => { 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 · Never expires"); + 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({}); @@ -796,7 +765,7 @@ it("lists invite links and revokes one by row or by pasted link", async () => { }), ); await waitFor(() => - expect(list).toHaveTextContent("Revoked · 2 uses · Never expires"), + expect(list).toHaveTextContent("Revoked · 2 uses · Expires"), ); expect(calls.filter((c) => c.route === "invite-revoke")).toEqual([ { route: "invite-revoke", body: { id: permanent } }, diff --git a/src/bundled/moderation/CommunityAdmin.tsx b/src/bundled/moderation/CommunityAdmin.tsx index 7d762bb0e1..47f2d90e73 100644 --- a/src/bundled/moderation/CommunityAdmin.tsx +++ b/src/bundled/moderation/CommunityAdmin.tsx @@ -70,14 +70,10 @@ import { canShareInvite, shareInvite } from "./shareInvite"; import { InviteLinks } from "./InviteLinks"; const DAY = 24 * 60 * 60; -const NEVER = "never"; -const EXPIRY = [ - ...[1, 3, 7, 30].map((days) => ({ - value: String(days * DAY), - label: days === 1 ? "1 day" : `${days} days`, - })), - { value: NEVER, label: "Never expires" }, -]; +const EXPIRY = [1, 3, 7, 30].map((days) => ({ + value: String(days * DAY), + label: days === 1 ? "1 day" : `${days} days`, +})); const USES = [ { value: "", label: "No limit" }, ...[1, 5, 10, 25].map((uses) => ({ @@ -605,11 +601,7 @@ function MembershipContent({ setLink({ settings }); setCopied(false); setError(""); - mintInvite( - community, - ttl === NEVER ? null : Number(ttl), - uses ? Number(uses) : null, - ).then( + mintInvite(community, Number(ttl), uses ? Number(uses) : null).then( (invite) => { if (minting.current === request) setLink({ settings, url: invite.url }); }, diff --git a/src/bundled/moderation/InviteLinks.tsx b/src/bundled/moderation/InviteLinks.tsx index a336cd3ff0..19e905318b 100644 --- a/src/bundled/moderation/InviteLinks.tsx +++ b/src/bundled/moderation/InviteLinks.tsx @@ -21,8 +21,7 @@ const STATUS: Record = { }; /** How a link's expiry reads wherever it is shown. */ -export function inviteExpiry(expiresAt: number | null) { - if (expiresAt === null) return "Never expires"; +export function inviteExpiry(expiresAt: number) { const date = new Date(expiresAt * 1000).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short", diff --git a/src/bundled/moderation/api.ts b/src/bundled/moderation/api.ts index b336f96752..448da7cdec 100644 --- a/src/bundled/moderation/api.ts +++ b/src/bundled/moderation/api.ts @@ -19,8 +19,7 @@ export type Invite = { invite_id: string; code: string; url: string; - /** Unix seconds, or null for a link that never expires. */ - expires_at: number | null; + expires_at: number; max_uses: number | null; uses_remaining: number | null; }; @@ -29,7 +28,7 @@ export type InviteSummary = { id: string; created_by: string; created_at: number; - expires_at: number | null; + expires_at: number; max_uses: number | null; use_count: number; revoked_at: number | null; @@ -56,19 +55,11 @@ export function allowedActions( return [target.role === "admin" ? "demote" : "promote", "remove"]; } -/** Mints a link; a null `ttl_secs` makes one that never expires. */ export const mintInvite = ( community: string, - ttl_secs: number | null, + ttl_secs: number, max_uses: number | null, -) => - communityRequest( - community, - "invite", - ttl_secs === null - ? { never_expires: true, max_uses } - : { ttl_secs, max_uses }, - ); +) => communityRequest(community, "invite", { ttl_secs, max_uses }); /** One page of the community's invites, newest first. */ export const listInvites = (community: string, before?: string) => diff --git a/src/features/communities/admin-protocol.test.ts b/src/features/communities/admin-protocol.test.ts index 9b3c7cf53b..4a69bc2e81 100644 --- a/src/features/communities/admin-protocol.test.ts +++ b/src/features/communities/admin-protocol.test.ts @@ -1,31 +1,8 @@ import { expect, it } from "vitest"; -import { - adminReason, - inviteListPath, - inviteRequest, - revokeRequest, -} from "./admin-protocol"; +import { adminReason, inviteListPath, revokeRequest } from "./admin-protocol"; const id = "0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f"; -it("mints either a bounded expiry or one that never expires", () => { - expect(inviteRequest({ ttl_secs: 60, max_uses: 2, extra: 1 })).toEqual({ - ttl_secs: 60, - max_uses: 2, - }); - expect(inviteRequest({ never_expires: true })).toEqual({ - never_expires: true, - max_uses: null, - }); - for (const body of [ - { never_expires: true, ttl_secs: 60 }, - { never_expires: false, ttl_secs: 60 }, - { never_expires: "true" }, - {}, - ]) - expect(() => inviteRequest(body)).toThrow("Invalid invite expiry"); -}); - it("pages the invite list only by the relay's cursor", () => { expect(inviteListPath({})).toBe("/api/invites"); expect(inviteListPath({ before: `1795049564000000_${id}` })).toBe( diff --git a/src/features/communities/admin-protocol.ts b/src/features/communities/admin-protocol.ts index 102a70b8ee..6ece5b877f 100644 --- a/src/features/communities/admin-protocol.ts +++ b/src/features/communities/admin-protocol.ts @@ -10,23 +10,15 @@ const KINDS: Record = { add: 9030, remove: 9031, role: 9032 }; /** Normalized `POST /api/invites` body; unknown fields are dropped. */ export function inviteRequest(value: unknown) { - const { - ttl_secs: ttl, - max_uses: uses = null, - never_expires: never, - } = (value ?? {}) as { + const { ttl_secs: ttl, max_uses: uses = null } = (value ?? {}) as { ttl_secs?: unknown; max_uses?: unknown; - never_expires?: unknown; }; - if (never !== undefined && (never !== true || ttl !== undefined)) - throw new Error("Invalid invite expiry"); if ( - never !== true && - (typeof ttl !== "number" || - !Number.isSafeInteger(ttl) || - ttl < MIN_TTL || - ttl > MAX_TTL) + typeof ttl !== "number" || + !Number.isSafeInteger(ttl) || + ttl < MIN_TTL || + ttl > MAX_TTL ) throw new Error("Invalid invite expiry"); if ( @@ -37,9 +29,7 @@ export function inviteRequest(value: unknown) { uses > MAX_USES) ) throw new Error("Invalid invite use limit"); - return never === true - ? { never_expires: true, max_uses: uses } - : { ttl_secs: ttl as number, max_uses: uses }; + return { ttl_secs: ttl, max_uses: uses }; } /** `GET /api/invites` path for one page; `before` is the relay's opaque cursor. */ From cc4726a6a66d65938247b15bcfd2a1131ca19026 Mon Sep 17 00:00:00 2001 From: Will Pfleger Date: Fri, 20 Nov 2026 16:05:44 -0500 Subject: [PATCH 05/10] fix(moderation): apply revoke receipts and keep revokes across tab changes Apply the revoke receipt to the loaded row so a failed follow-up read cannot leave it Active, keep a Refresh/Retry independent of the write that preserves older pages, keep the confirmation open with its error and a retry when revoke fails, keep the Links panel mounted after its first visit so an in-flight revoke lands across Back/Forward, and show listed links without an expiry as never expiring. Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Signed-off-by: Will Pfleger --- .../moderation/CommunityAdmin.test.tsx | 161 ++++++++++++++++++ src/bundled/moderation/CommunityAdmin.tsx | 7 +- src/bundled/moderation/InviteLinks.tsx | 136 +++++++++++---- src/bundled/moderation/api.ts | 2 +- 4 files changed, 267 insertions(+), 39 deletions(-) diff --git a/src/bundled/moderation/CommunityAdmin.test.tsx b/src/bundled/moderation/CommunityAdmin.test.tsx index bcb0addbd6..4e2fcf34b2 100644 --- a/src/bundled/moderation/CommunityAdmin.test.tsx +++ b/src/bundled/moderation/CommunityAdmin.test.tsx @@ -791,3 +791,164 @@ it("lists invite links and revokes one by row or by pasted link", async () => { ).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; + 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(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()); + 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 + ? unavailable() + : 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( + "community writes are temporarily unavailable", + ); + 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"); +}); diff --git a/src/bundled/moderation/CommunityAdmin.tsx b/src/bundled/moderation/CommunityAdmin.tsx index 47f2d90e73..8c4bb2cce1 100644 --- a/src/bundled/moderation/CommunityAdmin.tsx +++ b/src/bundled/moderation/CommunityAdmin.tsx @@ -554,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(""); @@ -836,17 +838,20 @@ function MembershipContent({
)} - {method === "links" && ( + {/* Mounted from the first visit so a revoke in flight survives Back/Forward. */} + {(method === "links" || linksVisited) && ( )} diff --git a/src/bundled/moderation/InviteLinks.tsx b/src/bundled/moderation/InviteLinks.tsx index 19e905318b..a6ef95544b 100644 --- a/src/bundled/moderation/InviteLinks.tsx +++ b/src/bundled/moderation/InviteLinks.tsx @@ -21,7 +21,8 @@ const STATUS: Record = { }; /** How a link's expiry reads wherever it is shown. */ -export function inviteExpiry(expiresAt: number) { +export function inviteExpiry(expiresAt: number | null) { + if (expiresAt === null) return "Never expires"; const date = new Date(expiresAt * 1000).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short", @@ -40,20 +41,29 @@ const uses = (invite: InviteSummary) => ? `${invite.use_count} ${invite.use_count === 1 ? "use" : "uses"}` : `${invite.use_count} of ${invite.max_uses} uses`; +/** Whether `a` sorts before `b` in the relay's newest-first order. */ +const newer = (a: InviteSummary, b: InviteSummary) => + a.created_at !== b.created_at ? a.created_at > b.created_at : a.id > b.id; + /** 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 [invites, setInvites] = useState(null); - const [next, setNext] = useState(null); + const [list, setList] = useState<{ + invites: InviteSummary[]; + next: string | null; + } | null>(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); const [notice, setNotice] = useState(""); @@ -62,6 +72,9 @@ export function InviteLinks({ { 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); const load = useCallback( @@ -72,10 +85,23 @@ export function InviteLinks({ try { const page = await listInvites(community, before); if (read !== reads.current) return; - setInvites((shown) => - before ? [...(shown ?? []), ...page.invites] : page.invites, - ); - setNext(page.next_before); + setList((shown) => { + if (before) + return { + invites: [...(shown?.invites ?? []), ...page.invites], + next: page.next_before, + }; + // A refresh replaces the first page and keeps any older pages shown. + const last = page.invites.at(-1); + const older = + page.next_before && last + ? (shown?.invites ?? []).filter((invite) => newer(last, invite)) + : []; + return { + invites: [...page.invites, ...older], + next: older.length ? (shown?.next ?? null) : page.next_before, + }; + }); } catch (reason) { if (read === reads.current) setError(message(reason)); } finally { @@ -85,37 +111,63 @@ export function InviteLinks({ [community], ); useEffect(() => { - void load(); - return () => { + if (visible) void load(); + }, [load, visible]); + useEffect( + () => () => { ++reads.current; - }; - }, [load]); + }, + [], + ); + // Leaving the tab drops an unsent confirmation, as Members does. + useEffect(() => { + if (!visible && !revoking) { + setPending(null); + setRevokeError(""); + } + }, [visible, revoking]); 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); - setError(""); + setRevokeError(""); setNotice(""); try { - await revokeInvite( + 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(""); + setPending(null); setNotice("Invite link revoked. People who already joined stay in."); - await load(); } catch (reason) { - setError(message(reason)); + // The outcome may be unknown after a timeout; Refresh shows what the relay holds. + setRevokeError(message(reason)); } finally { setRevoking(false); - setPending(null); } } + const shown = list?.invites.map((invite) => + revoked[invite.id] === undefined + ? invite + : { + ...invite, + revoked_at: revoked[invite.id] ?? null, + status: "revoked" as const, + }, + ); + return (
-

Invite links

- {invites === null ? ( +
+

Invite links

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

Loading invite links…

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

No invite links yet.

) : (
    - {invites.map((invite) => { + {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 ( @@ -205,13 +268,13 @@ export function InviteLinks({ })}
)} - {next && ( + {list?.next && (
@@ -220,16 +283,9 @@ export function InviteLinks({
{error && ( -
-

- {error} -

- {invites === null && ( - - )} -
+

+ {error} +

)} {notice && (

@@ -237,15 +293,15 @@ export function InviteLinks({

)}
- {pending && ( + {pending && visible && ( setPending(null)} + onClose={close} actions={ <> - } - /> + > + {revokeError && ( +

+ {revokeError} +

+ )} +
)}
); diff --git a/src/bundled/moderation/api.ts b/src/bundled/moderation/api.ts index 448da7cdec..be31fe44da 100644 --- a/src/bundled/moderation/api.ts +++ b/src/bundled/moderation/api.ts @@ -28,7 +28,7 @@ export type InviteSummary = { id: string; created_by: string; created_at: number; - expires_at: number; + expires_at: number | null; max_uses: number | null; use_count: number; revoked_at: number | null; From 3b8e6440821cd05ff47d6fc025d1cc3dd08356ab Mon Sep 17 00:00:00 2001 From: Will Pfleger Date: Fri, 20 Nov 2026 16:12:45 -0500 Subject: [PATCH 06/10] fix(moderation): readable revoke refusals and focus after a row revoke Map the relay's revoke refusal codes to plain messages in the confirmation, move focus to the invite list once a revoked row loses its Revoke button, and assert the paging cursor. Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Signed-off-by: Will Pfleger --- .../moderation/CommunityAdmin.test.tsx | 13 +++++++-- src/bundled/moderation/InviteLinks.tsx | 28 +++++++++++++++++-- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/src/bundled/moderation/CommunityAdmin.test.tsx b/src/bundled/moderation/CommunityAdmin.test.tsx index 4e2fcf34b2..6fcc27bbe1 100644 --- a/src/bundled/moderation/CommunityAdmin.test.tsx +++ b/src/bundled/moderation/CommunityAdmin.test.tsx @@ -813,7 +813,7 @@ const unavailable = () => it("shows a revoke from its receipt and keeps older pages on refresh", async () => { const user = userEvent.setup(); let reads = 0; - broker({ + const calls = broker({ invites: (body) => { reads++; if ((body as { before?: string }).before) @@ -836,6 +836,11 @@ it("shows a revoke from its receipt and keeps older pages on refresh", async () 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), ); @@ -851,6 +856,7 @@ it("shows a revoke from its receipt and keeps older pages on refresh", async () }), ); 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(); @@ -912,7 +918,7 @@ it("keeps the confirmation open with a retry when revoke fails", async () => { invites: () => Response.json({ invites: [link(1)], next_before: null }), "invite-revoke": () => ++attempts === 1 - ? unavailable() + ? Response.json({ error: "invite_not_found" }, { status: 404 }) : Response.json({ id: linkId(1), revoked_at: 1700000100 }), }); const { relay: data } = relay(owner); @@ -923,8 +929,9 @@ it("keeps the confirmation open with a retry when revoke fails", async () => { const dialog = await screen.findByRole("alertdialog"); await user.click(within(dialog).getByRole("button", { name: "Revoke" })); expect(await within(dialog).findByRole("alert")).toHaveTextContent( - "community writes are temporarily unavailable", + "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()); diff --git a/src/bundled/moderation/InviteLinks.tsx b/src/bundled/moderation/InviteLinks.tsx index a6ef95544b..ec223c180a 100644 --- a/src/bundled/moderation/InviteLinks.tsx +++ b/src/bundled/moderation/InviteLinks.tsx @@ -13,6 +13,18 @@ import styles from "./CommunityAdmin.module.css"; const message = (reason: unknown) => 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", @@ -76,6 +88,12 @@ export function InviteLinks({ // Confirmed revocations by id; they win over any list read that raced them. const [revoked, setRevoked] = useState>({}); const reads = 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) => { @@ -148,11 +166,12 @@ export function InviteLinks({ ); 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(message(reason)); + setRevokeError(revokeMessage(reason) ?? ""); } finally { setRevoking(false); } @@ -239,7 +258,12 @@ export function InviteLinks({ 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)}`; From b9c3cfaff3b71494785e7c052e7aa7e1201d109e Mon Sep 17 00:00:00 2001 From: Will Pfleger Date: Fri, 20 Nov 2026 16:28:57 -0500 Subject: [PATCH 07/10] fix(moderation): refresh re-reads every loaded invite page Refresh walks the relay's cursors over as many pages as are shown and replaces the list only when every read succeeds, instead of merging page one into older pages by whole-second timestamps. Rows are deduplicated by id and confirmed revoke receipts still win over stale reads. Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Signed-off-by: Will Pfleger --- .../moderation/CommunityAdmin.test.tsx | 128 ++++++++++++++++++ src/bundled/moderation/InviteLinks.tsx | 42 +++--- 2 files changed, 149 insertions(+), 21 deletions(-) diff --git a/src/bundled/moderation/CommunityAdmin.test.tsx b/src/bundled/moderation/CommunityAdmin.test.tsx index 6fcc27bbe1..1c6bb651a6 100644 --- a/src/bundled/moderation/CommunityAdmin.test.tsx +++ b/src/bundled/moderation/CommunityAdmin.test.tsx @@ -959,3 +959,131 @@ it("shows a listed link without an expiry as never expiring", async () => { 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"); +}); diff --git a/src/bundled/moderation/InviteLinks.tsx b/src/bundled/moderation/InviteLinks.tsx index ec223c180a..21f99ccbc7 100644 --- a/src/bundled/moderation/InviteLinks.tsx +++ b/src/bundled/moderation/InviteLinks.tsx @@ -53,10 +53,6 @@ const uses = (invite: InviteSummary) => ? `${invite.use_count} ${invite.use_count === 1 ? "use" : "uses"}` : `${invite.use_count} of ${invite.max_uses} uses`; -/** Whether `a` sorts before `b` in the relay's newest-first order. */ -const newer = (a: InviteSummary, b: InviteSummary) => - a.created_at !== b.created_at ? a.created_at > b.created_at : a.id > b.id; - /** The community's invite links, with revoking by row or by pasted link. */ export function InviteLinks({ community, @@ -88,6 +84,8 @@ export function InviteLinks({ // 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); @@ -101,24 +99,26 @@ export function InviteLinks({ setLoading(true); setError(""); try { - const page = await listInvites(community, before); - if (read !== reads.current) return; + // 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) => { - if (before) - return { - invites: [...(shown?.invites ?? []), ...page.invites], - next: page.next_before, - }; - // A refresh replaces the first page and keeps any older pages shown. - const last = page.invites.at(-1); - const older = - page.next_before && last - ? (shown?.invites ?? []).filter((invite) => newer(last, invite)) - : []; - return { - invites: [...page.invites, ...older], - next: older.length ? (shown?.next ?? null) : page.next_before, - }; + 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)); From 6dfe731c12993e92fbf36f1fc9becbbd92be56e7 Mon Sep 17 00:00:00 2001 From: Will Pfleger Date: Fri, 20 Nov 2026 16:39:49 -0500 Subject: [PATCH 08/10] fix(moderation): keep a sent revoke's failure while Links is hidden Leaving the Links tab now drops only a confirmation that was never sent, so a revoke that fails while Members is shown still shows its error and Retry on return. Tests cover the hidden panel, a dismissed unsent confirmation, and a failure that arrives while hidden. Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Signed-off-by: Will Pfleger --- .../moderation/CommunityAdmin.test.tsx | 71 +++++++++++++++++++ src/bundled/moderation/InviteLinks.tsx | 10 ++- 2 files changed, 75 insertions(+), 6 deletions(-) diff --git a/src/bundled/moderation/CommunityAdmin.test.tsx b/src/bundled/moderation/CommunityAdmin.test.tsx index 1c6bb651a6..f0efa713f7 100644 --- a/src/bundled/moderation/CommunityAdmin.test.tsx +++ b/src/bundled/moderation/CommunityAdmin.test.tsx @@ -1087,3 +1087,74 @@ it("ignores an older list response that arrives after a newer one", async () => 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"); +}); diff --git a/src/bundled/moderation/InviteLinks.tsx b/src/bundled/moderation/InviteLinks.tsx index 21f99ccbc7..7862464454 100644 --- a/src/bundled/moderation/InviteLinks.tsx +++ b/src/bundled/moderation/InviteLinks.tsx @@ -137,13 +137,11 @@ export function InviteLinks({ }, [], ); - // Leaving the tab drops an unsent confirmation, as Members does. + // Leaving the tab drops an unsent confirmation, as Members does; a sent + // attempt stays, so its failure shows on return. useEffect(() => { - if (!visible && !revoking) { - setPending(null); - setRevokeError(""); - } - }, [visible, revoking]); + if (!visible && !revoking && !revokeError) setPending(null); + }, [visible, revoking, revokeError]); const pastedCode = pasted.trim() ? pastedInviteCode(community, pasted) : null; const pastedError = From c782aa29e7be9a02cac8b883e82ec5d885940236 Mon Sep 17 00:00:00 2001 From: Will Pfleger Date: Fri, 20 Nov 2026 16:39:51 -0500 Subject: [PATCH 09/10] fix(moderation): keep focus on the revoke action through a failure The confirm action is no longer disabled while loading; loading alone blocks a second submit and keeps it focusable, so Enter can retry after a refusal. Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Signed-off-by: Will Pfleger --- .../moderation/CommunityAdmin.test.tsx | 32 +++++++++++++++++++ src/bundled/moderation/InviteLinks.tsx | 3 +- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/bundled/moderation/CommunityAdmin.test.tsx b/src/bundled/moderation/CommunityAdmin.test.tsx index f0efa713f7..8fbc83cf9e 100644 --- a/src/bundled/moderation/CommunityAdmin.test.tsx +++ b/src/bundled/moderation/CommunityAdmin.test.tsx @@ -1158,3 +1158,35 @@ it("shows a revoke failure that arrived while Links was hidden", async () => { 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; + }); + 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}"); + // 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/InviteLinks.tsx b/src/bundled/moderation/InviteLinks.tsx index 7862464454..4d50ad1159 100644 --- a/src/bundled/moderation/InviteLinks.tsx +++ b/src/bundled/moderation/InviteLinks.tsx @@ -329,7 +329,8 @@ export function InviteLinks({