[GH-ISSUE #2956] [Bug] Attached browser scenarios accept worker-controlled captures under the block policy #1041

Closed
opened 2026-10-15 18:30:34 +00:00 by bsakaguchi · 1 comment
Owner

Originally created by @dakjdakd on GitHub (Oct 13, 2026).
Original GitHub issue: https://github.com/morluto/rea/issues/2956

Before submitting

  • I searched the open and closed issues for a related report.
  • I removed credentials, tokens, private paths, and sensitive target data.

Area

Process capture or runtime observation

Observed behavior

An attached browser scenario can request environment.service_workers: "block", navigate to a page already controlled by a service worker, and report every capture step as completed. The worker continues intercepting requests throughout the captured page's lifetime. The policy is evaluated against the page that existed before navigation, rather than the document whose behavior is being collected.

The reduced case starts with an owned Chrome profile containing a registration for a local HTTP origin. The selected tab is then moved to about:blank. REA connects to that tab and navigates back to the registered origin under the default block policy. Both scenario_start and a subsequent wait step complete, but the destination reports a non-null service-worker controller and a fetch returns the worker's synthetic response.

There is also a directly related lifecycle problem: after REA reports disconnected-external, ServiceWorkerContainer.prototype.register is still replaced in the live document. Its descriptor is nonconfigurable, so the caller cannot restore it through ordinary property replacement. Calling register continues rejecting until the document is reloaded. This is the same policy installation surviving outside its owning session, rather than a separate registration-management feature request.

Reproduction

Use an existing Chrome installation with a fresh, disposable profile and a loopback debugging endpoint. The fixture must run over HTTP on a literal loopback address, where Chrome permits service-worker registration. No preexisting browser profile, remote application, or private target is needed.

Serve this worker as /sw.js with Content-Type: application/javascript:

self.addEventListener("install", () => self.skipWaiting());
self.addEventListener("activate", event => event.waitUntil(clients.claim()));
self.addEventListener("fetch", event => {
  if (new URL(event.request.url).pathname === "/probe") {
    event.respondWith(new Response("service-worker-intercepted"));
  }
});

The HTTP fixture's normal /probe response should contain a different string, such as network. Serve a small HTML document at /; a title and a paragraph are sufficient. Launch the owned Chrome instance initially at that document, enable loopback remote debugging, and obtain its endpoint. Keep the fixture server and Chrome process alive while exercising the scenario.

The following is the production API sequence used in the reproduction, with the fixture origin and discovered endpoint supplied by the local harness. It uses the actual scenario schema, session, and provider rather than a simulated browser. The imports refer to a built source checkout:

import { chromium } from "playwright-core";
import { browserScenarioSchema } from "./dist/domain/browserScenario.js";
import { PlaywrightScenarioSession } from "./dist/browser/PlaywrightScenarioSession.js";
import { PlaywrightBrowserScenarioProvider } from "./dist/browser/PlaywrightBrowserScenarioProvider.js";

// endpoint and origin identify the disposable local fixture.
const owner = await chromium.connectOverCDP(endpoint);
const context = owner.contexts()[0];
const page = context.pages()[0]; // The owned profile has one fixture tab.
await page.waitForLoadState();

const cdp = await context.newCDPSession(page);
const { targetInfo } = await cdp.send("Target.getTargetInfo");
await cdp.detach();

await page.evaluate(async () => {
  await navigator.serviceWorker.register("/sw.js");
  await navigator.serviceWorker.ready;
});
await page.goto("about:blank");

const scenario = browserScenarioSchema.parse({
  browser: {
    mode: "connect",
    cdp_endpoint: endpoint,
    target_id: targetInfo.targetId,
  },
  start_url: { url: origin },
  environment: { service_workers: "block" },
  actions: [
    { step_id: "wait", action: "wait_for_timeout", duration_ms: 1 },
  ],
  capture: {
    events: [],
    after_each_step: ["url"],
    at_end: ["url"],
  },
});

const provider = new PlaywrightBrowserScenarioProvider((selected, options) =>
  PlaywrightScenarioSession.open(selected, process.env, options),
);
const result = await provider.captureScenario(scenario);
console.log(result.ok ? result.value.steps : result.error);

console.log(await page.evaluate(async () => ({
  controlled: navigator.serviceWorker.controller !== null,
  response: await (await fetch("/probe")).text(),
  registerConfigurable: Object.getOwnPropertyDescriptor(
    ServiceWorkerContainer.prototype, "register",
  )?.configurable,
  registerSource: ServiceWorkerContainer.prototype.register.toString(),
})));

On the affected implementation, inspect the completed steps, the worker response, and the register descriptor together. They demonstrate that block was accepted, worker-controlled execution occurred, and the injected policy outlived its connection. Reload the selected page and inspect register again to distinguish a live-document mutation from a persistent change to Chrome or the worker itself. Close only the harness-owned browser and remove its disposable profile afterward.

Expected behavior

The attached-browser block policy should reject a capture when the documents being captured contain a service-worker controller or existing registration. In this example, the initial destination should produce BrowserObservationError with reason target_not_allowed, instead of a successful capture containing completed steps.

The same rule should follow the scenario through later navigations and child frames. Inspecting the initial destination once is insufficient when a subsequent action, link click, redirect, or embedded frame reaches another registered origin. A block request should remain meaningful at each capture boundary.

Existing registrations belong to the caller and should survive rejection. The appropriate recovery is for the caller to choose allow if worker-driven application behavior is required, or to use an appropriately prepared independent browser context. REA should not silently unregister workers in an externally owned profile.

The temporary register replacement should end with the scenario. Successful cleanup should restore the live document's original property state without requiring a reload; subsequent documents should not inherit the finished scenario's policy. A later caller replacement should also be preserved rather than overwritten during restoration.

Impact and scope

This affects the attached Chromium scenario workflow and the reliability of the requested environment policy. An analyst can reasonably select block to avoid worker-mediated requests, yet obtain data influenced by a caller's cached or synthetic responses. A successful result does not identify that the selected policy failed to hold.

The stale wrapper additionally changes the caller's application after capture has ended. A subsequent application action can fail to register or update its worker even though REA has reported that it disconnected. The browser and registration remain alive, which makes the discrepancy easy to miss if cleanup is assessed only by connection ownership.

The issue concerns enforcing and releasing an existing policy. It does not require a new browser provider, a new action vocabulary, request interception, or permission to remove external registrations. The launch workflow already delegates worker blocking to its provider-owned Playwright context. Explicit allow should continue admitting worker-driven behavior.

REA version

Source revision ebaaa79ca02bde4a73013a2a9a781d0b07a57ee4.

Runtime and platform

Node.js 24.18.0; Windows x64; Chrome 154.0.8037.98. The reproduction uses an actual installed Chrome instance and a separate local fixture profile.

Target and artifact context

An owned local HTTP application with one real service-worker registration, one selected browser tab, and a reduced browser scenario requesting URL artifacts.

Interface

Other — production browser-scenario provider API. The behavior sits below the shared CLI/MCP workflow.

Earliest failure stage

Capture or observation.

Relevant output or evidence

The executed baseline reproduction recorded:

{
  "before": { "url": "about:blank" },
  "afterCaptureServiceWorker": {
    "controller": true,
    "probe": "service-worker-intercepted"
  },
  "cleanup": "disconnected-external",
  "capturedSteps": [
    { "status": "completed", "step_id": "scenario_start" },
    { "status": "completed", "step_id": "wait" }
  ],
  "after": {
    "configurable": false,
    "source": "() => Promise.reject(new Error(\"service workers are blocked by scenario policy\"))"
  }
}

Typed outcome or recovery expected

Reject the worker-influenced capture with target_not_allowed, retain any observations according to the existing partial-observation contract, and report external disconnect only after the owned policy effects have been released. If restoration cannot be confirmed, keep cleanup uncertainty and the retry capability visible.

Analysis or suspected cause

Source inspection identifies two parts of the same ownership gap in PlaywrightScenarioSession: blockAttachedServiceWorkers checks controller and registrations before goto(start_url), and its init script replaces register with configurable: false without retaining an original descriptor or restoration action. Checking about:blank says nothing about registrations at the eventual destination. Removing an init script from future navigation does not restore a method already replaced in the current JavaScript realm.

Additional context

The existing attached-browser behavior already rejects caller-owned registrations rather than removing them. A fix can preserve that choice by validating current frames at navigation and capture boundaries and giving the temporary wrapper an explicit lifecycle owner. Navigation may execute the destination's normal application code, including worker behavior, before rejection. This should be documented as fail-closed capture validation, not prevention or rollback of everything the browser did during navigation.

The fix is available in PR #2957, from the independent fix/browser-service-worker-policy branch. That PR addresses this issue only.

Originally created by @dakjdakd on GitHub (Oct 13, 2026). Original GitHub issue: https://github.com/morluto/rea/issues/2956 ## Before submitting - [x] I searched the open and closed issues for a related report. - [x] I removed credentials, tokens, private paths, and sensitive target data. ## Area Process capture or runtime observation ## Observed behavior An attached browser scenario can request `environment.service_workers: "block"`, navigate to a page already controlled by a service worker, and report every capture step as completed. The worker continues intercepting requests throughout the captured page's lifetime. The policy is evaluated against the page that existed before navigation, rather than the document whose behavior is being collected. The reduced case starts with an owned Chrome profile containing a registration for a local HTTP origin. The selected tab is then moved to `about:blank`. REA connects to that tab and navigates back to the registered origin under the default block policy. Both `scenario_start` and a subsequent wait step complete, but the destination reports a non-null service-worker controller and a fetch returns the worker's synthetic response. There is also a directly related lifecycle problem: after REA reports `disconnected-external`, `ServiceWorkerContainer.prototype.register` is still replaced in the live document. Its descriptor is nonconfigurable, so the caller cannot restore it through ordinary property replacement. Calling register continues rejecting until the document is reloaded. This is the same policy installation surviving outside its owning session, rather than a separate registration-management feature request. ## Reproduction Use an existing Chrome installation with a fresh, disposable profile and a loopback debugging endpoint. The fixture must run over HTTP on a literal loopback address, where Chrome permits service-worker registration. No preexisting browser profile, remote application, or private target is needed. Serve this worker as `/sw.js` with `Content-Type: application/javascript`: ```js self.addEventListener("install", () => self.skipWaiting()); self.addEventListener("activate", event => event.waitUntil(clients.claim())); self.addEventListener("fetch", event => { if (new URL(event.request.url).pathname === "/probe") { event.respondWith(new Response("service-worker-intercepted")); } }); ``` The HTTP fixture's normal `/probe` response should contain a different string, such as `network`. Serve a small HTML document at `/`; a title and a paragraph are sufficient. Launch the owned Chrome instance initially at that document, enable loopback remote debugging, and obtain its endpoint. Keep the fixture server and Chrome process alive while exercising the scenario. The following is the production API sequence used in the reproduction, with the fixture origin and discovered endpoint supplied by the local harness. It uses the actual scenario schema, session, and provider rather than a simulated browser. The imports refer to a built source checkout: ```js import { chromium } from "playwright-core"; import { browserScenarioSchema } from "./dist/domain/browserScenario.js"; import { PlaywrightScenarioSession } from "./dist/browser/PlaywrightScenarioSession.js"; import { PlaywrightBrowserScenarioProvider } from "./dist/browser/PlaywrightBrowserScenarioProvider.js"; // endpoint and origin identify the disposable local fixture. const owner = await chromium.connectOverCDP(endpoint); const context = owner.contexts()[0]; const page = context.pages()[0]; // The owned profile has one fixture tab. await page.waitForLoadState(); const cdp = await context.newCDPSession(page); const { targetInfo } = await cdp.send("Target.getTargetInfo"); await cdp.detach(); await page.evaluate(async () => { await navigator.serviceWorker.register("/sw.js"); await navigator.serviceWorker.ready; }); await page.goto("about:blank"); const scenario = browserScenarioSchema.parse({ browser: { mode: "connect", cdp_endpoint: endpoint, target_id: targetInfo.targetId, }, start_url: { url: origin }, environment: { service_workers: "block" }, actions: [ { step_id: "wait", action: "wait_for_timeout", duration_ms: 1 }, ], capture: { events: [], after_each_step: ["url"], at_end: ["url"], }, }); const provider = new PlaywrightBrowserScenarioProvider((selected, options) => PlaywrightScenarioSession.open(selected, process.env, options), ); const result = await provider.captureScenario(scenario); console.log(result.ok ? result.value.steps : result.error); console.log(await page.evaluate(async () => ({ controlled: navigator.serviceWorker.controller !== null, response: await (await fetch("/probe")).text(), registerConfigurable: Object.getOwnPropertyDescriptor( ServiceWorkerContainer.prototype, "register", )?.configurable, registerSource: ServiceWorkerContainer.prototype.register.toString(), }))); ``` On the affected implementation, inspect the completed steps, the worker response, and the register descriptor together. They demonstrate that block was accepted, worker-controlled execution occurred, and the injected policy outlived its connection. Reload the selected page and inspect register again to distinguish a live-document mutation from a persistent change to Chrome or the worker itself. Close only the harness-owned browser and remove its disposable profile afterward. ## Expected behavior The attached-browser block policy should reject a capture when the documents being captured contain a service-worker controller or existing registration. In this example, the initial destination should produce `BrowserObservationError` with reason `target_not_allowed`, instead of a successful capture containing completed steps. The same rule should follow the scenario through later navigations and child frames. Inspecting the initial destination once is insufficient when a subsequent action, link click, redirect, or embedded frame reaches another registered origin. A block request should remain meaningful at each capture boundary. Existing registrations belong to the caller and should survive rejection. The appropriate recovery is for the caller to choose `allow` if worker-driven application behavior is required, or to use an appropriately prepared independent browser context. REA should not silently unregister workers in an externally owned profile. The temporary register replacement should end with the scenario. Successful cleanup should restore the live document's original property state without requiring a reload; subsequent documents should not inherit the finished scenario's policy. A later caller replacement should also be preserved rather than overwritten during restoration. ## Impact and scope This affects the attached Chromium scenario workflow and the reliability of the requested environment policy. An analyst can reasonably select block to avoid worker-mediated requests, yet obtain data influenced by a caller's cached or synthetic responses. A successful result does not identify that the selected policy failed to hold. The stale wrapper additionally changes the caller's application after capture has ended. A subsequent application action can fail to register or update its worker even though REA has reported that it disconnected. The browser and registration remain alive, which makes the discrepancy easy to miss if cleanup is assessed only by connection ownership. The issue concerns enforcing and releasing an existing policy. It does not require a new browser provider, a new action vocabulary, request interception, or permission to remove external registrations. The launch workflow already delegates worker blocking to its provider-owned Playwright context. Explicit `allow` should continue admitting worker-driven behavior. ## REA version Source revision `ebaaa79ca02bde4a73013a2a9a781d0b07a57ee4`. ## Runtime and platform Node.js 24.18.0; Windows x64; Chrome 154.0.8037.98. The reproduction uses an actual installed Chrome instance and a separate local fixture profile. ## Target and artifact context An owned local HTTP application with one real service-worker registration, one selected browser tab, and a reduced browser scenario requesting URL artifacts. ## Interface Other — production browser-scenario provider API. The behavior sits below the shared CLI/MCP workflow. ## Earliest failure stage Capture or observation. ## Relevant output or evidence The executed baseline reproduction recorded: ```json { "before": { "url": "about:blank" }, "afterCaptureServiceWorker": { "controller": true, "probe": "service-worker-intercepted" }, "cleanup": "disconnected-external", "capturedSteps": [ { "status": "completed", "step_id": "scenario_start" }, { "status": "completed", "step_id": "wait" } ], "after": { "configurable": false, "source": "() => Promise.reject(new Error(\"service workers are blocked by scenario policy\"))" } } ``` ## Typed outcome or recovery expected Reject the worker-influenced capture with `target_not_allowed`, retain any observations according to the existing partial-observation contract, and report external disconnect only after the owned policy effects have been released. If restoration cannot be confirmed, keep cleanup uncertainty and the retry capability visible. ## Analysis or suspected cause Source inspection identifies two parts of the same ownership gap in `PlaywrightScenarioSession`: `blockAttachedServiceWorkers` checks controller and registrations before `goto(start_url)`, and its init script replaces register with `configurable: false` without retaining an original descriptor or restoration action. Checking `about:blank` says nothing about registrations at the eventual destination. Removing an init script from future navigation does not restore a method already replaced in the current JavaScript realm. ## Additional context The existing attached-browser behavior already rejects caller-owned registrations rather than removing them. A fix can preserve that choice by validating current frames at navigation and capture boundaries and giving the temporary wrapper an explicit lifecycle owner. Navigation may execute the destination's normal application code, including worker behavior, before rejection. This should be documented as fail-closed capture validation, not prevention or rollback of everything the browser did during navigation. The fix is available in [PR #2957](https://github.com/morluto/rea/pull/2957), from the independent `fix/browser-service-worker-policy` branch. That PR addresses this issue only.
bsakaguchi 2026-10-15 18:30:34 +00:00
Author
Owner

@dakjdakd commented on GitHub (Oct 14, 2026):

Resolved on main by f6905719c, which incorporates the fix reviewed in #2957.

Attached service_workers: "block" scenarios now check the documents being captured, including after navigation, and reject frames with an existing controller or registration. The policy has an explicit owner: setup is bounded and cancellable, future-document scripts are removed before live-frame restoration, and the owned policy is released before disconnecting. Caller-owned workers, property replacements, and initialization scripts are preserved.

The implementation and regression coverage are already on main, so #2957 is being closed as superseded and this issue is complete.

<!-- gh-comment-id:6167353916 --> @dakjdakd commented on GitHub (Oct 14, 2026): Resolved on main by [f6905719c](https://github.com/morluto/rea/commit/f6905719c3c80d829037e509d6e46129b131d893), which incorporates the fix reviewed in #2957. Attached `service_workers: "block"` scenarios now check the documents being captured, including after navigation, and reject frames with an existing controller or registration. The policy has an explicit owner: setup is bounded and cancellable, future-document scripts are removed before live-frame restoration, and the owned policy is released before disconnecting. Caller-owned workers, property replacements, and initialization scripts are preserved. The implementation and regression coverage are already on main, so #2957 is being closed as superseded and this issue is complete.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
morluto/rea#1041
No description provided.