Skip to content

Commit 8d32680

Browse files
author
Brain
committed
Fix avatar validation, portable defaults, and broker registration
Signed-off-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz>
1 parent 3f7929b commit 8d32680

14 files changed

Lines changed: 450 additions & 63 deletions

‎crates/agent-controller/src/secret.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,11 @@ impl Secret {
4343
),
4444
};
4545
if let Some(picture) = picture {
46-
content.insert("picture".into(), json!(picture));
46+
if picture.is_empty() {
47+
content.remove("picture");
48+
} else {
49+
content.insert("picture".into(), json!(picture));
50+
}
4751
}
4852
let auth: Vec<String> =
4953
serde_json::from_str(auth).map_err(|_| "Invalid owner authorization")?;

‎crates/agent-controller/tests/avatar_profile.rs‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,10 +75,14 @@ fn replacement_preserves_unowned_metadata_and_omitted_picture_but_can_clear() {
7575
.confirm(std::slice::from_ref(&event), event["id"].as_str().unwrap())
7676
.unwrap();
7777
let content: Value = serde_json::from_str(event["content"].as_str().unwrap()).unwrap();
78-
assert_eq!(
79-
content["picture"],
80-
picture.unwrap_or("https://images.example/old.png")
81-
);
78+
if picture == Some("") {
79+
assert!(content.get("picture").is_none());
80+
} else {
81+
assert_eq!(
82+
content["picture"],
83+
picture.unwrap_or("https://images.example/old.png")
84+
);
85+
}
8286
assert_eq!(content["about"], "Keep me");
8387
assert_eq!(content["nip05"], "[email protected]");
8488
assert_eq!(content["extension"], json!({"nested":[1,2]}));

‎docs/communities.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,12 @@ remote side effect and is not undone if later profile setup fails or is cancelle
4242
Profile editing preserves existing fields that this editor does not expose.
4343
After a confirmed Settings save, the profile also becomes the device-local
4444
default used in Personal space and new-community setup; other existing community
45-
profiles are not changed. Community-hosted media is not copied into that default:
45+
profiles are not changed. Media under the current community's `/media/` path is
46+
not copied into that default:
4647
its previous picture is kept, while public URLs and explicit removal still update
47-
it. First-join seeding follows the same rule. The top-right button and menu show the selected
48+
it. First-join seeding follows the same rule. URLs hosted by another community and
49+
URLs entered in Personal space are not classified by this guard; user-supplied HTTPS
50+
URLs are not guaranteed portable. The top-right button and menu show the selected
4851
community's name and avatar through its existing profile/media session. Pending
4952
or unavailable community profiles show an identity fallback, not another
5053
community's avatar. Personal space uses the local default. Merely loading a

‎src/app/ProfileSettings.avatar.test.tsx‎

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,11 @@ function deferred<T>() {
4040
});
4141
return { promise, resolve };
4242
}
43-
function setup(selected: string | null = a, picture = "") {
43+
function setup(
44+
selected: string | null = a,
45+
picture = "",
46+
inheritedPicture = "",
47+
) {
4448
let state: ClientSnapshot = {
4549
status: "ready",
4650
viewer: "a".repeat(64),
@@ -73,7 +77,20 @@ function setup(selected: string | null = a, picture = "") {
7377
string,
7478
Awaited<ReturnType<typeof api.inspectProfile>>
7579
>([
76-
[a, original("Alpha human")],
80+
[
81+
a,
82+
{
83+
...original("Alpha human"),
84+
profile: {
85+
...original("Alpha human").profile,
86+
picture: inheritedPicture,
87+
},
88+
existing: {
89+
...original("Alpha human").existing,
90+
picture: inheritedPicture,
91+
},
92+
},
93+
],
7794
[b, original("Beta human")],
7895
]);
7996
vi.mocked(api.inspectProfile).mockImplementation(async (id) => {
@@ -393,6 +410,10 @@ it("confirms a dispatched save through its captured session after leaving Settin
393410

394411
it.each([
395412
["https://a.example/media/upload.png", "https://public.example/previous.png"],
413+
[
414+
"https://A.example:443/media/upload.png",
415+
"https://public.example/previous.png",
416+
],
396417
["https://public.example/new.png", "https://public.example/new.png"],
397418
["", ""],
398419
])(
@@ -421,3 +442,29 @@ it.each([
421442
});
422443
},
423444
);
445+
446+
it.each(["http://images.example/avatar.png", "data:image/png;base64,AA=="])(
447+
"explains inherited invalid picture %s and recovers after removal",
448+
async (picture) => {
449+
setup(a, "", picture);
450+
await editName();
451+
expect(screen.getByRole("button", { name: "Save profile" })).toBeDisabled();
452+
expect(screen.getByRole("alert")).toHaveTextContent(
453+
"Use an HTTPS image URL without credentials",
454+
);
455+
fireEvent.click(screen.getByRole("button", { name: "Edit avatar" }));
456+
const input = await screen.findByLabelText("Picture URL (optional)");
457+
expect(input).toHaveValue(picture);
458+
expect(input).toHaveAccessibleDescription(/Use an HTTPS image URL/);
459+
fireEvent.click(screen.getByRole("button", { name: "Remove avatar" }));
460+
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
461+
expect(screen.getByRole("button", { name: "Save profile" })).toBeEnabled();
462+
save();
463+
await screen.findByText("Profile updated");
464+
expect(api.publishProfile).toHaveBeenCalledWith(
465+
a,
466+
{ name: "Changed", picture: "", about: "Keep this" },
467+
expect.objectContaining({ picture }),
468+
);
469+
},
470+
);

‎src/bundled/agents/AgentCard.tsx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
MenuSeparator,
99
} from "../../shared/design-system/ui/Menu";
1010
import { ChoiceRow } from "../../shared/design-system/ui/ChoiceRow";
11-
import { avatarPreview } from "../../features/profiles/avatar-upload";
11+
import { useAvatarPreview } from "../../features/profiles/use-avatar-preview";
1212
import {
1313
DotsThreeIcon,
1414
UsersIcon,
@@ -52,9 +52,13 @@ export function AgentCard({
5252
);
5353
const managed = editable.length === 1 ? editable[0] : undefined;
5454
const source = avatarSource(managed?.picture ?? avatar);
55+
const managedPicture = useAvatarPreview(
56+
managed?.picture ?? "",
57+
managed?.relayUrl,
58+
);
5559
const picture =
5660
managed?.picture != null
57-
? avatarPreview(managed.picture, managed.relayUrl)
61+
? managedPicture
5862
: source?.startsWith("data:")
5963
? source
6064
: source

‎src/bundled/agents/AgentEditor.tsx‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { AvatarEditor } from "../../features/profiles/AvatarEditor";
2-
import { avatarPreview } from "../../features/profiles/avatar-upload";
3-
import { avatarSource } from "../../shared/avatar-source";
2+
import { useAvatarPreview } from "../../features/profiles/use-avatar-preview";
3+
import { avatarPictureError } from "../../features/profiles/avatar-upload";
44
import { XIcon } from "../../shared/design-system/icons";
55
import { IconButton } from "../../shared/design-system/ui/IconButton";
66
import { useEffect, useRef, useState } from "react";
@@ -54,6 +54,10 @@ export function AgentEditor({
5454
const stale = current.revision !== agent.revision;
5555
const blocked = state.busy || uploading || state.status !== "ready";
5656
const picture = current.picture ?? agent.picture ?? avatar ?? "";
57+
const preview = useAvatarPreview(
58+
state.data?.avatarEditingAvailable ? "" : picture,
59+
agent.relayUrl,
60+
);
5761
const canClose =
5862
!state.busy || !!(state.pendingLaunch || state.pendingCredentialWrite);
5963
const launchBlocked = !!agentLaunchBlock(state, agent) || dirty;
@@ -105,12 +109,9 @@ export function AgentEditor({
105109
onSubmit={(event) => {
106110
event.preventDefault();
107111
if (blocked || !dirty || stale) return;
108-
if (
109-
current.picture &&
110-
(!current.picture.startsWith("https://") ||
111-
!avatarSource(current.picture))
112-
) {
113-
setError("Use an HTTPS image URL without credentials.");
112+
const pictureError = avatarPictureError(current.picture ?? "");
113+
if (pictureError) {
114+
setError(pictureError);
114115
return;
115116
}
116117
let edit: ReturnType<typeof agentEdit>;
@@ -161,7 +162,7 @@ export function AgentEditor({
161162
/>
162163
) : (
163164
<Avatar
164-
src={avatarPreview(picture, agent.relayUrl)}
165+
src={preview}
165166
alt=""
166167
fallback={displayName}
167168
size="large"

‎src/features/communities/CommunityDialog.test.tsx‎

Lines changed: 76 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -155,22 +155,67 @@ it("names exact relay claim refusals and keeps other failures generic", async ()
155155
}
156156
});
157157

158-
it("keeps a community upload out of first-join local defaults without changing the published profile", async () => {
158+
it.each([
159+
"https://relay.example/media/avatar.png",
160+
"https://RELAY.example:443/media/avatar.png",
161+
])(
162+
"keeps %s out of first-join local defaults without changing the published profile",
163+
async (picture) => {
164+
api.inspectProfile.mockResolvedValueOnce({
165+
exists: true,
166+
existing: { name: "Fixture" },
167+
profile: {
168+
name: "Fixture",
169+
picture,
170+
about: "",
171+
},
172+
});
173+
vi.stubGlobal(
174+
"fetch",
175+
vi.fn(async (url: string) => {
176+
const route = String(url).split("/").at(-1);
177+
if (route === "register") return Response.json({ id: "x" });
178+
if (route === "info") return Response.json({ name: "Fixture" });
179+
throw new Error(`Unexpected request: ${url}`);
180+
}),
181+
);
182+
const communities = {
183+
snapshot: () => ({ status: "ready", profile: { name: "", picture: "" } }),
184+
joined: vi.fn(),
185+
} as unknown as Communities;
186+
render(
187+
<CommunityDialog
188+
communities={communities}
189+
mode="join"
190+
close={() => {}}
191+
/>,
192+
);
193+
const user = userEvent.setup();
194+
await user.type(screen.getByLabelText("Relay URL"), "wss://relay.example");
195+
await user.click(screen.getByRole("button", { name: "Continue" }));
196+
await user.click(
197+
await screen.findByRole("button", { name: "Open community" }),
198+
);
199+
expect(api.publishProfile).not.toHaveBeenCalled();
200+
expect(communities.joined).toHaveBeenCalledWith(
201+
expect.objectContaining({ id: "https://relay.example" }),
202+
{ name: "Fixture", picture: "", about: "" },
203+
);
204+
},
205+
);
206+
207+
it("explains an inherited invalid avatar when editing at join and recovers on replacement", async () => {
208+
const picture = "http://images.example/avatar.png";
159209
api.inspectProfile.mockResolvedValueOnce({
160210
exists: true,
161-
existing: { name: "Fixture" },
162-
profile: {
163-
name: "Fixture",
164-
picture: "https://relay.example/media/avatar.png",
165-
about: "",
166-
},
211+
existing: { name: "Fixture", picture },
212+
profile: { name: "Fixture", picture, about: "" },
167213
});
168214
vi.stubGlobal(
169215
"fetch",
170216
vi.fn(async (url: string) => {
171-
const route = String(url).split("/").at(-1);
172-
if (route === "register") return Response.json({ id: "x" });
173-
if (route === "info") return Response.json({ name: "Fixture" });
217+
if (url.endsWith("/register")) return Response.json({ id: "x" });
218+
if (url.endsWith("/info")) return Response.json({ name: "Fixture" });
174219
throw new Error(`Unexpected request: ${url}`);
175220
}),
176221
);
@@ -184,12 +229,28 @@ it("keeps a community upload out of first-join local defaults without changing t
184229
const user = userEvent.setup();
185230
await user.type(screen.getByLabelText("Relay URL"), "wss://relay.example");
186231
await user.click(screen.getByRole("button", { name: "Continue" }));
232+
await user.type(await screen.findByLabelText("Display name"), " changed");
233+
expect(
234+
screen.getByRole("button", { name: "Publish profile & open" }),
235+
).toBeDisabled();
236+
expect(screen.getByRole("alert")).toHaveTextContent("Use an HTTPS image URL");
237+
await user.click(screen.getByRole("button", { name: "Edit avatar" }));
238+
const input = await screen.findByLabelText("Picture URL (optional)");
239+
expect(input).toHaveAccessibleDescription(/Use an HTTPS image URL/);
240+
await user.clear(input);
241+
await user.type(input, "https://images.example/new.png");
242+
await user.click(screen.getByRole("button", { name: "Done" }));
243+
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
187244
await user.click(
188-
await screen.findByRole("button", { name: "Open community" }),
245+
screen.getByRole("button", { name: "Publish profile & open" }),
189246
);
190-
expect(api.publishProfile).not.toHaveBeenCalled();
191-
expect(communities.joined).toHaveBeenCalledWith(
192-
expect.objectContaining({ id: "https://relay.example" }),
193-
{ name: "Fixture", picture: "", about: "" },
247+
expect(api.publishProfile).toHaveBeenCalledWith(
248+
"https://relay.example",
249+
{
250+
name: "Fixture changed",
251+
picture: "https://images.example/new.png",
252+
about: "",
253+
},
254+
{ name: "Fixture", picture },
194255
);
195256
});

‎src/features/communities/ProfileFields.tsx‎

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,11 @@
11
import { Field } from "../../shared/design-system/ui/Field";
22
import { Input } from "../../shared/design-system/ui/Input";
33
import { AvatarEditor } from "../profiles/AvatarEditor";
4+
import { avatarPictureError } from "../profiles/avatar-upload";
45
import type { PersonalProfile } from "./service";
56
import { PROFILE_ABOUT_MAX_LENGTH } from "./service";
67
import { Textarea } from "../../shared/design-system/ui/Textarea";
78

8-
function validPicture(value: string) {
9-
if (!value) return true;
10-
try {
11-
const url = new URL(value);
12-
return url.protocol === "https:" && !url.username && !url.password;
13-
} catch {
14-
return false;
15-
}
16-
}
17-
189
export function profilesEqual(left: PersonalProfile, right: PersonalProfile) {
1910
return (
2011
left.name === right.name &&
@@ -26,7 +17,7 @@ export function profilesEqual(left: PersonalProfile, right: PersonalProfile) {
2617
export function canSaveProfile(profile: PersonalProfile) {
2718
return (
2819
!!profile.name.trim() &&
29-
validPicture(profile.picture) &&
20+
!avatarPictureError(profile.picture) &&
3021
(profile.about?.length ?? 0) <= PROFILE_ABOUT_MAX_LENGTH
3122
);
3223
}
Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
11
import { communityDestination } from "./destination";
22
import type { PersonalProfile } from "./service";
33

4-
/** Community media needs that community's credentials; never seed another one with it. */
4+
/** Keep current-community media out of the local default used for other communities. */
55
export function profileDefault(
66
profile: PersonalProfile,
77
previous: PersonalProfile,
88
community?: string,
99
): PersonalProfile {
1010
if (!community || !profile.picture) return profile;
11-
return profile.picture.startsWith(
12-
`${communityDestination(community).url}/media/`,
13-
)
14-
? { ...profile, picture: previous.picture }
15-
: profile;
11+
try {
12+
const picture = new URL(profile.picture);
13+
return picture.origin === communityDestination(community).url &&
14+
picture.pathname.startsWith("/media/")
15+
? { ...profile, picture: previous.picture }
16+
: profile;
17+
} catch {
18+
return profile;
19+
}
1620
}

‎src/features/profiles/AvatarEditor.test.tsx‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,5 +184,18 @@ it("rejects unsafe URLs before selecting the draft", async () => {
184184
target: { value },
185185
});
186186
expect(screen.getByRole("button", { name: "Done" })).toBeDisabled();
187+
expect(
188+
screen.getByLabelText("Picture URL (optional)"),
189+
).toHaveAccessibleDescription(/Use an HTTPS image URL/);
187190
}
188191
});
192+
193+
it("accepts equivalent HTTPS spellings without a misleading validation error", async () => {
194+
render(<Form />);
195+
await open();
196+
fireEvent.change(screen.getByLabelText("Picture URL (optional)"), {
197+
target: { value: "HTTPS://IMAGES.example:443/avatar.png" },
198+
});
199+
expect(screen.getByRole("button", { name: "Done" })).toBeEnabled();
200+
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
201+
});

0 commit comments

Comments
 (0)