From 5222a8ebef942fc1370cd5aa3b7308ab75936726 Mon Sep 17 00:00:00 2001 From: morgmart <98432065+morgmart@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:50:47 -0800 Subject: [PATCH] feat(tasks): ask the relay who can see a place, not member lists The relay's `buzz-channel-readers` answer (block/buzz#9603) now decides who can see a task's place, in the assignee picker, the move preview, the lost-access note on a task and the agent tools. Member lists only supply names for the picker to ask about. When there is no answer (an older relay, a refusal or a failure), the app doesn't know: it flags and unassigns nobody, the picker offers everyone it can list, and the relay's own check refuses a bad save by name. - The lost-access note returns: "Riley can't see this task anymore.", with "Unassign Riley" or "Unassign all" for someone who can edit. - The question is asked as the owner, who signs the save, in pages of 100; any page that fails makes the whole answer unknown. Co-authored-by: Carl Co-Authored-By: Claude Opus 5.5 Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com> --- src/bundled/tasks/TaskView.test.tsx | 149 ++++++++++++++++++++- src/bundled/tasks/TaskView.tsx | 116 +++++++++++++--- src/bundled/tasks/places.ts | 43 ++++-- src/bundled/tasks/tools.test.ts | 58 +++++++- src/bundled/tasks/tools.ts | 21 ++- src/features/relay/channel-readers.test.ts | 113 ++++++++++++++++ src/features/relay/channel-readers.ts | 116 ++++++++++++++++ src/features/relay/native.ts | 16 +++ src/features/relay/session.ts | 3 + src/features/relay/transport.ts | 4 + 10 files changed, 590 insertions(+), 49 deletions(-) create mode 100644 src/features/relay/channel-readers.test.ts create mode 100644 src/features/relay/channel-readers.ts diff --git a/src/bundled/tasks/TaskView.test.tsx b/src/bundled/tasks/TaskView.test.tsx index e645d10ded..2a0205346f 100644 --- a/src/bundled/tasks/TaskView.test.tsx +++ b/src/bundled/tasks/TaskView.test.tsx @@ -35,6 +35,10 @@ const theirs = revision("c".repeat(64), "Their title"); const project = "33333333-3333-4333-8333-333333333333"; const launch = "44444444-4444-4444-8444-444444444444"; const leo = "c".repeat(64); +const riley = "9".repeat(64); +/** The relay's answer for `home`: Leo can see it, Riley can't. */ +const relayReaders = async (_channel: string, pubkeys: readonly string[]) => + new Map(pubkeys.map((key) => [key, key !== riley])); const dm = "55555555-5555-4555-8555-555555555555"; type Answer = ChannelReachState; @@ -50,13 +54,17 @@ const opened = (post: boolean): Answer => ({ function setup( publish: () => Promise, answers: Record = { [home]: opened(true) }, + readers: RelaySession["channelReaders"] = relayReaders, ) { const signed: { tags: string[][] }[] = []; const channels: ChannelSummary[] = [ { id: home, name: "design", channelType: "stream", viewerRole: "member" }, { id: launch, name: "launch", channelType: "stream", readOnly: true }, ]; - const profiles = new Map([[leo, { name: "Leo" }]]); + const profiles = new Map([ + [leo, { name: "Leo" }], + [riley, { name: "Riley" }], + ]); const list = { status: "ready", channels }; const metadata = (d: string, name: string, extra: string[][] = []) => ({ id: d.slice(0, 8).padEnd(64, "0"), @@ -115,6 +123,7 @@ function setup( ["d", home], ["p", viewer], ["p", leo], + ["p", riley], ], }, ].filter((event) => @@ -125,6 +134,7 @@ function setup( ? [theirs] : []; }), + channelReaders: readers, configArtifactWriter: { sign: vi.fn(async (template: { tags: string[][] }) => { signed.push(template); @@ -300,3 +310,140 @@ it("starts a new task from a DM with no place, and won't create until one is pic fireEvent.click(create); expect(signed).toHaveLength(0); }); + +const assignedTo = (...people: string[]) => + taskOf({ + ...revision("d".repeat(64), "Fix the header"), + tags: [ + ...revision("d".repeat(64), "Fix the header").tags, + ...people.map((key) => ["assignee", key]), + ], + }) as Task; + +it("names someone the relay says lost access, and unassigns only them", async () => { + const { session, signed } = setup(async () => ""); + const onSaved = vi.fn(); + render( + {}} + onSaved={onSaved} + />, + ); + expect( + await screen.findByText("Riley can’t see this task anymore."), + ).toBeInTheDocument(); + expect(screen.queryByText(/Leo can’t see/)).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Unassign Riley" })); + await vi.waitFor(() => expect(onSaved).toHaveBeenCalled()); + const tags = signed[0]?.tags ?? []; + expect(tags.filter(([name]) => name === "assignee")).toEqual([ + ["assignee", leo], + ]); +}); + +it("offers to unassign several who lost access all at once", async () => { + const { session } = setup( + async () => "", + undefined, + async (_, pubkeys) => new Map(pubkeys.map((key) => [key, false])), + ); + render( + {}} + onSaved={() => {}} + />, + ); + expect( + await screen.findByText("Leo and Riley can’t see this task anymore."), + ).toBeInTheDocument(); + expect( + screen.getByRole("button", { name: "Unassign all" }), + ).toBeInTheDocument(); +}); + +it("names someone who lost access to a view-only reader, with no way to unassign", async () => { + const { session } = setup(async () => "", { [home]: opened(false) }); + render( + {}} + onSaved={() => {}} + />, + ); + expect( + await screen.findByText("Riley can’t see this task anymore."), + ).toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: /Unassign/ }), + ).not.toBeInTheDocument(); +}); + +it("offers only people the relay says can see the task", async () => { + const { session } = setup(async () => ""); + render( + {}} + onSaved={() => {}} + />, + ); + fireEvent.click(await screen.findByRole("combobox", { name: "Assignees" })); + expect(await screen.findByRole("option", { name: /Leo/ })).toBeVisible(); + expect(screen.queryByRole("option", { name: /Riley/ })).toBeNull(); +}); + +it("says nothing about access, and offers everyone, when the relay can't say", async () => { + const { session } = setup( + async () => "", + undefined, + async () => { + throw new Error("not-allowed"); + }, + ); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + render( + {}} + onSaved={() => {}} + />, + ); + fireEvent.click(await screen.findByRole("combobox", { name: "Assignees" })); + expect(await screen.findByRole("option", { name: /Leo/ })).toBeVisible(); + expect(screen.queryByText(/can’t see/)).toBeNull(); + warn.mockRestore(); +}); + +it("unassigns on a move only those the relay says can't see the destination", async () => { + const { session, signed } = setup(async () => "", { + [home]: opened(true), + [launch]: opened(true), + }); + const onSaved = vi.fn(); + render( + {}} + onSaved={onSaved} + />, + ); + fireEvent.click(await screen.findByRole("button", { name: "Move…" })); + fireEvent.click(await screen.findByRole("combobox", { name: "Move to" })); + fireEvent.click(await screen.findByRole("option", { name: /launch/ })); + expect( + await screen.findByText(/Riley can’t see #launch and will be unassigned/), + ).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Move" })); + await vi.waitFor(() => expect(signed).toHaveLength(1)); + expect( + (signed[0]?.tags ?? []).filter(([name]) => name === "assignee"), + ).toEqual([["assignee", leo]]); +}); diff --git a/src/bundled/tasks/TaskView.tsx b/src/bundled/tasks/TaskView.tsx index 25338d97b8..c46b69dfbf 100644 --- a/src/bundled/tasks/TaskView.tsx +++ b/src/bundled/tasks/TaskView.tsx @@ -63,7 +63,8 @@ import { type Place, placeLabel, projectOf, - readReaders, + readMembers, + whoCanRead, } from "./places"; import { usePlaceAccess, usePlaces, useTaskPlaces } from "./react"; import { saveTask, type SaveTarget } from "./store"; @@ -161,6 +162,7 @@ function TaskDetails({ const places = usePlaces(session, [task.home]); const project = projectOf(task, places); const home = places.get(task.home); + const lostRead = useWhoCanRead(session, task.home, task.assignees); // Immediate changes: status and assignees, on the revision shown. const change = async (next: Partial) => { if (saving) return; @@ -265,6 +267,18 @@ function TaskDetails({ )} + + void change({ + assignees: task.assignees.filter((key) => !lost.includes(key)), + }), + })} + /> {task.description.trim() ? ( >; +/** Assignees the relay says can't see the task anymore, and to someone who + * can edit, a way to unassign them. Never why, and nothing when the relay + * can't say. */ +function LostAccess({ + session, + assignees, + read, + disabled, + unassign, +}: { + session: RelaySession; + assignees: readonly string[]; + read: ReadonlyMap | null | undefined; + disabled: boolean; + unassign?: (lost: readonly string[]) => void; +}) { + const person = usePeople(session, assignees); + const lost = assignees.filter((key) => read?.get(key) === false); + if (!lost.length) return null; + const names = listNames(lost.map((key) => person(key).name)); + return ( +
+

+ {names} can’t see this task anymore. +

+ {unassign ? ( + + ) : null} +
+ ); +} + /** Up to four people, chosen from the people who can see the task. Agents * are never offered: a person always answers for the work. */ function AssigneePicker({ @@ -393,12 +441,21 @@ function AssigneePicker({ disabled: boolean; onChange(assignees: readonly string[]): void; }) { - // Its members and those of the places it is filed under. An open place - // has more readers than these; the relay checks every assignee either way. - const readers = useReadersOf(session, home); + // The members the viewer can see here and where it is filed, less anyone + // the relay says can't see it. When it can't say, all of them: the relay + // refuses a bad save by name. + const members = useMembersOf(session, home); + const candidates = useMemo( + () => [...(members ?? [])].filter((key) => !assignees.includes(key)), + [members, assignees], + ); + const read = useWhoCanRead(session, home, candidates); const pubkeys = useMemo( - () => [...new Set([...assignees, ...(readers?.people ?? [])])], - [assignees, readers], + () => [ + ...assignees, + ...candidates.filter((key) => read?.get(key) !== false), + ], + [assignees, candidates, read], ); const person = usePeople(session, pubkeys); const [search, setSearch] = useState(""); @@ -727,14 +784,12 @@ function MoveTask({ const change = to ? accessChange(task.home, to, named) : undefined; const destination = to && named.get(to); const label = destination ? placeLabel(destination, named) : "that place"; - const readers = useReadersOf(session, to); + // Only those the relay says can't see it; when it can't say, nobody. + const read = useWhoCanRead(session, to, task.assignees); const person = usePeople(session, task.assignees); - const dropped = - readers && !readers.anyone - ? task.assignees.filter((pubkey) => !readers.people.has(pubkey)) - : []; + const dropped = task.assignees.filter((key) => read?.get(key) === false); const problem = to ? placeProblem(target.access, label) : ""; - const ready = !!to && problem === undefined && !!readers; + const ready = !!to && problem === undefined && read !== undefined; const move = async () => { if (!to || !ready) return; setPending(true); @@ -838,21 +893,42 @@ const placeList = ( const listNames = (names: readonly string[]) => new Intl.ListFormat("en", { type: "conjunction" }).format(names); -/** Who can see what lives in `home`; undefined until read, or with no home. */ -function useReadersOf(session: RelaySession, home: string | undefined) { - const [readers, setReaders] = - useState>>(); +/** People to offer for a task in `home`, from the member lists the viewer + * can read; undefined until read, or with no home. */ +function useMembersOf(session: RelaySession, home: string | undefined) { + const [members, setMembers] = useState>(); useEffect(() => { - setReaders(undefined); + setMembers(undefined); if (!home) return; const controller = new AbortController(); - readReaders(session, home, controller.signal).then( - (read) => !controller.signal.aborted && setReaders(read), + readMembers(session, home, controller.signal).then( + (read) => !controller.signal.aborted && setMembers(read), () => {}, ); return () => controller.abort(); }, [session, home]); - return readers; + return members; +} + +/** The relay's answer to which of `pubkeys` can see `place`: undefined while + * asking, null when it can't say, so nobody is flagged or unassigned. */ +function useWhoCanRead( + session: RelaySession, + place: string | undefined, + pubkeys: readonly string[], +) { + const [read, setRead] = useState | null>(); + const key = pubkeys.join(","); + useEffect(() => { + setRead(undefined); + if (!place) return; + const controller = new AbortController(); + whoCanRead(session, place, key ? key.split(",") : [], controller.signal) + .then((answer) => !controller.signal.aborted && setRead(answer ?? null)) + .catch(() => {}); + return () => controller.abort(); + }, [session, place, key]); + return read; } function TaskEditor({ diff --git a/src/bundled/tasks/places.ts b/src/bundled/tasks/places.ts index 7390ba477c..5bccb4d463 100644 --- a/src/bundled/tasks/places.ts +++ b/src/bundled/tasks/places.ts @@ -18,8 +18,6 @@ export type Place = Readonly<{ kind: "chat" | "channel"; /** The channel it is filed under (NIP-29 `parent`), if any. */ parent?: string | undefined; - /** Open to everyone in the community. */ - open?: true | undefined; /** What it takes from the places above it (`parent_access`): `guest` * lets their people read but not post, `none` shuts them out. */ parentAccess?: "guest" | "none" | undefined; @@ -73,7 +71,6 @@ function placeOf(event: RelayEvent): Place | undefined { ? { archived: true as const } : {}), ...(isChannelId(parent) ? { parent } : {}), - ...(channelVisibility(event) === "public" ? { open: true as const } : {}), ...parentAccessOf(event), }; } @@ -98,21 +95,19 @@ export function placeLabel( : `#${place.name}`; } -/** Who can see what lives in `home`: anyone, when a place it is seen from - * is open; otherwise the members of those places, from their relay-signed - * rosters. The relay refuses an assignee who can't. */ -export async function readReaders( +/** People to offer for a task in `home`: the members of it and of the + * places it is seen from, as far as the viewer can read their relay-signed + * rosters. A list of names only; who of them can see `home` is the relay's + * answer, from {@link whoCanRead}. */ +export async function readMembers( session: Pick, home: string, signal: AbortSignal, -): Promise }>> { +): Promise> { const read = session.snapshotRead; const author = session.relayAuthor; - if (!read || !author) return { anyone: false, people: new Set() }; - const places = await readPlaces(session, [home], signal); - const chain = seenFrom(home, places); - if (chain.some((id) => places.get(id)?.open)) - return { anyone: true, people: new Set() }; + if (!read || !author) return new Set(); + const chain = seenFrom(home, await readPlaces(session, [home], signal)); const rosters = await read( [{ kinds: [39002], authors: [author], "#d": chain, limit: chain.length }], { signal }, @@ -122,7 +117,27 @@ export async function readReaders( if (roster.pubkey === author && chain.includes(tag(roster, "d") ?? "")) for (const [name, value] of roster.tags) if (name === "p" && isPubkey(value)) people.add(value); - return { anyone: false, people }; + return people; +} + +/** The relay's answer to which of `pubkeys` can see `place`, or undefined + * when there is none: an older relay, a refusal or a failure. Undefined + * means the app doesn't know, so it flags and unassigns nobody, and the + * relay's own check catches a real problem at save time. */ +export async function whoCanRead( + session: Pick, + place: string, + pubkeys: readonly string[], + signal: AbortSignal, +): Promise | undefined> { + if (!pubkeys.length) return new Map(); + try { + return await session.channelReaders?.(place, pubkeys, signal); + } catch (reason) { + signal.throwIfAborted(); + console.warn("Couldn’t ask the relay who can see a place:", reason); + return undefined; + } } /** The places named by `ids`, and the projects they are filed in. This diff --git a/src/bundled/tasks/tools.test.ts b/src/bundled/tasks/tools.test.ts index 101a87d418..57e1292169 100644 --- a/src/bundled/tasks/tools.test.ts +++ b/src/bundled/tasks/tools.test.ts @@ -99,6 +99,18 @@ function answer(events: Event[], filters: Filter[]) { }); } +/** Who the relay says can read each place: its own judgment, including + * project members let into a filed channel, never the rosters'. */ +const canRead: Record = { + [home]: [viewer, person], + [chat]: [viewer, person], + [secret]: [viewer], + [lobby]: [viewer, leo], + [project]: [viewer, leo], + [filed]: [viewer, leo], + [shut]: [viewer], +}; + type Signed = { kind: number; content: string; tags: string[][] }; /** The owner can read `heads` and every place; the agent can read every @@ -107,6 +119,10 @@ function setup( publish: () => Promise, heads: () => Event[], where = chat, + readers: RelaySession["channelReaders"] = async (channel, pubkeys) => + new Map( + pubkeys.map((key) => [key, canRead[channel]?.includes(key) ?? false]), + ), ) { const signed: Signed[] = []; const posted: Signed[] = []; @@ -152,6 +168,7 @@ function setup( snapshotRead: vi.fn(async (filters: Filter[]) => answer([...heads(), ...places()], filters), ), + channelReaders: readers, configArtifactWriter: { sign: vi.fn(async (template: Signed) => { signed.push(template); @@ -408,11 +425,13 @@ it("refuses an assignee who can't see the task", async () => { ); await expect( call("tasks_update", { id, assignees: [person, leo] }), - ).rejects.toThrow("Leo can't see this task"); + ).rejects.toThrow( + "Leo can't see #design, so they can't be assigned. Nothing changed.", + ); expect(signed).toHaveLength(0); }); -it("counts a project's people only where the channel lets them in", async () => { +it("goes by the relay's answer of who can see a place, not its member lists", async () => { const there = (home: string) => () => [head("d".repeat(64), [], { home })]; // Filed in the project as usual: Leo, only in the project, can see it. const open = setup(async () => "", there(filed)); @@ -422,10 +441,43 @@ it("counts a project's people only where the channel lets them in", async () => const closed = setup(async () => "", there(shut)); await expect( closed.call("tasks_update", { id, assignees: [leo] }), - ).rejects.toThrow("Leo can't see this task"); + ).rejects.toThrow("Leo can't see #payroll-review"); expect(closed.signed).toHaveLength(0); }); +it("keeps someone on a move when the relay says they can see the destination", async () => { + // Leo isn't on #billing's member list, but reads it through Payments. + const { call, signed } = setup( + async () => "", + () => [head("d".repeat(64), [["assignee", leo]], { home: lobby })], + ); + const preview = await call("tasks_update", { id, place: filed }); + expect(preview).not.toContain("unassigned"); + const confirm = /confirm "([^"]+)"/.exec(preview)?.[1]; + await call("tasks_update", { id, place: filed, confirm }); + expect(assignees(signed[0])).toEqual([leo]); +}); + +it("flags and unassigns nobody when the relay can't say who can see a place", async () => { + const unknown = async () => { + throw new Error("not-allowed"); + }; + const { call, signed } = setup( + async () => "", + () => [head("d".repeat(64), [["assignee", leo]], { home: filed })], + chat, + unknown, + ); + const preview = await call("tasks_update", { id, place: shut }); + expect(preview).not.toContain("Leo"); + const confirm = /confirm "([^"]+)"/.exec(preview)?.[1]; + await call("tasks_update", { id, place: shut, confirm }); + expect(assignees(signed[0])).toEqual([leo]); + // An edit isn't refused either; the relay's own check decides the save. + await call("tasks_update", { id, assignees: [leo, person] }); + expect(assignees(signed[1])).toEqual([leo, person]); +}); + it("names a project member a move shuts out", async () => { const { call, signed } = setup( async () => "", diff --git a/src/bundled/tasks/tools.ts b/src/bundled/tasks/tools.ts index dbcbd39256..7f386fd3b2 100644 --- a/src/bundled/tasks/tools.ts +++ b/src/bundled/tasks/tools.ts @@ -32,7 +32,7 @@ import { placeLabel, projectOf, readPlaces, - readReaders, + whoCanRead, } from "./places"; import { readTask, @@ -128,8 +128,9 @@ function assigneesArg(args: Args) { return [...new Set(list)]; } -/** Refuses anyone who isn't a known person able to see what lives in - * `home`, rather than guessing: an agent never answers for a task. */ +/** Refuses anyone who isn't a known person, or whom the relay says can't + * see what lives in `home`, rather than guessing: an agent never answers + * for a task. When the relay can't say, the save's own check decides. */ async function checkAssignees( session: RelaySession, reads: TaskSource, @@ -149,12 +150,11 @@ async function checkAssignees( if (profile.isAgent) throw new Error("Only people can be assigned, never agents"); } - const readers = await readReaders(reads, home, signal); - if (readers.anyone) return; - const blind = assignees.filter((pubkey) => !readers.people.has(pubkey)); + const read = await whoCanRead(session, home, assignees, signal); + const blind = assignees.filter((pubkey) => read?.get(pubkey) === false); if (blind.length) throw new Error( - `${blind.map((pubkey) => nameOf(session, pubkey)).join(", ")} can't see this task, so they can't be assigned`, + `${blind.map((pubkey) => nameOf(session, pubkey)).join(", ")} can't see ${labelOf(home, await readPlaces(reads, [home], signal))}, so they can't be assigned. Nothing changed.`, ); } @@ -644,10 +644,9 @@ export function addTaskTools(agents: Agents) { return `Moved.\n\n${describe(moved, session, places)}`; } const { gain, lose } = accessChange(task.home, to, places); - const readers = await readReaders(reads, to, signal); - const keep = readers.anyone - ? task.assignees - : task.assignees.filter((pubkey) => readers.people.has(pubkey)); + // Only those the relay says can't see it; when it can't say, nobody. + const read = await whoCanRead(session, to, task.assignees, signal); + const keep = task.assignees.filter((pubkey) => read?.get(pubkey) !== false); const dropped = task.assignees.filter((pubkey) => !keep.includes(pubkey)); for (const [key, value] of previews) if (value.expires < Date.now()) previews.delete(key); diff --git a/src/features/relay/channel-readers.test.ts b/src/features/relay/channel-readers.test.ts new file mode 100644 index 0000000000..103749eb1a --- /dev/null +++ b/src/features/relay/channel-readers.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, it, vi } from "vitest"; +import { + channelReadersCapability, + channelReadersRequest, + createChannelReadersReader, + parseChannelReaders, +} from "./channel-readers"; +import { ReadError } from "./errors"; + +const channel = "00000000-0000-8000-8000-00000000000a"; +const a = "a".repeat(64); +const b = "b".repeat(64); +const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status }); + +describe("channel readers answer", () => { + it("is advertised by the relay's supported extensions", () => { + expect( + channelReadersCapability({ + supported_extensions: ["buzz-channel-access", "buzz-channel-readers"], + }), + ).toBe(true); + expect( + channelReadersCapability({ + supported_extensions: ["buzz-channel-access"], + }), + ).toBe(false); + expect(channelReadersCapability(undefined)).toBe(false); + }); + + it("asks about one channel and a bounded set of distinct people", () => { + expect(channelReadersRequest(channel, [a, b])).toEqual([ + { access: "readers", channel, pubkeys: [a, b] }, + ]); + expect(() => channelReadersRequest(channel, [])).toThrow(); + expect(() => channelReadersRequest(channel, [a, a])).toThrow(); + expect(() => channelReadersRequest(channel, ["A".repeat(64)])).toThrow(); + expect(() => channelReadersRequest("bad id", [a])).toThrow(); + }); + + it("reads exactly one entry per person, in order, and nothing partial", () => { + expect( + parseChannelReaders( + [ + { pubkey: a, read: true }, + { pubkey: b, read: false }, + ], + [a, b], + ), + ).toEqual( + new Map([ + [a, true], + [b, false], + ]), + ); + for (const body of [ + [{ pubkey: a, read: true }], + [ + { pubkey: b, read: true }, + { pubkey: a, read: false }, + ], + [ + { pubkey: a, read: "yes" }, + { pubkey: b, read: false }, + ], + { error: "not-allowed" }, + ]) + expect(() => parseChannelReaders(body, [a, b])).toThrow(ReadError); + }); + + it("fails on a refusal or an error, never answering false for everyone", async () => { + for (const [status, kind] of [ + [403, "denied"], + [503, "unavailable"], + ] as const) { + const read = createChannelReadersReader(async () => + json( + { error: "not-allowed: the signer cannot read this channel" }, + status, + ), + ); + const failure = await read(channel, [a], new AbortController().signal) + .then(() => undefined) + .catch((error: unknown) => error); + expect(failure).toBeInstanceOf(ReadError); + expect((failure as ReadError).kind).toBe(kind); + } + }); + + it("asks in pages of the relay's limit and joins the answers", async () => { + const people = Array.from({ length: 150 }, (_, at) => + at.toString(16).padStart(64, "0"), + ); + const request = vi.fn(async (body: unknown) => { + const [{ pubkeys }] = body as [{ pubkeys: string[] }]; + return json(pubkeys.map((pubkey) => ({ pubkey, read: true }))); + }); + const answer = await createChannelReadersReader(request)( + channel, + people, + new AbortController().signal, + ); + expect(request).toHaveBeenCalledTimes(2); + expect(answer.size).toBe(150); + expect( + await createChannelReadersReader(request)( + channel, + [], + new AbortController().signal, + ), + ).toEqual(new Map()); + }); +}); diff --git a/src/features/relay/channel-readers.ts b/src/features/relay/channel-readers.ts new file mode 100644 index 0000000000..d66e875e5e --- /dev/null +++ b/src/features/relay/channel-readers.ts @@ -0,0 +1,116 @@ +// The relay's answer to "which of these people can read this channel" +// (`buzz-channel-readers`): judged by the check a task's assignees meet, and +// asked only about a channel the viewer can read. It is a snapshot; the relay +// still checks every save. +import { ReadError } from "./errors.ts"; + +/** Relay NIP-11 `supported_extensions` entry for the readers answer. */ +export const CHANNEL_READERS_EXTENSION = "buzz-channel-readers"; +/** Most people one request may name. */ +export const CHANNEL_READERS_LIMIT = 100; + +/** Who of the people asked about can read the channel: one entry each. */ +export type ChannelReaders = ReadonlyMap; + +/** Throws when there is no complete answer: the viewer may not ask, or the + * relay couldn't say. Never a partial answer. */ +export type ChannelReadersReader = ( + channel: string, + pubkeys: readonly string[], + signal: AbortSignal, +) => Promise; + +const pubkey = /^[0-9a-f]{64}$/; +const channelId = /^[a-zA-Z0-9_-]{1,128}$/; + +export function channelReadersCapability(info: unknown): boolean { + const extensions = + typeof info === "object" && info !== null + ? (info as { supported_extensions?: unknown }).supported_extensions + : undefined; + return ( + Array.isArray(extensions) && extensions.includes(CHANNEL_READERS_EXTENSION) + ); +} + +export function channelReadersRequest( + channel: string, + pubkeys: readonly string[], +) { + if ( + !channelId.test(channel) || + pubkeys.length < 1 || + pubkeys.length > CHANNEL_READERS_LIMIT || + new Set(pubkeys).size !== pubkeys.length || + pubkeys.some((key) => !pubkey.test(key)) + ) + throw new Error("Invalid channel readers request"); + return [{ access: "readers", channel, pubkeys: [...pubkeys] }]; +} + +/** Strict: exactly one entry per person asked about, in order. */ +export function parseChannelReaders( + body: unknown, + pubkeys: readonly string[], +): ChannelReaders { + if ( + !Array.isArray(body) || + body.length !== pubkeys.length || + body.some( + (entry, at) => + typeof entry !== "object" || + entry === null || + (entry as { pubkey?: unknown }).pubkey !== pubkeys[at] || + typeof (entry as { read?: unknown }).read !== "boolean", + ) + ) + throw new ReadError("invalid-response", "Invalid channel readers answer"); + return new Map( + (body as { pubkey: string; read: boolean }[]).map( + (entry) => [entry.pubkey, entry.read] as const, + ), + ); +} + +/** Asks in pages of the relay's limit; any page that fails fails the whole + * answer. A refusal (403) is `denied`; anything else is `unavailable`. */ +export function createChannelReadersReader( + request: (body: unknown, signal: AbortSignal) => Promise, +): ChannelReadersReader { + const page = async ( + channel: string, + pubkeys: readonly string[], + signal: AbortSignal, + ) => { + const response = await request( + channelReadersRequest(channel, pubkeys), + signal, + ); + signal.throwIfAborted(); + if (!response.ok) + throw new ReadError( + response.status === 403 ? "denied" : "unavailable", + `Channel readers check failed (${response.status})`, + response.status, + ); + let body: unknown; + try { + body = await response.json(); + } catch { + throw new ReadError("invalid-response", "Invalid channel readers answer"); + } + return parseChannelReaders(body, pubkeys); + }; + return async (channel, pubkeys, signal) => { + const wanted = [...new Set(pubkeys)]; + const pages: Promise[] = []; + for (let at = 0; at < wanted.length; at += CHANNEL_READERS_LIMIT) + pages.push( + page(channel, wanted.slice(at, at + CHANNEL_READERS_LIMIT), signal), + ); + const answer = new Map(); + for (const part of await Promise.all(pages)) + for (const [key, read] of part) answer.set(key, read); + return answer; + }; +} diff --git a/src/features/relay/native.ts b/src/features/relay/native.ts index 08646cc4d0..6e9ca9fede 100644 --- a/src/features/relay/native.ts +++ b/src/features/relay/native.ts @@ -2,6 +2,10 @@ import { channelAccessCapability, createChannelAccessReader, } from "./channel-access"; +import { + channelReadersCapability, + createChannelReadersReader, +} from "./channel-readers"; import { artifactIncrementalCapability, artifactIncrementalFailure, @@ -542,6 +546,18 @@ export async function connectNativeTransport( ), } : {}), + ...(channelReadersCapability(info) + ? { + channelReaders: createChannelReadersReader((body, signal) => + admitSignedRequest( + origin, + transport.viewer, + () => nativeRelayRequest(origin, "/query", body, signal), + signal, + ), + ), + } + : {}), ...(artifactIncrementalCapability(info) ? { artifactIncremental: createArtifactIncrementalReader( diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts index 0c1eb8c84d..e55e8a5d60 100644 --- a/src/features/relay/session.ts +++ b/src/features/relay/session.ts @@ -2576,6 +2576,9 @@ export function createRelaySession( )) satisfies SnapshotRead) : undefined, configArtifactWriter: transport?.configArtifacts, + /** Which named people can read a channel, from the relay; absent when it + * can't say. */ + channelReaders: transport?.channelReaders, workflowAuthority: transport?.archiveAuthority, authorizeAgentLog: transport?.authorizeAgentLog, authorizeGit: transport?.authorizeGit, diff --git a/src/features/relay/transport.ts b/src/features/relay/transport.ts index 7d0b171a9b..24961ebeba 100644 --- a/src/features/relay/transport.ts +++ b/src/features/relay/transport.ts @@ -1,4 +1,5 @@ import type { ChannelAccessReader } from "./channel-access"; +import type { ChannelReadersReader } from "./channel-readers"; import type { ArtifactIncrementalReader } from "./artifact-incremental-reader.ts"; import type { VerifiedProfileAuthority } from "./verified-profile"; import type { ReminderHost } from "./reminders"; @@ -158,6 +159,9 @@ export interface ReadTransport { * (`buzz-channel-access`). Absent: posting where the viewer is not a * member stays unavailable. */ readonly channelAccess?: ChannelAccessReader; + /** The relay's answer to which named people can read a channel the viewer + * can read (`buzz-channel-readers`). Absent: the app can't know. */ + readonly channelReaders?: ChannelReadersReader; /** Strictly validated atomic writer snapshot; never an ordinary event-array query. */ readStateSnapshot?( signal: AbortSignal,