Skip to content

Commit 51898e0

Browse files
committed
fix(browser): preserve controlled document navigation authority
1 parent 214d55e commit 51898e0

18 files changed

Lines changed: 1498 additions & 43 deletions

‎docs/tools/chrome-extension.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,21 @@ Open the extension's Settings page to change the access mode. Switching to
132132
Selected tabs immediately detaches ungrouped tabs, including attaches already
133133
in flight. Agent-created tabs stay in the OpenClaw group in either mode.
134134

135+
An agent-created tab can initialize at `about:blank` on its creating relay
136+
connection until its first nonblank document commits. An explicitly commanded
137+
main-frame navigation of an already authorized tab can also temporarily use
138+
exact `about:blank`, for example during a performance trace reset. This requires
139+
Chrome to confirm that navigation on the same attachment; an iframe navigation
140+
or a blank URL alone cannot grant access.
141+
142+
Each exception ends on the next nonblank document commit, access-mode change,
143+
revocation, tab closure or replacement, reconnect, or extension restart.
144+
A commanded blank navigation also ends on debugger detachment or when its
145+
original group or window changes. Pausing a blank tab still revokes access.
146+
Ordinary blank tabs and other internal pages remain excluded; an uncommanded return to `about:blank`
147+
does not restore access. Failed navigation never closes an existing tab or
148+
restores a URL over user navigation.
149+
135150
The extension excludes incognito tabs, internal pages such as `chrome://` and
136151
`chrome-extension://`, and tabs without a usable current URL. `file://` access
137152
also requires Chrome's **Allow access to file URLs** setting.
Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
1+
import assert from "node:assert/strict";
2+
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
3+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4+
import {
5+
cleanupBackgroundHarnesses,
6+
loadBackground,
7+
sendRuntimeMessage,
8+
TEST_RELAY_KEY,
9+
} from "./background.test-harness.js";
10+
import type { BrowserTabSnapshot } from "./modules/tab-eligibility.js";
11+
12+
const config = (accessMode: "all" | "selected") => ({
13+
relayUrl: "ws://127.0.0.1:18797/extension",
14+
token: TEST_RELAY_KEY,
15+
authVersion: 2,
16+
accessMode,
17+
});
18+
19+
async function setup(mode: "all" | "selected" = "all", deferSocketClose = false) {
20+
const harness = await loadBackground({
21+
storedConfig: config(mode),
22+
deferSocketClose,
23+
initialTabs: [
24+
{ id: 100, url: "https://example.com/unrelated", groupId: 7 },
25+
{ id: 99, url: "about:blank", groupId: 7 },
26+
],
27+
});
28+
const socket = harness.relaySockets[0];
29+
assert(socket);
30+
await harness.authenticate(socket);
31+
let seq = 1000;
32+
const frames = () => socket.send.mock.calls.map(([raw]) => JSON.parse(raw));
33+
const request = async (message: Record<string, unknown>) => {
34+
const id = ++seq;
35+
socket.receive({ ...message, seq: id });
36+
await vi.waitFor(() => expect(frames().find((frame) => frame.seq === id)).toBeDefined());
37+
return frames().find((frame) => frame.seq === id);
38+
};
39+
// Exercise real policy/events with Chrome's full Tab observations, including
40+
// grouping events that arrive before the grouping API resolves.
41+
const group = harness.tabsGroup.getMockImplementation()!;
42+
harness.tabsGroup.mockImplementation(async (properties) => {
43+
const groupId = await group(properties);
44+
for (const tabId of properties.tabIds) {
45+
harness.updateTab(tabId, { groupId });
46+
}
47+
harness.tabGroupUpdatedListener?.({ id: groupId, title: "" });
48+
return groupId;
49+
});
50+
harness.tabGroupsUpdate.mockImplementation(async () => {
51+
harness.tabGroupUpdatedListener?.({ id: 7, title: "OpenClaw" });
52+
});
53+
const create = async (url = "about:blank") => {
54+
expect(await request({ type: "createTab", url, background: true })).toMatchObject({
55+
type: "result",
56+
result: { tabId: 101 },
57+
});
58+
};
59+
const attach = async () => {
60+
expect(await request({ type: "attach", tabId: 101 })).toMatchObject({ type: "result" });
61+
};
62+
return Object.assign(harness, { socket, request, frames, create, attach });
63+
}
64+
65+
const releases: Array<() => void> = [];
66+
beforeEach(() => vi.resetModules());
67+
afterEach(async () => {
68+
for (const release of releases.splice(0)) {
69+
release();
70+
}
71+
await cleanupBackgroundHarnesses();
72+
vi.unstubAllGlobals();
73+
});
74+
75+
describe("physical tab creation authority", () => {
76+
it.each([
77+
"initial blank",
78+
"committed then blank",
79+
"removed",
80+
"replaced",
81+
"selected revocation",
82+
] as const)("honors %s observed before tabs.create resolves", async (observation) => {
83+
const h = await setup(observation === "selected revocation" ? "selected" : "all");
84+
const create = h.tabsCreate.getMockImplementation()!;
85+
h.tabsCreate.mockImplementationOnce(async (properties) => {
86+
const tab = await create(properties);
87+
if (observation === "initial blank") {
88+
h.updateTab(tab.id, { url: "about:blank" });
89+
} else if (observation === "committed then blank") {
90+
h.updateTab(tab.id, { url: "https://example.com/committed" });
91+
h.updateTab(tab.id, { url: "about:blank" }, false);
92+
} else if (observation === "selected revocation") {
93+
h.updateTab(tab.id, { groupId: -1 });
94+
} else if (observation === "removed") {
95+
h.tabsRemovedListener?.(tab.id);
96+
} else {
97+
h.tabsReplacedListener(102, tab.id);
98+
}
99+
return tab;
100+
});
101+
expect(await h.request({ type: "createTab", url: "about:blank" })).toMatchObject({
102+
type: observation === "initial blank" ? "result" : "error",
103+
});
104+
expect(h.tabsRemove).not.toHaveBeenCalled();
105+
});
106+
107+
it.each([
108+
{ pendingUrl: "https://example.com/destination", response: "result" },
109+
{ pendingUrl: "chrome://settings", response: "error" },
110+
])(
111+
"checks the pending $pendingUrl appearing during navigation response validation",
112+
async ({ pendingUrl, response }) => {
113+
const h = await setup("selected");
114+
await h.create();
115+
await h.attach();
116+
h.debuggerSendCommand.mockImplementationOnce(async () => {
117+
const get = h.tabsGet.getMockImplementation()!;
118+
h.tabsGet.mockImplementationOnce(async (tabId) => {
119+
const before = await get(tabId);
120+
h.updateTab(tabId, { pendingUrl });
121+
return before;
122+
});
123+
return { frameId: "main" };
124+
});
125+
expect(
126+
await h.request({
127+
type: "cdp",
128+
tabId: 101,
129+
method: "Page.navigate",
130+
params: { url: pendingUrl },
131+
}),
132+
).toMatchObject({ type: response });
133+
},
134+
);
135+
136+
it("retires on a root document commit, but not an iframe commit", async () => {
137+
const h = await setup();
138+
await h.create();
139+
await h.attach();
140+
h.debuggerEventListener?.({ tabId: 101 }, "Page.frameNavigated", {
141+
frame: { id: "child", parentId: "main", url: "https://example.com/frame" },
142+
});
143+
expect(await h.request({ type: "cdp", tabId: 101, method: "Runtime.enable" })).toMatchObject({
144+
type: "result",
145+
});
146+
h.debuggerEventListener?.({ tabId: 101 }, "Page.frameNavigated", {
147+
frame: { id: "main", url: "https://example.com/committed" },
148+
});
149+
// Even before tabs.onUpdated catches up, that committed document has spent
150+
// the one initial-blank exception; a stale blank observation cannot restore it.
151+
expect(await h.request({ type: "cdp", tabId: 101, method: "Runtime.enable" })).toMatchObject({
152+
type: "error",
153+
});
154+
});
155+
156+
it("revokes a later empty group title during creation", async () => {
157+
const h = await setup("selected");
158+
h.tabGroupsUpdate.mockImplementationOnce(async () => {
159+
h.tabGroupUpdatedListener?.({ id: 7, title: "OpenClaw" });
160+
h.tabGroupUpdatedListener?.({ id: 7, title: "" });
161+
});
162+
expect(await h.request({ type: "createTab", url: "about:blank" })).toMatchObject({
163+
type: "error",
164+
});
165+
expect(h.tabsRemove).not.toHaveBeenCalled();
166+
});
167+
168+
it("leaves a revoked Selected tab alone when the group lookup beats its event", async () => {
169+
const h = await setup("selected");
170+
h.tabGroupsUpdate.mockImplementationOnce(async () => {
171+
h.tabGroupsGet.mockResolvedValue({ id: 7, title: "Other", windowId: 1 });
172+
});
173+
expect(await h.request({ type: "createTab", url: "about:blank" })).toMatchObject({
174+
type: "error",
175+
});
176+
expect(h.tabsRemove).not.toHaveBeenCalled();
177+
});
178+
179+
it("does not guess a cleanup tab when physical creation fails", async () => {
180+
const h = await setup();
181+
h.tabsCreate.mockRejectedValueOnce(new Error("create failed"));
182+
expect(await h.request({ type: "createTab", url: "about:blank" })).toMatchObject({
183+
type: "error",
184+
message: "create failed",
185+
});
186+
expect(h.tabsRemove).not.toHaveBeenCalled();
187+
expect(h.tabsGroup).not.toHaveBeenCalled();
188+
});
189+
190+
it.each(["removed", "replaced", "pause"] as const)(
191+
"rechecks %s after the failure-cleanup lookup yields",
192+
async (reason) => {
193+
const h = await setup();
194+
const lookup = createDeferred<Awaited<ReturnType<typeof h.tabsGet>>>();
195+
releases.push(() =>
196+
lookup.resolve({
197+
id: 101,
198+
url: "about:blank",
199+
groupId: 7,
200+
windowId: 1,
201+
title: "",
202+
incognito: false,
203+
}),
204+
);
205+
let inspectingCleanup = false;
206+
h.debuggerAttach.mockImplementationOnce(async () => {
207+
h.tabsGet.mockImplementationOnce(async () => {
208+
inspectingCleanup = true;
209+
return await lookup.promise;
210+
});
211+
throw new Error("attach failed");
212+
});
213+
const attaching = h.request({ type: "createTab", url: "about:blank" });
214+
await vi.waitFor(() => expect(inspectingCleanup).toBe(true));
215+
let pausing: Promise<unknown> | undefined;
216+
if (reason === "removed") {
217+
h.tabsRemovedListener?.(101);
218+
} else if (reason === "replaced") {
219+
h.tabsReplacedListener(102, 101);
220+
} else {
221+
pausing = sendRuntimeMessage(h, {
222+
type: "toggleTabAccess",
223+
accessMode: "all",
224+
tabId: 101,
225+
grant: false,
226+
});
227+
await vi.waitFor(() => expect(h.sessionStorageValues.deniedTabIdsV1).toEqual([101]));
228+
}
229+
lookup.resolve(await h.tabsGet(101));
230+
await pausing;
231+
expect(await attaching).toMatchObject({ type: "error", message: "attach failed" });
232+
expect(h.tabsRemove).not.toHaveBeenCalled();
233+
},
234+
);
235+
236+
it.each(["all", "selected"] as const)(
237+
"fences a %s revoke while grouping and leaves the user tab alone",
238+
async (mode) => {
239+
const h = await setup(mode);
240+
const deferred = createDeferred<number>();
241+
releases.push(() => deferred.resolve(7));
242+
const group = h.tabsGroup.getMockImplementation()!;
243+
h.tabsGroup.mockImplementationOnce(async (properties) => {
244+
await group(properties);
245+
return await deferred.promise;
246+
});
247+
const creating = h.request({ type: "createTab", url: "about:blank", focus: true });
248+
await vi.waitFor(() => expect(h.tabsGroup).toHaveBeenCalled());
249+
const revoke = sendRuntimeMessage(h, {
250+
type: "toggleTabAccess",
251+
accessMode: mode,
252+
tabId: 101,
253+
grant: false,
254+
});
255+
await expect(revoke).resolves.toMatchObject({ ok: true });
256+
deferred.resolve(7);
257+
expect(await creating).toMatchObject({
258+
type: "error",
259+
message: expect.stringMatching(/revoked/),
260+
});
261+
expect(h.windowsUpdate).not.toHaveBeenCalled();
262+
expect(h.tabsRemove).not.toHaveBeenCalled();
263+
expect(await h.request({ type: "attach", tabId: 101 })).toMatchObject({ type: "error" });
264+
},
265+
);
266+
});

0 commit comments

Comments
 (0)