diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 5ef2d6ea78..b86c5e31cf 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -83,7 +83,8 @@ if that desktop app is up and running. identity. Never paste a private key into a chat. - **More communities.** Use **Join a community** in the community picker with an invite link or address. To bring people in, use **Invite to community** there - or in **Membership**. + or in **Membership**. An invite's expiry can be **Never expires** on relays + that support it. - **Phone.** **Settings → Mobile app** signs the phone in with the same account, or pairs it with a QR code. diff --git a/src/bundled/moderation/CommunityAdmin.test.tsx b/src/bundled/moderation/CommunityAdmin.test.tsx index 0fef04afb4..b82baaf212 100644 --- a/src/bundled/moderation/CommunityAdmin.test.tsx +++ b/src/bundled/moderation/CommunityAdmin.test.tsx @@ -708,6 +708,141 @@ it("ignores a late mint from a previous Invite visit", async () => { ).toBeNull(); }); +const permanentInvite = (code: string, expires_at: number | null = null) => + Response.json({ + invite_id: "0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f", + code, + url: `https://primary.example/invite/${code}`, + expires_at, + max_uses: null, + uses_remaining: null, + }); + +async function chooseNever(user: ReturnType) { + await user.click( + screen.getByRole("button", { name: "Choose invite expiry" }), + ); + await user.click( + await screen.findByRole("menuitemradio", { name: "Never expires" }), + ); +} + +it("mints a link that never expires only when the admin creates it", async () => { + const user = userEvent.setup(); + let count = 0; + const calls = broker({ + invite: () => permanentInvite(String(++count), count === 1 ? 1 : null), + }); + const mints = () => calls.filter((c) => c.route === "invite"); + const { relay: data } = relay(owner); + render( true} />); + await user.click(await screen.findByRole("tab", { name: "Invite" })); + await screen.findByDisplayValue("https://primary.example/invite/1"); + await chooseNever(user); + const create = await screen.findByRole("button", { name: "Create link" }); + expect(mints()).toHaveLength(1); + await user.click(create); + await screen.findByDisplayValue("https://primary.example/invite/2"); + expect(mints().at(-1)?.body).toEqual({ never_expires: true, max_uses: null }); + expect(screen.queryByRole("button", { name: "Create link" })).toBeNull(); +}); + +it("asks again instead of minting when Never settings change or the tab returns", async () => { + const user = userEvent.setup(); + let count = 0; + const calls = broker({ invite: () => permanentInvite(String(++count)) }); + const mints = () => calls.filter((c) => c.route === "invite"); + const { relay: data } = relay(owner); + const view = render( + true} selectedMethod="invite" />, + ); + await screen.findByDisplayValue("https://primary.example/invite/1"); + await chooseNever(user); + await user.click(await screen.findByRole("button", { name: "Create link" })); + await screen.findByDisplayValue("https://primary.example/invite/2"); + await user.click( + screen.getByRole("button", { name: "Choose maximum invite uses" }), + ); + await user.click( + await screen.findByRole("menuitemradio", { name: /^1 use$/ }), + ); + expect( + await screen.findByRole("button", { name: "Create link" }), + ).toBeVisible(); + view.rerender( + true} + selectedMethod="members" + />, + ); + view.rerender( + true} selectedMethod="invite" />, + ); + expect( + await screen.findByRole("button", { name: "Create link" }), + ).toBeVisible(); + expect(mints()).toHaveLength(2); + expect(screen.queryByDisplayValue(/invite\/2$/)).toBeNull(); +}); + +it("drops a permanent link that resolves after its settings changed", async () => { + const user = userEvent.setup(); + let finish!: (response: Response) => void; + const held = new Promise((resolve) => { + finish = resolve; + }); + let count = 0; + const calls = broker({ + invite: () => (++count === 2 ? held : permanentInvite(String(count))), + }); + const mints = () => calls.filter((c) => c.route === "invite"); + const { relay: data } = relay(owner); + render( + true} selectedMethod="invite" />, + ); + await screen.findByDisplayValue("https://primary.example/invite/1"); + await chooseNever(user); + await user.click(await screen.findByRole("button", { name: "Create link" })); + await waitFor(() => expect(mints()).toHaveLength(2)); + await user.click( + screen.getByRole("button", { name: "Choose maximum invite uses" }), + ); + await user.click( + await screen.findByRole("menuitemradio", { name: /^1 use$/ }), + ); + await act(async () => { + finish(permanentInvite("old")); + await held; + }); + expect(screen.getByRole("button", { name: "Create link" })).toBeVisible(); + expect(screen.queryByDisplayValue(/invite\/old$/)).toBeNull(); + expect(mints()).toHaveLength(2); +}); + +it("withholds a finite link a relay returns for a Never request", async () => { + const user = userEvent.setup(); + let count = 0; + broker({ + invite: () => permanentInvite(String(++count), 1700003600), + }); + const { relay: data } = relay(owner); + render( + true} selectedMethod="invite" />, + ); + await screen.findByDisplayValue("https://primary.example/invite/1"); + await chooseNever(user); + await user.click(await screen.findByRole("button", { name: "Create link" })); + expect(await screen.findByRole("status")).toHaveTextContent( + "This relay can’t make permanent links yet. Choose an expiry instead.", + ); + expect( + screen.getByRole("textbox", { name: "Community invite link" }), + ).toHaveValue(""); + expect(screen.queryByDisplayValue(/invite\/2$/)).toBeNull(); + expect(screen.getByRole("button", { name: "Copy link" })).toBeDisabled(); +}); + 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"; @@ -720,7 +855,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: 4102444800, + expires_at: null, max_uses: null, use_count: 2, revoked_at: revoked ? 1700000100 : null, @@ -751,7 +886,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 · Expires"); + 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({}); @@ -765,7 +900,7 @@ it("lists invite links and revokes one by row or by pasted link", async () => { }), ); await waitFor(() => - expect(list).toHaveTextContent("Revoked · 2 uses · Expires"), + expect(list).toHaveTextContent("Revoked · 2 uses · Never 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 8c4bb2cce1..aacf5bb7e9 100644 --- a/src/bundled/moderation/CommunityAdmin.tsx +++ b/src/bundled/moderation/CommunityAdmin.tsx @@ -1,4 +1,5 @@ import { + useCallback, useEffect, useRef, useState, @@ -70,10 +71,14 @@ 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) => ({ @@ -572,40 +577,45 @@ function MembershipContent({ variant: QrVariant; svg?: string; } | null>(null); - // One minted link per settings; a missing entry for these settings mints. + // One minted link per settings. A missing entry mints automatically for an + // expiring link; a permanent link waits for the admin to create it. const settings = `${ttl}:${uses}`; + const never = ttl === NEVER; const [link, setLink] = useState<{ settings: string; url?: string; failed?: boolean; + unsupported?: boolean; } | null>(null); + // Generation counter: a completion from an older request is ignored. const minting = useRef(0); // StrictMode replays effects; never mint twice for the same settings. const requested = useRef(""); const current = link?.settings === settings ? link : null; const locked = stale || refreshing; - useEffect(() => { - if (open) return; - // A new visit needs a fresh link: the previous one may be exhausted. - ++minting.current; - requested.current = ""; - setLink(null); - setQr(null); - setCopied(false); - setError(""); - }, [open]); - useEffect(() => { - // Visiting a sharing tab, or changing its settings, creates the link to share. - if (!open || locked || current || requested.current === settings) return; - if (!active()) return; + const pending = current + ? !current.url && !current.failed && !current.unsupported + : !locked && !never; + const mint = useCallback(() => { + if (!active() || locked) return; requested.current = settings; const request = ++minting.current; setLink({ settings }); setCopied(false); setError(""); - mintInvite(community, Number(ttl), uses ? Number(uses) : null).then( + mintInvite( + community, + never ? null : Number(ttl), + uses ? Number(uses) : null, + ).then( (invite) => { - if (minting.current === request) setLink({ settings, url: invite.url }); + if (minting.current !== request) return; + // An older relay ignores never_expires and returns a finite link. + setLink( + never && invite.expires_at !== null + ? { settings, unsupported: true } + : { settings, url: invite.url }, + ); }, (reason) => { if (minting.current !== request) return; @@ -614,16 +624,42 @@ function MembershipContent({ setError(message(reason)); }, ); - }, [open, locked, current, active, community, settings, ttl, uses]); + }, [active, locked, community, settings, never, ttl, uses]); + // New settings discard the previous link and any request still in flight. + function choose(set: (value: string) => void) { + return (value: string) => { + ++minting.current; + requested.current = ""; + setLink(null); + setCopied(false); + set(value); + }; + } + useEffect(() => { + if (open) return; + // A new visit needs a fresh link: the previous one may be exhausted. + ++minting.current; + requested.current = ""; + setLink(null); + setQr(null); + setCopied(false); + setError(""); + }, [open]); + useEffect(() => { + // Visiting a sharing tab, or changing its settings, creates the link to + // share, unless it would never expire. + if (!open || never || current || requested.current === settings) return; + mint(); + }, [open, never, current, settings, mint]); useEffect(() => { if (!copied) return; const timer = setTimeout(() => setCopied(false), 2000); return () => clearTimeout(timer); }, [copied]); const url = current?.url; - // New settings have no link until the effect mints one; count them as - // pending so the code's place never collapses, which scrolled the dialog. - const pending = current ? !url && !current.failed : !locked; + // New expiring settings have no link until the effect mints one; pending + // holds the code's place so it never collapses, which scrolled the dialog. + const idle = never && !current; const variant = useQrVariant(); const drawn = url && qr?.url === url && qr.variant === variant ? qr : null; const showQr = @@ -727,6 +763,13 @@ function MembershipContent({ aria-labelledby="invite-share-panel-tab" >
+ {idle && ( +
+ +
+ )} {showQr && (
{drawn?.svg ? ( @@ -785,7 +828,7 @@ function MembershipContent({ }} onClick={() => { if (current?.failed) { - setLink(null); + mint(); return; } if (!url) return; @@ -805,12 +848,22 @@ function MembershipContent({ readOnly value={url ?? ""} placeholder={ - current?.failed - ? "Couldn’t create invite link" - : "Creating invite link…" + current?.unsupported + ? "No link created" + : current?.failed + ? "Couldn’t create invite link" + : idle + ? "Create a link that never expires" + : "Creating invite link…" } /> + {current?.unsupported && ( +

+ This relay can’t make permanent links yet. Choose an expiry + instead. +

+ )}
Expires after @@ -818,7 +871,7 @@ function MembershipContent({ label="Choose invite expiry" value={ttl} options={EXPIRY} - onChange={setTtl} + onChange={choose(setTtl)} // Stays usable while a link is made, so the closing menu can // return focus to it; the newest choice's link wins. disabled={locked} @@ -830,7 +883,7 @@ function MembershipContent({ label="Choose maximum invite uses" value={uses} options={USES} - onChange={setUses} + onChange={choose(setUses)} disabled={locked} />
diff --git a/src/bundled/moderation/api.ts b/src/bundled/moderation/api.ts index be31fe44da..b336f96752 100644 --- a/src/bundled/moderation/api.ts +++ b/src/bundled/moderation/api.ts @@ -19,7 +19,8 @@ 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; }; @@ -55,11 +56,19 @@ 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) => diff --git a/src/features/communities/admin-protocol.test.ts b/src/features/communities/admin-protocol.test.ts index 4a69bc2e81..9b3c7cf53b 100644 --- a/src/features/communities/admin-protocol.test.ts +++ b/src/features/communities/admin-protocol.test.ts @@ -1,8 +1,31 @@ import { expect, it } from "vitest"; -import { adminReason, inviteListPath, revokeRequest } from "./admin-protocol"; +import { + adminReason, + 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( diff --git a/src/features/communities/admin-protocol.ts b/src/features/communities/admin-protocol.ts index 6ece5b877f..102a70b8ee 100644 --- a/src/features/communities/admin-protocol.ts +++ b/src/features/communities/admin-protocol.ts @@ -10,15 +10,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 ( @@ -29,7 +37,9 @@ 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. */