Skip to content

Commit 0b715e3

Browse files
authored
refactor(ui): share Control UI resource route contract (#126386)
* refactor(ui): share Control UI resource route contract Gateway and Control UI now share browser-safe resource route grammar, while authorization and domain validation remain handler-owned. * perf(ui): keep resource routes out of startup Narrow browser-safe contract modules and the lazy authenticated avatar loader keep route/cache code out of the startup chunk while the stable Gateway barrel remains compatible.
1 parent 84c2111 commit 0b715e3

43 files changed

Lines changed: 774 additions & 633 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/gateway/assistant-avatar.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,4 +189,25 @@ describe("resolveGatewayAssistantAvatar", () => {
189189
}),
190190
).toEqual({ avatar: "/openclaw/avatar/main", resolution: null });
191191
});
192+
193+
it.each(["/avatar/main/extra", "//evil.example/avatar/main", "//[", "/avatar\\main"])(
194+
"rejects non-canonical same-origin avatar path %s",
195+
(avatar) => {
196+
const { cfg } = createWorkspace();
197+
198+
expect(
199+
resolveGatewayAssistantAvatar({
200+
cfg,
201+
identity: { agentId: "main", avatar, emoji: "🦞" },
202+
}),
203+
).toEqual({
204+
avatar: "🦞",
205+
resolution: {
206+
kind: "none",
207+
reason: "outside_workspace",
208+
source: avatar,
209+
},
210+
});
211+
},
212+
);
192213
});

‎src/gateway/assistant-avatar.ts‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import {
1515
} from "../shared/avatar-policy.js";
1616
import { createGatewayAvatarDataUrlCache } from "./assistant-avatar-cache.js";
1717
import { DEFAULT_ASSISTANT_IDENTITY } from "./assistant-identity.js";
18-
import { CONTROL_UI_AVATAR_PREFIX, normalizeControlUiBasePath } from "./control-ui-shared.js";
18+
import { buildControlUiResourcePath, matchControlUiResourceUrl } from "./control-ui-contract.js";
1919

