Skip to content

Commit 47ce269

Browse files
fix(ui): preserve profile avatars under Control UI base paths (#119308)
* fix(ui): preserve active session status layout * fix(ui): preserve avatar paths and fork lineage * fix(ui): preserve avatars under control UI base paths
1 parent 95d7d95 commit 47ce269

9 files changed

Lines changed: 151 additions & 26 deletions

‎src/gateway/server-http.ts‎

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ import {
7171
type GatewayWsClient,
7272
} from "./server/ws-types.js";
7373
import { isTerminalConfigEnabled } from "./terminal/enabled.js";
74-
import { matchUserProfileAvatarPath } from "./user-profiles-http-path.js";
74+
import { canonicalizeUserProfileAvatarPath } from "./user-profiles-http-path.js";
7575

7676
type PluginGatewayDispatchContext = {
7777
gatewayAuthSatisfied?: boolean;
@@ -523,16 +523,17 @@ export function createGatewayHttpServer(opts: {
523523
scopedRequestPath.startsWith("/__openclaw__/board/"),
524524
async () => (await getBoardHttpModule()).handleBoardHttpRequest(req, res),
525525
);
526-
addAdmittedStage(
527-
"user-profile-avatar",
528-
matchUserProfileAvatarPath(scopedRequestPath) !== undefined,
529-
async () =>
530-
(await getUserProfilesHttpModule()).handleUserProfileAvatarHttpRequest(
531-
req,
532-
res,
533-
scopedRequestPath,
534-
routeAuth,
535-
),
526+
const userProfileAvatarPath = canonicalizeUserProfileAvatarPath(
527+
scopedRequestPath,
528+
controlUiRouteBasePath,
529+
);
530+
addAdmittedStage("user-profile-avatar", userProfileAvatarPath !== undefined, async () =>
531+
(await getUserProfilesHttpModule()).handleUserProfileAvatarHttpRequest(
532+
req,
533+
res,
534+
userProfileAvatarPath ?? scopedRequestPath,
535+
routeAuth,
536+
),
536537
);
537538
addAdmittedStage(
538539
"openresponses",
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { describe, expect, it } from "vitest";
2+
import { canonicalizeUserProfileAvatarPath } from "./user-profiles-http-path.js";
3+
4+
describe("canonicalizeUserProfileAvatarPath", () => {
5+
it("preserves the root avatar route", () => {
6+
expect(canonicalizeUserProfileAvatarPath("/api/users/profile-1/avatar", "/wilfred")).toBe(
7+
"/api/users/profile-1/avatar",
8+
);
9+
});
10+
11+
it("removes an exact Control UI base-path prefix", () => {
12+
expect(
13+
canonicalizeUserProfileAvatarPath("/wilfred/api/users/profile-1/avatar", "/wilfred"),
14+
).toBe("/api/users/profile-1/avatar");
15+
});
16+
17+
it.each([
18+
"/wilfred-other/api/users/profile-1/avatar",
19+
"/wilfred/api/users/profile-1/avatar/extra",
20+
])("rejects non-matching alias %s", (pathname) => {
21+
expect(canonicalizeUserProfileAvatarPath(pathname, "/wilfred")).toBeUndefined();
22+
});
23+
});

‎src/gateway/user-profiles-http-path.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,17 @@ export function matchUserProfileAvatarPath(pathname: string): string | undefined
1515
return undefined;
1616
}
1717
}
18+
19+
export function canonicalizeUserProfileAvatarPath(
20+
pathname: string,
21+
controlUiBasePath: string,
22+
): string | undefined {
23+
if (matchUserProfileAvatarPath(pathname) !== undefined) {
24+
return pathname;
25+
}
26+
if (!controlUiBasePath || !pathname.startsWith(`${controlUiBasePath}/`)) {
27+
return undefined;
28+
}
29+
const canonicalPath = pathname.slice(controlUiBasePath.length);
30+
return matchUserProfileAvatarPath(canonicalPath) !== undefined ? canonicalPath : undefined;
31+
}

‎ui/src/app/bootstrap.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ export function bootstrapApplication(
276276
startup.password ?? "",
277277
startup.pendingBootstrapToken ?? "",
278278
undefined,
279-
{ persistDefaultConnectionSettings: documentMode === null },
279+
{ persistDefaultConnectionSettings: documentMode === null, basePath },
280280
);
281281
const agents = createAgentCapability(gateway);
282282
const startupLifecycle = createStartupLifecycle();

‎ui/src/app/gateway-store.test.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type {
66
GatewayEventFrame,
77
GatewayHelloOk,
88
} from "../api/gateway.ts";
9+
import { resolveAvatar, setAvatarGatewayOrigin } from "../lib/identity-avatar.ts";
910
import { createStorageMock } from "../test-helpers/storage.ts";
1011
import { createApplicationGateway } from "./gateway-store.ts";
1112
import { loadSettings } from "./settings.ts";
@@ -70,6 +71,7 @@ function createStore(
7071
params: {
7172
settings?: ReturnType<typeof loadSettings>;
7273
persistDefaultConnectionSettings?: boolean;
74+
basePath?: string;
7375
} = {},
7476
) {
7577
const clients: FakeGatewayClient[] = [];
@@ -82,7 +84,10 @@ function createStore(
8284
clients.push(client);
8385
return client as unknown as GatewayBrowserClient;
8486
},
85-
{ persistDefaultConnectionSettings: params.persistDefaultConnectionSettings },
87+
{
88+
persistDefaultConnectionSettings: params.persistDefaultConnectionSettings,
89+
basePath: params.basePath,
90+
},
8691
);
8792
const current = () => {
8893
const client = clients.at(-1);
@@ -103,16 +108,32 @@ describe("createApplicationGateway connection phase", () => {
103108
protocol: "http:",
104109
host: "127.0.0.1:18789",
105110
hostname: "127.0.0.1",
111+
origin: "http://127.0.0.1:18789",
106112
pathname: "/",
107113
} as Location);
108114
});
109115

110116
afterEach(() => {
117+
setAvatarGatewayOrigin(null);
111118
vi.useRealTimers();
112119
vi.unstubAllGlobals();
113120
vi.restoreAllMocks();
114121
});
115122

123+
it("passes the explicit same-origin base path to avatar resolution", () => {
124+
const settings = { ...loadSettings(), gatewayUrl: "ws://127.0.0.1:18789/ws" };
125+
const { gateway } = createStore({ settings, basePath: "/wilfred" });
126+
127+
gateway.start();
128+
129+
expect(
130+
resolveAvatar({ id: "[email protected]", profileAvatarUrl: "/api/users/p1/avatar" }),
131+
).toEqual({
132+
kind: "profile",
133+
url: "http://127.0.0.1:18789/wilfred/api/users/p1/avatar",
134+
});
135+
});
136+
116137
it("follows stopped -> connecting -> connected -> reconnecting -> offline", () => {
117138
const { gateway, current } = createStore();
118139

‎ui/src/app/gateway-store.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ export function createApplicationGateway(
6666
initialPassword = "",
6767
initialBootstrapToken = "",
6868
createClient: GatewayClientFactory = defaultClientFactory,
69-
options: { persistDefaultConnectionSettings?: boolean } = {},
69+
options: { persistDefaultConnectionSettings?: boolean; basePath?: string } = {},
7070
): ApplicationGateway {
7171
let settings = initialSettings;
7272
let persistConnectionSettings = options.persistDefaultConnectionSettings !== false;
@@ -288,6 +288,7 @@ export function createApplicationGateway(
288288
settings: { token: nextConnection.token },
289289
password: nextConnection.password,
290290
}),
291+
options.basePath,
291292
);
292293
updateSettings(
293294
{
@@ -327,6 +328,7 @@ export function createApplicationGateway(
327328
settings: { token: nextConnection.token },
328329
password: nextConnection.password,
329330
}),
331+
options.basePath,
330332
);
331333
connection = { ...connection, bootstrapToken: "" };
332334
if (persistConnectionSettings) {

‎ui/src/e2e/profile-page.e2e.test.ts‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ const allowMissingChromium = process.env.OPENCLAW_UI_E2E_ALLOW_MISSING_CHROMIUM
2121
const describeControlUiE2e = chromiumAvailable || !allowMissingChromium ? describe : describe.skip;
2222
const captureUiProof = process.env.OPENCLAW_CAPTURE_UI_PROOF === "1";
2323
const proofDir = path.join(process.cwd(), ".artifacts", "control-ui-e2e", "profile-identity");
24+
const basePath = "/wilfred";
25+
const profilePath = `${basePath}/settings/profile`;
2426

2527
async function screenshot(page: Page, name: string) {
2628
if (!captureUiProof) {
@@ -74,12 +76,13 @@ describeControlUiE2e("Control UI profile page mocked Gateway E2E", () => {
7476

7577
async function openProfilePage(page: Page) {
7678
const gateway = await installMockGateway(page, {
79+
basePath,
7780
presenceUsers: testPresenceUsers,
7881
methodResponses: {
7982
"users.self": { profile: testProfile },
8083
},
8184
});
82-
const response = await page.goto(`${server.baseUrl}settings/profile`);
85+
const response = await page.goto(new URL(profilePath, server.baseUrl).href);
8386
expect(response?.status()).toBe(200);
8487
return gateway;
8588
}
@@ -121,7 +124,7 @@ describeControlUiE2e("Control UI profile page mocked Gateway E2E", () => {
121124
viewport: { width: 1280, height: 800 },
122125
});
123126
const page = await context.newPage();
124-
await page.route(`${server.baseUrl}settings/profile`, async (route) => {
127+
await page.route(new URL(profilePath, server.baseUrl).href, async (route) => {
125128
const response = await route.fetch();
126129
const body = await response.text();
127130
await route.fulfill({
@@ -182,14 +185,15 @@ describeControlUiE2e("Control UI profile page mocked Gateway E2E", () => {
182185
});
183186
});
184187
const gateway = await installMockGateway(page, {
188+
basePath,
185189
presenceUsers: testPresenceUsers,
186190
methodResponses: {
187191
"users.self": { profile: testProfile },
188192
},
189193
});
190194

191195
try {
192-
const response = await page.goto(`${server.baseUrl}settings/profile`);
196+
const response = await page.goto(new URL(profilePath, server.baseUrl).href);
193197
expect(response?.status()).toBe(200);
194198
expect(response?.headers()["content-security-policy"]).toContain(
195199
"img-src 'self' data: blob:",
@@ -220,7 +224,7 @@ describeControlUiE2e("Control UI profile page mocked Gateway E2E", () => {
220224
await expect.poll(() => avatarRequests.length).toBe(1);
221225
expect(avatarRequests[0]).toEqual({
222226
authorization: "Bearer e2e-device-token",
223-
url: expect.stringContaining(`/api/users/${testProfile.id}/avatar?v=2`),
227+
url: new URL(`${basePath}/api/users/${testProfile.id}/avatar?v=2`, server.baseUrl).href,
224228
});
225229
expect(await sidebarAvatar.getAttribute("src")).toBe(imageUrl);
226230
expect(
@@ -286,7 +290,7 @@ describeControlUiE2e("Control UI profile page mocked Gateway E2E", () => {
286290
).toBe(false);
287291
expect(avatarRequests[1]).toEqual({
288292
authorization: "Bearer e2e-device-token",
289-
url: expect.stringContaining(`/api/users/${testProfile.id}/avatar?v=3`),
293+
url: new URL(`${basePath}/api/users/${testProfile.id}/avatar?v=3`, server.baseUrl).href,
290294
});
291295
if (captureUiProof) {
292296
await page.screenshot({
@@ -321,7 +325,7 @@ describeControlUiE2e("Control UI profile page mocked Gateway E2E", () => {
321325
expect(await originalSidebarImage?.evaluate((image) => image.isConnected)).toBe(true);
322326
expect(avatarRequests[2]).toEqual({
323327
authorization: "Bearer e2e-device-token",
324-
url: expect.stringContaining(`/api/users/${testProfile.id}/avatar?v=4`),
328+
url: new URL(`${basePath}/api/users/${testProfile.id}/avatar?v=4`, server.baseUrl).href,
325329
});
326330
if (captureUiProof) {
327331
await page.screenshot({
@@ -338,14 +342,15 @@ describeControlUiE2e("Control UI profile page mocked Gateway E2E", () => {
338342
const context = await browser.newContext();
339343
const page = await context.newPage();
340344
const gateway = await installMockGateway(page, {
345+
basePath,
341346
presenceUsers: testPresenceUsers,
342347
methodResponses: {
343348
"users.self": { sequence: [{}, { profile: testProfile }] },
344349
},
345350
});
346351

347352
try {
348-
const response = await page.goto(`${server.baseUrl}settings/profile`);
353+
const response = await page.goto(new URL(profilePath, server.baseUrl).href);
349354
expect(response?.status()).toBe(200);
350355

351356
const emptyState = page.locator(".profile-identity-empty");
@@ -370,6 +375,7 @@ describeControlUiE2e("Control UI profile page mocked Gateway E2E", () => {
370375
const context = await browser.newContext();
371376
const page = await context.newPage();
372377
const gateway = await installMockGateway(page, {
378+
basePath,
373379
deferredMethods: ["users.self"],
374380
presenceUsers: testPresenceUsers,
375381
methodResponses: {
@@ -378,7 +384,7 @@ describeControlUiE2e("Control UI profile page mocked Gateway E2E", () => {
378384
});
379385

380386
try {
381-
const response = await page.goto(`${server.baseUrl}settings/profile`);
387+
const response = await page.goto(new URL(profilePath, server.baseUrl).href);
382388
expect(response?.status()).toBe(200);
383389

384390
const refresh = page.locator(".profile-refresh");

‎ui/src/lib/identity-avatar.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,47 @@ describe("resolveAvatar profile URL origin restriction", () => {
9898
});
9999

100100
describe("resolveAvatar gateway origin trust", () => {
101+
it("applies an explicit base path for a same-origin gateway", () => {
102+
vi.stubGlobal("location", { origin: "https://gw.example.com" });
103+
setAvatarGatewayOrigin("wss://gw.example.com/ws", null, "/wilfred");
104+
expect(
105+
resolveAvatar({ id: "[email protected]", profileAvatarUrl: "/api/users/p1/avatar?v=2" }),
106+
).toEqual({
107+
kind: "profile",
108+
url: "https://gw.example.com/wilfred/api/users/p1/avatar?v=2",
109+
});
110+
});
111+
112+
it("never infers a base path from the WebSocket pathname", () => {
113+
vi.stubGlobal("location", { origin: "https://gw.example.com" });
114+
setAvatarGatewayOrigin("wss://gw.example.com/ws");
115+
expect(
116+
resolveAvatar({ id: "[email protected]", profileAvatarUrl: "/api/users/p1/avatar" }),
117+
).toEqual({ kind: "profile", url: "https://gw.example.com/api/users/p1/avatar" });
118+
});
119+
120+
it("does not apply the page base path to a cross-origin gateway", () => {
121+
vi.stubGlobal("location", { origin: "https://ui.example.com" });
122+
setAvatarGatewayOrigin("wss://gw.example.com/ws", null, "/wilfred");
123+
expect(
124+
resolveAvatar({ id: "[email protected]", profileAvatarUrl: "/api/users/p1/avatar" }),
125+
).toEqual({ kind: "profile", url: "https://gw.example.com/api/users/p1/avatar" });
126+
});
127+
128+
it("rejects non-exact avatar routes under a same-origin mount", () => {
129+
vi.stubGlobal("location", { origin: "https://gw.example.com" });
130+
setAvatarGatewayOrigin("wss://gw.example.com/ws", null, "/wilfred");
131+
for (const profileAvatarUrl of [
132+
"https://gw.example.com/wilfred/api/users/p1/avatar/extra",
133+
"https://gw.example.com/wilfred/api/users/p1/avatar/other",
134+
"https://gw.example.com/wilfred/api/secrets",
135+
]) {
136+
expect(resolveAvatar({ id: "[email protected]", profileAvatarUrl })).toMatchObject({
137+
kind: "initials",
138+
});
139+
}
140+
});
141+
101142
it("resolves relative paths against the configured gateway origin", () => {
102143
setAvatarGatewayOrigin("wss://gw.example.com/ws");
103144
expect(

‎ui/src/lib/identity-avatar.ts‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { AVATAR_MAX_BYTES } from "../../../src/shared/avatar-limits.js";
2+
import { normalizeBasePath } from "../app-route-paths.ts";
23
import { formatSenderLabel, type SenderIdentity } from "./chat/sender-label.ts";
34
import { fnv1aUtf16 } from "./fnv1a.ts";
45

@@ -12,6 +13,7 @@ export type IdentityAvatarInput = SenderIdentity & {
1213
const ORIGIN_PROBE = "https://origin-probe.invalid";
1314

1415
let appGatewayOrigin: string | null = null;
16+
let appGatewayBasePath = "";
1517
let appGatewayAuthHeader: string | null = null;
1618

1719
const IDENTITY_AVATAR_CACHE_MAX_ENTRIES = 128;
@@ -73,13 +75,22 @@ function toHttpOrigin(url: string | null | undefined): string | null {
7375
export function setAvatarGatewayOrigin(
7476
gatewayUrl: string | null | undefined,
7577
authHeader: string | null = null,
78+
controlUiBasePath = "",
7679
): void {
7780
const nextOrigin = toHttpOrigin(gatewayUrl);
81+
const documentOrigin = globalThis.location?.origin;
82+
const nextBasePath =
83+
nextOrigin && documentOrigin === nextOrigin ? normalizeBasePath(controlUiBasePath) : "";
7884
const nextAuthHeader = authHeader?.trim() || null;
79-
if (appGatewayOrigin !== nextOrigin || appGatewayAuthHeader !== nextAuthHeader) {
85+
if (
86+
appGatewayOrigin !== nextOrigin ||
87+
appGatewayBasePath !== nextBasePath ||
88+
appGatewayAuthHeader !== nextAuthHeader
89+
) {
8090
clearIdentityAvatarCache();
8191
}
8292
appGatewayOrigin = nextOrigin;
93+
appGatewayBasePath = nextBasePath;
8394
appGatewayAuthHeader = nextAuthHeader;
8495
}
8596

@@ -98,11 +109,17 @@ const USER_AVATAR_PATHNAME = /^\/api\/users\/[^/]+\/avatar$/u;
98109
function toTrustedAvatarUrl(value: string, gatewayOrigin: string | null): string | null {
99110
try {
100111
const parsed = new URL(value, ORIGIN_PROBE);
101-
if (!USER_AVATAR_PATHNAME.test(parsed.pathname)) {
112+
const relativeRoute = parsed.origin === ORIGIN_PROBE;
113+
const canonicalPathname = relativeRoute
114+
? parsed.pathname
115+
: appGatewayBasePath && parsed.pathname.startsWith(`${appGatewayBasePath}/`)
116+
? parsed.pathname.slice(appGatewayBasePath.length)
117+
: parsed.pathname;
118+
if (!USER_AVATAR_PATHNAME.test(canonicalPathname)) {
102119
return null;
103120
}
104-
const suffix = parsed.pathname + parsed.search;
105-
if (parsed.origin === ORIGIN_PROBE) {
121+
const suffix = `${appGatewayBasePath}${canonicalPathname}${parsed.search}`;
122+
if (relativeRoute) {
106123
return gatewayOrigin ? new URL(suffix, gatewayOrigin).toString() : suffix;
107124
}
108125
return gatewayOrigin && parsed.origin === gatewayOrigin ? gatewayOrigin + suffix : null;

0 commit comments

Comments
 (0)