fix(browser): preserve attached service-worker policies and ownership

This commit is contained in:
morluto
2026-10-13 03:29:28 +08:00
parent 02cedc3796
commit 221c856481
2 changed files with 91 additions and 8 deletions
+78 -1
View File
@@ -82,6 +82,8 @@ const fixture = () => {
const page = Object.assign(new EventEmitter(), {
url: () => "about:blank",
goto: vi.fn(async () => undefined),
evaluate: vi.fn(async (_script: unknown) => false),
addInitScript: vi.fn(async (_script: unknown) => undefined),
context: () => context,
});
const context = Object.assign(new EventEmitter(), {
@@ -116,7 +118,7 @@ const fixture = () => {
settle: vi.fn(async () => undefined),
close: vi.fn(async () => undefined),
};
return { cleanup, storage: mocks.storage };
return { cleanup, page, storage: mocks.storage };
};
beforeEach(() => {
@@ -137,6 +139,81 @@ it("uses browser disconnect as terminal storage release after detach failure", a
expect(storage.close).toHaveBeenCalledTimes(1);
});
it("leaves attached service-worker state alone when the policy allows it", async () => {
const { cleanup, page } = fixture();
const attached = browserScenarioSchema.parse({
...scenario,
browser: {
mode: "connect",
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "target",
},
environment: { service_workers: "allow" },
});
const session = await PlaywrightScenarioSession.open(attached, {}, {});
expect(mocks.openBrowser).toHaveBeenCalledWith(
attached,
{},
expect.any(Object),
);
expect(page.evaluate).not.toHaveBeenCalled();
expect(page.addInitScript).not.toHaveBeenCalled();
await expect(session.close()).resolves.toBe("disconnected-external");
expect(cleanup.close).toHaveBeenCalledTimes(1);
});
it("blocks new attached service-worker registration without removing existing registrations", async () => {
const { cleanup, page } = fixture();
const attached = browserScenarioSchema.parse({
...scenario,
browser: {
mode: "connect",
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "target",
},
environment: { service_workers: "block" },
});
const session = await PlaywrightScenarioSession.open(attached, {}, {});
expect(page.evaluate).toHaveBeenCalledTimes(2);
expect(page.addInitScript).toHaveBeenCalledTimes(1);
expect(page.addInitScript).toHaveBeenCalledWith(
expect.stringContaining("service workers are blocked by scenario policy"),
);
expect(page.addInitScript).toHaveBeenCalledWith(
expect.not.stringContaining("getRegistrations"),
);
expect(page.addInitScript).toHaveBeenCalledWith(
expect.not.stringContaining("unregister"),
);
await expect(session.close()).resolves.toBe("disconnected-external");
expect(cleanup.close).toHaveBeenCalledTimes(1);
});
it("rejects attached block when caller-owned registrations already exist", async () => {
const { cleanup, page } = fixture();
page.evaluate.mockResolvedValueOnce(true);
const attached = browserScenarioSchema.parse({
...scenario,
browser: {
mode: "connect",
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "target",
},
environment: { service_workers: "block" },
});
await expect(
PlaywrightScenarioSession.open(attached, {}, {}),
).rejects.toMatchObject({
_tag: "BrowserObservationError",
reason: "target_not_allowed",
});
expect(page.addInitScript).not.toHaveBeenCalled();
expect(cleanup.close).toHaveBeenCalledTimes(1);
});
it("preserves both cleanup failures and retries retained owners", async () => {
const { cleanup, storage } = fixture();
const detachFailure = new Error("CDP detach rejected");
+13 -7
View File
@@ -51,15 +51,18 @@ const installCookies = async (
};
const blockAttachedServiceWorkers = async (page: Page): Promise<void> => {
const controller = await page.evaluate(
"Boolean(navigator.serviceWorker?.controller)",
);
if (controller)
const hasServiceWorker = await page.evaluate(`(async () => {
if (!("serviceWorker" in navigator)) return false;
const serviceWorker = navigator.serviceWorker;
if (serviceWorker.controller !== null) return true;
return (await serviceWorker.getRegistrations()).length > 0;
})()`);
// An attached context belongs to the caller. Reject a block request when it
// already has a worker instead of unregistering that caller-owned resource.
if (hasServiceWorker)
throw new BrowserObservationError(OPERATION, "target_not_allowed");
const blockRegistration = `(() => {
if (!("serviceWorker" in navigator)) return;
void navigator.serviceWorker.getRegistrations()
.then((registrations) => Promise.all(registrations.map((item) => item.unregister())));
Object.defineProperty(ServiceWorkerContainer.prototype, "register", {
configurable: false,
value: () => Promise.reject(new Error("service workers are blocked by scenario policy"))
@@ -77,7 +80,10 @@ const initializePage = async (
): Promise<void> => {
context.setDefaultTimeout(0);
context.setDefaultNavigationTimeout(0);
if (scenario.browser.mode === "connect")
if (
scenario.browser.mode === "connect" &&
scenario.environment.service_workers === "block"
)
await blockAttachedServiceWorkers(page);
await installCookies(context, scenario, secrets);
};