Skip to content
This repository was archived by the owner on Jun 2, 2026. It is now read-only.

T1: Gut init script — remove Red-tier stealth patches - #7

Merged
2015kmadanap merged 33 commits into
mainfrom
t1-gut-init-script
May 28, 2026
Merged

2015kmadanap merged 33 commits into
mainfrom
t1-gut-init-script

Conversation

@2015kmadanap

Copy link
Copy Markdown

Summary

  • Remove all Red-tier JS stealth patches from stealthInitScript.ts: __chromeStealth guard, __stealthMarkNative global, C1 (webdriver getter), C2 (Function.prototype.toString masking + chrome.app/csi/loadTimes stubs + Notification.permission clamp), _markNative helper
  • Keep operational code: sanitizeUrl, Path D stamp, C3 (deferred print), C4 (print capture), C5 (window.open shim)
  • Update context.ts injection gate from if (stealth || suppressFocus) to if (suppressFocus) only
  • Remove stealth, chromeRuntimeStubs, printCapture from StealthInitScriptOptions type

Closes Sapoto-Health/automatic-document-fetcher#1137
Part of Sapoto-Health/automatic-document-fetcher#1136

Test plan

  • 43/43 tests pass (stealth-stubs + focus-shim-c5)
  • Removed stealth content confirmed absent via grep
  • Retained content (sanitizeUrl, C3/C4/C5, Path D) confirmed present
  • TypeScript compiles clean
  • Independent review: no blockers, no scope creep

🤖 Generated with Claude Code

2015kmadanap and others added 30 commits May 23, 2026 01:56
…t#1044 M2)

Squash-port of fork commits 42c8ffa..e0dc4b2 onto upstream/main HEAD
(b4d8076). Adds humanizeInput option to BrowserType.launch +
connectOverCDP that routes the Chromium mouse-move pipeline through a
pure Bezier path generator (~80-200ms per move), defeating linear-cursor
fingerprinting on anti-bot portals. Also forwards the existing
stealthMode option through the same channel boundary (was previously
silently stripped by the validator on connectOverCDP/launch).

