From 2c1ceabbf1f117daafe166e1134b47737b38e1f6 Mon Sep 17 00:00:00 2001
From: N0zoM1z0 <1705004398@qq.com>
Date: Tue, 14 Jul 2026 12:27:13 +0800
Subject: [PATCH] feat: add passive website reverse engineering
---
AGENTS.md | 12 +-
CONTRIBUTING.md | 4 +-
README.md | 42 +-
README_ar.md | 21 +-
README_ja.md | 7 +-
README_ko.md | 7 +-
README_zh.md | 7 +-
docs/architecture.mermaid | 13 +-
docs/browser-observation.md | 121 +++++
docs/error-contract.schema.json | 6 +
docs/mcp-prompts.md | 2 +-
package.json | 1 +
scripts/rea.mjs | 2 +-
scripts/verify-package.mjs | 4 +
scripts/verify-published-package.mjs | 4 +-
scripts/verify-real-browser.mjs | 286 ++++++++++
scripts/verify-real-hopper.mjs | 2 +-
skills/rea-analysis/SKILL.md | 21 +-
src/application/BrowserEvidence.ts | 61 +++
src/application/BrowserObservationPort.ts | 23 +
src/application/BrowserObservationService.ts | 126 +++++
src/application/CapabilityInventory.ts | 10 +
src/application/ProjectPermissionStore.ts | 2 +
src/browser/CdpBrowserProvider.ts | 229 ++++++++
src/browser/CdpCaptureDocuments.ts | 198 +++++++
src/browser/CdpCaptureEvents.ts | 300 ++++++++++
src/browser/CdpCaptureStorage.ts | 116 ++++
src/browser/CdpCaptureValues.ts | 98 ++++
src/browser/CdpConnection.ts | 252 +++++++++
src/browser/CdpEndpoint.ts | 207 +++++++
src/browser/CdpOptionalCommand.ts | 31 ++
src/browser/CdpPageCapture.ts | 446 +++++++++++++++
src/catalogIdentity.ts | 2 +
src/cli.ts | 2 +
src/cliBrowserCommands.ts | 173 ++++++
src/cliPolicyCommands.ts | 4 +
src/config.ts | 70 +++
src/contracts/browserToolContracts.ts | 92 ++++
src/contracts/errorSchemas.ts | 2 +
src/contracts/toolContractTypes.ts | 1 +
src/contracts/toolContracts.ts | 8 +-
src/domain/browserObservation.ts | 397 ++++++++++++++
src/domain/errors.ts | 55 ++
src/domain/permissionPolicy.ts | 11 +
src/generatedPackageMetadata.ts | 4 +-
src/main.ts | 7 +
src/server/createServer.ts | 10 +
src/server/registerBrowserTools.ts | 85 +++
src/server/registerSessionStatusTool.ts | 1 +
src/server/registerSessionTools.ts | 3 +
tests/browserCli.test.ts | 135 +++++
tests/browserMcp.test.ts | 170 ++++++
tests/browserObservation.test.ts | 126 +++++
tests/cdpBrowserProvider.test.ts | 497 +++++++++++++++++
tests/cdpCaptureDocuments.test.ts | 74 +++
tests/cdpConnection.test.ts | 56 ++
tests/config.test.ts | 54 ++
tests/contractSnapshot.test.ts | 13 +-
tests/enhancedTools.test.ts | 2 +-
tests/errors.test.ts | 8 +-
tests/fixtures/fakeCdpBrowser.ts | 544 +++++++++++++++++++
tests/integration/serverIntegration.test.ts | 8 +-
tests/permissionPolicy.test.ts | 39 ++
tests/promptMcp.test.ts | 2 +-
tests/readmeConsistency.test.ts | 6 +-
tests/runtime.test.ts | 6 +-
tests/serverIdentity.test.ts | 15 +-
tests/sessionMcp.test.ts | 2 +-
tests/setupSkill.test.ts | 2 +-
tests/toolContracts.test.ts | 11 +-
typedoc.json | 1 +
71 files changed, 5279 insertions(+), 80 deletions(-)
create mode 100644 docs/browser-observation.md
create mode 100644 scripts/verify-real-browser.mjs
create mode 100644 src/application/BrowserEvidence.ts
create mode 100644 src/application/BrowserObservationPort.ts
create mode 100644 src/application/BrowserObservationService.ts
create mode 100644 src/browser/CdpBrowserProvider.ts
create mode 100644 src/browser/CdpCaptureDocuments.ts
create mode 100644 src/browser/CdpCaptureEvents.ts
create mode 100644 src/browser/CdpCaptureStorage.ts
create mode 100644 src/browser/CdpCaptureValues.ts
create mode 100644 src/browser/CdpConnection.ts
create mode 100644 src/browser/CdpEndpoint.ts
create mode 100644 src/browser/CdpOptionalCommand.ts
create mode 100644 src/browser/CdpPageCapture.ts
create mode 100644 src/cliBrowserCommands.ts
create mode 100644 src/contracts/browserToolContracts.ts
create mode 100644 src/domain/browserObservation.ts
create mode 100644 src/server/registerBrowserTools.ts
create mode 100644 tests/browserCli.test.ts
create mode 100644 tests/browserMcp.test.ts
create mode 100644 tests/browserObservation.test.ts
create mode 100644 tests/cdpBrowserProvider.test.ts
create mode 100644 tests/cdpCaptureDocuments.test.ts
create mode 100644 tests/cdpConnection.test.ts
create mode 100644 tests/fixtures/fakeCdpBrowser.ts
diff --git a/AGENTS.md b/AGENTS.md
index 233f67985..dd16617e8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -26,13 +26,15 @@ See [docs/architecture.mermaid](docs/architecture.mermaid) for a visual architec
- `src/cli.ts`: one-shot CLI adapter for setup, diagnostics, analysis, and decompilation.
- `src/config.ts`: Zod-validated parsing of environment configuration into `AppConfig`.
- `src/domain/`: pure, side-effect-free modules. `errors.ts` (tagged error algebra), `result.ts` (`Result`/`ok`/`err`), `hopperValues.ts` (boundary parsers for Hopper JSON), `symbolAnalysis.ts` (Swift/ObjC name parsing).
-- `src/contracts/`: caller-visible schemas for 33 direct, 10 enhanced, 5 native, 2 artifact, and 18 session tools; `enhancedInputs.ts` owns enhanced input parsing.
+- `src/contracts/`: caller-visible schemas for 33 direct, 10 enhanced, 5 native, 2 artifact, 2 browser, and 18 session tools; `enhancedInputs.ts` owns enhanced input parsing.
+- `src/browser/`: loopback CDP discovery, bounded WebSocket transport, exact-origin target authorization, and passive browser observation normalization.
- `src/hopper/`: Hopper launch and Unix-socket protocol mechanics. `BridgeLauncher.ts` spawns the Hopper app with the in-process bridge, `HopperClient.ts` correlates request/response over the socket with timeouts and cancellation, `protocol.ts` frames bridge messages.
- `bridge/hopper_bridge.py`: runs inside Hopper and adapts declared operations to Hopper's public Python API. Hopper's bundled MCP server is not used.
- `src/application/`: shared CLI/MCP session composition, setup and diagnostics, and enhanced workflows.
- `src/server/`: MCP request translation. `createServer.ts` assembles the MCP server, `registerOfficialTools.ts`/`registerEnhancedTools.ts` register each tool set, `toolResult.ts` maps `Result` values to MCP content.
- `tests/`: Vitest suite. `tests/fixtures/` holds the fake launcher and fake Hopper bridge used as production seams.
- `scripts/verify-real-hopper.mjs`: real-Hopper end-to-end verifier.
+- `scripts/verify-real-browser.mjs`: real Chrome end-to-end verifier for the passive CDP provider.
- `scripts/print-mcp-config.mjs`: prints an MCP server config with absolute paths filled in (`npm run config:print -- /path/to/binary`).
## Build, Test, and Development Commands
@@ -49,7 +51,8 @@ See [docs/architecture.mermaid](docs/architecture.mermaid) for a visual architec
- `npm run jscpd`: detect duplicate code blocks.
- `npm run scan:todos`: scan for TODO, FIXME, and HACK markers.
- `npm run verify:hopper`: build and run the real-Hopper verifier with two distinct binaries.
-- `npm run verify:package`: pack and test the CLI, setup transaction, skill, and 68-tool target-free MCP server in an isolated environment.
+- `npm run verify:browser`: build and run the real Chrome verifier against `REA_BROWSER_EXECUTABLE` or a platform-default Chrome-family executable.
+- `npm run verify:package`: pack and test the CLI, setup transaction, skill, and 70-tool target-free MCP server in an isolated environment.
- `npm run docs:generate`: generate API documentation from JSDoc comments into `docs/api/` using TypeDoc.
- `npm run config:print -- /path/to/binary`: print an MCP server config with absolute paths.
- `HOPPER_TARGET_PATH=/path/to/binary npm start`: launch Hopper and run the built stdio MCP server.
@@ -62,6 +65,9 @@ Pre-commit hooks via Husky run `oxlint` on staged files before every commit. Use
- `HOPPER_LAUNCHER_PATH` (optional): override the Hopper executable path (defaults to `/Applications/Hopper Disassembler.app/Contents/MacOS/hopper`).
- `HOPPER_TARGET_KIND` (optional, default `executable`): startup kind for `HOPPER_TARGET_PATH`; dynamic targets are classified from their paths and headers.
- `HOPPER_LOADER_ARGS_JSON` (optional): JSON array overriding derived Hopper loader arguments for supported executable targets, e.g. `["-l","Mach-O","--aarch64"]`.
+- `REA_BROWSER_OBSERVE_ENABLED` (optional, default `false`): add browser observation authority to the administrator ceiling.
+- `REA_BROWSER_CDP_ENDPOINTS_JSON` (optional): approved literal loopback CDP HTTP endpoints.
+- `REA_BROWSER_ALLOWED_ORIGINS_JSON` (optional): exact HTTP(S) page origins approved for passive observation.
## Coding Style & Naming Conventions
@@ -69,7 +75,7 @@ Use ESM TypeScript, two-space indentation, and Prettier defaults. Keep compiler
## Testing Guidelines
-Name tests `*.test.ts`. Use Vitest and production seams (`tests/fixtures/`) rather than module mocks. Domain tests assert pure behavior; adapter tests use the fake launcher/socket; MCP tests connect with the beta.3 client. Preserve the 33 direct, 10 enhanced, 5 native, 2 artifact, and 18 session tool inventory (68 total). Cover malformed input, cancellation, timeouts, process exit, concurrency, limits, and clean shutdown. Real Hopper claims cannot be replaced by mocks — use `npm run verify:hopper` with two distinct binaries for end-to-end verification.
+Name tests `*.test.ts`. Use Vitest and production seams (`tests/fixtures/`) rather than module mocks. Domain tests assert pure behavior; adapter tests use the fake launcher/socket; MCP tests connect with the beta.3 client. Preserve the 33 direct, 10 enhanced, 5 native, 2 artifact, 2 browser, and 18 session tool inventory (70 total). Cover malformed input, cancellation, timeouts, process exit, concurrency, limits, and clean shutdown. Real Hopper and browser claims cannot be replaced by mocks; use `npm run verify:hopper` with two distinct binaries and `npm run verify:browser` with Chrome.
## Commit & Pull Request Guidelines
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 713a044e0..ac09b405e 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -13,7 +13,7 @@ npm run build
npm test
```
-Keep dependencies flowing inward through the existing domain, contracts, Hopper, application, server, and adapter layers. Parse unknown values at process and protocol boundaries, model expected failures with `Result`, and preserve the 33 direct, 10 enhanced, 5 native, 2 artifact, and 18 session tools (68 total) unless a deliberate contract change updates every verifier and snapshot.
+Keep dependencies flowing inward through the existing domain, contracts, provider, application, server, and adapter layers. Parse unknown values at process and protocol boundaries, model expected failures with `Result`, and preserve the 33 direct, 10 enhanced, 5 native, 2 artifact, 2 browser, and 18 session tools (70 total) unless a deliberate contract change updates every verifier and snapshot.
Before submitting a pull request, run:
@@ -70,7 +70,7 @@ Publish the public package:
npm publish --access public
```
-After npm registry propagation, verify the published CLI and connect a beta.3 MCP client to the published server to confirm all 68 tools:
+After npm registry propagation, verify the published CLI and connect a beta.3 MCP client to the published server to confirm all 70 tools:
```bash
npx -y rea-agents --help
diff --git a/README.md b/README.md
index 973939f88..08f341812 100644
--- a/README.md
+++ b/README.md
@@ -10,11 +10,11 @@
[](https://www.npmjs.com/package/rea-agents)
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
-[](#68-tools-for-investigation)
+[](#70-tools-for-investigation)
[](https://nodejs.org/)
[](LICENSE)
-[Quick start](#quick-start) · [Current status](#current-status) · [Investigation model](#the-investigation-model) · [68 tools](#68-tools-for-investigation) · [Roadmap](#roadmap) · [How it works](#how-it-works)
+[Quick start](#quick-start) · [Current status](#current-status) · [Investigation model](#the-investigation-model) · [70 tools](#70-tools-for-investigation) · [Roadmap](#roadmap) · [How it works](#how-it-works)
@@ -294,15 +294,16 @@ REA handles the app analysis in steps 1–5. The agent performs step 6 with its
- Analyze Swift and Objective-C metadata without manually untangling every mangled symbol.
- Leave names, comments, and bookmarks in Hopper so human and agent analysis reinforce each other.
-## 68 tools for investigation
+## 70 tools for investigation
-| Tool family | Count | Examples |
-| ------------------------- | ----: | ----------------------------------------------------------------------------------------------------------------------- |
-| Native inspection | 33 | procedures, pseudocode, assembly, strings, names, segments, callers, callees, xrefs, annotations |
-| Investigation workflows | 10 | `binary_overview`, `analyze_function`, `batch_decompile`, `trace_feature`, call graphs, Swift and Objective-C discovery |
-| Native macOS utilities | 5 | Mach-O metadata, code signatures, plists, architectures, Swift demangling; Hopper-free and provenance-bearing |
-| Artifact graph | 2 | deterministic directory, ZIP/APK/IPA, and ASAR inventory; explicitly selected extraction into an absent owned tree |
-| Workspace and observation | 18 | target lifecycle, Evidence v2 bundles, process/artifact/function comparison, evidence-linked residual-unknown lifecycle |
+| Tool family | Count | Examples |
+| ------------------------- | ----: | ---------------------------------------------------------------------------------------------------------------------------------- |
+| Native inspection | 33 | procedures, pseudocode, assembly, strings, names, segments, callers, callees, xrefs, annotations |
+| Investigation workflows | 10 | `binary_overview`, `analyze_function`, `batch_decompile`, `trace_feature`, call graphs, Swift and Objective-C discovery |
+| Native macOS utilities | 5 | Mach-O metadata, code signatures, plists, architectures, Swift demangling; Hopper-free and provenance-bearing |
+| Artifact graph | 2 | deterministic directory, ZIP/APK/IPA, and ASAR inventory; explicitly selected extraction into an absent owned tree |
+| Browser observation | 2 | exact-origin CDP page discovery and passive DOM, accessibility, script, resource, network, console, worker, and storage inspection |
+| Workspace and observation | 18 | target lifecycle, Evidence v2 bundles, process/artifact/function comparison, evidence-linked residual-unknown lifecycle |
The public interface describes what the agent is trying to learn. Providers decide how to answer. macOS utilities handle common semantic inspection without launching Hopper; Hopper handles deeper native analysis; the process harness implements controlled behavioral capture.
@@ -311,6 +312,7 @@ The public interface describes what the agent is trying to learn. Providers deci
REA is already useful for native application investigation on macOS:
- Open Mach-O, ELF, PE, `.app`, ZIP, APK, IPA, ASAR, plist, JavaScript, source-map, and Hopper database targets.
+- Attach to a user-owned Chrome-family browser over a configured loopback CDP endpoint, list only pages on approved exact origins, and capture bounded passive web evidence without navigation or JavaScript evaluation.
- Traverse content-addressed artifact graphs without extraction; on macOS, read-only DMG traversal additionally requires `native_mount_approved: true` and `REA_ARTIFACT_NATIVE_MOUNT_ENABLED=true`. Materialize only approved occurrences into absent output roots.
- Build bounded function dossiers with pseudocode, assembly, CFG edges, comments, calls, references, strings, and names.
- Search and trace features across symbols, strings, metadata, references, and call paths.
@@ -331,12 +333,27 @@ REA is already useful for native application investigation on macOS:
Hopper is the first provider, not the boundary of the project. Some current workflows still require Hopper and macOS; every evidence record identifies the provider and limitations behind its result.
+### Website observation with CDP
+
+REA can inspect an already-running Chrome-family browser that you own. Browser observation is disabled by default and requires a literal loopback CDP endpoint plus exact approved page origins:
+
+```bash
+export REA_BROWSER_OBSERVE_ENABLED=true
+export REA_BROWSER_CDP_ENDPOINTS_JSON='["http://127.0.0.1:9222"]'
+export REA_BROWSER_ALLOWED_ORIGINS_JSON='["http://127.0.0.1:3000"]'
+
+rea list-browser-targets http://127.0.0.1:9222 --approved --json
+rea inspect-web-page http://127.0.0.1:9222 TARGET_ID --approved --json
+```
+
+`list_browser_targets` and `inspect_web_page` expose the same Evidence v2 contracts over MCP. Inspection is passive: REA does not evaluate page JavaScript, navigate, click, close the page, or close the browser. It redacts query values and never retains headers, bodies, cookies, storage values, console argument values, or WebSocket payloads. Existing activity before attach is explicitly unavailable. See [Website observation with CDP](docs/browser-observation.md) for browser startup, schemas, limits, and the threat model.
+
## Roadmap
REA is growing into a toolkit for understanding software across static artifacts and observed behavior. The next capability families are:
1. **Artifact decomposition** — DMG, ASAR, ZIP, packages, universal-binary slices, application resources, embedded frameworks, mobile packages, and artifact graphs.
-2. **Web and Electron investigation** — Playwright/CDP capture of DOM, accessibility trees, screenshots, storage, console, IPC, HTTP, WebSocket, routes, and visual or structural differences.
+2. **Web and Electron investigation** — extend the shipped passive CDP observation with approved interaction, screenshots, Electron IPC, route discovery, controlled replay, and visual or structural differences.
3. **Deterministic behavior harnesses** — stronger process-tree ownership, protocol fixtures, network policy, filesystem tracing, signals, reconnects, and cross-version comparison.
4. **JavaScript and source recovery** — bundle indexing, AST/module reconstruction, source-map discovery, historical-source matching, and CodeDB-backed cross-references.
5. **Runtime observation** — approval-gated LLDB, Frida, system logs, process and filesystem observers, and native API tracing.
@@ -381,8 +398,9 @@ flowchart LR
Router --> Hopper["Hopper provider"]
Router --> Native["Native macOS provider"]
Router --> Artifact["Artifact graph provider"]
+ Router --> Browser["Browser CDP provider"]
Router --> Process["Process capture provider"]
- Router -. roadmap .-> More["Browser, dynamic,
and additional static providers"]
+ Router -. roadmap .-> More["Dynamic and additional
static providers"]
Hopper --> Target["Target software"]
Process --> Target
Native --> Target
diff --git a/README_ar.md b/README_ar.md
index 16187da35..097053d4c 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -10,11 +10,11 @@
[](https://www.npmjs.com/package/rea-agents)
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
-[](#منصة-من-68-أداة)
+[](#منصة-من-70-أداة)
[](https://nodejs.org/)
[](LICENSE)
-[البدء السريع](#البدء-السريع) · [من الملف التنفيذي إلى السلوك](#من-الملف-التنفيذي-إلى-السلوك) · [68 أداة](#منصة-من-68-أداة) · [كيف يعمل](#كيف-يعمل) · [الأسئلة الشائعة](#الأسئلة-الشائعة)
+[البدء السريع](#البدء-السريع) · [من الملف التنفيذي إلى السلوك](#من-الملف-التنفيذي-إلى-السلوك) · [70 أداة](#منصة-من-70-أداة) · [كيف يعمل](#كيف-يعمل) · [الأسئلة الشائعة](#الأسئلة-الشائعة)
@@ -155,15 +155,16 @@ rea uninstall --purge-data
افحص التحقق من الإدخال، والتشفير، والصلاحيات، والتخزين، ومسارات الأخطاء من دون رفع الملف التنفيذي إلى خدمة بعيدة.
-## منصة من 68 أداة
+## منصة من 70 أداة
-| عائلة الأدوات | العدد | أمثلة |
-| --------------------- | ----: | ----------------------------------------------------------------------------------- |
-| فحص الملفات التنفيذية | 33 | الدوال، والشيفرة شبه المصدرية، والتعليمات، والسلاسل، والأسماء، والمراجع، والتعليقات |
-| التحليل المركب | 10 | النظرة العامة، وفك الترجمة الدفعي، ومخططات الاستدعاء، والمراجع، واكتشاف الأنواع |
-| أدوات macOS الأصلية | 5 | بيانات Mach-O والتوقيعات وملفات plist والمعماريات وفك رموز Swift دون تشغيل Hopper |
-| رسم القطع الأثرية | 2 | جرد حتمي للدلائل وZIP/APK/IPA وASAR واستخراج معاملاتي محدد صراحة |
-| جلسة الملف التنفيذي | 18 | فتح الأهداف وحزم الأدلة ومقارنة العمليات والقطع والدوال وسجل المجهولات المتبقية |
+| عائلة الأدوات | العدد | أمثلة |
+| --------------------- | ----: | ---------------------------------------------------------------------------------------- |
+| فحص الملفات التنفيذية | 33 | الدوال، والشيفرة شبه المصدرية، والتعليمات، والسلاسل، والأسماء، والمراجع، والتعليقات |
+| التحليل المركب | 10 | النظرة العامة، وفك الترجمة الدفعي، ومخططات الاستدعاء، والمراجع، واكتشاف الأنواع |
+| أدوات macOS الأصلية | 5 | بيانات Mach-O والتوقيعات وملفات plist والمعماريات وفك رموز Swift دون تشغيل Hopper |
+| رسم القطع الأثرية | 2 | جرد حتمي للدلائل وZIP/APK/IPA وASAR واستخراج معاملاتي محدد صراحة |
+| مراقبة المتصفح | 2 | اكتشاف صفحات CDP ضمن أصول دقيقة وفحص سلبي لـ DOM وإتاحة الوصول والبرامج والشبكة والتخزين |
+| جلسة الملف التنفيذي | 18 | فتح الأهداف وحزم الأدلة ومقارنة العمليات والقطع والدوال وسجل المجهولات المتبقية |
## استخدام REA مع وكلاء برمجة آخرين
diff --git a/README_ja.md b/README_ja.md
index a6c99a25c..b7e37cee4 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -10,11 +10,11 @@
[](https://www.npmjs.com/package/rea-agents)
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
-[](#68-ツールのワークベンチ)
+[](#70-ツールのワークベンチ)
[](https://nodejs.org/)
[](LICENSE)
-[クイックスタート](#クイックスタート) · [バイナリから動作へ](#バイナリから動作へ) · [68 ツール](#68-ツールのワークベンチ) · [仕組み](#仕組み) · [FAQ](#faq)
+[クイックスタート](#クイックスタート) · [バイナリから動作へ](#バイナリから動作へ) · [70 ツール](#70-ツールのワークベンチ) · [仕組み](#仕組み) · [FAQ](#faq)
@@ -145,7 +145,7 @@ REA は手順 1〜5 のバイナリ解析を処理し、手順 6 はエージェ
- Swift / Objective-C のメタデータを解析する。
- Hopper に名前、コメント、ブックマークを残し、人間とエージェントの調査を共有する。
-## 68 ツールのワークベンチ
+## 70 ツールのワークベンチ
| ツール群 | 数 | 例 |
| ---------------------- | --: | ------------------------------------------------------------------------------------------------------------------- |
@@ -153,6 +153,7 @@ REA は手順 1〜5 のバイナリ解析を処理し、手順 6 はエージェ
| 合成解析 | 10 | `binary_overview`, `analyze_function`, `batch_decompile`, `get_call_graph`, `find_xrefs_to_name`, Swift / ObjC 検出 |
| macOS ネイティブ | 5 | Mach-O メタデータ、署名、plist、アーキテクチャ、Swift デマングル。Hopper 起動不要 |
| アーティファクトグラフ | 2 | ディレクトリ、ZIP/APK/IPA、ASAR の決定的一覧と明示選択されたトランザクション抽出 |
+| ブラウザ観察 | 2 | 完全一致 origin に限定した CDP ページ検出と受動的な DOM、アクセシビリティ、スクリプト、通信、保存領域の調査 |
| バイナリセッション | 18 | `open_binary`、`binary_session`、証拠バンドル、プロセス/成果物/関数比較、残余未知レジストリ |
## 他のコーディングエージェントで使う
diff --git a/README_ko.md b/README_ko.md
index 7e8f1ffd3..a7e0c7e46 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -10,11 +10,11 @@
[](https://www.npmjs.com/package/rea-agents)
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
-[](#68개-도구로-구성된-워크벤치)
+[](#70개-도구로-구성된-워크벤치)
[](https://nodejs.org/)
[](LICENSE)
-[빠른 시작](#빠른-시작) · [바이너리에서 동작까지](#바이너리에서-동작까지) · [68개 도구](#68개-도구로-구성된-워크벤치) · [작동 방식](#작동-방식) · [FAQ](#faq)
+[빠른 시작](#빠른-시작) · [바이너리에서 동작까지](#바이너리에서-동작까지) · [70개 도구](#70개-도구로-구성된-워크벤치) · [작동 방식](#작동-방식) · [FAQ](#faq)
@@ -145,7 +145,7 @@ REA는 1–5단계의 바이너리 분석을 처리합니다. 6단계는 에이
- Swift 및 Objective-C 메타데이터를 분석합니다.
- Hopper에 이름, 주석, 북마크를 남겨 사람과 에이전트의 분석을 연결합니다.
-## 68개 도구로 구성된 워크벤치
+## 70개 도구로 구성된 워크벤치
| 도구 그룹 | 수 | 예시 |
| ------------------- | --: | -------------------------------------------------------------------------------------------------------------------- |
@@ -153,6 +153,7 @@ REA는 1–5단계의 바이너리 분석을 처리합니다. 6단계는 에이
| 합성 분석 | 10 | `binary_overview`, `analyze_function`, `batch_decompile`, `get_call_graph`, `find_xrefs_to_name`, Swift 및 ObjC 탐색 |
| macOS 네이티브 도구 | 5 | Mach-O 메타데이터, 코드 서명, plist, 아키텍처, Swift 디맹글링. Hopper 실행 불필요 |
| 아티팩트 그래프 | 2 | 디렉터리, ZIP/APK/IPA, ASAR 결정적 인벤토리와 명시적으로 선택한 트랜잭션 추출 |
+| 브라우저 관찰 | 2 | 정확한 origin 범위의 CDP 페이지 검색과 수동 DOM, 접근성, 스크립트, 네트워크, 콘솔 및 저장소 조사 |
| 바이너리 세션 | 18 | `open_binary`, `binary_session`, 증거 번들, 프로세스·아티팩트·함수 비교, 잔여 미지수 레지스트리 |
## 다른 코딩 에이전트에서 사용하기
diff --git a/README_zh.md b/README_zh.md
index f89c64a3b..4bdc6cd9c 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -10,11 +10,11 @@
[](https://www.npmjs.com/package/rea-agents)
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
-[](#68-个工具组成的工作台)
+[](#70-个工具组成的工作台)
[](https://nodejs.org/)
[](LICENSE)
-[快速开始](#快速开始) · [从二进制到行为](#从二进制到行为) · [68 个工具](#68-个工具组成的工作台) · [工作原理](#工作原理) · [常见问题](#常见问题)
+[快速开始](#快速开始) · [从二进制到行为](#从二进制到行为) · [70 个工具](#70-个工具组成的工作台) · [工作原理](#工作原理) · [常见问题](#常见问题)
@@ -145,7 +145,7 @@ REA 负责第 1–5 步中的二进制分析。第 6 步由智能体使用其常
- 分析 Swift 和 Objective-C 元数据。
- 在 Hopper 中留下名称、注释与书签,使人与智能体的分析互相增强。
-## 68 个工具组成的工作台
+## 70 个工具组成的工作台
| 工具类别 | 数量 | 示例 |
| -------------- | ---: | -------------------------------------------------------------------------------------------------------------------- |
@@ -153,6 +153,7 @@ REA 负责第 1–5 步中的二进制分析。第 6 步由智能体使用其常
| 组合分析 | 10 | `binary_overview`, `analyze_function`, `batch_decompile`, `get_call_graph`, `find_xrefs_to_name`、Swift 与 ObjC 发现 |
| macOS 原生工具 | 5 | Mach-O 元数据、代码签名、plist、架构与 Swift 符号还原,无需启动 Hopper |
| 制品图谱 | 2 | 确定性目录、ZIP/APK/IPA 与 ASAR 清单,以及显式选择的事务式提取 |
+| 浏览器观察 | 2 | 基于精确来源范围的 CDP 页面发现,以及被动 DOM、无障碍树、脚本、网络、控制台与存储检查 |
| 二进制会话 | 18 | `open_binary`、`binary_session`、证据包、进程、制品与函数比较、残余未知项注册表 |
## 与其他编程智能体一起使用
diff --git a/docs/architecture.mermaid b/docs/architecture.mermaid
index 39eed561a..60d7b68d5 100644
--- a/docs/architecture.mermaid
+++ b/docs/architecture.mermaid
@@ -20,8 +20,12 @@ graph TD
HOPPER["src/hopper/
Hopper launch & Unix-socket protocol
BridgeLauncher, HopperClient, protocol"]
end
+ subgraph "Browser Provider Layer"
+ BROWSER["src/browser/
Loopback CDP transport
exact-origin passive observation"]
+ end
+
subgraph "Contracts Layer"
- CONTRACTS["src/contracts/
Caller-visible tool schemas
68 direct, enhanced, native, artifact, and session tools"]
+ CONTRACTS["src/contracts/
Caller-visible tool schemas
70 analysis, browser, and session tools"]
end
subgraph "Domain Layer"
@@ -29,11 +33,11 @@ graph TD
end
subgraph "Configuration"
- CONFIG["src/config.ts
Zod-validated env parsing
provider settings and approved roots"]
+ CONFIG["src/config.ts
Zod-validated env parsing
provider settings, origins, and approved roots"]
end
subgraph "Tests"
- TESTS["tests/
Vitest suite
fixtures/ holds fake launcher & bridge seams"]
+ TESTS["tests/
Vitest suite
fixtures/ holds fake launcher, bridge, and CDP seams"]
end
DISPATCH --> CLI
@@ -47,9 +51,12 @@ graph TD
SERVER --> CONTRACTS
SERVER --> APP
APP --> HOPPER
+ APP --> BROWSER
HOPPER --> BRIDGE
APP --> DOMAIN
CONTRACTS --> DOMAIN
HOPPER --> DOMAIN
+ BROWSER --> DOMAIN
TESTS -.-> MAIN
TESTS -.-> HOPPER
+ TESTS -.-> BROWSER
diff --git a/docs/browser-observation.md b/docs/browser-observation.md
new file mode 100644
index 000000000..1728d61d3
--- /dev/null
+++ b/docs/browser-observation.md
@@ -0,0 +1,121 @@
+# Website observation with CDP
+
+REA can attach to a user-owned Chrome-family browser through the Chrome DevTools Protocol (CDP) and produce bounded Evidence v2 about an existing page. This is a passive reverse-engineering capability, not a general browser automation or remote-control surface.
+
+## Shipped surfaces
+
+- `list_browser_targets` / `rea list-browser-targets` discovers page targets whose current URL matches an approved exact origin.
+- `inspect_web_page` / `rea inspect-web-page` captures bounded DOM structure, accessibility nodes, scripts, resources, attach-window network and console metadata, WebSocket frame sizes, workers, quota, and optionally storage key names or script sources.
+- Both surfaces return the same provider-neutral normalized results and Evidence v2 provenance.
+- MCP session results are retained as `rea://evidence/{evidenceId}` resources. One-shot CLI output is not retained by a long-lived REA session.
+
+## Start a browser
+
+Start a separate browser profile with an explicit debugging port. The exact executable name varies by platform and installation:
+
+```bash
+google-chrome \
+ --remote-debugging-port=9222 \
+ --user-data-dir=/tmp/rea-browser-profile \
+ http://127.0.0.1:3000
+```
+
+REA does not launch, own, or terminate this browser. Use a dedicated profile and stop it yourself when the investigation is complete. Do not expose the debugging port on a non-loopback interface.
+
+## Configure authority
+
+Browser observation is fail-closed by default. Configure the administrator ceiling before starting REA:
+
+```bash
+export REA_BROWSER_OBSERVE_ENABLED=true
+export REA_BROWSER_CDP_ENDPOINTS_JSON='["http://127.0.0.1:9222"]'
+export REA_BROWSER_ALLOWED_ORIGINS_JSON='["http://127.0.0.1:3000"]'
+```
+
+`REA_BROWSER_CDP_ENDPOINTS_JSON` accepts at most 16 literal `http://127.0.0.1:PORT` or `http://[::1]:PORT` endpoints. `localhost`, private-LAN addresses, HTTPS endpoints, credentials, paths, queries, fragments, and implicit ports are rejected.
+
+`REA_BROWSER_ALLOWED_ORIGINS_JSON` accepts at most 32 exact HTTP(S) origins. Paths, credentials, queries, fragments, and wildcards are rejected. An input must stay within both this administrator ceiling and any active project/session/once grant.
+
+Configuration is reloadable through the existing `SIGHUP` permission-policy path. A request still requires `approved: true`; configuration alone does not make a tool call implicit.
+
+Inspect the exact effective scope without contacting the browser:
+
+```bash
+rea policy explain browser_observe \
+ --origins http://127.0.0.1:9222 \
+ --origins http://127.0.0.1:3000 \
+ --network loopback \
+ --json
+```
+
+## CLI workflow
+
+Configured origins are used by default. `--allowed-origins` can request a narrower set that still fits the configured ceiling.
+
+```bash
+rea list-browser-targets http://127.0.0.1:9222 --approved --json
+rea inspect-web-page http://127.0.0.1:9222 TARGET_ID \
+ --approved \
+ --observation-ms 1000 \
+ --json
+```
+
+Script content and storage key names require separate opt-ins:
+
+```bash
+rea inspect-web-page http://127.0.0.1:9222 TARGET_ID \
+ --approved \
+ --include-script-sources \
+ --include-storage-keys \
+ --json
+```
+
+Script content may contain application secrets and becomes part of the returned Evidence. Storage values remain redacted even when key-name capture is approved.
+
+## MCP input
+
+```json
+{
+ "cdp_endpoint": "http://127.0.0.1:9222",
+ "allowed_origins": ["http://127.0.0.1:3000"],
+ "target_id": "TARGET_ID_FROM_LIST_BROWSER_TARGETS",
+ "approved": true,
+ "observation_ms": 500,
+ "include_script_sources": false,
+ "include_storage_keys": false
+}
+```
+
+Call `list_browser_targets` first because target IDs are browser-instance-specific. REA rechecks the selected target's current type and origin immediately before attaching.
+
+REA establishes an authorized main-frame boundary before enabling Runtime, Debugger, or Network observation, rechecks it before document capture, and validates it again afterward. If the main frame navigates during final capture, REA discards the mixed result and returns `target_changed`.
+
+## Data minimization
+
+REA removes sensitive values before normalized event data is retained:
+
+- URLs retain a bounded path and at most 256 bounded query parameter names, replace every retained query value with `[REDACTED]`, and remove credentials and fragments.
+- DOM snapshots retain node types, node names, value lengths, and attribute names, but not text or attribute values.
+- Network observations retain method, status, MIME type, size, type, and redacted URLs, but not request/response headers, bodies, post data, cookies, or response content.
+- Console observations with an approved stack source retain call type, argument types, timestamp, and redacted source location, but not argument values or descriptions. Events without a source URL are excluded because their origin cannot be established.
+- WebSocket observations retain direction, opcode, and payload byte length, but not payload content.
+- Storage observations always redact values. Key names, IndexedDB names, and cache names are omitted unless explicitly requested.
+- Script metadata is included only when CDP supplies a URL on an allowed origin. URL-less scripts are excluded because their origin cannot be established. Source content is omitted unless explicitly requested and remains subject to per-script and aggregate byte limits.
+
+Cross-origin frames, resources, scripts, events, and workers are excluded unless their exact origins are also approved. Excluded target details are counted without being exposed.
+
+## Completeness and limits
+
+The default observation window is 500 ms and the maximum is 10 seconds. Frames (200), DOM nodes (2,000), accessibility nodes (2,000), scripts (200), resources (2,000), workers (500), and each storage key/name inventory (1,000) have conservative defaults and caller-visible hard bounds. Script source bytes, network events, console events, and WebSocket events are bounded separately. The CLI exposes the same limits as kebab-case options such as `--max-frames` and `--max-storage-keys`.
+
+A bounded result reports `completeness.status: "truncated"`, named truncated sections, and dropped event counts rather than implying exhaustive capture. Disallowed-origin entries are filtered before collection-limit accounting, so they cannot consume an approved origin's output budget.
+
+CDP discovery, WebSocket connection, and each command have a 5-second timeout. Version discovery is capped at 64 KiB, target discovery at 2 MiB and 1,000 targets, each WebSocket message at 16 MiB, and correlated pending commands at 128. Malformed unsolicited protocol events poison the connection so later commands fail closed.
+
+Network and console coverage starts only after REA attaches and enables the relevant CDP domains. `prior_activity_available` is always `false`; absence from these arrays is not evidence that an event never occurred. Source maps are reported only as redacted declarative URLs and are never fetched.
+
+## Non-goals and threat model
+
+The first browser provider deliberately does not expose generic CDP commands, `Runtime.evaluate`, navigation, input, downloads, screenshots, page closure, or browser closure. REA disables the domains it enabled, detaches the target session, and closes only its own WebSocket.
+
+This feature is not a browser sandbox or network containment mechanism. The attached page and browser continue running with their existing privileges and may make external requests independently of REA. CDP gives deep access to the selected browser profile, so use a dedicated profile, approve only origins you intend to inspect, and treat other same-user processes as outside this boundary.
diff --git a/docs/error-contract.schema.json b/docs/error-contract.schema.json
index 4c31f236d..39d31b5af 100644
--- a/docs/error-contract.schema.json
+++ b/docs/error-contract.schema.json
@@ -460,6 +460,7 @@
"type": "array",
"items": { "type": "string" }
},
+ "origins": { "type": "array", "items": { "type": "string" } },
"network": {
"type": "string",
"enum": ["none", "loopback", "external"]
@@ -488,6 +489,7 @@
"type": "array",
"items": { "type": "string" }
},
+ "origins": { "type": "array", "items": { "type": "string" } },
"network": {
"type": "string",
"enum": ["none", "loopback", "external"]
@@ -511,6 +513,10 @@
"type": "array",
"items": { "type": "string" }
},
+ "origins": {
+ "type": "array",
+ "items": { "type": "string" }
+ },
"network": {
"type": "string",
"enum": ["none", "loopback", "external"]
diff --git a/docs/mcp-prompts.md b/docs/mcp-prompts.md
index 37bb615bd..ce9d44a78 100644
--- a/docs/mcp-prompts.md
+++ b/docs/mcp-prompts.md
@@ -1,7 +1,7 @@
# Guided MCP prompts and completion
REA exposes six provider-neutral investigation workflows through the MCP
-`prompts` capability. They complement the 68 tools; they do not add, remove, or
+`prompts` capability. They complement the 70 tools; they do not add, remove, or
invoke tools by themselves.
## Prompt inventory
diff --git a/package.json b/package.json
index b19c45c5b..d4a6310b3 100644
--- a/package.json
+++ b/package.json
@@ -70,6 +70,7 @@
"test:watch": "vitest",
"typecheck": "tsc --noEmit",
"verify:hopper": "npm run build && node scripts/verify-real-hopper.mjs",
+ "verify:browser": "npm run build && node scripts/verify-real-browser.mjs",
"verify:hopper:linux": "npm run build && node scripts/verify-real-hopper-linux.mjs",
"verify:setup:linux": "npm run build && node scripts/verify-linux-setup-e2e.mjs",
"build:fixtures": "node scripts/build-conformance-fixtures.mjs",
diff --git a/scripts/rea.mjs b/scripts/rea.mjs
index a9ba8206b..695fbc79f 100755
--- a/scripts/rea.mjs
+++ b/scripts/rea.mjs
@@ -1,7 +1,7 @@
#!/usr/bin/env node
// Route production MCP before importing Incur. Incur owns registration helpers
-// such as `mcp add`, while only dist/main.js may serve the 68-tool stdio server.
+// such as `mcp add`, while only dist/main.js may serve the 70-tool stdio server.
const args = process.argv.slice(2);
const { default: packageJson } = await import("../package.json", {
with: { type: "json" },
diff --git a/scripts/verify-package.mjs b/scripts/verify-package.mjs
index f5dc1fbbc..1f267ed9a 100644
--- a/scripts/verify-package.mjs
+++ b/scripts/verify-package.mjs
@@ -130,6 +130,8 @@ try {
!help.includes("extract-artifact") ||
!help.includes("investigate-versions") ||
!help.includes("import-reference-source") ||
+ !help.includes("list-browser-targets") ||
+ !help.includes("inspect-web-page") ||
!help.includes("compare") ||
!llms.includes("decompile") ||
!llms.includes("function") ||
@@ -140,6 +142,8 @@ try {
!llms.includes("capabilities") ||
!llms.includes("providers") ||
!llms.includes("inventory-artifact") ||
+ !llms.includes("list-browser-targets") ||
+ !llms.includes("inspect-web-page") ||
doctor.healthy !== expectedDoctorHealth ||
doctorExecution.status !== (expectedDoctorHealth ? 0 : 1) ||
doctor.checks?.find(({ name }) => name === "hopper")?.ok !== true
diff --git a/scripts/verify-published-package.mjs b/scripts/verify-published-package.mjs
index 316237969..7b6e0da78 100644
--- a/scripts/verify-published-package.mjs
+++ b/scripts/verify-published-package.mjs
@@ -22,7 +22,7 @@ transport.stderr?.on("data", (chunk) => {
try {
await client.connect(transport);
const tools = await client.listTools();
- if (tools.tools.length !== 68)
+ if (tools.tools.length !== 70)
throw new Error(
`Published MCP exposed ${String(tools.tools.length)} tools`,
);
@@ -40,5 +40,5 @@ try {
}
process.stdout.write(
- `${JSON.stringify({ package: "rea-agents", version, mcpTools: 68 })}\n`,
+ `${JSON.stringify({ package: "rea-agents", version, mcpTools: 70 })}\n`,
);
diff --git a/scripts/verify-real-browser.mjs b/scripts/verify-real-browser.mjs
new file mode 100644
index 000000000..835c2141c
--- /dev/null
+++ b/scripts/verify-real-browser.mjs
@@ -0,0 +1,286 @@
+#!/usr/bin/env node
+
+import { spawn } from "node:child_process";
+import { access, mkdtemp, readFile, rm } from "node:fs/promises";
+import { createServer } from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { WebSocketServer } from "ws";
+
+import { CdpBrowserProvider } from "../dist/browser/CdpBrowserProvider.js";
+import {
+ inspectWebPageInputSchema,
+ listBrowserTargetsInputSchema,
+} from "../dist/domain/browserObservation.js";
+
+const SECRET_VALUES = [
+ "network-secret-value",
+ "console-secret-value",
+ "storage-secret-value",
+ "websocket-secret-value",
+];
+
+const executable = await browserExecutable();
+const profile = await mkdtemp(join(tmpdir(), "rea-real-browser-"));
+const site = await startSite();
+let browser;
+try {
+ browser = spawn(
+ executable,
+ [
+ "--headless=new",
+ "--remote-debugging-address=127.0.0.1",
+ "--remote-debugging-port=0",
+ `--user-data-dir=${profile}`,
+ "--no-first-run",
+ "--no-default-browser-check",
+ "--disable-background-networking",
+ "--disable-component-update",
+ "--disable-sync",
+ "--metrics-recording-only",
+ `${site.origin}/app?startup=browser-secret-value`,
+ ],
+ { stdio: ["ignore", "ignore", "pipe"] },
+ );
+ let stderr = "";
+ browser.stderr.on("data", (chunk) => {
+ if (stderr.length < 64 * 1_024) stderr += chunk.toString("utf8");
+ });
+ const port = await devtoolsPort(profile, browser, () => stderr);
+ const endpoint = `http://127.0.0.1:${String(port)}`;
+ const provider = new CdpBrowserProvider();
+ const target = await pageTarget(provider, endpoint, site.origin);
+ const observed = await provider.inspectPage(
+ inspectWebPageInputSchema.parse({
+ cdp_endpoint: endpoint,
+ allowed_origins: [site.origin],
+ approved: true,
+ target_id: target,
+ observation_ms: 1_000,
+ include_storage_keys: true,
+ }),
+ );
+ if (!observed.ok) throw observed.error;
+ assertObservation(observed.value, site.origin);
+ const serialized = JSON.stringify(observed.value);
+ for (const secret of [...SECRET_VALUES, "browser-secret-value"])
+ if (serialized.includes(secret))
+ throw new Error(
+ `Passive browser result retained redacted value: ${secret}`,
+ );
+
+ const withSource = await provider.inspectPage(
+ inspectWebPageInputSchema.parse({
+ cdp_endpoint: endpoint,
+ allowed_origins: [site.origin],
+ approved: true,
+ target_id: target,
+ observation_ms: 200,
+ include_script_sources: true,
+ }),
+ );
+ if (!withSource.ok) throw withSource.error;
+ const source = withSource.value.scripts.items.find(
+ (script) =>
+ script.source.included &&
+ script.source.content.includes("reaSourceMarker"),
+ );
+ if (source === undefined)
+ throw new Error(
+ "Real Chrome did not return explicitly approved script source",
+ );
+
+ process.stdout.write(
+ `${JSON.stringify({
+ browser: observed.value.browser.product,
+ endpoint,
+ target,
+ domNodes: observed.value.dom.nodes.length,
+ accessibilityNodes: observed.value.accessibility.nodes.length,
+ scripts: observed.value.scripts.items.length,
+ networkRequests: observed.value.network.requests.length,
+ consoleEvents: observed.value.console.events.length,
+ websocketEvents: observed.value.network.websocket_events.length,
+ verified: true,
+ })}\n`,
+ );
+} finally {
+ if (browser !== undefined) await stopProcess(browser);
+ await site.close();
+ await rm(profile, { recursive: true, force: true });
+}
+
+async function browserExecutable() {
+ const candidates = [
+ process.env.REA_BROWSER_EXECUTABLE,
+ process.argv[2],
+ "/usr/bin/google-chrome-stable",
+ "/usr/bin/google-chrome",
+ "/usr/bin/chromium",
+ "/usr/bin/chromium-browser",
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
+ ].filter(
+ (candidate) => typeof candidate === "string" && candidate.length > 0,
+ );
+ for (const candidate of candidates) {
+ try {
+ await access(candidate);
+ return candidate;
+ } catch {
+ // Continue through explicit and platform-default candidates.
+ }
+ }
+ throw new Error(
+ "No Chrome-family executable found; set REA_BROWSER_EXECUTABLE to run real-browser verification",
+ );
+}
+
+async function devtoolsPort(profile, child, stderr) {
+ const activePort = join(profile, "DevToolsActivePort");
+ for (let attempt = 0; attempt < 200; attempt += 1) {
+ if (child.exitCode !== null)
+ throw new Error(`Chrome exited before CDP startup: ${stderr()}`);
+ try {
+ const [port] = (await readFile(activePort, "utf8")).trim().split("\n");
+ const parsed = Number(port);
+ if (Number.isSafeInteger(parsed) && parsed > 0) return parsed;
+ } catch {
+ // Chrome writes this file only after its CDP listener is ready.
+ }
+ await delay(25);
+ }
+ throw new Error(`Timed out waiting for Chrome CDP startup: ${stderr()}`);
+}
+
+async function pageTarget(provider, endpoint, origin) {
+ for (let attempt = 0; attempt < 100; attempt += 1) {
+ const listed = await provider.listTargets(
+ listBrowserTargetsInputSchema.parse({
+ cdp_endpoint: endpoint,
+ allowed_origins: [origin],
+ approved: true,
+ }),
+ );
+ if (listed.ok && listed.value.targets.items[0] !== undefined)
+ return listed.value.targets.items[0].target_id;
+ await delay(25);
+ }
+ throw new Error("Real Chrome did not expose the local test page target");
+}
+
+function assertObservation(result, origin) {
+ if (result.target.origin !== origin)
+ throw new Error("Real Chrome target origin was not preserved exactly");
+ if (result.frames.length < 1 || result.dom.nodes.length < 1)
+ throw new Error(
+ `Real Chrome DOM/frame observation was empty: ${JSON.stringify({ frames: result.frames.length, domTotal: result.dom.total_nodes, domReturned: result.dom.nodes.length, limitations: result.limitations })}`,
+ );
+ if (result.accessibility.nodes.length < 1)
+ throw new Error("Real Chrome accessibility observation was empty");
+ if (!result.scripts.items.some((script) => script.url.includes("/app.js")))
+ throw new Error("Real Chrome script metadata was missing");
+ if (!result.resources.some((resource) => resource.url.includes("/app.js")))
+ throw new Error("Real Chrome resource metadata was missing");
+ if (!result.network.requests.some((request) => request.url.includes("/api")))
+ throw new Error(
+ "Real Chrome attach-window network observation was missing",
+ );
+ if (result.console.events.length < 1)
+ throw new Error(
+ "Real Chrome attach-window console observation was missing",
+ );
+ if (result.network.websocket_events.length < 1)
+ throw new Error("Real Chrome WebSocket metadata was missing");
+ if (!result.storage.local_storage_keys.includes("rea-storage-key"))
+ throw new Error("Real Chrome local-storage key inventory was missing");
+ if (!result.storage.indexed_db_names.includes("rea-browser-db"))
+ throw new Error("Real Chrome IndexedDB name inventory was missing");
+ if (!result.storage.cache_names.includes("rea-browser-cache"))
+ throw new Error("Real Chrome cache name inventory was missing");
+}
+
+async function startSite() {
+ let port = 0;
+ const server = createServer((request, response) => {
+ if (request.url?.startsWith("/app.js") === true) {
+ response.setHeader("content-type", "text/javascript");
+ response.end(script(port));
+ return;
+ }
+ if (request.url?.startsWith("/api") === true) {
+ response.setHeader("content-type", "application/json");
+ response.end('{"ok":true,"secret":"response-secret-value"}');
+ return;
+ }
+ response.setHeader("content-type", "text/html");
+ response.end(
+ '
REA browser verifierBrowser evidence
',
+ );
+ });
+ const webSockets = new WebSocketServer({ noServer: true });
+ server.on("upgrade", (request, socket, head) => {
+ webSockets.handleUpgrade(request, socket, head, (webSocket) => {
+ webSocket.on("message", () =>
+ webSocket.send("websocket-response-secret"),
+ );
+ });
+ });
+ await new Promise((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", resolve);
+ });
+ const address = server.address();
+ if (address === null || typeof address === "string")
+ throw new Error("Local browser verifier did not bind a TCP port");
+ port = address.port;
+ return {
+ origin: `http://127.0.0.1:${String(port)}`,
+ async close() {
+ for (const client of webSockets.clients) client.terminate();
+ await new Promise((resolve) => webSockets.close(resolve));
+ await new Promise((resolve, reject) =>
+ server.close((error) =>
+ error === undefined ? resolve() : reject(error),
+ ),
+ );
+ },
+ };
+}
+
+function script(port) {
+ return `
+ export const reaSourceMarker = "approved-source-marker";
+ localStorage.setItem("rea-storage-key", "storage-secret-value");
+ indexedDB.open("rea-browser-db", 1);
+ caches.open("rea-browser-cache");
+ const observe = () => {
+ console.log("rea-browser-observation", "console-secret-value");
+ fetch("/api?token=network-secret-value", {
+ headers: { Authorization: "Bearer request-secret-value" }
+ });
+ const socket = new WebSocket("ws://127.0.0.1:${String(port)}/live?token=websocket-url-secret");
+ socket.addEventListener("open", () => socket.send("websocket-secret-value"));
+ socket.addEventListener("message", () => socket.close());
+ };
+ observe();
+ setInterval(observe, 150);
+`;
+}
+
+function delay(milliseconds) {
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
+}
+
+async function stopProcess(child) {
+ if (child.exitCode !== null) return;
+ child.kill("SIGTERM");
+ const exited = await Promise.race([
+ new Promise((resolve) => child.once("exit", () => resolve(true))),
+ delay(2_000).then(() => false),
+ ]);
+ if (!exited) {
+ child.kill("SIGKILL");
+ await new Promise((resolve) => child.once("exit", resolve));
+ }
+}
diff --git a/scripts/verify-real-hopper.mjs b/scripts/verify-real-hopper.mjs
index a173596e4..2914f11a3 100644
--- a/scripts/verify-real-hopper.mjs
+++ b/scripts/verify-real-hopper.mjs
@@ -300,7 +300,7 @@ try {
const expectedNames = TOOL_CONTRACTS.map(({ name }) => name).sort();
const actualNames = listed.tools.map(({ name }) => name).sort();
if (JSON.stringify(actualNames) !== JSON.stringify(expectedNames)) {
- throw new Error("The real server did not expose the intended 68 tools");
+ throw new Error("The real server did not expose the intended 70 tools");
}
const options = { timeout };
diff --git a/skills/rea-analysis/SKILL.md b/skills/rea-analysis/SKILL.md
index 3f59510f1..4902a925d 100644
--- a/skills/rea-analysis/SKILL.md
+++ b/skills/rea-analysis/SKILL.md
@@ -1,15 +1,30 @@
---
name: rea-analysis
-description: Reverse engineer apps with REA. Explore how features work, then build a version tailored to your project.
+description: Reverse engineer apps and websites with REA. Explore how features work, then build a version tailored to your project.
metadata:
- version: "12"
- tool_count: 68
+ version: "13"
+ tool_count: 70
---
# REA
Use REA when the user wants to understand how an app or feature works, compare app versions, decompile code, or build a similar feature.
+For a website already open in a user-owned Chrome-family browser, use
+`list_browser_targets` and `inspect_web_page` instead of opening a binary. Ask
+the user to approve the exact page origins and loopback CDP endpoint before the
+first call. Browser observation is disabled unless the operator configured
+`REA_BROWSER_OBSERVE_ENABLED`, `REA_BROWSER_CDP_ENDPOINTS_JSON`, and
+`REA_BROWSER_ALLOWED_ORIGINS_JSON` before starting REA.
+
+Browser inspection is passive. Never claim that it clicked, navigated,
+evaluated page JavaScript, captured prior activity, or contained the page's
+network. Query values, headers, bodies, cookies, storage values, console values,
+and WebSocket payloads are deliberately absent. Request script sources or
+storage key names only when the user separately approves those more sensitive
+outputs. Treat truncation and attach-window coverage as explicit limitations,
+and cite the returned Evidence v2 IDs.
+
## Understand the request
Identify the app and what the user wants to understand or build. Do not ask for information they already provided.
diff --git a/src/application/BrowserEvidence.ts b/src/application/BrowserEvidence.ts
new file mode 100644
index 000000000..edba27982
--- /dev/null
+++ b/src/application/BrowserEvidence.ts
@@ -0,0 +1,61 @@
+import type { ProviderIdentity } from "./AnalysisProvider.js";
+import {
+ createEvidence,
+ type Evidence,
+ type EvidenceObservation,
+} from "../domain/evidence.js";
+import { jsonValueSchema } from "../domain/jsonValue.js";
+import type {
+ BrowserTargetList,
+ InspectWebPageInput,
+ ListBrowserTargetsInput,
+ WebPageInspection,
+} from "../domain/browserObservation.js";
+
+type BrowserEvidenceInput = ListBrowserTargetsInput | InspectWebPageInput;
+type BrowserEvidenceResult = BrowserTargetList | WebPageInspection;
+
+/** Create Evidence v2 for a policy-scoped external browser observation. */
+export const createBrowserEvidence = (
+ operation: "list_browser_targets" | "inspect_web_page",
+ input: BrowserEvidenceInput,
+ result: BrowserEvidenceResult,
+ provider: ProviderIdentity,
+): Evidence =>
+ createEvidence(undefined, provider, {
+ predicateType:
+ operation === "list_browser_targets"
+ ? "rea.browser-target-list/v1"
+ : "rea.web-page-inspection/v1",
+ operation,
+ parameters: browserParameters(input),
+ result: jsonValueSchema.parse(result),
+ confidence: "observed",
+ authority: "external-service",
+ environment:
+ "target" in result
+ ? {
+ id: `${result.browser.product}@${result.browser.revision}`,
+ platform: process.platform,
+ architecture: process.arch,
+ isolation: "none",
+ }
+ : null,
+ limitations: result.limitations,
+ });
+
+const browserParameters = (
+ input: BrowserEvidenceInput,
+): EvidenceObservation["parameters"] => ({
+ cdp_endpoint: input.cdp_endpoint,
+ allowed_origins: input.allowed_origins,
+ ...("target_id" in input
+ ? {
+ target_id: input.target_id,
+ observation_ms: input.observation_ms,
+ include_script_sources: input.include_script_sources,
+ include_storage_keys: input.include_storage_keys,
+ limits: input.limits,
+ }
+ : { offset: input.offset, limit: input.limit }),
+});
diff --git a/src/application/BrowserObservationPort.ts b/src/application/BrowserObservationPort.ts
new file mode 100644
index 000000000..f9e3cb45a
--- /dev/null
+++ b/src/application/BrowserObservationPort.ts
@@ -0,0 +1,23 @@
+import type { AnalysisError } from "../domain/errors.js";
+import type {
+ BrowserTargetList,
+ InspectWebPageInput,
+ ListBrowserTargetsInput,
+ WebPageInspection,
+} from "../domain/browserObservation.js";
+import type { Result } from "../domain/result.js";
+import type { ProviderIdentity } from "./AnalysisProvider.js";
+import type { ExecutionOptions } from "./AnalysisProvider.js";
+
+/** Provider-neutral application boundary for passive browser observation. */
+export interface BrowserObservationPort {
+ identity(): ProviderIdentity;
+ listTargets(
+ input: ListBrowserTargetsInput,
+ options?: ExecutionOptions,
+ ): Promise>;
+ inspectPage(
+ input: InspectWebPageInput,
+ options?: ExecutionOptions,
+ ): Promise>;
+}
diff --git a/src/application/BrowserObservationService.ts b/src/application/BrowserObservationService.ts
new file mode 100644
index 000000000..859a33168
--- /dev/null
+++ b/src/application/BrowserObservationService.ts
@@ -0,0 +1,126 @@
+import type { Evidence } from "../domain/evidence.js";
+import type {
+ InspectWebPageInput,
+ ListBrowserTargetsInput,
+} from "../domain/browserObservation.js";
+import {
+ AnalysisCapabilityUnavailableError,
+ AnalysisProtocolError,
+ PermissionRequiredError,
+ type AnalysisError,
+} from "../domain/errors.js";
+import { err, ok, type Result } from "../domain/result.js";
+import type { ExecutionOptions } from "./AnalysisProvider.js";
+import type { BrowserObservationPort } from "./BrowserObservationPort.js";
+import type { PermissionAuthority } from "./PermissionAuthority.js";
+import { createBrowserEvidence } from "./BrowserEvidence.js";
+
+type ScopedBrowserInput = Pick<
+ ListBrowserTargetsInput,
+ "cdp_endpoint" | "allowed_origins"
+> & { readonly target_id?: string };
+
+/** Authorize and execute one policy-scoped target discovery observation. */
+export const listBrowserTargets = async (
+ browser: BrowserObservationPort | undefined,
+ authority: PermissionAuthority | undefined,
+ input: ListBrowserTargetsInput,
+ options: ExecutionOptions = {},
+): Promise> => {
+ const ready = await prepare(
+ browser,
+ authority,
+ input,
+ "list_browser_targets",
+ );
+ if (!ready.ok) return ready;
+ const result = await ready.value.listTargets(input, options);
+ return result.ok
+ ? ok(
+ createBrowserEvidence(
+ "list_browser_targets",
+ input,
+ result.value,
+ ready.value.identity(),
+ ),
+ )
+ : result;
+};
+
+/** Authorize and execute one policy-scoped passive page inspection. */
+export const inspectWebPage = async (
+ browser: BrowserObservationPort | undefined,
+ authority: PermissionAuthority | undefined,
+ input: InspectWebPageInput,
+ options: ExecutionOptions = {},
+): Promise> => {
+ const ready = await prepare(browser, authority, input, "inspect_web_page");
+ if (!ready.ok) return ready;
+ const result = await ready.value.inspectPage(input, options);
+ return result.ok
+ ? ok(
+ createBrowserEvidence(
+ "inspect_web_page",
+ input,
+ result.value,
+ ready.value.identity(),
+ ),
+ )
+ : result;
+};
+
+const prepare = async (
+ browser: BrowserObservationPort | undefined,
+ authority: PermissionAuthority | undefined,
+ input: ScopedBrowserInput,
+ operation: "list_browser_targets" | "inspect_web_page",
+): Promise> => {
+ if (authority === undefined)
+ return err(
+ new AnalysisCapabilityUnavailableError(
+ "rea-cdp-browser",
+ operation,
+ "browser observation permission policy is not configured",
+ ),
+ );
+ const authorized = await authority.authorize(
+ {
+ capability: "browser_observe",
+ roots: [],
+ executables: [],
+ environment_names: [],
+ origins: [input.cdp_endpoint, ...input.allowed_origins],
+ network: browserNetworkScope(input.allowed_origins),
+ mount: false,
+ operation_identity: `${operation}:${input.target_id ?? input.cdp_endpoint}`,
+ },
+ "read",
+ );
+ if (!authorized.ok)
+ return err(
+ authorized.error instanceof PermissionRequiredError
+ ? authorized.error
+ : new AnalysisProtocolError(authorized.error.message, {
+ cause: authorized.error,
+ }),
+ );
+ return browser === undefined
+ ? err(
+ new AnalysisCapabilityUnavailableError(
+ "rea-cdp-browser",
+ operation,
+ "browser observation provider is not configured",
+ ),
+ )
+ : ok(browser);
+};
+
+const browserNetworkScope = (
+ allowedOrigins: readonly string[],
+): "loopback" | "external" =>
+ allowedOrigins.every((origin) => {
+ const hostname = new URL(origin).hostname;
+ return hostname === "127.0.0.1" || hostname === "[::1]";
+ })
+ ? "loopback"
+ : "external";
diff --git a/src/application/CapabilityInventory.ts b/src/application/CapabilityInventory.ts
index 46bdbab0b..95e637665 100644
--- a/src/application/CapabilityInventory.ts
+++ b/src/application/CapabilityInventory.ts
@@ -54,6 +54,7 @@ export const buildCapabilityInventory = (
policy: {
readonly processCaptureEnabled: boolean;
readonly evidenceFileRoots: number;
+ readonly browserObservationEnabled?: boolean;
},
) => {
const status = statusSchema.parse(sessionStatus);
@@ -97,6 +98,7 @@ const availabilityFor = (
policy: {
readonly processCaptureEnabled: boolean;
readonly evidenceFileRoots: number;
+ readonly browserObservationEnabled?: boolean;
},
): {
readonly reason: ToolAvailabilityReason;
@@ -113,6 +115,14 @@ const availabilityFor = (
reason: "policy_disabled",
remediation: "Configure or grant an evidence_read root.",
};
+ if (kind === "browser-provider")
+ return policy.browserObservationEnabled === true
+ ? { reason: "available", remediation: null }
+ : {
+ reason: "policy_disabled",
+ remediation:
+ "Enable browser observation and configure exact CDP endpoint and page origins.",
+ };
if (kind === "session") return { reason: "available", remediation: null };
if (!targetOpen)
return {
diff --git a/src/application/ProjectPermissionStore.ts b/src/application/ProjectPermissionStore.ts
index bfed9ad89..91029236a 100644
--- a/src/application/ProjectPermissionStore.ts
+++ b/src/application/ProjectPermissionStore.ts
@@ -12,6 +12,7 @@ const grantSchema = z.object({
grant_id: z.string().min(1),
capability: z.enum([
"process_capture",
+ "browser_observe",
"evidence_read",
"evidence_write",
"investigation_input",
@@ -26,6 +27,7 @@ const grantSchema = z.object({
roots: z.array(z.string()),
executables: z.array(z.string()),
environment_names: z.array(z.string()),
+ origins: z.array(z.string()).optional(),
network: z.enum(["none", "loopback", "external"]),
mount: z.boolean(),
lifetime: z.literal("project"),
diff --git a/src/browser/CdpBrowserProvider.ts b/src/browser/CdpBrowserProvider.ts
new file mode 100644
index 000000000..67914d98b
--- /dev/null
+++ b/src/browser/CdpBrowserProvider.ts
@@ -0,0 +1,229 @@
+import type { BrowserObservationPort } from "../application/BrowserObservationPort.js";
+import type { ProviderIdentity } from "../application/AnalysisProvider.js";
+import type { ExecutionOptions } from "../application/AnalysisProvider.js";
+import {
+ browserTargetListSchema,
+ sanitizeBrowserUrl,
+ webPageInspectionSchema,
+ type BrowserTargetList,
+ type InspectWebPageInput,
+ type ListBrowserTargetsInput,
+ type WebPageInspection,
+} from "../domain/browserObservation.js";
+import {
+ AnalysisError,
+ BrowserObservationError,
+ ProviderAdapterError,
+} from "../domain/errors.js";
+import { err, ok, type Result } from "../domain/result.js";
+import { CdpConnection } from "./CdpConnection.js";
+import {
+ discoverCdpEndpoint,
+ type CdpEndpointDiscovery,
+ type CdpEndpointTarget,
+} from "./CdpEndpoint.js";
+import { capturePage } from "./CdpPageCapture.js";
+
+const IDENTITY: ProviderIdentity = {
+ id: "rea-cdp-browser",
+ name: "REA Chrome DevTools Protocol observation provider",
+ version: "1",
+};
+
+/** Passive, origin-scoped browser observation through a user-owned CDP endpoint. */
+export class CdpBrowserProvider implements BrowserObservationPort {
+ identity(): ProviderIdentity {
+ return IDENTITY;
+ }
+
+ async listTargets(
+ input: ListBrowserTargetsInput,
+ options: ExecutionOptions = {},
+ ): Promise> {
+ try {
+ const discovery = await discoverCdpEndpoint(
+ input.cdp_endpoint,
+ "list_browser_targets",
+ options.signal,
+ );
+ const allowedOrigins = new Set(input.allowed_origins);
+ const selected = selectTargets(discovery, allowedOrigins);
+ const items = selected.allowed.slice(
+ input.offset,
+ input.offset + input.limit,
+ );
+ const nextOffset = input.offset + items.length;
+ return ok(
+ browserTargetListSchema.parse({
+ schema_version: 1,
+ browser: discovery.version,
+ targets: {
+ items,
+ offset: input.offset,
+ limit: input.limit,
+ total: selected.allowed.length,
+ next_offset:
+ nextOffset < selected.allowed.length ? nextOffset : null,
+ has_more: nextOffset < selected.allowed.length,
+ },
+ excluded: selected.excluded,
+ limitations: [
+ "Only page targets whose current URL matches an approved exact origin are listed.",
+ ],
+ }),
+ );
+ } catch (cause: unknown) {
+ return err(providerError(cause, "list_browser_targets"));
+ }
+ }
+
+ async inspectPage(
+ input: InspectWebPageInput,
+ options: ExecutionOptions = {},
+ ): Promise> {
+ let connection: CdpConnection | undefined;
+ let sessionId: string | undefined;
+ try {
+ const discovery = await discoverCdpEndpoint(
+ input.cdp_endpoint,
+ "inspect_web_page",
+ options.signal,
+ );
+ const target = authorizeTarget(discovery, input);
+ connection = await CdpConnection.connect(
+ discovery.browserWebSocketUrl,
+ options.signal,
+ );
+ const attached = await connection.send(
+ "Target.attachToTarget",
+ { targetId: target.id, flatten: true },
+ undefined,
+ options.signal,
+ );
+ sessionId = attachedSessionId(attached);
+ const result = await capturePage({
+ connection,
+ sessionId,
+ discovery,
+ target,
+ input,
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
+ ...(options.progress === undefined
+ ? {}
+ : { progress: options.progress }),
+ });
+ return ok(webPageInspectionSchema.parse(result));
+ } catch (cause: unknown) {
+ return err(providerError(cause, "inspect_web_page"));
+ } finally {
+ if (connection !== undefined) {
+ if (sessionId !== undefined)
+ await bestEffortCleanup(connection, sessionId);
+ await connection.close();
+ }
+ }
+ }
+}
+
+const selectTargets = (
+ discovery: CdpEndpointDiscovery,
+ allowedOrigins: ReadonlySet,
+): {
+ readonly allowed: readonly BrowserTargetList["targets"]["items"][number][];
+ readonly excluded: BrowserTargetList["excluded"];
+} => {
+ const allowed = [];
+ let disallowedOrigin = 0;
+ let unsupportedUrl = 0;
+ let nonPage = 0;
+ for (const target of discovery.targets) {
+ if (target.type !== "page") {
+ nonPage += 1;
+ continue;
+ }
+ const url = sanitizeBrowserUrl(target.url);
+ if (url.origin === null) {
+ unsupportedUrl += 1;
+ continue;
+ }
+ if (!allowedOrigins.has(url.origin)) {
+ disallowedOrigin += 1;
+ continue;
+ }
+ allowed.push({
+ target_id: target.id,
+ type: target.type,
+ title: target.title.slice(0, 16_384),
+ url: url.url,
+ origin: url.origin,
+ attached: target.attached,
+ });
+ }
+ allowed.sort((left, right) => left.target_id.localeCompare(right.target_id));
+ return {
+ allowed,
+ excluded: {
+ disallowed_origin: disallowedOrigin,
+ unsupported_url: unsupportedUrl,
+ non_page: nonPage,
+ },
+ };
+};
+
+const authorizeTarget = (
+ discovery: CdpEndpointDiscovery,
+ input: InspectWebPageInput,
+): CdpEndpointTarget => {
+ const target = discovery.targets.find(
+ (candidate) => candidate.id === input.target_id,
+ );
+ if (target === undefined)
+ throw new BrowserObservationError("inspect_web_page", "target_not_found");
+ const origin = sanitizeBrowserUrl(target.url).origin;
+ if (
+ target.type !== "page" ||
+ origin === null ||
+ !input.allowed_origins.includes(origin)
+ )
+ throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
+ return target;
+};
+
+const attachedSessionId = (value: unknown): string => {
+ if (typeof value !== "object" || value === null || !("sessionId" in value))
+ throw new BrowserObservationError("inspect_web_page", "protocol_error");
+ if (typeof value.sessionId !== "string" || value.sessionId.length > 256)
+ throw new BrowserObservationError("inspect_web_page", "protocol_error");
+ return value.sessionId;
+};
+
+const bestEffortCleanup = async (
+ connection: CdpConnection,
+ sessionId: string,
+): Promise => {
+ for (const method of [
+ "Network.disable",
+ "Debugger.disable",
+ "Runtime.disable",
+ "Page.disable",
+ ]) {
+ try {
+ await connection.send(method, {}, sessionId);
+ } catch {
+ // Cleanup continues so detach is still attempted.
+ }
+ }
+ try {
+ await connection.send("Target.detachFromTarget", { sessionId });
+ } catch {
+ // Closing REA's socket is the final non-destructive cleanup boundary.
+ }
+};
+
+const providerError = (
+ cause: unknown,
+ operation: "list_browser_targets" | "inspect_web_page",
+): AnalysisError =>
+ cause instanceof AnalysisError
+ ? cause
+ : new ProviderAdapterError(IDENTITY.id, operation, { cause });
diff --git a/src/browser/CdpCaptureDocuments.ts b/src/browser/CdpCaptureDocuments.ts
new file mode 100644
index 000000000..b716dbf17
--- /dev/null
+++ b/src/browser/CdpCaptureDocuments.ts
@@ -0,0 +1,198 @@
+import type {
+ InspectWebPageInput,
+ WebPageInspection,
+} from "../domain/browserObservation.js";
+import {
+ allowedSanitizedUrl,
+ boundedText,
+ numberValue,
+ recordValue,
+ recordsValue,
+ requiredRecord,
+ stringValue,
+ type UnknownRecord,
+} from "./CdpCaptureValues.js";
+
+/** Normalize allowed frames while retaining a bounded prefix and total count. */
+export const captureFrames = (
+ result: unknown,
+ allowedOrigins: ReadonlySet,
+ maximum: number,
+): {
+ readonly total: number;
+ readonly items: WebPageInspection["frames"];
+} => {
+ const root = recordValue(requiredRecord(result).frameTree);
+ if (root === undefined) return { total: 0, items: [] };
+ const items: WebPageInspection["frames"] = [];
+ let total = 0;
+ for (const tree of walkFrameTrees(root)) {
+ const frame = recordValue(tree.frame);
+ const frameId = stringValue(frame?.id);
+ const sanitized = allowedSanitizedUrl(frame?.url, allowedOrigins);
+ if (
+ frame === undefined ||
+ frameId === undefined ||
+ frameId.length > 256 ||
+ sanitized === undefined ||
+ sanitized.origin === null
+ )
+ continue;
+ total += 1;
+ if (items.length >= maximum) continue;
+ items.push({
+ frame_id: frameId,
+ parent_frame_id:
+ (stringValue(frame.parentId) ?? "").slice(0, 256) || null,
+ url: sanitized.url,
+ origin: sanitized.origin,
+ });
+ }
+ return { total, items };
+};
+
+/** Read the current main-frame URL from an untrusted Page.getFrameTree result. */
+export const mainFrameUrl = (result: unknown): string | undefined =>
+ stringValue(
+ recordValue(recordValue(requiredRecord(result).frameTree)?.frame)?.url,
+ );
+
+/** Normalize allowed resources while retaining a bounded prefix and total count. */
+export const captureResources = (
+ result: unknown,
+ allowedOrigins: ReadonlySet,
+ maximum: number,
+): {
+ readonly total: number;
+ readonly items: WebPageInspection["resources"];
+} => {
+ const root = recordValue(requiredRecord(result).frameTree);
+ if (root === undefined) return { total: 0, items: [] };
+ const items: WebPageInspection["resources"] = [];
+ let total = 0;
+ for (const tree of walkFrameTrees(root)) {
+ for (const resource of recordsValue(tree.resources)) {
+ const url = allowedSanitizedUrl(resource.url, allowedOrigins);
+ if (url === undefined || url.origin === null) continue;
+ total += 1;
+ if (items.length >= maximum) continue;
+ const contentSize = numberValue(resource.contentSize);
+ items.push({
+ url: url.url,
+ origin: url.origin,
+ type: (stringValue(resource.type) ?? "Other").slice(0, 100),
+ mime_type: (stringValue(resource.mimeType) ?? "").slice(0, 256),
+ content_size:
+ contentSize === undefined ? null : Math.max(0, contentSize),
+ });
+ }
+ }
+ return { total, items };
+};
+
+const walkFrameTrees = function* (
+ root: UnknownRecord,
+): Generator {
+ const pending = [root];
+ while (pending.length > 0) {
+ const tree = pending.pop();
+ if (tree === undefined) return;
+ const children = recordsValue(tree.childFrames);
+ for (let index = children.length - 1; index >= 0; index -= 1) {
+ const child = children[index];
+ if (child !== undefined) pending.push(child);
+ }
+ yield tree;
+ }
+};
+
+export const captureDom = (
+ result: unknown,
+ allowedOrigins: ReadonlySet,
+ input: InspectWebPageInput,
+): {
+ readonly total: number;
+ readonly nodes: WebPageInspection["dom"]["nodes"];
+} => {
+ const root = requiredRecord(result);
+ const strings = Array.isArray(root.strings)
+ ? root.strings.map((value) => stringValue(value) ?? "")
+ : [];
+ const nodes: WebPageInspection["dom"]["nodes"] = [];
+ let total = 0;
+ for (const document of recordsValue(root.documents)) {
+ const documentUrl = indexedString(strings, document.documentURL);
+ if (allowedSanitizedUrl(documentUrl, allowedOrigins) === undefined)
+ continue;
+ const documentNodes = recordValue(document.nodes);
+ if (documentNodes === undefined) continue;
+ const nodeTypes = numberArray(documentNodes.nodeType);
+ const nodeNames = numberArray(documentNodes.nodeName);
+ const nodeValues = numberArray(documentNodes.nodeValue);
+ const parents = numberArray(documentNodes.parentIndex);
+ const attributes = Array.isArray(documentNodes.attributes)
+ ? documentNodes.attributes
+ : [];
+ const baseIndex = nodes.length;
+ total += nodeTypes.length;
+ for (
+ let index = 0;
+ index < nodeTypes.length && nodes.length < input.limits.max_dom_nodes;
+ index += 1
+ ) {
+ const attributeIndexes = numberArray(attributes[index]);
+ const parent = Math.trunc(parents[index] ?? -1);
+ nodes.push({
+ index: nodes.length,
+ parent_index: parent < 0 ? -1 : baseIndex + parent,
+ node_type: Math.max(0, Math.trunc(nodeTypes[index] ?? 0)),
+ node_name: indexedString(strings, nodeNames[index]).slice(0, 256),
+ node_value_length: indexedString(strings, nodeValues[index]).length,
+ attribute_names: attributeIndexes
+ .filter((_value, attributeIndex) => attributeIndex % 2 === 0)
+ .map((value) => indexedString(strings, value).slice(0, 256))
+ .slice(0, 200),
+ });
+ }
+ }
+ return { total, nodes };
+};
+
+export const captureAccessibility = (
+ results: readonly unknown[],
+ maximum: number,
+): {
+ readonly total: number;
+ readonly nodes: WebPageInspection["accessibility"]["nodes"];
+} => {
+ const all = results.flatMap((result) =>
+ recordsValue(requiredRecord(result).nodes),
+ );
+ return {
+ total: all.length,
+ nodes: all.slice(0, maximum).map((node) => ({
+ node_id: (stringValue(node.nodeId) ?? "").slice(0, 256),
+ parent_id: (stringValue(node.parentId) ?? "").slice(0, 256) || null,
+ role: axText(node.role),
+ name: axText(node.name),
+ description: axText(node.description),
+ ignored: node.ignored === true,
+ })),
+ };
+};
+
+const axText = (value: unknown): string | null =>
+ boundedText(recordValue(value)?.value, 1_024);
+
+const indexedString = (strings: readonly string[], index: unknown): string => {
+ const integer = numberValue(index);
+ return integer === undefined ? "" : (strings[Math.trunc(integer)] ?? "");
+};
+
+const numberArray = (value: unknown): readonly number[] =>
+ Array.isArray(value)
+ ? value.flatMap((item) => {
+ const number = numberValue(item);
+ return number === undefined ? [] : [number];
+ })
+ : [];
diff --git a/src/browser/CdpCaptureEvents.ts b/src/browser/CdpCaptureEvents.ts
new file mode 100644
index 000000000..83da575d8
--- /dev/null
+++ b/src/browser/CdpCaptureEvents.ts
@@ -0,0 +1,300 @@
+import type {
+ InspectWebPageInput,
+ WebPageInspection,
+} from "../domain/browserObservation.js";
+import type { CdpEvent } from "./CdpConnection.js";
+import {
+ allowedSanitizedUrl,
+ boundedText,
+ isHttpUrl,
+ numberValue,
+ recordValue,
+ recordsValue,
+ stringValue,
+ type UnknownRecord,
+} from "./CdpCaptureValues.js";
+
+export interface CapturedScript {
+ readonly scriptId: string;
+ readonly url: string;
+ readonly origin: string | null;
+ readonly hash: string;
+ readonly length: number;
+ readonly isModule: boolean;
+ readonly language: string | null;
+ readonly sourceMapUrl: string | null;
+}
+
+type NetworkState = WebPageInspection["network"]["requests"][number];
+
+/** Bounded event accumulator that drops payload values at ingestion time. */
+export class CdpCaptureEvents {
+ readonly scripts = new Map();
+ readonly network = new Map();
+ readonly allowedWebSockets = new Set();
+ readonly console: WebPageInspection["console"]["events"] = [];
+ readonly websockets: WebPageInspection["network"]["websocket_events"] = [];
+ dropped = 0;
+ originViolation = false;
+ navigationDuringCapture = false;
+ #mainFrameId: string | undefined;
+
+ constructor(
+ private readonly input: InspectWebPageInput,
+ private readonly allowedOrigins: ReadonlySet,
+ ) {}
+
+ beginAuthorizedFrame(frameId: string): void {
+ this.#mainFrameId = frameId;
+ this.originViolation = false;
+ this.navigationDuringCapture = false;
+ this.dropped = 0;
+ this.scripts.clear();
+ this.network.clear();
+ this.allowedWebSockets.clear();
+ this.console.length = 0;
+ this.websockets.length = 0;
+ }
+
+ beginFinalCapture(frameId: string): void {
+ this.#mainFrameId = frameId;
+ this.navigationDuringCapture = false;
+ }
+
+ ingest(event: CdpEvent): void {
+ const params = recordValue(event.params);
+ if (params === undefined) return;
+ switch (event.method) {
+ case "Debugger.scriptParsed":
+ this.#script(params);
+ break;
+ case "Network.requestWillBeSent":
+ this.#request(params);
+ break;
+ case "Network.responseReceived":
+ this.#response(params);
+ break;
+ case "Network.loadingFinished":
+ this.#finished(params);
+ break;
+ case "Runtime.consoleAPICalled":
+ this.#console(params);
+ break;
+ case "Page.frameNavigated":
+ this.#frameNavigated(params);
+ break;
+ case "Network.webSocketCreated":
+ this.#websocketCreated(params);
+ break;
+ case "Network.webSocketFrameSent":
+ this.#websocket(params, "sent");
+ break;
+ case "Network.webSocketFrameReceived":
+ this.#websocket(params, "received");
+ break;
+ }
+ }
+
+ #script(params: UnknownRecord): void {
+ const scriptId = stringValue(params.scriptId);
+ const rawUrl = stringValue(params.url) ?? "";
+ const sanitized = allowedSanitizedUrl(rawUrl, this.allowedOrigins);
+ if (
+ scriptId === undefined ||
+ scriptId.length > 256 ||
+ sanitized === undefined
+ )
+ return;
+ if (
+ this.scripts.size >= this.input.limits.max_scripts &&
+ !this.scripts.has(scriptId)
+ ) {
+ this.dropped += 1;
+ return;
+ }
+ this.scripts.set(scriptId, {
+ scriptId,
+ url: sanitized.url,
+ origin: sanitized.origin,
+ hash: (stringValue(params.hash) ?? "").slice(0, 512),
+ length: Math.max(
+ 0,
+ Math.min(
+ Number.MAX_SAFE_INTEGER,
+ Math.trunc(numberValue(params.length) ?? 0),
+ ),
+ ),
+ isModule: params.isModule === true,
+ language: boundedText(params.scriptLanguage, 100),
+ sourceMapUrl: this.#sourceMap(params.sourceMapURL),
+ });
+ }
+
+ #sourceMap(value: unknown): string | null {
+ const sanitized = allowedSanitizedUrl(value, this.allowedOrigins);
+ return sanitized?.url ?? null;
+ }
+
+ #request(params: UnknownRecord): void {
+ const requestId = stringValue(params.requestId);
+ const request = recordValue(params.request);
+ const sanitized = allowedSanitizedUrl(request?.url, this.allowedOrigins);
+ if (
+ requestId === undefined ||
+ requestId.length > 256 ||
+ request === undefined ||
+ sanitized === undefined
+ )
+ return;
+ if (
+ this.network.size >= this.input.limits.max_network_events &&
+ !this.network.has(requestId)
+ ) {
+ this.dropped += 1;
+ return;
+ }
+ const initiator = recordValue(params.initiator);
+ const initiatorUrl = allowedSanitizedUrl(
+ firstCallFrame(initiator)?.url,
+ this.allowedOrigins,
+ );
+ this.network.set(requestId, {
+ request_id: requestId,
+ url: sanitized.url,
+ origin: sanitized.origin ?? "",
+ method: (stringValue(request.method) ?? "GET").slice(0, 32),
+ resource_type: boundedText(params.type, 100),
+ status: null,
+ mime_type: null,
+ encoded_data_length: null,
+ initiator: {
+ type: (stringValue(initiator?.type) ?? "other").slice(0, 100),
+ url: initiatorUrl?.url ?? null,
+ line: integerOrNull(firstCallFrame(initiator)?.lineNumber),
+ column: integerOrNull(firstCallFrame(initiator)?.columnNumber),
+ },
+ });
+ }
+
+ #response(params: UnknownRecord): void {
+ const requestId = stringValue(params.requestId);
+ if (requestId === undefined || requestId.length > 256) return;
+ const current = this.network.get(requestId);
+ const response = recordValue(params.response);
+ if (current === undefined || response === undefined) return;
+ this.network.set(requestId, {
+ ...current,
+ status: numberValue(response.status) ?? null,
+ mime_type: boundedText(response.mimeType, 256),
+ });
+ }
+
+ #finished(params: UnknownRecord): void {
+ const requestId = stringValue(params.requestId);
+ if (requestId === undefined || requestId.length > 256) return;
+ const current = this.network.get(requestId);
+ if (current === undefined) return;
+ this.network.set(requestId, {
+ ...current,
+ encoded_data_length: Math.max(
+ 0,
+ numberValue(params.encodedDataLength) ?? 0,
+ ),
+ });
+ }
+
+ #console(params: UnknownRecord): void {
+ const frame = firstCallFrame(recordValue(params.stackTrace));
+ const source = allowedSanitizedUrl(frame?.url, this.allowedOrigins);
+ if (frame === undefined || source === undefined) return;
+ if (this.console.length >= this.input.limits.max_console_events) {
+ this.dropped += 1;
+ return;
+ }
+ this.console.push({
+ type: (stringValue(params.type) ?? "unknown").slice(0, 100),
+ timestamp: numberValue(params.timestamp) ?? 0,
+ argument_types: recordsValue(params.args)
+ .map((argument) =>
+ (stringValue(argument.type) ?? "unknown").slice(0, 100),
+ )
+ .slice(0, 100),
+ url: source?.url ?? null,
+ line: integerOrNull(frame?.lineNumber),
+ column: integerOrNull(frame?.columnNumber),
+ });
+ }
+
+ #websocket(params: UnknownRecord, direction: "sent" | "received"): void {
+ const requestId = stringValue(params.requestId);
+ if (
+ requestId === undefined ||
+ requestId.length > 256 ||
+ (!this.network.has(requestId) && !this.allowedWebSockets.has(requestId))
+ )
+ return;
+ if (this.websockets.length >= this.input.limits.max_websocket_events) {
+ this.dropped += 1;
+ return;
+ }
+ const response = recordValue(params.response);
+ const payload = stringValue(response?.payloadData) ?? "";
+ this.websockets.push({
+ request_id: requestId,
+ direction,
+ opcode: Math.max(0, Math.trunc(numberValue(response?.opcode) ?? 0)),
+ payload_bytes: Buffer.byteLength(payload),
+ });
+ }
+
+ #websocketCreated(params: UnknownRecord): void {
+ const requestId = stringValue(params.requestId);
+ const rawUrl = stringValue(params.url);
+ if (
+ requestId === undefined ||
+ requestId.length > 256 ||
+ rawUrl === undefined
+ )
+ return;
+ let parsed: URL;
+ try {
+ parsed = new URL(rawUrl);
+ } catch {
+ return;
+ }
+ if (parsed.protocol === "ws:") parsed.protocol = "http:";
+ else if (parsed.protocol === "wss:") parsed.protocol = "https:";
+ else return;
+ if (
+ this.allowedOrigins.has(parsed.origin) &&
+ (this.allowedWebSockets.has(requestId) ||
+ this.allowedWebSockets.size < this.input.limits.max_websocket_events)
+ )
+ this.allowedWebSockets.add(requestId);
+ else if (this.allowedOrigins.has(parsed.origin)) this.dropped += 1;
+ }
+
+ #frameNavigated(params: UnknownRecord): void {
+ const frame = recordValue(params.frame);
+ if (stringValue(frame?.id) !== this.#mainFrameId) return;
+ this.navigationDuringCapture = true;
+ const rawUrl = stringValue(frame?.url);
+ if (
+ isHttpUrl(rawUrl) &&
+ allowedSanitizedUrl(rawUrl, this.allowedOrigins) === undefined
+ )
+ this.originViolation = true;
+ }
+}
+
+const firstCallFrame = (
+ value: UnknownRecord | undefined,
+): UnknownRecord | undefined => {
+ const callFrames = recordsValue(value?.callFrames);
+ return callFrames[0];
+};
+
+const integerOrNull = (value: unknown): number | null => {
+ const number = numberValue(value);
+ return number === undefined ? null : Math.max(0, Math.trunc(number));
+};
diff --git a/src/browser/CdpCaptureStorage.ts b/src/browser/CdpCaptureStorage.ts
new file mode 100644
index 000000000..21f6b32f5
--- /dev/null
+++ b/src/browser/CdpCaptureStorage.ts
@@ -0,0 +1,116 @@
+import type {
+ InspectWebPageInput,
+ WebPageInspection,
+} from "../domain/browserObservation.js";
+import { CdpConnection } from "./CdpConnection.js";
+import { optionalCdpCommand } from "./CdpOptionalCommand.js";
+import {
+ numberValue,
+ recordValue,
+ recordsValue,
+ stringValue,
+} from "./CdpCaptureValues.js";
+
+/** Capture redacted, bounded storage metadata for one authorized origin. */
+export const captureStorage = async (
+ context: {
+ readonly connection: CdpConnection;
+ readonly sessionId: string;
+ readonly input: InspectWebPageInput;
+ readonly signal?: AbortSignal;
+ },
+ origin: string,
+ limitations: string[],
+): Promise<{
+ readonly value: WebPageInspection["storage"];
+ readonly truncated: boolean;
+}> => {
+ const quota = recordValue(
+ await optionalCdpCommand(
+ context,
+ "Storage.getUsageAndQuota",
+ { origin },
+ limitations,
+ ),
+ );
+ const local = context.input.include_storage_keys
+ ? await storageKeys(context, origin, true, limitations)
+ : [];
+ const session = context.input.include_storage_keys
+ ? await storageKeys(context, origin, false, limitations)
+ : [];
+ const indexed = context.input.include_storage_keys
+ ? stringArray(
+ recordValue(
+ await optionalCdpCommand(
+ context,
+ "IndexedDB.requestDatabaseNames",
+ { securityOrigin: origin },
+ limitations,
+ ),
+ )?.databaseNames,
+ )
+ : [];
+ const caches = context.input.include_storage_keys
+ ? recordsValue(
+ recordValue(
+ await optionalCdpCommand(
+ context,
+ "CacheStorage.requestCacheNames",
+ { securityOrigin: origin },
+ limitations,
+ ),
+ )?.caches,
+ ).flatMap((cache) => {
+ const name = stringValue(cache.cacheName);
+ return name === undefined ? [] : [name.slice(0, 1_024)];
+ })
+ : [];
+ const maximum = context.input.limits.max_storage_keys;
+ return {
+ value: {
+ origin,
+ usage_bytes: numberValue(quota?.usage) ?? null,
+ quota_bytes: numberValue(quota?.quota) ?? null,
+ local_storage_keys: local.slice(0, maximum),
+ session_storage_keys: session.slice(0, maximum),
+ indexed_db_names: indexed.slice(0, maximum),
+ cache_names: caches.slice(0, maximum),
+ values_redacted: true,
+ },
+ truncated: [local, session, indexed, caches].some(
+ (items) => items.length > maximum,
+ ),
+ };
+};
+
+const storageKeys = async (
+ context: Parameters[0],
+ origin: string,
+ isLocalStorage: boolean,
+ limitations: string[],
+): Promise => {
+ const result = recordValue(
+ await optionalCdpCommand(
+ context,
+ "DOMStorage.getDOMStorageItems",
+ { storageId: { securityOrigin: origin, isLocalStorage } },
+ limitations,
+ ),
+ );
+ return Array.isArray(result?.entries)
+ ? result.entries.flatMap((entry) => {
+ if (!Array.isArray(entry)) return [];
+ const key = stringValue(entry[0]);
+ return key === undefined ? [] : [key.slice(0, 1_024)];
+ })
+ : [];
+};
+
+const stringArray = (value: unknown): readonly string[] =>
+ Array.isArray(value)
+ ? value.flatMap((item) => {
+ const text = stringValue(item);
+ return text === undefined ? [] : [text.slice(0, 1_024)];
+ })
+ : [];
diff --git a/src/browser/CdpCaptureValues.ts b/src/browser/CdpCaptureValues.ts
new file mode 100644
index 000000000..439786cff
--- /dev/null
+++ b/src/browser/CdpCaptureValues.ts
@@ -0,0 +1,98 @@
+import { createHash } from "node:crypto";
+
+import {
+ AnalysisCancelledError,
+ BrowserObservationError,
+} from "../domain/errors.js";
+import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
+
+export type UnknownRecord = Readonly>;
+
+const isRecord = (value: unknown): value is UnknownRecord =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+export const recordValue = (value: unknown): UnknownRecord | undefined =>
+ isRecord(value) ? value : undefined;
+
+export const recordsValue = (value: unknown): readonly UnknownRecord[] =>
+ Array.isArray(value)
+ ? value.flatMap((item) => {
+ const record = recordValue(item);
+ return record === undefined ? [] : [record];
+ })
+ : [];
+
+export const stringValue = (value: unknown): string | undefined =>
+ typeof value === "string" ? value : undefined;
+
+export const numberValue = (value: unknown): number | undefined =>
+ typeof value === "number" && Number.isFinite(value) ? value : undefined;
+
+export const requiredRecord = (value: unknown): UnknownRecord => {
+ const record = recordValue(value);
+ if (record === undefined)
+ throw new BrowserObservationError("inspect_web_page", "protocol_error");
+ return record;
+};
+
+export const boundedText = (value: unknown, maximum = 1_024): string | null => {
+ const text = stringValue(value);
+ return text === undefined ? null : text.slice(0, maximum);
+};
+
+export const isHttpUrl = (value: string | undefined): boolean => {
+ if (value === undefined) return false;
+ try {
+ const protocol = new URL(value).protocol;
+ return protocol === "http:" || protocol === "https:";
+ } catch {
+ return false;
+ }
+};
+
+export const allowedSanitizedUrl = (
+ value: unknown,
+ allowedOrigins: ReadonlySet,
+): ReturnType | undefined => {
+ const text = stringValue(value);
+ if (text === undefined) return undefined;
+ const sanitized = sanitizeBrowserUrl(text);
+ return sanitized.origin !== null && allowedOrigins.has(sanitized.origin)
+ ? sanitized
+ : undefined;
+};
+
+export const sourceResult = (
+ source: string,
+): { included: true; sha256: string; bytes: number; content: string } => ({
+ included: true,
+ sha256: createHash("sha256").update(source).digest("hex"),
+ bytes: Buffer.byteLength(source),
+ content: source,
+});
+
+export const sourceExcluded = (
+ reason: string,
+): { included: false; reason: string } => ({ included: false, reason });
+
+export const delayWithCancellation = async (
+ durationMs: number,
+ signal?: AbortSignal,
+): Promise => {
+ if (durationMs === 0) return;
+ if (signal?.aborted === true)
+ throw new AnalysisCancelledError("inspect_web_page");
+ await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ signal?.removeEventListener("abort", onAbort);
+ resolve();
+ }, durationMs);
+ const onAbort = (): void => {
+ clearTimeout(timer);
+ signal?.removeEventListener("abort", onAbort);
+ reject(new AnalysisCancelledError("inspect_web_page"));
+ };
+ signal?.addEventListener("abort", onAbort, { once: true });
+ if (signal?.aborted === true) onAbort();
+ });
+};
diff --git a/src/browser/CdpConnection.ts b/src/browser/CdpConnection.ts
new file mode 100644
index 000000000..280134ee5
--- /dev/null
+++ b/src/browser/CdpConnection.ts
@@ -0,0 +1,252 @@
+import WebSocket, { type RawData } from "ws";
+
+import {
+ AnalysisCancelledError,
+ AnalysisError,
+ AnalysisTimeoutError,
+ BrowserObservationError,
+} from "../domain/errors.js";
+
+export interface CdpEvent {
+ readonly method: string;
+ readonly params: unknown;
+ readonly sessionId?: string;
+}
+
+interface PendingCommand {
+ readonly resolve: (value: unknown) => void;
+ readonly reject: (error: AnalysisError) => void;
+ readonly timer: ReturnType;
+ readonly removeAbort: () => void;
+}
+
+const CONNECT_TIMEOUT_MS = 5_000;
+const COMMAND_TIMEOUT_MS = 5_000;
+const MAX_PAYLOAD_BYTES = 16 * 1_024 * 1_024;
+const MAX_PENDING_COMMANDS = 128;
+
+/** Correlated, bounded JSON-RPC transport for a browser-level CDP socket. */
+export class CdpConnection {
+ readonly #pending = new Map();
+ readonly #listeners = new Set<(event: CdpEvent) => void>();
+ #nextId = 1;
+ #closed = false;
+ #protocolFailed = false;
+
+ private constructor(private readonly socket: WebSocket) {
+ socket.on("message", (data) => this.#receive(data));
+ socket.on("close", () => this.#failPending("disconnected"));
+ socket.on("error", () => this.#failPending("disconnected"));
+ }
+
+ /** Connect to one already-validated loopback browser WebSocket. */
+ static async connect(
+ url: string,
+ signal?: AbortSignal,
+ ): Promise {
+ if (signal?.aborted === true)
+ throw new AnalysisCancelledError("inspect_web_page");
+ const socket = new WebSocket(url, {
+ handshakeTimeout: CONNECT_TIMEOUT_MS,
+ maxPayload: MAX_PAYLOAD_BYTES,
+ perMessageDeflate: false,
+ });
+ await waitForOpen(socket, signal);
+ return new CdpConnection(socket);
+ }
+
+ /** Subscribe to validated CDP event envelopes. */
+ onEvent(listener: (event: CdpEvent) => void): () => void {
+ this.#listeners.add(listener);
+ return () => this.#listeners.delete(listener);
+ }
+
+ /** Execute one bounded command, optionally within a flat target session. */
+ async send(
+ method: string,
+ params: Readonly> = {},
+ sessionId?: string,
+ signal?: AbortSignal,
+ ): Promise {
+ if (this.#protocolFailed)
+ throw new BrowserObservationError("inspect_web_page", "protocol_error");
+ if (this.#closed || this.socket.readyState !== WebSocket.OPEN)
+ throw new BrowserObservationError("inspect_web_page", "disconnected");
+ if (this.#pending.size >= MAX_PENDING_COMMANDS)
+ throw new BrowserObservationError("inspect_web_page", "payload_limit");
+ if (signal?.aborted === true)
+ throw new AnalysisCancelledError("inspect_web_page");
+ const id = this.#nextId;
+ this.#nextId += 1;
+ return await new Promise((resolve, reject) => {
+ const onAbort = (): void => {
+ const pending = this.#pending.get(id);
+ if (pending === undefined) return;
+ clearTimeout(pending.timer);
+ pending.removeAbort();
+ this.#pending.delete(id);
+ reject(new AnalysisCancelledError("inspect_web_page"));
+ };
+ signal?.addEventListener("abort", onAbort, { once: true });
+ const timer = setTimeout(() => {
+ signal?.removeEventListener("abort", onAbort);
+ this.#pending.delete(id);
+ reject(
+ new AnalysisTimeoutError("inspect_web_page", COMMAND_TIMEOUT_MS),
+ );
+ }, COMMAND_TIMEOUT_MS);
+ this.#pending.set(id, {
+ resolve,
+ reject,
+ timer,
+ removeAbort: () => signal?.removeEventListener("abort", onAbort),
+ });
+ this.socket.send(
+ JSON.stringify({
+ id,
+ method,
+ params,
+ ...(sessionId ? { sessionId } : {}),
+ }),
+ (error) => {
+ if (error === undefined || error === null) return;
+ const pending = this.#pending.get(id);
+ if (pending === undefined) return;
+ this.#complete(id, pending);
+ reject(
+ new BrowserObservationError("inspect_web_page", "disconnected", {
+ cause: error,
+ }),
+ );
+ },
+ );
+ });
+ }
+
+ /** Close only REA's socket; never close the browser or selected page. */
+ async close(): Promise {
+ if (this.#closed) return;
+ this.#closed = true;
+ this.#failPending("disconnected");
+ if (this.socket.readyState === WebSocket.CLOSED) return;
+ await new Promise((resolve) => {
+ const timer = setTimeout(() => {
+ this.socket.terminate();
+ resolve();
+ }, 1_000);
+ this.socket.once("close", () => {
+ clearTimeout(timer);
+ resolve();
+ });
+ this.socket.close();
+ });
+ }
+
+ #receive(data: RawData): void {
+ let message: unknown;
+ try {
+ message = JSON.parse(rawText(data));
+ } catch {
+ this.#failPending("protocol_error");
+ return;
+ }
+ if (!isRecord(message)) {
+ this.#failPending("protocol_error");
+ return;
+ }
+ if ("id" in message && typeof message.id === "number") {
+ this.#receiveResponse(message, message.id);
+ return;
+ }
+ if ("method" in message && typeof message.method === "string") {
+ const event: CdpEvent = {
+ method: message.method,
+ params: "params" in message ? message.params : {},
+ ...(typeof message.sessionId === "string"
+ ? { sessionId: message.sessionId }
+ : {}),
+ };
+ for (const listener of this.#listeners) listener(event);
+ }
+ }
+
+ #receiveResponse(message: Record, id: number): void {
+ const pending = this.#pending.get(id);
+ if (pending === undefined) return;
+ this.#complete(id, pending);
+ if ("error" in message) {
+ pending.reject(
+ new BrowserObservationError("inspect_web_page", "protocol_error"),
+ );
+ return;
+ }
+ pending.resolve("result" in message ? message.result : {});
+ }
+
+ #complete(id: number, pending: PendingCommand): void {
+ clearTimeout(pending.timer);
+ pending.removeAbort();
+ this.#pending.delete(id);
+ }
+
+ #failPending(reason: "disconnected" | "protocol_error"): void {
+ if (reason === "disconnected") this.#closed = true;
+ else this.#protocolFailed = true;
+ for (const [id, pending] of this.#pending) {
+ this.#complete(id, pending);
+ pending.reject(new BrowserObservationError("inspect_web_page", reason));
+ }
+ }
+}
+
+const rawText = (data: RawData): string =>
+ Array.isArray(data)
+ ? Buffer.concat(data).toString("utf8")
+ : Buffer.isBuffer(data)
+ ? data.toString("utf8")
+ : Buffer.from(data).toString("utf8");
+
+const isRecord = (value: unknown): value is Record =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+const waitForOpen = async (
+ socket: WebSocket,
+ signal?: AbortSignal,
+): Promise =>
+ await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ cleanup();
+ socket.terminate();
+ reject(new AnalysisTimeoutError("inspect_web_page", CONNECT_TIMEOUT_MS));
+ }, CONNECT_TIMEOUT_MS);
+ const onOpen = (): void => {
+ cleanup();
+ resolve();
+ };
+ const onFailure = (cause: unknown): void => {
+ cleanup();
+ reject(
+ signal?.aborted === true
+ ? new AnalysisCancelledError("inspect_web_page")
+ : new BrowserObservationError(
+ "inspect_web_page",
+ "endpoint_unreachable",
+ { cause },
+ ),
+ );
+ };
+ const onAbort = (): void => {
+ socket.terminate();
+ onFailure(new AnalysisCancelledError("inspect_web_page"));
+ };
+ const cleanup = (): void => {
+ clearTimeout(timer);
+ socket.off("open", onOpen);
+ socket.off("error", onFailure);
+ signal?.removeEventListener("abort", onAbort);
+ };
+ socket.once("open", onOpen);
+ socket.once("error", onFailure);
+ signal?.addEventListener("abort", onAbort, { once: true });
+ if (signal?.aborted === true) onAbort();
+ });
diff --git a/src/browser/CdpEndpoint.ts b/src/browser/CdpEndpoint.ts
new file mode 100644
index 000000000..d63a5e32b
--- /dev/null
+++ b/src/browser/CdpEndpoint.ts
@@ -0,0 +1,207 @@
+import { request } from "node:http";
+
+import { z } from "zod";
+
+import {
+ AnalysisCancelledError,
+ AnalysisError,
+ AnalysisTimeoutError,
+ BrowserObservationError,
+} from "../domain/errors.js";
+
+const HTTP_TIMEOUT_MS = 5_000;
+const MAX_VERSION_BYTES = 64 * 1_024;
+const MAX_TARGET_LIST_BYTES = 2 * 1_024 * 1_024;
+
+const endpointVersionSchema = z.object({
+ Browser: z.string().min(1).max(1_024),
+ "Protocol-Version": z.string().min(1).max(100),
+ "User-Agent": z.string().max(16_384),
+ "V8-Version": z.string().max(1_024),
+ "WebKit-Version": z.string().max(1_024),
+ webSocketDebuggerUrl: z.string().min(1).max(2_048),
+});
+
+const endpointTargetSchema = z.object({
+ id: z.string().min(1).max(256),
+ type: z.string().min(1).max(100),
+ title: z.string().max(16_384).default(""),
+ url: z.string().max(65_536),
+ attached: z.boolean().default(false),
+});
+const endpointTargetsSchema = z.array(endpointTargetSchema).max(1_000);
+
+export type CdpEndpointTarget = z.infer;
+
+export interface CdpEndpointDiscovery {
+ readonly browserWebSocketUrl: string;
+ readonly version: {
+ readonly product: string;
+ readonly protocol_version: string;
+ readonly revision: string;
+ readonly user_agent: string;
+ readonly js_version: string;
+ };
+ readonly targets: readonly CdpEndpointTarget[];
+}
+
+type BrowserOperation = "list_browser_targets" | "inspect_web_page";
+
+/** Read bounded CDP discovery endpoints without following redirects. */
+export const discoverCdpEndpoint = async (
+ endpoint: string,
+ operation: BrowserOperation,
+ signal?: AbortSignal,
+): Promise => {
+ const versionInput = await readJson(
+ new URL("/json/version", endpoint),
+ MAX_VERSION_BYTES,
+ operation,
+ signal,
+ );
+ const targetsInput = await readJson(
+ new URL("/json/list", endpoint),
+ MAX_TARGET_LIST_BYTES,
+ operation,
+ signal,
+ );
+ const version = parseEndpointValue(
+ endpointVersionSchema,
+ versionInput,
+ operation,
+ );
+ const targets = parseEndpointValue(
+ endpointTargetsSchema,
+ targetsInput,
+ operation,
+ );
+ return {
+ browserWebSocketUrl: safeBrowserWebSocketUrl(
+ endpoint,
+ version.webSocketDebuggerUrl,
+ operation,
+ ),
+ version: {
+ product: version.Browser,
+ protocol_version: version["Protocol-Version"],
+ revision: version["WebKit-Version"],
+ user_agent: version["User-Agent"],
+ js_version: version["V8-Version"],
+ },
+ targets,
+ };
+};
+
+const parseEndpointValue =