2020
type GatewayAssistantIdentity = {
2121
agentId: string;
@@ -36,13 +36,12 @@ type OpenGatewayAssistantAvatarProjection = {
3636
const gatewayAvatarDataUrlCache = createGatewayAvatarDataUrlCache();
3737

3838
function resolveSameOriginAvatarUrl(cfg: OpenClawConfig, source: string): string | undefined {
39-
const basePath = normalizeControlUiBasePath(cfg.gateway?.controlUi?.basePath);
40-
const unbasedPrefix = `${CONTROL_UI_AVATAR_PREFIX}/`;
41-
const basedPrefix = basePath ? `${basePath}${unbasedPrefix}` : unbasedPrefix;
42-
if (basePath && source.startsWith(unbasedPrefix)) {
43-
return `${basePath}${source}`;
39+
const basePath = cfg.gateway?.controlUi?.basePath;
40+
const unbased = matchControlUiResourceUrl("agentAvatar", source);
41+
if (unbased) {
42+
return `${buildControlUiResourcePath("agentAvatar", basePath, unbased.value)}${unbased.search}${unbased.hash}`;
4443
}
45-
return source.startsWith(basedPrefix) ? source : undefined;
44+
return matchControlUiResourceUrl("agentAvatar", source, basePath) ? source : undefined;
4645
}
4746

4847
/**

‎src/gateway/authenticated-presence-user.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { SystemPresence } from "../infra/system-presence.js";
2-
import { formatUserProfileAvatarPath } from "./user-profiles-http-path.js";
2+
import { buildControlUiUserAvatarPath } from "./control-ui-contract.js";
33

44
type AuthenticatedPresenceProfile = {
55
profileId: string;
@@ -29,7 +29,7 @@ export function buildAuthenticatedPresenceUser(params: {
2929
: {}),
3030
// This authenticated route resolves uploaded avatars first and then the
3131
// gateway-side Gravatar proxy, so it remains present without an upload.
32-
avatarUrl: formatUserProfileAvatarPath(
32+
avatarUrl: buildControlUiUserAvatarPath(
3333
params.authenticatedUserProfile.profileId,
3434
params.authenticatedUserProfile.avatarRevision,
3535
),

‎src/gateway/channel-avatar-http.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import { createServer } from "node:http";
44
import type { AddressInfo } from "node:net";
55
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
6+
import { buildControlUiChannelAvatarUrl } from "./control-ui-contract.js";
67
import { HTTP_IMAGE_MAX_BYTES } from "./http-image-response.js";
78

89
const mocks = vi.hoisted(() => ({
@@ -99,7 +100,7 @@ describe("handleChannelAvatarHttpRequest", () => {
99100
});
100101

101102
const avatarRoute = (sessionKey: string) =>
102-
`http://127.0.0.1:${port}/__openclaw__/channel-avatar/${encodeURIComponent(sessionKey)}`;
103+
`http://127.0.0.1:${port}${buildControlUiChannelAvatarUrl("", sessionKey, "test-revision")}`;
103104

104105
it("serves managed conversation bytes with sandboxed image headers", async () => {
105106
const response = await fetch(avatarRoute("agent:main:discord:direct:user-1"));

‎src/gateway/channel-avatar-http.ts‎

Lines changed: 6 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,8 @@ import { createLazyRuntimeModule } from "../shared/lazy-runtime.js";
77
import { sessionDeliveryOrigin } from "../utils/delivery-context.shared.js";
88
import type { AuthRateLimiter } from "./auth-rate-limit.js";
99
import type { ResolvedGatewayAuth } from "./auth.js";
10-
import { CONTROL_UI_CHANNEL_AVATAR_PATH_PREFIX } from "./control-ui-contract.js";
10+
import { parseControlUiResourcePath } from "./control-ui-contract.js";
1111
import { respondNotFound } from "./control-ui-http-utils.js";
12-
import { normalizeControlUiBasePath } from "./control-ui-shared.js";
1312
import { sendMethodNotAllowed } from "./http-common.js";
1413
import {
1514
HTTP_IMAGE_MAX_BYTES,
@@ -31,31 +30,6 @@ const channelAvatarBytes = new Map<string, HttpImageRepresentation>();
3130

3231
const getSessionStoreModule = createLazyRuntimeModule(() => import("./session-utils-store.js"));
3332

34-
type ChannelAvatarRequest = { matched: false } | { matched: true; sessionKey: string | null };
35-
36-
function parseChannelAvatarRequest(
37-
urlRaw: string | undefined,
38-
basePath: string | undefined,
39-
): ChannelAvatarRequest {
40-
if (!urlRaw) {
41-
return { matched: false };
42-
}
43-
const pathname = new URL(urlRaw, "http://localhost").pathname;
44-
const prefix = `${normalizeControlUiBasePath(basePath)}${CONTROL_UI_CHANNEL_AVATAR_PATH_PREFIX}/`;
45-
if (!pathname.startsWith(prefix)) {
46-
return { matched: false };
47-
}
48-
const encoded = pathname.slice(prefix.length);
49-
if (!encoded || encoded.includes("/")) {
50-
return { matched: true, sessionKey: null };
51-
}
52-
try {
53-
return { matched: true, sessionKey: decodeURIComponent(encoded) || null };
54-
} catch {
55-
return { matched: true, sessionKey: null };
56-
}
57-
}
58-
5933
function touchChannelAvatarCache(
6034
sessionKey: string,
6135
reference: string,
@@ -115,7 +89,8 @@ export async function handleChannelAvatarHttpRequest(
11589
rateLimiter?: AuthRateLimiter;
11690
},
11791
): Promise<boolean> {
118-
const parsed = parseChannelAvatarRequest(req.url, opts.basePath);
92+
const pathname = req.url ? new URL(req.url, "http://localhost").pathname : undefined;
93+
const parsed = parseControlUiResourcePath("channelAvatar", pathname, opts.basePath);
11994
if (!parsed.matched) {
12095
return false;
12196
}
@@ -134,7 +109,7 @@ export async function handleChannelAvatarHttpRequest(
134109
if (!requestAuth) {
135110
return true;
136111
}
137-
if (!parsed.sessionKey) {
112+
if (!parsed.value) {
138113
res.setHeader("cache-control", "no-store");
139114
respondNotFound(res);
140115
return true;
@@ -143,7 +118,7 @@ export async function handleChannelAvatarHttpRequest(
143118
let reference: string | undefined;
144119
try {
145120
const { entry } = (await getSessionStoreModule()).loadGatewaySessionEntryReadOnly(
146-
parsed.sessionKey,
121+
parsed.value,
147122
{ clone: false },
148123
);
149124
reference = sessionDeliveryOrigin(entry)?.avatar;
@@ -158,7 +133,7 @@ export async function handleChannelAvatarHttpRequest(
158133

159134
let image: HttpImageRepresentation | undefined;
160135
try {
161-
image = await loadChannelAvatar(parsed.sessionKey, reference);
136+
image = await loadChannelAvatar(parsed.value, reference);
162137
} catch {
163138
// The media may have expired or been pruned after the session row was written.
164139
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/** HTTP path for the Control UI bootstrap config payload. */
2+
export const CONTROL_UI_BOOTSTRAP_CONFIG_PATH = "/control-ui-config.json";
3+
4+
/** Fragment marker selecting the host-authorized browser-owner bootstrap profile. */
5+
export const CONTROL_UI_BOOTSTRAP_PROFILE_FRAGMENT_PARAM = "bootstrapProfile";
6+
export const CONTROL_UI_OWNER_BOOTSTRAP_PROFILE_HINT = "owner";
7+
export type ControlUiBootstrapProfileHint = typeof CONTROL_UI_OWNER_BOOTSTRAP_PROFILE_HINT;
8+
9+
/** Carries the gateway-configured Control UI mount path into browser bootstrap. */
10+
export const CONTROL_UI_BASE_PATH_ATTRIBUTE = "data-openclaw-control-ui-base-path";
11+
12+
/** Marks whether the served document CSP permits the terminal WASM runtime. */
13+
export const CONTROL_UI_TERMINAL_ENABLED_ATTRIBUTE = "data-openclaw-terminal-enabled";
14+
15+
/** Sandbox policy for assistant-provided embed surfaces inside Control UI. */
16+
export type ControlUiEmbedSandboxMode = "strict" | "scripts" | "trusted";
17+
18+
/** Route grant successfully issued during authenticated Control UI bootstrap. */
19+
export type ControlUiPluginFrameGrantAck = {
20+
pluginId: string;
21+
path: string;
22+
match: "exact" | "prefix";
23+
};
24+
25+
/** Runtime config consumed by the browser Control UI during bootstrap. */
26+
export type ControlUiBootstrapConfig = {
27+
basePath: string;
28+
assistantName: string;
29+
assistantAvatar: string;
30+
assistantAvatarSource?: string | null;
31+
assistantAvatarStatus?: "none" | "local" | "remote" | "data" | null;
32+
assistantAvatarReason?: string | null;
33+
assistantAgentId?: string;
34+
serverVersion?: string;
35+
/** Exact immutable build serving this Control UI when available. */
36+
serverBuildId?: string;
37+
/**
38+
* Git branch of a source-checkout (non-release) gateway install. Omitted for
39+
* package installs and mainline (main/master) checkouts so the UI only flags
40+
* gateways running unreleased branch code.
41+
*/
42+
devGitBranch?: string;
43+
localMediaPreviewRoots?: string[];
44+
embedSandbox?: ControlUiEmbedSandboxMode;
45+
allowExternalEmbedUrls?: boolean;
46+
automaticallyFetchFavicons?: boolean;
47+
seamColor?: string;
48+
/**
49+
* Whether the operator terminal surface is enabled (`gateway.terminal.enabled`).
50+
* The Control UI hides the terminal entirely when false so a disabled kill
51+
* switch removes the surface rather than showing a button that errors on open.
52+
*/
53+
terminalEnabled?: boolean;
54+
/** Whether the Labs-gated CLI agents model-picker group is enabled. */
55+
cliAgentsEnabled?: boolean;
56+
pluginFrameGrants?: ControlUiPluginFrameGrantAck[];
57+
};
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
import { describe, expect, it } from "vitest";
2+
import {
3+
buildControlUiChannelAvatarUrl,
4+
buildControlUiResourcePath,
5+
buildControlUiRootAssetPath,
6+
buildControlUiUserAvatarPath,
7+
canonicalizeControlUiUserAvatarPath,
8+
CONTROL_UI_ROOT_PUBLIC_ASSETS,
9+
matchControlUiResourceUrl,
10+
parseControlUiUserAvatarPath,
11+
parseControlUiResourcePath,
12+
type ControlUiResourceRoute,
13+
} from "./control-ui-contract.js";
14+
15+
const ROUTES = [
16+
{
17+
route: "agentAvatar",
18+
value: "ops/main",
19+
path: "/avatar/ops%2Fmain",
20+
},
21+
{
22+
route: "catalogIcon",
23+
value: "https://cdn.example.test/icon.svg",
24+
path: "/__openclaw__/catalog-icon/https%3A%2F%2Fcdn.example.test%2Ficon.svg",
25+
},
26+
{
27+
route: "channelAvatar",
28+
value: "agent:main:discord:direct:user-1",
29+
path: "/__openclaw__/channel-avatar/agent%3Amain%3Adiscord%3Adirect%3Auser-1",
30+
},
31+
{
32+
route: "linkFavicon",
33+
value: "docs.example.test",
34+
path: "/__openclaw__/link-favicon/docs.example.test",
35+
},
36+
{
37+
route: "pluginIcon",
38+
value: "@scope/plugin",
39+
path: "/__openclaw__/plugin-icon/%40scope%2Fplugin",
40+
},
41+
{
42+
route: "userAvatar",
43+
value: "profile/a b",
44+
path: "/api/users/profile%2Fa%20b/avatar",
45+
},
46+
{
47+
route: "workspaceIcon",
48+
value: "agent:main:one",
49+
path: "/__openclaw__/workspace-icon/agent%3Amain%3Aone",
50+
},
51+
] as const satisfies readonly {
52+
route: ControlUiResourceRoute;
53+
value: string;
54+
path: string;
55+
}[];
56+
57+
describe("Control UI resource route contract", () => {
58+
it.each(ROUTES)("round-trips $route as one encoded segment", ({ route, value, path }) => {
59+
expect(buildControlUiResourcePath(route, "", value)).toBe(path);
60+
expect(buildControlUiResourcePath(route, "control/", value)).toBe(`/control${path}`);
61+
expect(parseControlUiResourcePath(route, path)).toEqual({ matched: true, value });
62+
expect(parseControlUiResourcePath(route, `/control${path}`, "/control/")).toEqual({
63+
matched: true,
64+
value,
65+
});
66+
});
67+
68+
it.each([
69+
["blank segment", "/__openclaw__/workspace-icon/"],
70+
["raw nested segment", "/__openclaw__/workspace-icon/agent/main"],
71+
["malformed escape", "/__openclaw__/workspace-icon/%zz"],
72+
])("claims a %s without producing a route value", (_label, pathname) => {
73+
expect(parseControlUiResourcePath("workspaceIcon", pathname)).toEqual({
74+
matched: true,
75+
value: null,
76+
});
77+
});
78+
79+
it("does not claim another resource route", () => {
80+
expect(
81+
parseControlUiResourcePath("workspaceIcon", "/__openclaw__/plugin-icon/firecrawl"),
82+
).toEqual({ matched: false });
83+
});
84+
85+
it("builds and canonicalizes cache-busted user avatar paths", () => {
86+
expect(buildControlUiUserAvatarPath("profile/a b", "hash/image")).toBe(
87+
"/api/users/profile%2Fa%20b/avatar?v=hash%2Fimage",
88+
);
89+
expect(buildControlUiUserAvatarPath("profile/a b", 1_725_000_123_456)).toBe(
90+
"/api/users/profile%2Fa%20b/avatar?v=1725000123456",
91+
);
92+
expect(
93+
canonicalizeControlUiUserAvatarPath("/wilfred/api/users/profile%2F1/avatar", "/wilfred"),
94+
).toBe("/api/users/profile%2F1/avatar");
95+
expect(
96+
canonicalizeControlUiUserAvatarPath("/wilfred-other/api/users/profile-1/avatar", "/wilfred"),
97+
).toBeUndefined();
98+
});
99+
100+
it("preserves malformed configured-base user avatar ownership", () => {
101+
expect(
102+
parseControlUiUserAvatarPath("/wilfred/api/users/profile-1/avatar/extra", "/wilfred"),
103+
).toEqual({ matched: true, value: null });
104+
});
105+
106+
it("builds revision-aware channel avatar paths through the route contract", () => {
107+
expect(buildControlUiChannelAvatarUrl("/control", "agent:main/one", "hash/image")).toBe(
108+
"/control/__openclaw__/channel-avatar/agent%3Amain%2Fone?v=hash%2Fimage",
109+
);
110+
});
111+
112+
it("matches exact same-origin resource URLs without parser reinterpretation", () => {
113+
expect(matchControlUiResourceUrl("agentAvatar", "/avatar/main?v=2#profile")).toEqual({
114+
value: "main",
115+
search: "?v=2",
116+
hash: "#profile",
117+
});
118+
expect(
119+
matchControlUiResourceUrl("agentAvatar", "/control/avatar/main?v=2", "/control"),
120+
).toEqual({ value: "main", search: "?v=2", hash: "" });
121+
for (const value of [
122+
"//evil.example/avatar/main",
123+
"//[",
124+
"/avatar\\main",
125+
"/avatar/main/extra",
126+
"/avatar/%zz",
127+
]) {
128+
expect(matchControlUiResourceUrl("agentAvatar", value), value).toBeUndefined();
129+
}
130+
});
131+
132+
it("builds every declared root asset under the normalized mount", () => {
133+
expect(new Set(CONTROL_UI_ROOT_PUBLIC_ASSETS).size).toBe(CONTROL_UI_ROOT_PUBLIC_ASSETS.length);
134+
for (const asset of CONTROL_UI_ROOT_PUBLIC_ASSETS) {
135+
expect(buildControlUiRootAssetPath("/control/", asset)).toBe(`/control/${asset}`);
136+
}
137+
});
138+
});

0 commit comments

Comments
 (0)