Path remapping vs fork:
  protocol.yml LaunchOptions/connectOverCDP -> shards
    packages/protocol/spec/mixins.yml (LaunchOptions)
    packages/protocol/spec/browserType.yml (connectOverCDP)
  validator.ts + channels.d.ts -> regenerated via
    `node utils/generate_channels.js` (not hand-edited)
  MCP CLI flag (--humanize-input) / config / env var
    fork: packages/playwright/src/mcp/{program,config,browser/*}.ts
    upstream: packages/playwright-core/src/tools/mcp/{program,config}.ts
    (upstream tools/mcp does not yet carry the fork's
     browserContextFactory split or `stealth` CLI option; only
     humanizeInput is wired on the MCP side here.)

Server-side wiring updated to match upstream's BrowserOptions shape:
  - BrowserOptions in server/browser.ts adds stealthMode/humanizeInput
  - server/browserType.ts (_innerLaunch) reads options.humanizeInput
  - server/chromium/chromium.ts (_connectOverCDPInternal +
    _connectOverCDPImpl signatures, browserOptions build) threads both
  - client/browserType.ts (_connectOverCDP) explicitly forwards both
    fields (launch already spreads ...options through to the channel)
  - server/chromium/crInput.ts (RawMouseImpl) tracks _lastPos and walks
    a generateBezierPath on move when humanizeInput is on, _lastPos is
    initialized, and no buttons are held (drag-detection guard).

Theme verified independently: tests/library/bezier-input.spec.ts and
tests/library/humanize-input-channel.spec.ts travel as-is.

Type-check: `npx tsc --noEmit` -> 9 errors pre-port, 9 errors post-port
(all pre-existing missing-generated-source errors; no new errors).
Generator: `node utils/generate_channels.js`. Test suite not run
(per M2 instructions, kept fast).

Refs: Sapoto-Health/automatic-document-fetcher#1044 (M2 part 1)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Squash-port of fork commits 4e62e09..57f0a82 onto sync/upstream-1.61.
Adds the pmAutofillPreflight ladder module and the browser_wait_for_pm_autofill
MCP tool, which gives Sapoto's LoginAgent a deterministic signal for when
Bitwarden/1Password has finished autofilling the credentials form (preventing
the submit-empty-fields race documented in Sapoto's prompt-engineering notes).

Path relocations vs fork (per PRD M6 verdict - mechanical relocation):
  - mcp/browser/pmAutofillPreflight.ts        -> tools/backend/pmAutofillPreflight.ts
  - mcp/browser/tools/waitForPmAutofill.ts    -> tools/backend/waitForPmAutofill.ts
  - mcp/browser/tools.ts (registry insert)    -> tools/backend/tools.ts
  - tests/mcp/pm-autofill-preflight.spec.ts   -> unchanged location, import path retargeted

Migrated tool registration from upstream's defineTool to defineTabTool (the
browser_wait_for_pm_autofill tool is tab-scoped; defineTabTool enforces
modal-state hygiene per upstream's M3 convention). The ladder module's
'playwright-core' Page/Locator import was retargeted to upstream's
'../../..' package-root pattern used by sibling tools/backend modules.
ToolCapability 'install' -> 'core-install' was n/a (tool uses 'core').

Theme verified independently: tests/mcp/pm-autofill-preflight.spec.ts travels
as-is apart from the import path retarget.

Type-check: npx tsc --noEmit -> 9 errors pre-port, 9 errors post-port (all
pre-existing missing-generated-source errors; no new errors). ESLint clean on
all touched files. Test suite not run (per M2 instructions, kept fast).

Refs: Sapoto-Health/automatic-document-fetcher#1044 (M2 part 2)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…crosoft#1044 M3)

Squash-port of fork commit 8691f9d onto sync/upstream-1.61. Helps the
Sapoto DiscoveryAgent on Material UI / Angular CDK portals tell whether
overlay menus are open by surfacing aria-haspopup state and the explicit
negative aria-expanded value.

Path remapping vs fork:
  - packages/playwright-core/src/utils/isomorphic/ariaSnapshot.ts
    -> packages/isomorphic/ariaSnapshot.ts (per upstream package move)
  - packages/injected/src/{ariaSnapshot,roleUtils}.ts: same paths

Verified upstream baseline before porting:
  - renderAriaTree() iterates over ariaNode.expanded as truthy-only;
    upstream had no [haspopup] support and no negative [expanded=false]
    rendering. Both gaps re-introduced exactly as on the fork.
  - AriaProps in packages/isomorphic/ariaSnapshot.ts gains `haspopup`
    plus matching ariaPropsEqual()/KeyParser entries.

Retry-removal (fork 948eb9a): MOOT. Upstream merged _snapshotForAI into
ariaSnapshotForFrame() at packages/playwright-core/src/server/page.ts:1109.
The reshaped function calls incrementalAriaSnapshot() directly and only
triggers continuePolling on missing body or thrown errors -- no
`if (!result.full.trim()) return true` block to delete. Nothing to port.

Refs: Sapoto-Health/automatic-document-fetcher#1044 (M3)
…r_print (microsoft#1044 M3)

Squash-port from fork pr-27-window-open-focus-steal-shim. Adds two MCP
tools used by Sapoto agent runners:

  - browser_take_ocr_friendly_screenshot - high-fidelity device-pixel-ratio
    PNG capture tuned for downstream OCR. Supports tiled capture for tall
    pages (default tileHeight=800px CSS), optional CSS style injection, and
    a hideFixed flag that promotes position:fixed elements to absolute so
    headers/footers don't repeat across tiles. Consumed by DiscoveryAgent's
    OCR pipeline.
  - browser_trigger_print - invokes Chromium print-to-PDF on the active
    page. Functional at the page-evaluate layer today (delegates to
    page.pdf() like browser_pdf_save); the Path D srcdoc-iframe capture
    bridge that consumes the print event ports separately in M4.

Path relocation vs fork:
  - mcp/browser/tools/screenshot.ts (ocrScreenshot block) ->
    tools/backend/screenshot.ts (appended)
  - mcp/browser/tools/pdf.ts (triggerPrint block) ->
    tools/backend/pdf.ts (appended)
  - tests/mcp/screenshot.spec.ts OCR cases travel to the matching upstream
    spec file (6 OCR tests appended).

Conversions:
  - defineTool -> defineTabTool: n/a, both fork tools already used
    defineTabTool.
  - ToolCapability: ocrScreenshot stays on 'core'; triggerPrint stays on
    'pdf'. No 'install' -> 'core-install' rename triggered.
  - zod import: playwright-core/lib/mcpBundle -> 'zod' (direct).
  - formatObject import: playwright-core/lib/utils -> '@isomorphic/stringUtils'.
  - Response API: fork's response.addResult(title, data, { ..., contentType,
    skipScaling }) -> upstream's resolveClientFile + addFileResult +
    registerImageResult pattern (no contentType/skipScaling fields in
    upstream's FilenameTemplate; dropped per current API).

triggerPrint dependency note: the fork's implementation was self-contained
(plain tab.page.pdf() call) and not coupled to the Path D srcdoc-iframe
print capture handler. A TODO(M4) comment in the file body flags the
follow-up bridge work:

  // TODO(M4): re-wire to the Path D srcdoc-iframe print capture bridge
  // when that ports in.

Type-check: npx tsc --noEmit -> 9 errors pre-port, 9 errors post-port
(all pre-existing missing-generated-source errors; no new errors).

Refs: Sapoto-Health/automatic-document-fetcher#1044 (M3)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
 M3)

Per-flag overlap audit against upstream HEAD
(packages/playwright-core/src/tools/mcp/{program,config}.ts +
 packages/playwright-core/src/tools/backend/{context,tab,tools}.ts):

| Flag                  | Upstream equivalent                                          | Verdict |
|-----------------------|--------------------------------------------------------------|---------|
| --allowed-tools       | none — filteredTools only filters by capability              | PORT    |
| --filter-internal-urls| none — _onPageCreated accepts every page                     | PORT    |
| --disable-downloads   | none — tab.ts always registers page.on('download')           | PORT    |
| --keep-browser-alive  | upstream removed the auto-close: _onPageClosed has no        | DROP    |
|                       | closeBrowserContext() call (only mcp/program.ts disposed     |         |
|                       | callback closes), so the fork flag guards a codepath that    |         |
|                       | no longer exists upstream                                    |         |
| --timeout-download    | none — waitForCompletion does not await download saves       | PORT    |
| --suppress-focus      | none — selectTab calls bringToFront unconditionally          | PORT    |

Surviving flags + path relocations (fork packages/playwright/src/mcp/ -> upstream packages/playwright-core/src/tools/{mcp,backend}/):
  --allowed-tools         -> tools/mcp/{program,config,config.d}.ts + tools/backend/{tools,context}.ts (filteredTools allowedTools filter, ContextConfig field)
  --filter-internal-urls  -> tools/mcp/{program,config,config.d}.ts + tools/backend/context.ts (_isInternalUrl helper, gate in _initializeBrowserContext both initial pages and 'page' event)
  --disable-downloads    -> tools/mcp/{program,config,config.d}.ts + tools/backend/tab.ts (conditional eventsHelper.addEventListener for 'download')
  --timeout-download    -> tools/mcp/{program,config,config.d}.ts + tools/backend/tab.ts (Download.savePromise + _waitForPendingDownloads in waitForCompletion, default 30000ms in defaultConfig.timeouts)
  --suppress-focus      -> tools/mcp/{program,config,config.d}.ts + tools/backend/context.ts (gate bringToFront in selectTab). NOTE: only the CLI/config flag is ported. The fork's stealth init-script shim (window.focus noop, select-dropdown suppression, window.open focus-steal C-block) is M4 and is intentionally NOT touched here.

Env vars: PLAYWRIGHT_MCP_ALLOWED_TOOLS, PLAYWRIGHT_MCP_FILTER_INTERNAL_URLS,
PLAYWRIGHT_MCP_DISABLE_DOWNLOADS, PLAYWRIGHT_MCP_TIMEOUT_DOWNLOAD,
PLAYWRIGHT_MCP_SUPPRESS_FOCUS — all wired through configFromEnv().

CLIOptions key is camelCase allowedTools (not the fork's 'allowed-tools'
dashed key) to match upstream conventions; commander's auto camelCase
mapping from --allowed-tools handles the CLI side.

Tests travelled (only --timeout-download had fork tests):
  - tests/mcp/files.spec.ts: "slow download completes before waitForCompletion returns"
  - tests/mcp/files.spec.ts: "download timeout does not block forever"
Both rewritten to upstream args style (target:'e2' not ref:'e2') and
upstream parseResponse helper.

Dropped (now redundant with upstream):
  - --keep-browser-alive — upstream's _onPageClosed no longer auto-closes
    the browser context on empty tabs; only the factory disposed callback
    closes (which happens when the last client disconnects, not when tabs
    drain). The fork flag is therefore a no-op against upstream.

Type-check baseline: 9 pre-existing generated-module errors (codegen not run).
Post-port: same 9 errors, no new ones.

Refs: Sapoto-Health/automatic-document-fetcher#1044 (M3)
Squash-port of fork stealth commits (09922ed, 5cc320c, c84d333,
33568d4, 0b05680, 464b541) onto sync/upstream-1.61. Adds the
stealthMode option's actual init-script + CDP-stub implementation
(the option was already plumbed through channel/validator in M2 Bezier
port; this is the wiring it activates).

Core (playwright-core):
  - crPage.ts: rename utility world (`__playwright_utility_world_` →
    `__chrome_util_`) so Error.stack sourceURLs no longer leak the
    framework name; gate `Log.enable` on stealthMode; rapid
    Runtime.enable/disable cycle around context discovery (initial
    binding + on-frame-navigated) so the Runtime domain is never visible
    to page scripts; new `_updateUserAgentBrands()` + exported
    `buildChromeBrands()` that emits Chrome's three-entry UA Client Hint
    brand list (Chromium / Google Chrome / GREASE).
  - crNetworkManager.ts: skip `Network.enable` under stealthMode UNLESS
    request interception is active (Fetch.requestPaused needs networkId
    correlation); re-enable Network on the first session that flips
    interception on later.

MCP (tools/):
  - New `tools/backend/stealthInitScript.ts` consolidates the renderer-
    side stubs into a single addInitScript: navigator.webdriver=false
    (boolean, not undefined), chrome.app/csi/loadTimes with
    Function.prototype.toString masking via a WeakMap that survives
    Akamai bmak's `.toString.call(weirdThis)` pattern (Sapoto microsoft#1036),
    navigator.languages multi-locale padding, Notification.permission
    default-fallback, deferred window.print() override. Each section is
    wrapped in try/catch with a separate guard so a failure in one stub
    cannot abort the rest of the init script (the regression that
    started Sapoto microsoft#1036).
  - tools/backend/context.ts wires the script into
    `_initializeBrowserContext` (alongside the user-provided
    `--init-script` block).
  - mcp/program.ts: new `--no-stealth` CLI flag (default on).
  - mcp/config.ts: plumbs stealth through CLIOptions → launchOptions
    (so server reads `options.stealthMode` on both launch and
    CDP-attach paths) and through ContextConfig.stealth (so the init
    script can be skipped); env var `PLAYWRIGHT_MCP_STEALTH=0/false`.
  - mcp/browserFactory.ts: forward stealthMode to `connectOverCDP` on
    the CDP-attach path (the launch path already gets it via
    launchOptions).

Tests:
  - `tests/library/stealth-stubs.spec.ts` — 10 unit tests. `buildChromeBrands`
    covered directly; the init script is evaluated under Node `vm` with a
    deliberately sparse browser-shaped sandbox so the assertions don't
    need a real Chromium download. The third-party-frame regression
    (Sapoto microsoft#1036) is gated by an explicit no-DOM-no-navigator probe.

DEFERRED — empirical r1226 Chromium fingerprint audit: stubs were
validated against the merge-base Chromium binary (r1212).
Chromium has rolled 6 builds since (r1212 → r1226); some stubs may
have become no-ops, others may have new detection vectors. Follow-up
will rerun scripts/observatory/recon/ against Chase / BofA / Citi /
Capital One / Fidelity to validate end-to-end and prune dead stubs.

Refs: Sapoto-Health/automatic-document-fetcher#1044 (M3)
…-steal shim (microsoft#1044 M4)

Squash-port of fork commits onto sync/upstream-1.61. Both features inject
page-side init scripts that ride alongside the existing stealth stubs
(commit 623afae), so they land in tools/backend/stealthInitScript.ts
under their own try/catch-guarded sections.

Path D — fork 7e1319f (+189/+332 test LOC):
  Bridges contentWindow.print() inside about:srcdoc iframes to the Electron
  host via window.electronAPI.requestPrintCapture. Climbs up to 8 parent
  windows; derives frameSelector from id (SAFE_ID pre-filter) / data-print-id /
  iframe[srcdoc] fallback. The deferred branch (C3) walks the bridge when no
  top-frame override arrives; the suppressFocus print override (new C4)
  mirrors the same walk so externalBrowser iframe prints also reach the
  bridge. Addresses Sapoto issues microsoft#957 and microsoft#1006.

window.open focus-steal shim — fork pr-27-window-open-focus-steal-shim tip
(b7e783a, squash of 27ccbef..b7e783a):
  New C5 section gated on suppressFocus. Monkey-patches window.open to
  re-route download-URL popups through a same-origin fetch() (Layer 1 CDP
  Fetch.enable then captures the bytes), preventing macOS Chrome's
  NEW_FOREGROUND_TAB focus-steal. Falls back to <a download> on HTTP error
  or CORS failure. Restricted print-proxy on unnamed empty-URL popups only
  (named targets like 'helpWindow' fall through to native). Electron bridge
  detection via window.electronAPI.requestPrintCapture structural fingerprint
  (not bare typeof). Addresses Sapoto issue microsoft#1036.

Path relocation vs fork:
  - packages/playwright/src/mcp/browser/browserContextFactory.ts
    (BOTH features) → packages/playwright-core/src/tools/backend/stealthInitScript.ts
    (new C3 bridge-walk extension; new C4 + C5 sections appended; existing
    M3 stealth structure preserved as C1/C2)
  - tests/library/srcdoc-print-bridge.spec.ts travels as-is — test is
    self-contained (inlines the bridge logic against a stub electronAPI),
    no production import retargeting needed
  - CDP_STEALTH_INIT_SCRIPT remains exported (now as
    buildStealthInitScript({ suppressFocus: false })) so existing
    tests/library/stealth-stubs.spec.ts keeps working
  - context.ts wiring calls buildStealthInitScript({ suppressFocus: !!this.config.suppressFocus })

Backward-compat:
  - __SAPOTO_PATHD_BRIDGE_V1__ global stamp preserved (Sapoto build greps for it)
  - [DeferredPrint], [Print Capture], [FocusShim] log markers preserved
    (production diagnostics in app_logs)
  - DOWNLOAD_PATH_RE tightened per fork 1969a46 (no longer includes
    documents?/transactions?); preserves the post-tightening shape
  - _findClickableContext from pre-c741e1b41 is NOT ported (removed by
    refactor commit c741e1b — focus-suppression decoupled from download
    capture)

Refs: Sapoto-Health/automatic-document-fetcher#1036, microsoft#957, microsoft#1006, microsoft#1043
Refs: Sapoto-Health/automatic-document-fetcher#1044 (M4)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…oft#1044 M5)

Final-phase hygiene before the cherry-picked themes ship as a stacked PR set.
Tightens the type assertions added by M2-M4 to comply with upstream's
@typescript-eslint/no-explicit-any rule scoped to packages/playwright-core/src/tools/**.

Replacements: 28 occurrences across 5 files
  - client/browserType.ts (+2 fork-extended ConnectOverCDPOptions params)
  - server/chromium/crNetworkManager.ts (+2 narrowed via real _browser.options type)
  - tools/mcp/browserFactory.ts (+2 typed via ChannelOwner & LaunchOptions extensions; cleaned a pre-existing as any for _guid as a bonus)
  - tools/mcp/config.ts (+2 ForkLaunchOptions intersection type)
  - tests/library/srcdoc-print-bridge.spec.ts (+20 typed via BridgeWindow / BridgePayload aliases)

TS 6.0 strictness errors fixed: 0 beyond the 9 baseline.
Pre-existing baseline `Cannot find module '../generated/*Source'` errors (9)
NOT addressed in M5 — those depend on running the codegen step (npm run gen),
which is part of M1's "absorb mechanical upstream sweeps" follow-up.

Refs: Sapoto-Health/automatic-document-fetcher#1044 (M5)
- bezierInput.ts: drop curly braces around single-statement if (curly rule),
  add explicit linebreak before donor-search break (nonblock-statement-body-position).
- crInput.ts: wrap actualMove() in progress.race() to satisfy the
  progress/await-must-use-progress lint rule. actualMove already uses
  progress.race internally for each dispatch; the outer race aligns
  cancellation semantics with the non-click path. Also replace the
  setTimeout-based bezier inter-step dwell with progress.wait() so each
  await in the loop participates in progress cancellation.

Lint pipeline now passes for ported fork code. M5 follow-up; no behavior
change beyond clean cancellation propagation through the bezier walk.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…rands (microsoft#1044 task #9)

stealth-stubs.spec.ts (added in M3 commit 623afae) failed to load
under babel-jest because its `buildChromeBrands` import from crPage.ts
transitively pulls in dom.ts's `declare readonly` class-field syntax —
which babel-jest's parser doesn't handle (chokes on
`declare readonly _context: FrameExecutionContext;` at dom.ts:122).

Extracts buildChromeBrands into a new pure-utility file chromeUaBrands.ts
(55 LOC, depends only on the type-only `Protocol` import from
./protocol.d.ts) so it has no DOM imports, breaking the transitive
chain. crPage.ts now imports + re-exports from the new file so existing
callers keep working; the spec imports the helper directly.

All 11 stealth-stub tests pass across 3 browser projects (33 runs). No
changes to the stubs themselves or to crPage.ts behavior. bezier-input
and humanize-input-channel specs still green. `tsc --noEmit` and full
build remain clean.

Refs: Sapoto-Health/automatic-document-fetcher#1044 (task #9)
…rosoft#1044)

Five bugs surfaced by Codex review on the M2-M4 ports; all five validated
as real by a debate pass before fixing.

P1 — stealth env/config disable knob (config.ts + program.ts):
  configFromCLIOptions was forcing stealthMode=true whenever the user
  hadn't explicitly passed --no-stealth, because commander's --no- form
  defaults cliOptions.stealth to true. PLAYWRIGHT_MCP_STEALTH=0 and
  config-file stealth:false were silently stomped. program.ts now
  normalizes cliOptions.stealth to undefined when the flag is absent
  (mirrors sandbox flag pattern); config.ts emits stealthMode only when
  defined. Same idiom applied to humanizeInput.

P1 — Network.enable gate (crNetworkManager.ts):
  Stealth mode was skipping Network.enable in the default non-intercepting
  path. Self-healing only kicked in when Fetch.enable flipped on, so
  page.on('request') listeners under stealth saw zero events. Drops the
  gate — fingerprint surface is handled by stealthInitScript.ts, not by
  hiding the Network domain. Removes the now-dead Network.enable
  re-arm path in _updateProtocolRequestInterceptionForSession.

P2 — explicit --humanize-input=off ignored (config.ts):
  launchOptions.humanizeInput was only written for the true case, so
  --humanize-input=off couldn't override a config/env true. Emits
  whenever the value is defined.

P2 — PM autofill preflight rung 3 (pmAutofillPreflight.ts):
  Auto-derived a username selector and ran rung 3 (focus-click) even
  though the schema documents omitting usernameSelector should skip it.
  Now gates rung 3 on the user-provided selector only. Drops the
  resolveUsernameSelector helper. Tests updated to supply an explicit
  selector for the rung-3 assertions.

P2 — hideFixed screenshot CSS (screenshot.ts):
  '* { position: fixed !important; position: absolute !important; }'
  collapsed all elements to absolute due to later-wins cascade. Replaced
  with a page.evaluate walk that sets only fixed/sticky elements to
  static.

Refs: Sapoto-Health/automatic-document-fetcher#1044
Refs: codex review on PR Sapoto-Health#28
…(Sapoto microsoft#1036)

The M4 squash port (5616743) re-applied the renderer-side FocusShim but
dropped the core-side suppressFocus chain that propagates the CLI flag to
Target.createTarget({ background: true }). As a result, browser_tabs
{ action: "new" } created foreground Chrome targets that stole OS focus,
even with --suppress-focus set — reintroducing the exact bug microsoft#1036 was
opened to fix.

This restores the propagation:

  --suppress-focus (CLI)
    → Config.suppressFocus
    → connectOverCDP({ suppressFocus })       (client + channel + validator)
    → BrowserOptions.suppressFocus            (server)
    → Target.createTarget({ background })     (CRBrowserContext.doCreateNewPage)

Mirrors the fork-side reference at b7e783a. Protocol regen via
utils/generate_channels.js produced only the expected 3 minimal additions
(one validator line + two channel typedef lines).

Verification: npx tsc --noEmit clean. No new tests — fork shipped the
original chain without a Target.createTarget background-arg test
(manual Sapoto microsoft#1036 repro was the verification path).
…stantMode removal

Upstream 4b1b9d6 (chore: remove cdp port from launch options) removed
the assistantMode gate from chromiumSwitches() as a side effect. Result:
core no longer adds --disable-blink-features=AutomationControlled to
fork-launched Chromium contexts.

MCP CLI (tools/mcp/config.ts:254) papers over this for its own launches,
but anyone calling fork launch() / launchPersistentContext() directly
inherits the regression — and bank portals doing automation detection
(Chase, BofA, Citi, CapOne, Fidelity) will see the leaked
AutomationControlled blink-feature.

This re-adds the flag unconditionally (no assistantMode gate — that
parameter was removed upstream). Belt-and-suspenders: Sapoto autodocs's
own chromeManager/effects.ts:78 already disables AutomationControlled
in spawn args for the connectOverCDP path, but this protects every
fork-launched context (tests, scripts, future call sites) and makes
the MCP-CLI push a harmless dedupe rather than the sole defense.

Note: --enable-automation was also removed in 4b1b9d6; that's
actually a stealth improvement (it triggers webdriver=true) so we
leave that absence untouched.

Verification: npx tsc --noEmit clean. Patch is purely additive to the
disabledFeatures string array.
The M3 stealth port (623afae) pushed _updateUserAgentBrands()
unconditionally inside the !isStorageStatePage block. Upstream had just
landed connectOverCDP({ noDefaults }) (71a9b30, microsoft#40185) which computes
skipDefaultOverrides at crPage.ts:537-538 and gates setFocusEmulationEnabled
+ _updateEmulateMedia on it. The M3 port missed propagating the same gate
to UA brand emulation.

Result before this fix: a caller passing connectOverCDP({ noDefaults: true })
still gets UA brand overrides they explicitly opted out of. Today's Sapoto
callsites don't pass noDefaults, so this was dormant — but the fork
shouldn't ship the contradiction.

The fix mirrors how upstream gates the two adjacent overrides in the same
block.

Verification: npx tsc --noEmit clean; stealth-stubs.spec.ts 11/11 pass
(brand emulation unchanged on the default noDefaults:false path).
The M3 port (d1dc677) left browser_trigger_print calling page.pdf()
with a TODO(M4) comment pointing at the srcdoc-iframe print bridge.
M4 landed but pdf.ts was never updated.

page.pdf() bypasses the entire Path D bridge — no window.print() event
ever fires, so the stealthInitScript.ts C3 block (lines 227-310) doesn't
intercept, and the Electron host's printCaptureHandler.ts never runs.
The captured PDF loses per-portal CSS/iframe scoping and degrades to a
vanilla Chromium print-to-PDF.

This restores the fork's original implementation:
    await tab.page.evaluate(() => window.print());

which is what the bridge is designed to intercept. Returns a text result
matching the fork's behavior. Callers who actually want raw page.pdf()
have browser_pdf_save.

Verification: npx tsc --noEmit clean. No new test added — the Path D
bridge logic is already covered end-to-end by tests/library/srcdoc-print-bridge.spec.ts,
and the Electron-side capture handler lives in the Sapoto autodocs repo
and is tested there.
Codex review flagged that the FocusShim C5 block in stealthInitScript.ts
(lines 431-615) had no direct test. Path D srcdoc bridge was covered by
srcdoc-print-bridge.spec.ts; stealth VM context (C1-C3) by
stealth-stubs.spec.ts; C5 was the gap.

This new spec covers 18 scenarios mapped to specific C5 production branches:
- Install gating on suppressFocus=true/false (3 tests)
- _self/_parent/_top + named-popup carve-outs (2 tests)
- Empty-URL print-capture proxy (3 tests, including proxy.print() forwarding)
- Same-origin / cross-origin / non-download URL handling (4 tests)
- DOWNLOAD_PATH_RE extensionless match (statements path) (1 test)
- HTTP non-OK and network-error <a download> CORS fallback (2 tests)
- Electron bridge bypass: real shape + truthy-non-function fingerprint
  + throwing-getter fingerprint protection (3 tests — covers
  Codex P1 fixes from dd3a5e8)

Result: 18 passed (438ms). Coverage of 14 of 16 C5 sub-features.
Uncovered (deferred, low value): native .toString() masking on `open`
and the install-crash try/catch guard.

Note: the vm sandbox requires explicit URL injection
(Node's vm.createContext doesn't expose WHATWG URL by default) —
without it, 7 download-path scenarios silently fall through to native
when the shim's `new URL(u, location.href)` ReferenceErrors.
Same intrinsic-leakage caveat noted in stealth-stubs.spec.ts.
…ners alive (microsoft#1044)

P0 — every Sapoto chrome-mode agent run was failing immediately. Root
cause: the M3 CLI flags port dropped --keep-browser-alive after the
overlap audit found upstream had removed the closeBrowserContext()-
on-last-tab path the flag gated. But Sapoto's four agent runners still
pass keepBrowserAlive: externalBrowser, which makes mcpPaths.ts:201 add
--keep-browser-alive to the MCP child's argv. Commander's strict-option
parsing exits 1 → MCP child dies → 60s SDK timeout → opaque agent error.

Re-adds the flag as a commander option with no downstream wiring
(upstream's auto-close path is gone, so there's nothing to gate). This
preserves CLI compat for downstream consumers without resurrecting the
dead code path the original gate guarded.

Refs: Sapoto-Health/automatic-document-fetcher#1044
…oft#1044 P0)

Chrome-mode agent runs were broken because the M3 CDP-stealth port
collapsed three concerns into one gate at tools/backend/context.ts:388-391.
The outer `if (this.config.stealth !== false)` made the entire init
script — stealth stubs (C1/C2), Path D deferred print (C3/C4), AND
FocusShim window.open intercept (C5) — install only when stealth was on.

Sapoto passes --no-stealth for chrome mode (chrome's real identity must
not be overridden by fingerprint stubs), so the entire script never
installed -> window.open opened a real new tab -> window.print() fired
the native print dialog. Visible regression: Netflix invoice flow opens
a focus-stealing tab and triggers the native Chrome print dialog.

Splits the gate. buildStealthInitScript() now accepts BOTH {stealth,
suppressFocus} and emits sections per their independent gates:
  - C1/C2 stealth stubs              -> gated on stealth
  - C3 deferred print + Path D       -> gated on suppressFocus
  - C4 suppressFocus print override  -> gated on suppressFocus
  - C5 FocusShim window.open         -> gated on suppressFocus

_initializeBrowserContext installs the script whenever either flag is
truthy. When both are off, the addInitScript call is skipped entirely.

Bug 2 (chrome-mode Path D PDF generation) is already wired up via
src/main/downloads/printCapture.ts — it listens for [Print Capture]
markers on Runtime.consoleAPICalled and calls Page.printToPDF through
the active capture layer. With the gate split here, the C4 marker
now actually fires in chrome mode, so no additional Sapoto-side
plumbing is required.

Test changes:
  - stealth-stubs.spec.ts: window.print deferred-handler test now
    builds with {stealth:true, suppressFocus:true} because C3 is gated
    on suppressFocus (not stealth). Added a paired test confirming
    print is untouched at suppressFocus:false. Third-party-frame guard
    test updated similarly to cover the full surface.
  - focus-shim-c5.spec.ts: added a regression test for the exact
    chrome-mode combination {stealth:false, suppressFocus:true} —
    asserts FocusShim still installs, window.open routes through
    fetch, and C1 stubs DO NOT install. Helper signature extended
    to accept an optional `stealth` argument (defaults to true so
    existing tests are unaffected).

Refs: Sapoto-Health/automatic-document-fetcher#1044

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…addresses codex P2)

Codex review on commit 4d43286 flagged that the gate-split inadvertently
moved C3 (deferred window.print() + iframe Path D bridge) from its original
M3 stealth gate onto suppressFocus. Combined with C4's immediate overwrite of
window.print at line 344, C3 was unreachable in both modes — regressing the
M3-era early-print defer that credentials mode relies on while Sapoto's
electronAPI bridge finishes attaching.

Restores C3 to gate on `stealth`. Per Sapoto's actual modes:
  - Credentials mode (stealth=true, suppressFocus=false) → C3 installs
    (deferred handler + electronAPI bridge walk for iframe Path D)
  - Chrome mode    (stealth=false, suppressFocus=true)  → C4 installs
    (immediate bridge for chrome-mode Layer-4 print capture)

These modes are mutually exclusive in Sapoto's runtime, so C3 and C4 never
conflict.

Test updates:
  - Two stealth-stubs tests that built with suppressFocus=true to exercise C3
    revert to the default CDP_STEALTH_INIT_SCRIPT shape (stealth=true,
    suppressFocus=false).
  - New stealth-stubs test asserts C3 installs in credentials-mode shape.

Refs: Sapoto-Health/automatic-document-fetcher#1044
Refs: codex review on PR Sapoto-Health#28
…oft#1045) (microsoft#29)

* feat(stealth): decompose stealthMode into typed cdpStealth feature set (microsoft#1045 A1)

Replaces the previous-generation `stealthMode: boolean` on BrowserOptions
with `cdpStealth: Set<CdpStealthFeature>` plus three new booleans
(`printCapture`, `chromeRuntimeStubs`, `focusEmulation`). Wire format is
`cdpStealth: string[]`, rehydrated to a typed Set at the server boundary.

PRD microsoft#1045 Tracer A1 — types + propagation only. crPage call sites use a
coarse `cdpStealth.size > 0` check to preserve PR microsoft#28's bundled behavior;
A3 will migrate to per-feature `cdpStealth.has(...)` gating.

`network-skip` is intentionally rejected (Codex P1 review on PR microsoft#28
removed Network.enable gating because it broke page.on('request')).

Backward-compat: legacy callers passing `stealthMode: true` get translated
to the full 3-feature bundle at the client option-parsing layer
(`resolveCdpStealthAlias` in packages/isomorphic/) for one release cycle.

* fix(stealth): wire resolveCdpStealthAlias into launchServer path (microsoft#1045 A1, codex P1)

A1 removed `stealthMode` from BrowserTypeLaunchParams/BrowserTypeLaunchPersistentContextParams
and `client/browserType.ts` was updated to call `resolveCdpStealthAlias` before
the validator runs (for `launch` / `launchPersistentContext` / `_connectOverCDP`).

The launchServer path was missed. `BrowserServerLauncherImpl.launchServer`
runs the same validators against raw options without first translating the
legacy `stealthMode: true|false` alias, so `tObject` silently drops the unknown
property and the server-side `Browser.options.cdpStealth` ends up empty for
callers still on the legacy boolean — including anyone whose
`_defaultLaunchOptions` carries `stealthMode`.

This patch mirrors the client-side call sites: resolve the alias on the raw
options up front, then thread the resulting `cdpStealth` into `launchOptions`
before the validator pass. Already-migrated callers passing `cdpStealth: [...]`
are unaffected (the resolver is a no-op when `cdpStealth` is set).

A test-only `_preLaunchedBrowserForTest` hook on the returned BrowserServer
(mirrors the existing `_userDataDirForTest` test-only pattern) lets the
regression tests inspect server-side `Browser.options.cdpStealth` without
adding a public API.

Three new tests in `tests/library/humanize-input-channel.spec.ts` (the file
that already owns the `stealthMode → cdpStealth` round-trip regression suite):
- launchServer expands legacy `stealthMode: true` to the full 3-feature Set
- launchServer with legacy `stealthMode: false` yields empty `cdpStealth`
- launchServer preserves explicit `cdpStealth` (alias is a no-op)

All three were confirmed to fail without the wiring (the first test
failed with `runtime-cycle missing from launchServer alias expansion`)
and pass after.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
… marker (microsoft#1044 Arch A)

Decouples FocusShim's focus-suppression from its content-capture mechanism.
The post-c741e1b41 shim's same-origin fetch() worked for URLs serving PDF
bytes directly but silently broke for HTML-auto-print portals (Netflix
/invoice/print/<id>): fetch() retrieves the HTML, Layer 1 rejects text/html,
no artifact is produced, agent gives up.

C5 now emits a console.warn marker that Sapoto's main process catches via
Runtime.consoleAPICalled (same pattern as printCapture.ts). Sapoto then
spawns a hidden CDP target via Target.createTarget({background: true}) and
lets Chrome render the URL naturally — Layer 1 catches PDFs, Layer 4
catches HTML-auto-print markers. No focus steal because background:true.

Drops _fetchAndForget (no remaining callers). Cross-origin download branch
also routes to the marker (closes the "accepted focus-steal for one popup"
trade-off from microsoft#1043).

Marker emits the FULL absolute URL (not sanitized) — the marker is the
navigation target and would 401 on portals carrying auth tokens in query
params; existing src/main/redaction/ handles remote-log sanitization.

Folds in fork PR microsoft#30. Squash-merged from feat/focus-shim-background-target:
  0d3af0b feat(mcp): replace FocusShim fetch() with [FocusShim] background-open marker
  a307fa4 fix(mcp): preserve query/hash in [FocusShim] background-open marker (codex P1)

Refs: Sapoto-Health/automatic-document-fetcher#1044
) (microsoft#31)

* A4: opaque per-page utility-world name (PRD microsoft#1045)

Replace `__chrome_util_${page.guid}` with a fresh 16-char lowercase-hex
token generated per CRPage via `crypto.randomBytes(8).toString('hex')`.
The previous shape leaked two detection-grade fingerprints into any
surface that surfaced the world name — Runtime.executionContextCreated
events and Error.stack sourceURL tags:

  1. The literal `__chrome_` prefix — real Chrome has no built-in
     execution context whose name starts with that prefix; anti-bot
     stack scrapers (Akamai bmak, DataDome) treat it as a tell.
  2. The embedded Playwright `SdkObject.guid` format `page@<32hex>` —
     any thrown stack scraped by page scripts identifies the page as
     automation-driven regardless of every other stealth posture.

The rename is always-on; it is NOT gated by the `cdpStealth` feature
set introduced in A1, because the leak exists regardless of CDP-domain
posture — any exception thrown inside the utility world surfaces the
name through `Error.stack` and would be visible to a page that wraps
the global Error constructor or scrapes `console.debug` output.

Implementation:
- New `crUtilityWorldName.ts` exposes `generateUtilityWorldName()` and
  the `UTILITY_WORLD_NAME_PATTERN` regex. Pure helper, no dependencies
  beyond `node:crypto`. Both are exported so the unit and integration
  test suites can share the contract.
- `crPage.ts` calls the helper once at CRPage construction time. No
  behavioral change beyond the string itself; the name still feeds
  `Page.addScriptToEvaluateOnNewDocument` and is matched against
  `Runtime.executionContextCreated` events.

Tests:
- `tests/library/utility-world-name.spec.ts` — 4 unit tests against the
  generator. Locks the 16-hex shape, asserts no `__chrome_` or
  `__playwright_` prefix and no `page@<32hex>` substring across a
  64-call sweep, and asserts 256 consecutive calls produce 256 distinct
  values (per-call uniqueness, no caching).
- `tests/library/chromium/utility-world-name-leak.spec.ts` — 3 real-
  Chromium integration tests. Captures the world name via CDP
  `Runtime.executionContextCreated`, evaluates `new Error().stack`
  inside the utility world and asserts the stack contains zero frames
  matching `/__chrome_util_/`, `/__playwright_/`, or
  `/page@[0-9a-f]{32}/`, and asserts two pages in the same context get
  distinct utility-world names (per-page differentiation, not per-
  context).

Acceptance-criterion coverage:
- [x] `utilityWorldName` set per-page to a fresh 16-char hex string
- [x] No occurrences of the literal `__chrome_util_` in src/
- [x] Per-page differentiation enforced by test
- [x] Integration test asserts zero leaked frames
- [x] `npm run build`, `npx tsc --noEmit`, `npm run check-deps` pass

* test(stealth): strengthen utility-world Error.stack leak assertion + nits (microsoft#1045 A4, codex)

Codex flagged that the raw Runtime.evaluate stack probe could pass
vacuously when Chromium emits anonymous-eval frames without source labels.
Fix: tag the evaluated expression with //# sourceURL=${worldName}, then
self-validate that the captured stack contains the opaque hex marker
before asserting it contains no forbidden substrings. The positive check
proves V8 is actually attaching source labels in this CDP flow, so the
negative check has teeth.

Two nits folded in:
- utility-world-name.spec.ts: refresh stale comment ref to the leak spec.
- crPage.ts: trim verbose constructor comment.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…s, BRIDGE sentinel, langs clamp, webdriver shape, FocusShim warn→debug) (PRD microsoft#1045) (microsoft#32)

* A5: init script gating (PRD microsoft#1045) — printCapture + chromeRuntimeStubs flags

Decompose the consolidated CDP stealth init script along two new axes so
callers can opt out of subsections that don't apply to their browser mode:

- printCapture (default true) gates BOTH C3 (deferred print + Path D
  iframe bridge) and C4 (suppressFocus-mode print fast-path). Callers
  that own print capture out-of-band (e.g. CDP Page.printToPDF) opt out.
- chromeRuntimeStubs (default true) gates the chrome.{app,csi,loadTimes}
  + Notification.permission sub-stubs inside C2. The Function.prototype.
  toString patch and the __stealthMarkNative cross-section helper still
  install (C1/C4/C5 depend on the helper handshake).

Companion changes inside the same gate:

- C1 navigator.webdriver moved BELOW _markNative; getter now lives on
  Navigator.prototype (mirroring real Chrome) and is masked native so
  its .toString() reads as `function webdriver() { [native code] }`.
  Test-sandbox fallback retains an instance-level define when no
  Navigator constructor is present.
- The navigator.languages length-1 clamp is REMOVED — rewriting a
  single-locale array to ['en-US','en'] was itself a fingerprint when
  the underlying OS exposed a single locale. Real Chrome's value
  passes through unchanged.
- All 13 [FocusShim] console.warn calls downgraded to console.debug.
  Page-level RUM and antibot hooks listening on console.warn no longer
  pick up the shim's lifecycle chatter.
- window.__SAPOTO_PATHD_BRIDGE_V1__ = true is no longer installed on
  window. Replaced by `void '__SAPOTO_PATHD_BRIDGE_V1_STAMP__'` so the
  build-time grep target (scripts/prepare-mcp-assets.js, parallel
  tracer B6) stays intact without polluting the global namespace.

Tests: tests/library/stealth-stubs.spec.ts extended with 9 new
assertions covering each gate (presence/absence per flag combination),
the webdriver descriptor location + shape on Navigator.prototype, the
sentinel-literal presence + window-pollution absence, the languages
clamp removal, the __stealthMarkNative handshake when chrome.* stubs
are off, and the FocusShim debug-vs-warn shift. 21/21 pass.

Verified: npm run build, npx tsc --noEmit (no new errors vs base),
npm run check-deps all green. Build output contains the sentinel
literal exactly once and zero `__SAPOTO_PATHD_BRIDGE_V1__ = true`
occurrences.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(stealth): align webdriver getter shape with B5/real-Chrome (microsoft#1045 A5, codex)

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…le (PRD microsoft#1045) (microsoft#33)

* A3: Decompose coarse cdpStealth gate into per-feature checks (PRD microsoft#1045)

Tracer A1 substituted the legacy `stealthMode` boolean with the placeholder
`cdpStealth.size > 0` at three CDP-domain call sites. A3 decomposes that
into per-subcomponent membership checks so each gate can be flipped
independently from the CLI/channel surface (A2/B-series).

Three distinct subcomponents, four call sites:
  - `log-skip`       → crPage Log.enable skip
  - `runtime-cycle`  → crPage Runtime.enable cycle on init + frameNavigated
                       (same flag drives both sites by design)
  - `worker-runtime` → NEW: crServiceWorker Runtime.enable→disable cycle
                       (previously upstream issued Runtime.enable unconditionally
                       here, leaving the long-lived Runtime domain visible to
                       worker scripts)

Refactor:
  - New `cdpStealthGates.ts` module exposes pure-decision helpers
    (`shouldSkipLogEnable`, `shouldCycleRuntimeOnInit`,
    `shouldCycleRuntimeOnFrameNavigation`, `shouldCycleWorkerRuntime`)
    so each gate is testable without a real Chromium/CRSession.
  - `crPage.ts` migrated to call them at the three existing sites.
  - `crServiceWorker.ts` wires the NEW `worker-runtime` cycle.
  - `tools/backend/context.ts` docstring (`stealth?: boolean`) updated to
    reflect that core-side CDP minimization now lives in the per-feature
    `cdpStealth` set; the boolean drives only the renderer init-script
    bundle.

`network-skip` stays intentionally absent (codex P1 review on PR microsoft#28
removed Network.enable gating because it broke `page.on('request')`
listeners). `Emulation.setFocusEmulationEnabled` was already ungated by
cdpStealth — focus emulation wiring moves to the `focusEmulation` boolean
in a later tracer (B4).

Tests: 7 new test cases in `tests/library/cdp-stealth-gates.spec.ts`:
  - shouldSkipLogEnable helper
  - log-skip stub-CDP integration
  - runtime-cycle init stub-CDP integration
  - runtime-cycle frameNavigated stub-CDP integration (initial guard)
  - worker-runtime stub-CDP integration
  - cross-helper independence sanity

All 13 tests in cdp-stealth-{gates,options}.spec.ts pass. `npm run build`
and `npm run check-deps` are clean; `npx tsc --noEmit` shows the same 12
pre-existing errors as the base (all in files unrelated to A3 — the
symlinked node_modules/playwright path).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(stealth): chain worker runIfWaitingForDebugger after cycle + clean up literal refs (microsoft#1045 A3, codex blocker + concerns)

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…#1045) (microsoft#34)

* A6: Serialize Mouse.click move → down → up (PRD microsoft#1045)

Replace the Promise.all race in Mouse.click() (non-delayed path) with
sequential `await move; await down; await up`. The prior code let the
mousePressed and mouseReleased CDP dispatches resolve interleaved with
the trailing bezier mouseMoved dispatches emitted by RawMouseImpl.move(),
producing a detectable event-order inversion on the CDP wire — a
mousePressed command arriving at the browser before the bezier had
finished sending its mouseMoved commands. Antibot fingerprinters
(Akamai bmak, PerimeterX, DataDome) inspect that ordering and flag the
inversion as a non-human click.

Sequential awaits remove the race entirely. The humanized and
non-humanized paths now behave identically with respect to event
ordering; the delayed path was already sequential and is left
unchanged structurally (only the explanatory comment is added).

Test: tests/library/click-event-order.spec.ts
- Drives a real Chromium via the worktree-local playwright-core build
  (required directly to bypass linked-worktree node_modules resolution
  that would otherwise load the main checkout's stale bundle).
- Hooks the chromium RawMouseImpl._client.send and asserts the captured
  Input.dispatchMouseEvent sequence matches /mouseMoved+ mousePressed
  mouseReleased/.
- Covers humanizeInput=true (~12+ bezier mouseMoved dispatches) and
  humanizeInput=false (single teleport mouseMoved); both must serialize
  identically per A6.
- Verified with teeth: reverting the source change and rebuilding makes
  the humanizeInput=true test fail with the exact original bug pattern
  (mouseMoved, mousePressed, mouseReleased, mouseMoved x N).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(stealth): scope click-event-order test to chromium project + comment cleanup (microsoft#1045 A6, codex)

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…(PRD microsoft#1045) (microsoft#35)

* A2: decomposed CLI flag surface for fork MCP (PRD microsoft#1045)

Replace the single-boolean `--stealth` / `--no-stealth` MCP CLI flag with
the five-flag surface PRD microsoft#1045 specifies, mapping 1:1 to the
`BrowserOptions` fields A1 wired through the channel:

  --cdp-stealth=<comma-list>      → launchOptions.cdpStealth (string[])
  --print-capture                 → launchOptions.printCapture
  --chrome-runtime-stubs={on|off} → launchOptions.chromeRuntimeStubs
  --focus-emulation={on|off}     → launchOptions.focusEmulation

`--cdp-stealth` accepts the canonical 3 features ("runtime-cycle",
"log-skip", "worker-runtime"), the "all" sentinel, or an empty value.
`network-skip` is rejected with a loud error at the CLI layer (Codex P1
review on PR microsoft#28 removed Network.enable gating because it broke
page.on('request') listeners; surface the rejection at the entry point
so a stale invocation script doesn't silently no-op deeper in).

`--stealth` / `--no-stealth` retained as one-cycle aliases for
`--cdp-stealth=all` / `--cdp-stealth=`. Commander now accepts both
positive and negative forms as separate options; `resolveStealthAlias`
mirrors the precedence in `@isomorphic/cdpStealthAlias` so explicit
`cdpStealth` wins over the legacy boolean.

Env-var equivalents added for each new flag
(PLAYWRIGHT_MCP_CDP_STEALTH, *_PRINT_CAPTURE, *_CHROME_RUNTIME_STUBS,
*_FOCUS_EMULATION) using the same parser.

No runtime-behavior change — A3 consumes the parsed cdpStealth Set in
crPage, A5 migrates the init-script gating off the legacy
`config.stealth` field.

Tests (`tests/library/mcp-cli-flag-surface.spec.ts`, 20 cases) pin both
the leaf `parseCdpStealthCLI` parser and the integrated translation
through `resolveCLIConfigForMCP`, including the never-passed vs.
explicit-empty distinction (required so a CLI invocation can opt out of
all stealth even when env / config-file defaults would enable them).

* fix(stealth): default-on flag semantics + CDP endpoint forwarding + transition aliasing (microsoft#1045 A2, codex blockers + concerns)
…isting (microsoft#1083)

Architecture A's backgroundOpenBridge spawns hidden CDP targets via
Target.createTarget({background:true}) to capture popup-PDF downloads
without focus theft. Those targets ARE real pages in the BrowserContext,
so the existing browserContext.on('page') listener in _onPageCreated
adds them to _tabs[] — which surfaces them through browser_tabs to the
agent. The agent then interacts with the hidden target as if it were
a normal tab, runs browser_trigger_print on it, and reports failure
even though the bridge correctly captured the PDF.

Filters out pages whose URL starts with the well-known marker
'about:blank#__sapoto_bg=' that Sapoto's bridge uses when spawning
hidden targets. _onPageCreated reads page.url() synchronously at
listener entry — before the bridge's subsequent Page.navigate has
fired — so the filter sees the marker even though the URL changes
later.

Adds a CDP integration test in tests/mcp/cdp.spec.ts that reproduces
the perception leak (Target.createTarget with the marker URL +
background:true) and asserts browser_tabs no longer surfaces the
hidden target. Verified the test FAILS without the filter and passes
with it.

Refs: Sapoto-Health/automatic-document-fetcher#1083
Refs: Sapoto-Health/automatic-document-fetcher#1044
…t docstring (opus review)

Two findings from the opus adversarial review of f75885f:

1. Docstring at _isSapotoBackgroundTarget overclaimed the timing guarantee
   as "synchronous". The 'page' event is actually emitted from
   _markInitialized (page.ts:246) after _initialize's Promise.all resolves.
   The filter is still race-free in practice, but for non-obvious reasons:
   waitForDebuggerOnStart pauses the renderer until playwright sends
   Runtime.runIfWaitingForDebugger; _handleFrameTree synchronously writes
   frame._url = marker before that unpause. Replaced the misleading
   docstring with the accurate three-invariant explanation.

2. Bumped the marker prefix to a versioned token (V1) mirroring the
   __SAPOTO_PATHD_BRIDGE_V1__ convention so future protocol changes can be
   detected if one side drifts.

Also documents the URL-pattern-matching security limitation (a hostile
in-context page can construct a marker URL and hide a popup from the
agent — fix would require target-ID registry or HMAC marker).

Refs: Sapoto-Health/automatic-document-fetcher#1083

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…sage, tileHeight, humanizeInput CDP attach

Four validated codex review findings on PR microsoft#28:

P1 — crPage.ts UA locale wipe (Finding 9):
  _updateUserAgentBrands sent Emulation.setUserAgentOverride with only
  userAgent + userAgentMetadata, but the CDP call is a full replace, not
  a merge. Both _updateUserAgent (which sets acceptLanguage) and
  _updateUserAgentBrands ride the same _initialize Promise.all, so a
  late brands resolution wipes the locale. Now passes acceptLanguage
  through the second payload.

P2 — pdf.ts trigger_print honest message (Finding 10):
  browser_trigger_print unconditionally reported "Page printed and
  captured as a PDF automatically" even in modes where no capture path
  is wired. Replaced with an honest result that describes the actual
  outcome based on whether an Electron bridge is detected in-page.

P2 — screenshot.ts tileHeight validation (Finding 11):
  Zod schema accepted negative tileHeight, which silently skipped the
  OCR capture loop (numTiles became <= 0). Now constrained to a
  nonnegative integer at the schema layer.

P2 — browserFactory.ts CDP-attach humanizeInput (Finding 13):
  createCDPBrowser forwarded the other A2 fields but dropped
  humanizeInput, so --humanize-input only worked on the launch path,
  not on --cdp-endpoint. Now threaded through with the same guard as
  the siblings.

Refs: Sapoto-Health/automatic-document-fetcher#1044
Refs: codex review on PR Sapoto-Health#28
- Add docs/stealth-principles.md as the governing anti-detection design
  reference: core philosophy, 6 design principles, threat model,
  CDP-specific risks, Green/Yellow/Red risk classification,
  implementation checklist, and testing philosophy.
- Rewrite CLAUDE.md to lead with the fork's stealth purpose, link to
  the principles doc, add fork architecture diagram, Sapoto key files
  table, stealth test inventory, and 9 stealth development rules.
…acer microsoft#1137)

Remove all Red-tier stealth JS patches: C1 navigator.webdriver getter,
C2 Function.prototype.toString masking + chrome.{app,csi,loadTimes} stubs
+ Notification.permission clamp, __chromeStealth idempotency guard,
__stealthMarkNative global, and _markNative usage from C4/C5. Remove
stealth/printCapture/chromeRuntimeStubs from StealthInitScriptOptions.
Update context.ts injection gate from if(stealth||suppressFocus) to
if(suppressFocus). Keep operational code: sanitizeUrl, Path D stamp,
C3 deferred print, C4 print capture, C5 window.open shim.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

if (!browser.launchOptions.args.some(a => a.includes('--disable-blink-features')))
browser.launchOptions.args.push(`--disable-blink-features=AutomationControlled`);

P2 Badge Append AutomationControlled to existing blink feature lists

When a user already supplies another --disable-blink-features=... argument (for example from config or launchOptions.args), this guard skips adding AutomationControlled entirely unless their existing value happens to include it. That leaves the new webdriver suppression disabled for those launches even though the validator intends to add it for every Chromium MCP session; the existing argument needs to be merged with AutomationControlled rather than treating any blink-feature switch as sufficient.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +166 to +167
if (config.suppressFocus)
connectOptions.suppressFocus = true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Thread suppressFocus through launched browsers too

When --suppress-focus is used without --cdp-endpoint (the default persistent/isolated MCP launch paths), this is the only place that forwards the flag into BrowserOptions; createIsolatedBrowser and createPersistentBrowser only spread config.browser.launchOptions, while config.suppressFocus is top-level. In those headed launch modes CRBrowserContext.doCreateNewPage() therefore sees options.suppressFocus as undefined and omits Target.createTarget({ background: true }), so browser_tabs new-tab operations can still steal OS focus despite the flag.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pre-existing — browserFactory.ts not modified by this PR. Valid but out of scope for microsoft#1136.

Comment on lines +399 to +400
if (cliOptions.focusEmulation !== undefined)
launchOptions.focusEmulation = cliOptions.focusEmulation;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor the focus-emulation off switch

This exposes and forwards --focus-emulation=off, but no call site consumes BrowserOptions.focusEmulation: CRPage still sends Emulation.setFocusEmulationEnabled({ enabled: true }) for every main frame unless noDefaults is set. In any run that passes the advertised off value, the option is accepted and visible in launch options but the CDP domain is still enabled, so the new CLI flag does not actually gate the fingerprint surface it documents.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pre-existing — config.ts only touched for import order fix. Blink-features merge logic predates this PR. Valid but out of scope for microsoft#1136.

…him-c5

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 00acdec27a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +444 to +446
if (suppressFocus) {
this._disposables.push(await browserContext.addInitScript(
buildStealthInitScript({ suppressFocus })));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor --print-capture when installing print bridge

When MCP is launched with --print-capture but without --suppress-focus, the new flag is accepted and forwarded onto launchOptions.printCapture, but this Context setup never consults it and skips buildStealthInitScript entirely. Since buildStealthInitScript({ suppressFocus: false }) is the path that installs the C3 deferred window.print() bridge, browser_trigger_print can still fall through to a native dialog/no-op in that advertised print-capture-only configuration.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By design per PRD microsoft#1136. The gate change from stealth || suppressFocus → suppressFocus only is intentional. Sapoto always passes suppressFocus=true, so C3/C4/C5 are never lost. --print-capture alone without --suppress-focus was never a real use case.

…/order rule

Pre-existing lint failures on main — fixing here to unblock CI.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: de0212222d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +523 to +527
this._client.send('Runtime.enable', {}).then(() => {
if (shouldCycleRuntimeOnInit(this._crPage._browserContext._browser.options.cdpStealth)) {
return Promise.resolve().then(() => {
return this._client._sendMayFail('Runtime.disable');
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve Runtime for console events

When runtime-cycle is enabled (for example via the legacy --stealth alias or --cdp-stealth=runtime-cycle), this disables the Runtime domain immediately after context discovery. The page’s console plumbing in this same FrameSession depends on Runtime.consoleAPICalled, so after initialization normal page.on('console') / browser_console_messages output and other Runtime events stop arriving until another brief re-enable cycle. In those stealth sessions, any console diagnostics emitted by the page after load are silently lost.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pre-existing — cdpStealthGates.ts not modified by this PR. Runtime-cycle's console event trade-off is a known consequence documented in stealth-principles.md. Out of scope for microsoft#1136.

@github-actions

Copy link
Copy Markdown

Test results for "MCP"

15 failed
❌ [chrome] › mcp/capabilities.spec.ts:19 › test snapshot tool list @mcp-macos-latest-chrome
❌ [chrome] › mcp/capabilities.spec.ts:19 › test snapshot tool list @mcp-ubuntu-latest-chrome
❌ [chrome] › mcp/capabilities.spec.ts:19 › test snapshot tool list @mcp-windows-latest-chrome
❌ [chromium] › mcp/capabilities.spec.ts:19 › test snapshot tool list @mcp-macos-latest-chromium
❌ [chromium] › mcp/pm-autofill-preflight.spec.ts:111 › preview-retract — not reported as filled (two-consecutive-hits) @mcp-macos-latest-chromium
❌ [chromium] › mcp/capabilities.spec.ts:19 › test snapshot tool list @mcp-windows-latest-chromium
❌ [chromium] › mcp/capabilities.spec.ts:19 › test snapshot tool list @mcp-ubuntu-latest-chromium
❌ [firefox] › mcp/capabilities.spec.ts:19 › test snapshot tool list @mcp-ubuntu-latest-firefox
❌ [firefox] › mcp/capabilities.spec.ts:19 › test snapshot tool list @mcp-windows-latest-firefox
❌ [firefox] › mcp/capabilities.spec.ts:19 › test snapshot tool list @mcp-macos-latest-firefox
❌ [firefox] › mcp/pm-autofill-preflight.spec.ts:111 › preview-retract — not reported as filled (two-consecutive-hits) @mcp-macos-latest-firefox
❌ [msedge] › mcp/capabilities.spec.ts:19 › test snapshot tool list @mcp-windows-latest-msedge
❌ [webkit] › mcp/capabilities.spec.ts:19 › test snapshot tool list @mcp-macos-latest-webkit
❌ [webkit] › mcp/capabilities.spec.ts:19 › test snapshot tool list @mcp-windows-latest-webkit
❌ [webkit] › mcp/capabilities.spec.ts:19 › test snapshot tool list @mcp-ubuntu-latest-webkit

7369 passed, 1131 skipped


Merge workflow run.

@github-actions

Copy link
Copy Markdown

Test results for "tests 1"

10 failed
❌ [chromium-page] › page/page-click.spec.ts:39 › should issue clicks in parallel in page and popup @ubuntu-22.04-chromium-tip-of-tree
❌ [chromium-page] › page/page-click.spec.ts:39 › should issue clicks in parallel in page and popup @chromium-ubuntu-22.04-arm-node20
❌ [chromium-page] › page/page-click.spec.ts:39 › should issue clicks in parallel in page and popup @chromium-ubuntu-22.04-node24
❌ [chromium-page] › page/page-click.spec.ts:39 › should issue clicks in parallel in page and popup @chromium-ubuntu-22.04-node20
❌ [chromium-page] › page/page-click.spec.ts:39 › should issue clicks in parallel in page and popup @chromium-ubuntu-22.04-node22
❌ [firefox-library] › library/browsertype-basic.spec.ts:34 › should throw when trying to connect with not-chromium @firefox-ubuntu-22.04-node20
❌ [firefox-page] › page/page-click.spec.ts:39 › should issue clicks in parallel in page and popup @firefox-ubuntu-22.04-node20
❌ [webkit-library] › library/browsertype-basic.spec.ts:34 › should throw when trying to connect with not-chromium @webkit-ubuntu-22.04-node20
❌ [webkit-page] › page/page-click.spec.ts:39 › should issue clicks in parallel in page and popup @webkit-ubuntu-22.04-node20
❌ [webkit-page] › page/page-click.spec.ts:1203 › should fire contextmenu event on right click in correct order @webkit-ubuntu-22.04-node20

3 flaky ⚠️ [chromium-library] › library/video.spec.ts:719 › screencast › should work with video+trace `@ubuntu-22.04-chromium-tip-of-tree`
⚠️ [chromium-library] › library/beforeunload.spec.ts:130 › should support dismissing the dialog multiple times `@chromium-ubuntu-22.04-node24`
⚠️ [chromium-library] › library/popup.spec.ts:261 › should not throw when click closes popup `@chromium-ubuntu-22.04-node22`

44654 passed, 875 skipped


Merge workflow run.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant