+ Viewers cannot start conversations. Existing members
+ keep their posting access.
+
+ >
+ )}
{channel.viewerRole === "guest" || channel.joinRole === "guest"
- ? "Viewing only. Ask an owner or admin to participate."
+ ? channel.guestReplies || channel.guestReactions
+ ? `Viewers can ${[channel.guestReplies ? "reply in threads" : "", channel.guestReactions ? "react" : ""].filter(Boolean).join(" and ")}. Only members with posting access can start conversations.`
+ : "Viewing only. Ask an owner or admin to participate."
: channel.joinRole === "member"
? `New people can participate. People already in the ${policy?.subject ?? "channel"} keep their access.`
: "New peopleβs access could not be confirmed."}
diff --git a/src/features/messages/MediaReviewViewer.comments.test.tsx b/src/features/messages/MediaReviewViewer.comments.test.tsx
index 3ae894a0fb..d5d8f2cc11 100644
--- a/src/features/messages/MediaReviewViewer.comments.test.tsx
+++ b/src/features/messages/MediaReviewViewer.comments.test.tsx
@@ -38,6 +38,7 @@ type MediaKind = "image" | "video";
type ReviewFixtureOptions = {
kind: MediaKind;
typingAgent?: ReturnType;
+ guestReplies?: boolean;
openComments?: boolean;
replies?: (
viewer: ReturnType,
@@ -57,6 +58,7 @@ function mime(kind: MediaKind) {
async function setupReview({
kind,
typingAgent,
+ guestReplies = false,
openComments = true,
replies: buildReplies = () => [],
extraRootTags = [],
@@ -130,8 +132,23 @@ async function setupReview({
return events.filter((event) => event.kind === 0);
if (filter.kinds?.includes(39002) || filter.kinds?.includes(39000))
return [
- roster(relay, "one", [viewer.pubkey]),
- metadata(relay, "one", "One"),
+ guestReplies
+ ? signed(relay, {
+ kind: 39002,
+ content: "",
+ created_at: 1_700_000_000,
+ tags: [
+ ["d", "one"],
+ ["p", viewer.pubkey, "", "guest"],
+ ],
+ })
+ : roster(relay, "one", [viewer.pubkey]),
+ guestReplies
+ ? metadata(relay, "one", "One", 1_700_000_000, [
+ ["t", "stream"],
+ ["guest_replies", "true"],
+ ])
+ : metadata(relay, "one", "One"),
];
if (filter.ids)
return events.filter((event) => filter.ids?.includes(event.id));
@@ -835,6 +852,19 @@ it("shares legacy fractional timecodes between timeline markers and sidebar and
).toBeInTheDocument();
});
+it("keeps frame reactions writer-only when Guests can reply", async () => {
+ const { user, sign } = await setupReview({
+ kind: "video",
+ guestReplies: true,
+ });
+ const react = await screen.findByRole("button", {
+ name: "React π at current frame",
+ });
+ expect(react).toBeDisabled();
+ await user.click(react);
+ expect(sign).not.toHaveBeenCalled();
+});
+
it.each(["image", "video"] as const)(
"starts an empty %s review with a dark stage and comments closed",
async (kind) => {
diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx
index d7d0bbca7e..615cef1bf2 100644
--- a/src/features/messages/MessageComposer.tsx
+++ b/src/features/messages/MessageComposer.tsx
@@ -1,3 +1,4 @@
+import { channelCan } from "../relay/channel-permissions";
import { draftEditorId, traceDraft } from "../../shared/draft-diagnostics";
import {
soloModelPicksKey,
@@ -562,10 +563,8 @@ function Composer({
const listed =
session.channels?.get || soloConversation ? session.channels : undefined;
const channels = () => (listed?.list() ?? noChannels).channels;
- const writable = useListedChannel(
- listed,
- channelId,
- (channel) => !!channel && !channel.readOnly && !channel.archived,
+ const writable = useListedChannel(listed, channelId, (channel) =>
+ channelCan(channel, threadRootId ? "reply" : "post"),
);
const readOnly = !submission && !!session.channels?.get && !writable;
const cached = useListedChannel(
@@ -1316,7 +1315,8 @@ function Composer({
const editLocked = useListedChannel(
listed,
channelId,
- (channel) => !!channel?.archived || !!channel?.readOnly,
+ (channel) =>
+ !!channel && !channelCan(channel, threadRootId ? "reply" : "post"),
);
const editDisabled = disabled || editLocked;
const chips = useMemo(
diff --git a/src/features/messages/MessageManagement.tsx b/src/features/messages/MessageManagement.tsx
index ce7386c688..43144cb226 100644
--- a/src/features/messages/MessageManagement.tsx
+++ b/src/features/messages/MessageManagement.tsx
@@ -1,3 +1,4 @@
+import { channelCan } from "../relay/channel-permissions";
import {
BellIcon,
BellSlashIcon,
@@ -173,7 +174,7 @@ export function useMessageKeyActions(session: RelaySession) {
const channel = joined(row);
return (
!!channel &&
- !channel.readOnly &&
+ channelCan(channel, row.threadRootId ? "reply" : "post") &&
!channel.archived &&
!!session.viewer &&
row.authorId === session.viewer &&
@@ -247,7 +248,7 @@ export function MessageManagement({
(channel) =>
!!channel &&
!channel.cached &&
- (!channel.readOnly ||
+ (channelCan(channel, selection?.row.threadRootId ? "reply" : "post") ||
(channel.viewerRole === "guest" && !!selection?.authorization)),
);
const available =
@@ -590,7 +591,7 @@ function ManagedMessageItems({
const writable = useListedChannel(
session.channels,
row.channelId,
- (channel) => !!channel && !channel.readOnly && !channel.cached,
+ (channel) => channelCan(channel, row.threadRootId ? "reply" : "post"),
);
const threadRootId = row.threadRootId ?? row.id;
const following = useSyncExternalStore(session.unread.subscribeSync, () =>
@@ -745,7 +746,7 @@ function DeleteMessageDialog({
channel.id === row.channelId &&
!channel.archived &&
!channel.cached &&
- (!channel.readOnly ||
+ (channelCan(channel, row.threadRootId ? "reply" : "post") ||
(channel.viewerRole === "guest" && !!authorization)),
)
)
diff --git a/src/features/messages/MessageReactions.test.tsx b/src/features/messages/MessageReactions.test.tsx
index 4d3a85c203..500c26f21f 100644
--- a/src/features/messages/MessageReactions.test.tsx
+++ b/src/features/messages/MessageReactions.test.tsx
@@ -121,7 +121,9 @@ function harness(
disabled = false,
onFocusedRemoval,
audience,
+ removalAllowed = false,
}: {
+ removalAllowed?: boolean;
audience?: "agents";
disabled?: boolean;
onFocusedRemoval?: () => void;
@@ -145,6 +147,7 @@ function harness(
/>
{
+ const h = harness([react(), react(other)]);
+ render();
+ expect(screen.queryByTestId("inline-add-reaction")).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "π: 2 people" }));
+ await waitFor(() => expect(h.publish).toHaveBeenCalledOnce());
+ expect(h.session.outbox?.snapshot().map((item) => item.event.kind)).toEqual([
+ 5,
+ ]);
+ fireEvent.click(
+ screen.getByRole("button", { name: `π: ${other.pubkey.slice(0, 10)}` }),
+ );
+ expect(h.session.outbox?.snapshot()).toHaveLength(1);
+});
diff --git a/src/features/messages/MessageReactions.tsx b/src/features/messages/MessageReactions.tsx
index 4d5123ce19..0687d3e95c 100644
--- a/src/features/messages/MessageReactions.tsx
+++ b/src/features/messages/MessageReactions.tsx
@@ -37,6 +37,7 @@ type Props = {
session: RelaySession;
scope: string;
disabled: boolean;
+ removalAllowed?: boolean;
tools: ContributionReader;
inline: ContributionReader;
};
@@ -44,12 +45,12 @@ const noSubscribe = () => () => {};
const noOperations = Object.freeze([]);
const empty = () => noOperations;
-function useReactionAction({ row, session, disabled }: Props) {
+function useReactionAction({ row, session, disabled, removalAllowed }: Props) {
const presented = useConversationPresentation();
const [error, setError] = useState();
const active = useRef(false);
useLayoutEffect(() => {
- active.current = !disabled && presented;
+ active.current = (!disabled || !!removalAllowed) && presented;
});
useLayoutEffect(
() => () => {
@@ -79,6 +80,7 @@ function useReactionAction({ row, session, disabled }: Props) {
[];
if (mine.length) session.messages.remove(mine.map((event) => event.id));
else {
+ if (disabled) return false;
session.messages.react(row.id, content, emoji);
}
setError(undefined);
@@ -503,7 +505,7 @@ export function MessageReactions(
mine={mine}
session={session}
profiles={props.profiles}
- disabled={props.disabled}
+ disabled={props.disabled && !(mine && props.removalAllowed)}
busy={action.busy}
toggle={action.toggle}
onFocusedRemoval={props.onFocusedRemoval}
diff --git a/src/features/messages/MessageRow.tsx b/src/features/messages/MessageRow.tsx
index 9b538e2146..0ab5453799 100644
--- a/src/features/messages/MessageRow.tsx
+++ b/src/features/messages/MessageRow.tsx
@@ -1,3 +1,4 @@
+import { channelCan } from "../relay/channel-permissions";
import { snapshotAttachments } from "../relay/forwarded-message";
import { ForwardedMessage } from "./ForwardedMessage";
import { requestWork, isSettledWork } from "../agents/request-work";
@@ -331,6 +332,17 @@ function MessageRowContent({
row.channelId,
(channel) => !!channel?.readOnly,
);
+ const replyAllowed = useListedChannel(channels, row.channelId, (channel) =>
+ channelCan(channel, "reply"),
+ );
+ const reactionsAllowed = useListedChannel(
+ channels,
+ row.channelId,
+ (channel) => channelCan(channel, "react"),
+ );
+ const removalAllowed = useListedChannel(channels, row.channelId, (channel) =>
+ channelCan(channel, "removeReaction"),
+ );
const { messageTimestamps } = useClockPreference();
const solo = useListedChannel(
references?.channels,
@@ -528,7 +540,7 @@ function MessageRowContent({
session.outbox.supports(5) &&
(!session.channels.get || listed) &&
!archived &&
- !readOnly
+ reactionsAllowed
);
const rowRef = useRef(null);
const menuTrigger = useRef(null);
@@ -1166,7 +1178,7 @@ function MessageRowContent({
replyDisabled={
!!(row.delivery && !["accepted", "seen"].includes(row.delivery)) ||
archived ||
- (!!session?.channels.get && (!listed || readOnly))
+ (!!session?.channels.get && (!listed || !replyAllowed))
}
onSendToChannel={
session &&
@@ -1421,6 +1433,13 @@ function MessageRowContent({
tools={extensions.tools}
inline={extensions.inline}
profiles={directory.profiles}
+ removalAllowed={
+ removalAllowed &&
+ !archived &&
+ !!session.outbox?.supports(5) &&
+ (!session.channels.get || listed) &&
+ (!row.delivery || ["accepted", "seen"].includes(row.delivery))
+ }
disabled={
!canReact ||
(!!row.delivery && !["accepted", "seen"].includes(row.delivery))
diff --git a/src/features/messages/ThreadPanel.tsx b/src/features/messages/ThreadPanel.tsx
index 5ad943c84c..2a915ac0f3 100644
--- a/src/features/messages/ThreadPanel.tsx
+++ b/src/features/messages/ThreadPanel.tsx
@@ -1,4 +1,5 @@
// biome-ignore-all lint/a11y/noNoninteractiveTabindex: The thread region supports keyboard scrolling and Escape.
+import { channelCan } from "../relay/channel-permissions";
import { AgentConnectionSetup } from "../agents/AgentConnectionSetup";
import { TypingIndicator, useLiveConversationAgents } from "./TypingIndicator";
import { ActivityExpansion } from "./ActivityExpansion";
@@ -602,7 +603,8 @@ function ThreadMessages({
(listed) => {
const channel = listed ?? session.channels?.get?.(channelId);
if (channel?.archived) return "archived";
- if (channel?.viewerRole === "guest") return "guest";
+ if (channel?.viewerRole === "guest")
+ return channelCan(channel, "reply") ? "member" : "guest";
if (channel?.readOnly && !channel.cached) {
return channel.channelType === "stream" ||
channel.channelType === "forum" ||
diff --git a/src/features/messages/VideoReviewReactions.tsx b/src/features/messages/VideoReviewReactions.tsx
index 9d38e1b36f..84da478e05 100644
--- a/src/features/messages/VideoReviewReactions.tsx
+++ b/src/features/messages/VideoReviewReactions.tsx
@@ -1,3 +1,4 @@
+import { channelCan } from "../relay/channel-permissions";
import { IconButton } from "../../shared/design-system/ui/IconButton";
import { useState, useSyncExternalStore, type RefObject } from "react";
import type { RelaySession } from "../relay/session";
@@ -32,7 +33,7 @@ export function VideoReviewReactions({
session.channels.list,
);
const disabled = !channels.channels.some(
- (channel) => channel.id === channelId && !channel.readOnly,
+ (channel) => channel.id === channelId && channelCan(channel, "post"),
);
const [error, setError] = useState();
const select = (emoji: string) => {
diff --git a/src/features/relay/channel-details-protocol.ts b/src/features/relay/channel-details-protocol.ts
index 423d4c7f3c..77f1a7e61c 100644
--- a/src/features/relay/channel-details-protocol.ts
+++ b/src/features/relay/channel-details-protocol.ts
@@ -18,6 +18,8 @@ export type ChannelDetailsDraft = Readonly<{
visibility: "public" | "private";
/** Admission default only; omission preserves existing relay behavior. */
joinRole?: "member" | "guest" | undefined;
+ guestReplies?: boolean | undefined;
+ guestReactions?: boolean | undefined;
/** Absent means ongoing; retain existing custom temporary intervals. */
ttlSeconds?: number | undefined;
/** NIP-CL labels. Absent leaves the relay's set unchanged; empty clears it. */
@@ -81,6 +83,11 @@ export function detailsDraftErrors(draft: ChannelDetailsDraft) {
? "Channel visibility could not be verified."
: undefined,
labels: labelsError(draft?.labels),
+ guestPermissions: [draft?.guestReplies, draft?.guestReactions].some(
+ (value) => value !== undefined && typeof value !== "boolean",
+ )
+ ? "Viewer permissions could not be verified."
+ : undefined,
joinRole:
draft?.joinRole !== undefined &&
draft.joinRole !== "member" &&
@@ -118,7 +125,8 @@ export function validateDetailsDraft(draft: ChannelDetailsDraft): void {
errors.visibility ??
errors.lifetime ??
errors.labels ??
- errors.joinRole;
+ errors.joinRole ??
+ errors.guestPermissions;
if (error) throw new Error(error);
}
@@ -152,6 +160,7 @@ export function detailsSettings(
description,
visibility,
...(joinRole ? { joinRole } : {}),
+ ...guestPermissions(metadata),
...(ttlSeconds !== undefined ? { ttlSeconds } : {}),
labels: channelIdentity(metadata).labels,
canEdit:
@@ -192,6 +201,14 @@ export function detailsTemplate(
...(draft.joinRole !== undefined && draft.joinRole !== base.joinRole
? [["join_role", draft.joinRole]]
: []),
+ ...(
+ [
+ ["guest_replies", draft.guestReplies, base.guestReplies],
+ ["guest_reactions", draft.guestReactions, base.guestReactions],
+ ] as const
+ ).flatMap(([key, value, previous]) =>
+ value !== undefined && value !== previous ? [[key, String(value)]] : [],
+ ),
// NIP-CL: `t` tags replace the set; one empty `t` clears it; none keeps it.
...(draft.labels !== undefined &&
!sameLabels(draft.labels, base.labels ?? [])
@@ -226,6 +243,35 @@ export function channelTtl(event: RelayEvent): number | undefined {
}
}
+/** Only one exact signed boolean grants a capability; absence stays unsupported. */
+export function guestPermissions(event: RelayEvent) {
+ const read = (name: string): boolean | undefined => {
+ const tags = event.tags.filter(([key]) => key === name);
+ return tags.length === 1 &&
+ tags[0]?.length === 2 &&
+ ["true", "false"].includes(tags[0]?.[1] ?? "")
+ ? tags[0]?.[1] === "true"
+ : undefined;
+ };
+ return {
+ guestReplies: read("guest_replies"),
+ guestReactions: read("guest_reactions"),
+ };
+}
+
+function detailsKeys(tags: readonly (readonly string[])[]) {
+ let index = 3;
+ for (const key of [
+ "visibility",
+ "ttl",
+ "join_role",
+ "guest_replies",
+ "guest_reactions",
+ ])
+ if (tags[index]?.[0] === key) index++;
+ return tags.slice(index).every(([key]) => key === "t");
+}
+
/** Legacy absence means Member; malformed explicit defaults fail closed to Guest. */
export function channelJoinRole(event: RelayEvent): "member" | "guest" {
const tags = event.tags.filter(([key]) => key === "join_role");
@@ -265,26 +311,18 @@ export function validateDetailsTemplate(event: EventTemplate): void {
!["h", "name", "about"].every(
(key, index) => event.tags[index]?.[0] === key,
) ||
- ![
- [],
- ["visibility"],
- ["ttl"],
- ["visibility", "ttl"],
- ["join_role"],
- ["visibility", "join_role"],
- ["ttl", "join_role"],
- ["visibility", "ttl", "join_role"],
- ].some(
- (keys) =>
- keys.every((key, index) => event.tags[index + 3]?.[0] === key) &&
- event.tags.slice(keys.length + 3).every(([key]) => key === "t"),
- )
+ !detailsKeys(event.tags)
)
throw new Error("Invalid channel details command.");
const labels = detailsLabels(event.tags.filter(([key]) => key === "t"));
const visibility = event.tags.find(([key]) => key === "visibility");
if (visibility && !["private", "open"].includes(visibility[1] ?? ""))
throw new Error("Invalid channel details command.");
+ for (const key of ["guest_replies", "guest_reactions"]) {
+ const tag = event.tags.find(([name]) => name === key);
+ if (tag && !["true", "false"].includes(tag[1] ?? ""))
+ throw new Error("Invalid viewer permission.");
+ }
const ttl = event.tags.find(([key]) => key === "ttl")?.[1];
const joinRole = event.tags.find(([key]) => key === "join_role")?.[1];
if (joinRole !== undefined && joinRole !== "member" && joinRole !== "guest")
diff --git a/src/features/relay/channel-details.test.ts b/src/features/relay/channel-details.test.ts
index 88edc4fe65..386a5a6dd3 100644
--- a/src/features/relay/channel-details.test.ts
+++ b/src/features/relay/channel-details.test.ts
@@ -3,6 +3,7 @@ import { finalizeEvent, getPublicKey, type EventTemplate } from "nostr-tools";
import { createChannelDetails } from "./channel-details";
import {
channelVisibility,
+ guestPermissions,
channelJoinRole,
canonicalDetailsName,
detailsSettings,
@@ -1157,3 +1158,47 @@ it("keeps a region label when an editor replaces the label set with empty", asyn
await h.owner.capability.save(base, { ...base, labels: [] });
expect((await h.owner.capability.load(id)).labels).toEqual([region]);
});
+
+it("round-trips independent viewer grants and rejects malformed metadata commands", () => {
+ const h = harness();
+ for (const replies of [false, true])
+ for (const reactions of [false, true]) {
+ const grants = { guestReplies: replies, guestReactions: reactions };
+ const base = {
+ ...draft,
+ guestReplies: !replies,
+ guestReactions: !reactions,
+ };
+ const event = detailsTemplate(id, { ...draft, ...grants }, base);
+ expect(() => validateDetailsTemplate(event)).not.toThrow();
+ expect(guestPermissions(h.record(39000, event.tags))).toEqual(grants);
+ expect(
+ detailsTemplate(id, { ...draft, ...grants }, { ...draft, ...grants })
+ .tags,
+ ).toEqual(detailsTemplate(id, draft, draft).tags);
+ }
+ for (const name of ["guest_replies", "guest_reactions"])
+ for (const tags of [
+ [[name]],
+ [[name, "1"]],
+ [[name, "true", "extra"]],
+ [
+ [name, "true"],
+ [name, "false"],
+ ],
+ ]) {
+ expect(() =>
+ validateDetailsTemplate({
+ ...detailsTemplate(id, draft, draft),
+ tags: [...detailsTemplate(id, draft, draft).tags, ...tags],
+ }),
+ ).toThrow();
+ const permissions = guestPermissions(h.record(39000, tags));
+ expect(permissions.guestReplies).not.toBe(true);
+ expect(permissions.guestReactions).not.toBe(true);
+ }
+ expect(guestPermissions(h.record(39000, []))).toEqual({
+ guestReplies: undefined,
+ guestReactions: undefined,
+ });
+});
diff --git a/src/features/relay/channel-details.ts b/src/features/relay/channel-details.ts
index 21c0a56735..6f1bf9a1f3 100644
--- a/src/features/relay/channel-details.ts
+++ b/src/features/relay/channel-details.ts
@@ -123,6 +123,10 @@ export function createChannelDetails({
details.description !== draft.description ||
details.visibility !== draft.visibility ||
details.ttlSeconds !== draft.ttlSeconds ||
+ (draft.guestReplies !== undefined &&
+ details.guestReplies !== draft.guestReplies) ||
+ (draft.guestReactions !== undefined &&
+ details.guestReactions !== draft.guestReactions) ||
(draft.joinRole !== undefined && details.joinRole !== draft.joinRole) ||
(draft.labels !== undefined &&
JSON.stringify([...new Set(draft.labels)].sort()) !==
diff --git a/src/features/relay/channel-permissions.ts b/src/features/relay/channel-permissions.ts
new file mode 100644
index 0000000000..11e9d43819
--- /dev/null
+++ b/src/features/relay/channel-permissions.ts
@@ -0,0 +1,22 @@
+import type { ChannelSummary } from "./contracts";
+
+export type ChannelAction = "post" | "reply" | "react" | "removeReaction";
+
+/** Narrow Guest grants never turn a channel into a general writable resource. */
+export function channelCan(
+ channel: ChannelSummary | undefined,
+ action: ChannelAction,
+): boolean {
+ if (!channel || channel.archived || channel.cached) return false;
+ if (!channel.readOnly) return true;
+ if (
+ channel.viewerRole !== "guest" ||
+ !["stream", "forum"].includes(channel.channelType ?? "")
+ )
+ return false;
+ return action === "reply"
+ ? channel.guestReplies === true
+ : action === "react"
+ ? channel.guestReactions === true
+ : action === "removeReaction";
+}
diff --git a/src/features/relay/contracts.ts b/src/features/relay/contracts.ts
index 61ebdc3f2f..848c834e6a 100644
--- a/src/features/relay/contracts.ts
+++ b/src/features/relay/contracts.ts
@@ -26,6 +26,9 @@ export type ChannelSummary = Readonly<{
visibility?: "public" | "private" | undefined;
/** Default for future participants; never an existing participant's role. */
joinRole?: "member" | "guest" | undefined;
+ /** Explicit signed Guest grants; absence means unsupported or unverified. */
+ guestReplies?: boolean | undefined;
+ guestReactions?: boolean | undefined;
/** Viewer role from the relay-signed roster, independent of admission defaults. */
viewerRole?: "owner" | "admin" | "member" | "guest" | "bot" | undefined;
preview?: string | undefined;
diff --git a/src/features/relay/discovery.ts b/src/features/relay/discovery.ts
index d98e09dcc3..7c847d1708 100644
--- a/src/features/relay/discovery.ts
+++ b/src/features/relay/discovery.ts
@@ -1,6 +1,7 @@
import { byteSize } from "./budget";
import {
channelJoinRole,
+ guestPermissions,
channelTtl,
channelVisibility,
} from "./channel-details-protocol";
@@ -505,6 +506,7 @@ export class DiscoveryState {
? {
visibility: channelVisibility(event),
joinRole: channelJoinRole(event),
+ ...guestPermissions(event),
description: tag(event, "about") ?? "",
}
: {}),
diff --git a/src/features/relay/messages.ts b/src/features/relay/messages.ts
index 687ff3e7ef..b17fde9bd3 100644
--- a/src/features/relay/messages.ts
+++ b/src/features/relay/messages.ts
@@ -1,3 +1,4 @@
+import type { ChannelAction } from "./channel-permissions";
import {
forwardBody,
forwardQuote,
@@ -52,10 +53,15 @@ export function createMessages(
viewer: string | undefined,
find: (id: string) => EventData | undefined,
emojiTags: (content: string) => string[][],
- validateMentions: (channelId: string, pubkeys: readonly string[]) => void,
+ validateMentions: (
+ channelId: string,
+ pubkeys: readonly string[],
+ action?: ChannelAction,
+ ) => void,
canWrite: (
channelId: string,
owner?: AgentOwnerAuthorization,
+ action?: ChannelAction,
) => boolean = () => true,
relayOrigin?: string,
/** Resolves on relay OK. Reports are never echoed, so they bypass the outbox. */
@@ -73,8 +79,9 @@ export function createMessages(
kind: number,
channelId: string,
owner?: AgentOwnerAuthorization,
+ action: ChannelAction = "post",
) => {
- if (!canWrite(channelId, owner))
+ if (!canWrite(channelId, owner, action))
throw new Error("You donβt have write access to this conversation.");
if (!outbox?.supports(kind))
throw new Error("This connection cannot publish that operation");
@@ -87,14 +94,18 @@ export function createMessages(
if (!value) throw new Error("Message is empty");
return value;
};
- const mentionTags = (channelId: string, pubkeys: readonly string[]) => {
+ const mentionTags = (
+ channelId: string,
+ pubkeys: readonly string[],
+ action?: ChannelAction,
+ ) => {
if (
pubkeys.length > 32 ||
pubkeys.some((key) => !/^[0-9a-f]{64}$/.test(key))
)
throw new Error("Choose at most 32 valid mention recipients");
const unique = [...new Set(pubkeys)];
- validateMentions(channelId, unique);
+ validateMentions(channelId, unique, action);
return unique.map((key) => ["p", key]);
};
/** A one-to-one DM's agent partner must be `p`-tagged: a hosted agent is
@@ -146,7 +157,12 @@ export function createMessages(
/** The author's other copies of a message: its source reply and every
* sent-to-channel copy of it, deduplicated, never the message itself. */
const linkedCopies = (message: EventData, channelId: string) => {
- if (!ownedMessage(message) || message.kind !== 9) return [];
+ if (
+ !ownedMessage(message) ||
+ message.kind !== 9 ||
+ !canWrite(channelId, undefined, "post")
+ )
+ return [];
const sourceId = message.tags.find(
([name, value]) => name === "buzz:copy-of" && value,
)?.[1];
@@ -205,7 +221,12 @@ export function createMessages(
)
throw new Error("Reload the message before editing its attachments.");
const sendEdit = (targetId: string) =>
- writer(40003, channelId, ownerEdit ? authorization : undefined).send({
+ writer(
+ 40003,
+ channelId,
+ ownerEdit ? authorization : undefined,
+ threadReference(original) ? "reply" : "post",
+ ).send({
kind: 40003,
content: text(content),
tags: [
@@ -279,7 +300,16 @@ export function createMessages(
// The relay accepts exactly one target per deletion, so each copy gets its
// own event. One that cannot be queued does not stop the rest; any failure
// is reported once every other target has been attempted.
- const queue = writer(5, channelId, authorization);
+ const queue = writer(
+ 5,
+ channelId,
+ authorization,
+ originals.every((event) => event.kind === 7)
+ ? "removeReaction"
+ : originals.every((event) => !!threadReference(event))
+ ? "reply"
+ : "post",
+ );
const failures: unknown[] = [];
const operations = targets.flatMap((event) => {
try {
@@ -624,14 +654,14 @@ export function createMessages(
if (mediaTargetUrl && !mediaTarget)
throw new Error("A valid media target is required");
const message = attachmentMessage(content, attachments, relayOrigin);
- return writer(9, channelId).send({
+ return writer(9, channelId, undefined, "reply").send({
kind: 9,
content: text(message.content),
tags: [
["h", channelId],
...(parentId === rootId ? [] : [["e", rootId, "", "root"]]),
["e", parentId, "", "reply"],
- ...mentionTags(channelId, withDmAgents(channelId, mentions)),
+ ...mentionTags(channelId, withDmAgents(channelId, mentions), "reply"),
...referenceTags(references),
...pickTags(channelId, mentions, picks),
...(mediaTarget ? [[MEDIA_TARGET_TAG, mediaTarget]] : []),
@@ -680,7 +710,7 @@ export function createMessages(
if (!channelId) throw new Error("Message has no channel");
const value = text(content);
if (!validReactionContent(value)) throw new Error("Reaction is too long");
- return writer(7, channelId).send({
+ return writer(7, channelId, undefined, "react").send({
kind: 7,
content: value,
tags: [
diff --git a/src/features/relay/session-permissions.test.ts b/src/features/relay/session-permissions.test.ts
index 2582f94035..93ebac42a7 100644
--- a/src/features/relay/session-permissions.test.ts
+++ b/src/features/relay/session-permissions.test.ts
@@ -23,6 +23,7 @@ function deferred() {
async function setup(
initialRole = "member",
uploadAttachment?: AttachmentUpload,
+ grants = { replies: false, reactions: false },
) {
const viewer = keypair(),
relay = keypair(),
@@ -42,6 +43,7 @@ async function setup(
tags: [["h", id]],
created_at: time,
});
+ const extra: RelayEvent[] = [];
const events = () => [
signed(relay, {
kind: 39000,
@@ -53,6 +55,8 @@ async function setup(
["t", "stream"],
["public"],
["join_role", joinRole],
+ ["guest_replies", String(grants.replies)],
+ ["guest_reactions", String(grants.reactions)],
],
}),
signed(relay, {
@@ -78,6 +82,7 @@ async function setup(
own,
root,
canvas,
+ ...extra,
];
const sign = vi.fn(async (event: EventTemplate) => signed(viewer, event));
const publish = vi.fn(async (event: RelayEvent) => {
@@ -131,6 +136,15 @@ async function setup(
viewer,
peer,
agent,
+ async readExtra(event: RelayEvent) {
+ extra.push(event);
+ await owner.session.read([{ ids: [event.id], limit: 1 }]);
+ },
+ async grants(next: typeof grants) {
+ grants = next;
+ time++;
+ await owner.session.read([{ kinds: [39000], "#d": [id], limit: 1 }]);
+ },
async role(next: string) {
role = next;
time++;
@@ -381,3 +395,190 @@ it("rejects guest uploads and fences an upload completed after demotion", async
}
await rejected;
});
+
+it.each([
+ { replies: false, reactions: false },
+ { replies: true, reactions: false },
+ { replies: false, reactions: true },
+ { replies: true, reactions: true },
+])("grants only the opted-in Guest contributions: %j", async (grants) => {
+ const h = await setup("guest", undefined, grants);
+ expect(() => h.session.messages.send(id, "Root remains forbidden")).toThrow();
+ const reply = () =>
+ h.session.messages.reply(id, h.root.id, "Reply with mention", [
+ h.peer.pubkey,
+ ]);
+ const react = () => h.session.messages.react(h.root.id, "π");
+ const accepted: string[] = [];
+ if (grants.replies) accepted.push(reply());
+ else expect(reply).toThrow();
+ if (grants.reactions) accepted.push(react());
+ else expect(react).toThrow();
+ await vi.waitFor(() => {
+ for (const eventId of accepted)
+ expect(
+ h.session.outbox?.snapshot().find((item) => item.event.id === eventId)
+ ?.delivery,
+ ).toBe("accepted");
+ });
+ if (!grants.replies || !grants.reactions) {
+ expect(h.publish).toHaveBeenCalledTimes(accepted.length);
+ return;
+ }
+ const outbox = h.session.outbox;
+ assert(outbox);
+ for (const tags of [
+ [
+ ["h", id],
+ ["e", h.root.id, "", "root"],
+ ],
+ [
+ ["h", id],
+ ["e", h.root.id, "", "reply"],
+ ["broadcast", "1"],
+ ],
+ ]) {
+ const eventId = outbox.send({
+ kind: 9,
+ content: "Forbidden root or broadcast",
+ tags,
+ });
+ await vi.waitFor(() =>
+ expect(
+ outbox.snapshot().find((item) => item.event.id === eventId)?.delivery,
+ ).toBe("failed"),
+ );
+ }
+ expect(h.publish).toHaveBeenCalledTimes(accepted.length);
+});
+
+it("revokes a Guest reply while signing and rechecks its signed retry", async () => {
+ const h = await setup("guest", undefined, {
+ replies: true,
+ reactions: false,
+ });
+ const started = deferred(),
+ gate = deferred();
+ h.sign.mockImplementationOnce(async (template) => {
+ started.resolve();
+ await gate.promise;
+ return signed(h.viewer, template);
+ });
+ const eventId = h.session.messages.reply(
+ id,
+ h.root.id,
+ "Draft before revocation",
+ );
+ try {
+ await started.promise;
+ await h.grants({ replies: false, reactions: false });
+ } finally {
+ gate.resolve();
+ }
+ await vi.waitFor(() =>
+ expect(
+ h.session.outbox?.snapshot().find((item) => item.event.id === eventId)
+ ?.delivery,
+ ).toBe("failed"),
+ );
+ h.session.messages.retry(eventId);
+ await vi.waitFor(() =>
+ expect(
+ h.session.outbox?.snapshot().find((item) => item.event.id === eventId)
+ ?.delivery,
+ ).toBe("failed"),
+ );
+ expect(h.publish).not.toHaveBeenCalled();
+});
+
+it("lets a Guest manage its reply and remove its reaction after additions are disabled", async () => {
+ const h = await setup("guest", undefined, { replies: true, reactions: true });
+ const reply = h.session.messages.reply(id, h.root.id, "My reply");
+ const reaction = h.session.messages.react(h.root.id, "π");
+ await vi.waitFor(() => expect(h.publish).toHaveBeenCalledTimes(2));
+ h.session.messages.edit(reply, "Edited reply", reply);
+ await vi.waitFor(() => expect(h.publish).toHaveBeenCalledTimes(3));
+ await h.grants({ replies: true, reactions: false });
+ h.session.messages.remove([reaction]);
+ h.session.messages.remove([reply]);
+ await vi.waitFor(() => expect(h.publish).toHaveBeenCalledTimes(5));
+ expect(() => h.session.messages.remove([h.own.id])).toThrow();
+});
+
+it("allows reply attachments and rejects an upload finishing after its grant is revoked", async () => {
+ const started = deferred(),
+ gate = deferred();
+ const result = {
+ url: "https://relay.test/media/notes.txt",
+ name: "notes.txt",
+ size: 4,
+ type: "text/plain",
+ sha256: "a".repeat(64),
+ };
+ const upload = vi.fn(async () => {
+ started.resolve();
+ await gate.promise;
+ return result;
+ });
+ const h = await setup("guest", upload, { replies: true, reactions: false });
+ const attachments = h.session.attachments;
+ assert.exists(attachments);
+ const pending = attachments.upload(
+ new File(["text"], "notes.txt"),
+ id,
+ new AbortController().signal,
+ );
+ const rejected = expect(pending).rejects.toMatchObject({ code: "denied" });
+ try {
+ await started.promise;
+ await h.grants({ replies: false, reactions: true });
+ } finally {
+ gate.resolve();
+ }
+ await rejected;
+ expect(upload).toHaveBeenCalledOnce();
+ await h.grants({ replies: true, reactions: false });
+ await expect(
+ attachments.upload(
+ new File(["text"], "notes.txt"),
+ id,
+ new AbortController().signal,
+ ),
+ ).resolves.toEqual(result);
+});
+
+it("removes an old reaction by its last valid target after demotion", async () => {
+ const h = await setup("member");
+ const outbox = h.session.outbox;
+ assert.exists(outbox);
+ const context = signed(h.peer, {
+ kind: 0,
+ content: "{}",
+ tags: [],
+ created_at: 1700000000,
+ });
+ await h.readExtra(context);
+ const reaction = outbox.send({
+ kind: 7,
+ content: "π",
+ tags: [
+ ["e", context.id],
+ ["e", h.root.id],
+ ],
+ });
+ await vi.waitFor(() =>
+ expect(
+ outbox.snapshot().find((item) => item.event.id === reaction)?.delivery,
+ ).toBe("accepted"),
+ );
+ await h.role("guest");
+ h.session.messages.remove([reaction]);
+ await vi.waitFor(() => expect(h.publish).toHaveBeenCalledTimes(2));
+ expect(h.publish.mock.calls[1]?.[0]).toMatchObject({
+ kind: 5,
+ tags: expect.arrayContaining([
+ ["h", id],
+ ["e", reaction],
+ ]),
+ });
+});
diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts
index 51578d4bc0..a164e86f64 100644
--- a/src/features/relay/session.ts
+++ b/src/features/relay/session.ts
@@ -1,3 +1,5 @@
+import { channelCan, type ChannelAction } from "./channel-permissions";
+import { threadReference as contributionThread } from "./thread-reference";
import type { LocalAgentSource } from "../agents/local-activity";
// FOUNDATION: One relay session owns reads, local intent, delivery and shared views.
import { createSoloPreferences, soloGroups } from "./solo-preferences";
@@ -128,6 +130,7 @@ import {
import { relayPartition, transportPartition } from "./partition";
import { browserThreadFollows } from "./thread-follows";
import { createMessages } from "./messages";
+import { reactionTarget as reactionTargetId } from "./reaction-target";
import { retryRead } from "./read-retry";
import { messageAuthor } from "./fold";
import { createThreadView, resumeAfter, type ThreadResume } from "./threads";
@@ -1579,7 +1582,30 @@ export function createRelaySession(
? channel.members.filter((key) => key !== transport.viewer)
: [];
}
- function validateMentions(channelId: string, pubkeys: readonly string[]) {
+ function messageEvent(id: string) {
+ const outgoing = local().find((item) => item.event.id === id);
+ // Prefer admitted signed bytes to the optimistic projection when available.
+ return (
+ outgoing?.signed ??
+ recent.peek(id)?.event ??
+ retainedEvent(id) ??
+ outgoing?.event
+ );
+ }
+ function canContribute(channelId: string, action: ChannelAction) {
+ const channel = channels.queries.get?.(channelId);
+ return (
+ channels.canWrite(channelId) ||
+ (channel?.viewerRole === "guest" &&
+ channels.canParticipate(channelId) &&
+ channelCan(channel, action))
+ );
+ }
+ function validateMentions(
+ channelId: string,
+ pubkeys: readonly string[],
+ action: ChannelAction = "post",
+ ) {
if (!pubkeys.length) return;
const channel = channels.queries
.list()
@@ -1591,7 +1617,7 @@ export function createRelaySession(
const addressesPartnerOnly = pubkeys.every((key) => partners.includes(key));
if (
closed ||
- !channels.canWrite(channelId) ||
+ !canContribute(channelId, action) ||
!channel?.members ||
channel.archived ||
(transport?.subscribe &&
@@ -1617,6 +1643,57 @@ export function createRelaySession(
if ([9000, 9001, 9022].includes(event.kind)) return;
const id = event.tags.find(([key]) => key === "h")?.[1];
if (!id || channels.queries.get?.(id)?.viewerRole !== "guest") return;
+ const channel = channels.queries.get?.(id);
+ const thread = contributionThread(event);
+ const broadcast = event.tags.some(
+ ([key, value]) => key === "broadcast" && value === "1",
+ );
+ if (
+ (event.kind === 9 || event.kind === 40002) &&
+ thread &&
+ !broadcast &&
+ channelCan(channel, "reply")
+ )
+ return;
+ if (event.kind === 7 && channelCan(channel, "react")) return;
+ const contributionTargets = event.tags.filter(([key]) => key === "e");
+ if (
+ (event.kind === 5 || event.kind === 40003) &&
+ contributionTargets.length === 1
+ ) {
+ const target = contributionTargets[0]?.[1];
+ const original = messageEvent(target ?? "");
+ const reactionTarget =
+ original?.kind === 7 ? reactionTargetId(original) : undefined;
+ const reactionSource = reactionTarget
+ ? messageEvent(reactionTarget)
+ : undefined;
+ const originalChannel =
+ original?.tags.find(([key]) => key === "h")?.[1] ??
+ reactionSource?.tags.find(([key]) => key === "h")?.[1];
+ if (
+ original &&
+ messageAuthor(original, transport?.archiveAuthority) ===
+ transport?.viewer &&
+ originalChannel === id
+ ) {
+ if (
+ event.kind === 5 &&
+ original.kind === 7 &&
+ channelCan(channel, "removeReaction")
+ )
+ return;
+ if (
+ [9, 40002].includes(original.kind) &&
+ contributionThread(original) &&
+ !original.tags.some(
+ ([key, value]) => key === "broadcast" && value === "1",
+ ) &&
+ channelCan(channel, "reply")
+ )
+ return;
+ }
+ }
// Workflow-coordinate deletion is an ownership action, not a contribution.
// Full command validation still runs before signing and publication.
if (event.kind === 5 && isWorkflowOperation(event)) {
@@ -1681,6 +1758,7 @@ export function createRelaySession(
validateMentions(
destinations[0][1],
recipients.map((tag) => tag[1] ?? ""),
+ contributionThread(event) ? "reply" : "post",
);
}
async function prepareMentionPublication(
@@ -2688,11 +2766,11 @@ export function createRelaySession(
uploadLifetime.signal,
]);
combined.throwIfAborted();
- if (!channelId || closed || !channels.canWrite(channelId))
+ if (!channelId || closed || !canContribute(channelId, "reply"))
throw new UploadError("denied");
const result = await uploadAttachment(file, combined, progress);
combined.throwIfAborted();
- if (!channels.canWrite(channelId))
+ if (!canContribute(channelId, "reply"))
throw new UploadError("denied");
return result;
},
@@ -2751,22 +2829,12 @@ export function createRelaySession(
...createMessages(
writes?.outbox,
transport?.viewer,
- (id) => {
- const outgoing = local().find((item) => item.event.id === id);
- // The optimistic projection is unsigned even after publication. Use
- // its admitted signed record when an operation needs source evidence.
- return (
- outgoing?.signed ??
- recent.peek(id)?.event ??
- retainedEvent(id) ??
- outgoing?.event
- );
- },
+ messageEvent,
emoji.tags,
validateMentions,
- (id, owner) =>
+ (id, owner, action = "post") =>
!closed &&
- (channels.canWrite(id) ||
+ (canContribute(id, action) ||
// editOwnedAgent and messages.remove supply owner evidence;
// validateChannelWrite rechecks it before signing and publication.
(!!owner && channels.canParticipate(id))),