Skip to content
26 changes: 26 additions & 0 deletions browser-host/relay-broker-api.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2652,6 +2652,32 @@ test("an addition can ask the relay first, and its refusal reaches the app as wo
}
});

test("direct-message passes on which agent's add policy refused it", async () => {
const agent = "d".repeat(64);
const reasons = [
`forbidden: policy:owner_only — only the agent owner can add this agent (agent ${agent})`,
`forbidden: policy:nobody — this agent has disabled external channel additions (agent ${agent})`,
];
const h = await harness(() =>
Response.json({ error: reasons.shift() }, { status: 400 }),
);
try {
const transport = await connectBrokerTransport(h.base);
const person = "a".repeat(64);
await expect(
transport.openDirectMessage([person], new AbortController().signal),
).rejects.toThrow(`policy:owner_only (agent ${agent})`);
await expect(
transport.openDirectMessage([person], new AbortController().signal, {
channelId: "11111111-1111-4111-8111-111111111111",
includeHistory: "ask",
}),
).rejects.toThrow(`policy:nobody (agent ${agent})`);
} finally {
await h.close();
}
});

test.each([
{
accepted: false,
Expand Down
78 changes: 71 additions & 7 deletions src-tauri/src/relay/channel_writes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ pub(crate) async fn relay_direct_message(
let viewer = host.viewer().await?;
let tags = direct_message_tags(&viewer, pubkeys, channel, history.as_deref())?;
let adding = tags[0][0] == "h";
let failed = direct_message_refusal(adding, None);
let failed = || direct_message_refusal(adding, None);
let event = host
.sign(EventTemplate {
kind: if adding { 41011 } else { 41010 },
Expand All @@ -357,19 +357,19 @@ pub(crate) async fn relay_direct_message(
let reason = serde_json::from_str::<Value>(&response.body)
.ok()
.and_then(|body| body.get("error")?.as_str().map(str::to_owned));
return Err(direct_message_refusal(adding, reason.as_deref()).into());
return Err(direct_message_refusal(adding, reason.as_deref()));
}
let receipt: Value = serde_json::from_str(&response.body).map_err(|_| failed)?;
let receipt: Value = serde_json::from_str(&response.body).map_err(|_| failed())?;
if receipt.get("event_id") != event.get("id")
|| receipt.get("accepted") != Some(&Value::Bool(true))
{
return Err(failed.into());
return Err(failed());
}
let payload = receipt
.get("message")
.and_then(Value::as_str)
.and_then(|m| m.strip_prefix("response:"))
.ok_or(failed)?;
.ok_or_else(failed)?;
let result: Value = serde_json::from_str(payload)
.map_err(|_| "The relay returned an invalid direct message.")?;
let id = result
Expand All @@ -384,8 +384,13 @@ pub(crate) async fn relay_direct_message(

/// What to show for the relay's refusal of a DM command, from its exact
/// reason, as `directMessageRefusal` in `direct-message-policy.ts` words it.
/// A relay from before `ask` refuses the tag itself, which asks too.
fn direct_message_refusal(adding: bool, reason: Option<&str>) -> &'static str {
/// A relay from before `ask` refuses the tag itself, which asks too. An
/// agent's add-policy refusal passes on as `policy:<policy> (agent <pubkey>)`,
/// for the app to name the agent.
fn direct_message_refusal(adding: bool, reason: Option<&str>) -> String {
if let Some((policy, agent)) = reason.and_then(agent_policy_refusal) {
return format!("policy:{policy} (agent {agent})");
}
match reason {
Some("needs-choice: history" | r#"invalid: history must be "include", got "ask""#)
if adding =>
Expand All @@ -402,6 +407,26 @@ fn direct_message_refusal(adding: bool, reason: Option<&str>) -> &'static str {
_ if adding => "Couldn’t add them. Try again.",
_ => "The direct message could not be opened. Try again.",
}
.into()
}

/// The policy and agent of the relay's refusal of a DM command by an agent's
/// add policy, as `agentPolicyRefusal` reads it: the relay names the agent
/// after its policy code.
fn agent_policy_refusal(reason: &str) -> Option<(&str, &str)> {
let rest = reason.strip_prefix("forbidden: ").unwrap_or(reason);
let rest = rest.strip_prefix("policy:")?;
let policy = ["owner_only", "nobody"].into_iter().find(|policy| {
rest.strip_prefix(policy).is_some_and(|after| {
after.is_empty() || !after.starts_with(|c: char| c.is_alphanumeric() || c == '_')
})
})?;
let agent = rest.strip_suffix(')')?.rsplit_once("(agent ")?.1;
(agent.len() == 64
&& agent
.bytes()
.all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')))
.then_some((policy, agent))
}

/// The most people and agents one addition to a DM names, as
Expand Down Expand Up @@ -1224,6 +1249,45 @@ mod direct_message_tests {
);
}

#[test]
fn an_agents_add_policy_refusal_names_the_agent() {
let agent = key('d');
for (adding, reason, policy) in [
(
false,
format!(
"forbidden: policy:owner_only — only the agent owner can add this agent (agent {agent})"
),
"owner_only",
),
(
true,
format!(
"forbidden: policy:nobody — this agent has disabled external channel additions (agent {agent})"
),
"nobody",
),
] {
let shown = direct_message_refusal(adding, Some(&reason));
assert_eq!(shown, format!("policy:{policy} (agent {agent})"));
// The browser host maps a refusal again on its way out.
assert_eq!(direct_message_refusal(adding, Some(&shown)), shown);
}
// Without a whole agent key, or from a relay that names none, it is
// an ordinary refusal.
for reason in [
"forbidden: policy:owner_only — only the agent owner can add this agent".to_owned(),
format!("forbidden: policy:owner_only (agent {})", &agent[1..]),
format!("forbidden: policy:owner_onlyx (agent {agent})"),
format!("forbidden: policy:anyone (agent {agent})"),
] {
assert_eq!(
direct_message_refusal(true, Some(&reason)),
"Couldn’t add them. Try again."
);
}
}

#[test]
fn malformed_requests_are_refused() {
let viewer = key('a');
Expand Down
7 changes: 5 additions & 2 deletions src/app/shell/SearchResults.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,10 @@ import {
useNamePreference,
verifiedLabel,
} from "../../features/profiles/name-preference";
import { sortParticipantNames } from "../../features/identity-names/participant-order";
import {
dmNamedParticipants,
sortParticipantNames,
} from "../../features/identity-names/participant-order";
import {
directMessageWith,
messagePerson,
Expand All @@ -160,7 +163,7 @@ function conversationName(
return channel.name;
return (
sortParticipantNames(
channel.participants.map((id) =>
dmNamedParticipants(channel.participants, profiles).map((id) =>
resolveName(
id,
profiles.get(id)?.name ?? id.slice(0, 10),
Expand Down
55 changes: 52 additions & 3 deletions src/bundled/channels/MemberAdministration.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,18 @@ async function setup(
messageNavigation = true,
initialReads?: { names?: Promise<void>; roster?: Promise<void> },
ownership?: "own" | "other" | "invalid",
visibility: "private" | "public" | "solo" | "view-only-solo" = "private",
visibility:
| "private"
| "public"
| "solo"
| "view-only-solo"
| "dm" = "private",
targetPicture?: string,
targetProfiled = true,
) {
const solo = visibility === "solo" || visibility === "view-only-solo";
const visibilityFlag =
visibility === "solo"
visibility === "solo" || visibility === "dm"
? "private"
: visibility === "view-only-solo"
? "public"
Expand Down Expand Up @@ -130,7 +135,7 @@ async function setup(
content: "",
tags: [
["d", id],
["t", "stream"],
["t", visibility === "dm" ? "dm" : "stream"],
[visibilityFlag],
...(solo ? [["t", "buzz.solo"]] : []),
...(visibility === "view-only-solo" ? [["join_role", "guest"]] : []),
Expand Down Expand Up @@ -915,6 +920,50 @@ it("keeps removal in a View only Solo chat without showing role choices", async
).toBeInTheDocument();
expect(screen.queryAllByRole("menuitemradio")).toHaveLength(0);
});
it.each([
["their own agent", true, "own", true],
["another's agent", true, "other", false],
["a person", false, undefined, false],
] as const)(
"in a DM, offers removal of %s only when the viewer owns it",
async (_, agent, ownership, removable) => {
const t = await setup(
"member",
"member",
true,
undefined,
agent,
undefined,
false,
true,
undefined,
ownership,
"dm",
);
await t.user.click(
screen.getByRole("button", { name: /^Actions for Morgan/ }),
);
await screen.findByRole("menuitem", { name: "View profile" });
if (!removable) {
expect(
screen.queryByRole("menuitem", { name: /^Remove/ }),
).not.toBeInTheDocument();
return;
}
await t.user.click(
await screen.findByRole("menuitem", { name: "Remove from DM" }),
);
const dialog = await screen.findByRole("dialog", {
name: "Remove agent from DM",
});
await t.user.click(
within(dialog).getByRole("button", { name: "Remove agent" }),
);
await vi.waitFor(() =>
expect(t.publish.mock.calls[0]?.[0]).toMatchObject({ kind: 9001 }),
);
},
);
it("presents verified roles, protects owners/self, and confirms a separate deliberate role intent", async () => {
const t = await setup();
await expectProfileOnly(t.user, "Carl");
Expand Down
32 changes: 32 additions & 0 deletions src/bundled/channels/useChannelLabels.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -354,3 +354,35 @@ it("names group DMs with participants in alphabetical order", async () => {
await act(async () => root.unmount());
}
});

it("leaves agents out of DM names unless no other person is in it", async () => {
const ana = "a".repeat(64),
bot = "b".repeat(64);
const profiles = new Map<string, { name: string; isAgent?: true }>([
[ana, { name: "Ana" }],
[bot, { name: "Bot", isAgent: true }],
]);
const queries = {
snapshot: () => profiles,
subscribe: () => () => {},
ensure: async () => {},
} as unknown as Parameters<typeof useChannelLabels>[1];
let labels: (string | undefined)[] = [];
function Probe() {
labels = useChannelLabels(
[
{ id: "both", name: "", channelType: "dm", participants: [bot, ana] },
{ id: "agent", name: "", channelType: "dm", participants: [bot] },
],
queries,
).channels.map((channel) => channel.name);
return null;
}
const root = createRoot(container());
try {
await act(async () => root.render(createElement(Probe)));
expect(labels).toEqual(["Ana", "Bot"]);
} finally {
await act(async () => root.unmount());
}
});
7 changes: 5 additions & 2 deletions src/bundled/channels/useChannelLabels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import { useEffect, useMemo, useRef, useSyncExternalStore } from "react";
import type { ChannelSummary } from "../../features/relay/contracts";
import type { ProfileQueries } from "../../features/relay/profile-directory";
import { selectProfiles } from "../../features/relay/profile-selection";
import { sortParticipantNames } from "../../features/identity-names/participant-order";
import {
dmNamedParticipants,
sortParticipantNames,
} from "../../features/identity-names/participant-order";

/** Share bounded profiles, not per-row fetches; pickers may widen the name scope. */
export function useChannelLabels(
Expand Down Expand Up @@ -83,7 +86,7 @@ export function useChannelLabels(
return previous.channel;
const name = channel.participants.length
? sortParticipantNames(
channel.participants.map((id) =>
dmNamedParticipants(channel.participants, profiles).map((id) =>
resolveName(
id,
profiles.get(id)?.name ?? id.slice(0, 10),
Expand Down
40 changes: 40 additions & 0 deletions src/bundled/inbox/dm-label.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,43 @@ it("preserves missing-roster versus self-DM fallback and uses public labels for
expect(dmLabel(undefined, names, resolve)).toBe("Notes to self");
expect(dmLabel([key], names, resolve)).toBe(publicKeyLabels([key]).get(key));
});
it("names the people in a DM and leaves its agents out", () => {
const [ana, ben, cy, dee, bot, helper, unloaded] = [
"a",
"b",
"c",
"d",
"e",
"f",
"9",
].map((c) => c.repeat(64)) as [
string,
string,
string,
string,
string,
string,
string,
];
const profiles = new Map<string, { name: string; isAgent?: true }>([
[ana, { name: "Ana" }],
[ben, { name: "Ben" }],
[cy, { name: "Cy" }],
[dee, { name: "Dee" }],
[bot, { name: "Bot", isAgent: true }],
[helper, { name: "Helper", isAgent: true }],
]);
const resolve = (_key: string, fallback: string) => fallback;
// People and agents: only the people.
expect(dmLabel([bot, ana], profiles, resolve)).toBe("Ana");
// Only agents: no other person, so the agents.
expect(dmLabel([helper, bot], profiles, resolve)).toBe("Bot, Helper");
// More than three people and agents: "+N" counts people only.
expect(dmLabel([bot, dee, cy, helper, ben, ana], profiles, resolve)).toBe(
"Ana, Ben, Cy +1",
);
// A profile not loaded yet is named until it says it is an agent.
expect(dmLabel([bot, unloaded], profiles, resolve)).toBe(
publicKeyLabels([unloaded]).get(unloaded),
);
});
12 changes: 9 additions & 3 deletions src/bundled/inbox/dm-label.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import { formatPublicKey } from "../../shared/identity/public-key";
import { sortParticipantNames } from "../../features/identity-names/participant-order";
import {
dmNamedParticipants,
sortParticipantNames,
} from "../../features/identity-names/participant-order";

/** One label recipe for Activity rows and details; callers own profile reads. */
export function dmLabel(
participants: readonly string[] | undefined,
profiles: ReadonlyMap<string, { name?: string | undefined }>,
profiles: ReadonlyMap<
string,
{ name?: string | undefined; isAgent?: true | undefined }
>,
resolve: (
key: string,
fallback: string,
Expand All @@ -16,7 +22,7 @@ export function dmLabel(
if (!participants.length) return "Notes to self";
// Sort every name before bounding, so the shown three match other surfaces.
const names = sortParticipantNames(
participants.map((key) =>
dmNamedParticipants(participants, profiles).map((key) =>
resolve(
key,
profiles.get(key)?.name ?? formatPublicKey(key) ?? "Unknown person",
Expand Down
Loading
Loading