From be76f8090b5195680cdf73a8c21f65e6516efc92 Mon Sep 17 00:00:00 2001
From: N0zoM1z0 <1705004398@qq.com>
Date: Tue, 14 Jul 2026 17:47:50 +0800
Subject: [PATCH] feat: add web and Electron reverse-engineering workflows
---
CONTRIBUTING.md | 4 +-
README.md | 32 +-
README_ar.md | 9 +-
README_ja.md | 9 +-
README_ko.md | 9 +-
README_zh.md | 9 +-
docs/architecture.mermaid | 2 +-
docs/browser-observation.md | 61 +-
docs/electron-observation.md | 35 +
docs/mcp-prompts.md | 2 +-
package-lock.json | 4 +-
package.json | 1 +
scripts/fixtures/browser-verifier-site.mjs | 120 ++++
scripts/rea.mjs | 2 +-
scripts/verify-package.mjs | 13 +-
scripts/verify-published-package.mjs | 4 +-
scripts/verify-real-browser.mjs | 282 ++++++--
scripts/verify-real-hopper.mjs | 2 +-
skills/rea-analysis/SKILL.md | 28 +-
src/application/BrowserEvidence.ts | 162 ++++-
src/application/BrowserObservationPort.ts | 44 ++
src/application/BrowserObservationService.ts | 167 ++++-
src/application/CapabilityInventory.ts | 10 +
src/application/ElectronEvidence.ts | 60 ++
src/application/ElectronObservationPort.ts | 22 +
src/application/ElectronObservationService.ts | 116 +++
src/application/ProjectPermissionStore.ts | 1 +
src/browser/CdpBrowserProvider.ts | 262 ++++++-
src/browser/CdpCaptureCompleteness.ts | 119 +++
src/browser/CdpCaptureDocuments.ts | 264 ++++++-
src/browser/CdpCaptureEvents.ts | 457 ++++++++++--
src/browser/CdpCaptureValues.ts | 9 +-
src/browser/CdpElectronInspection.ts | 481 +++++++++++++
src/browser/CdpElectronProvider.ts | 223 ++++++
src/browser/CdpEndpoint.ts | 13 +-
src/browser/CdpObservationSession.ts | 416 +++++++++++
src/browser/CdpPageCapture.ts | 292 ++++++--
src/browser/CdpSafeMetadata.ts | 277 +++++++
src/browser/CdpScreenshot.ts | 164 +++++
src/browser/CdpWebMcpDiscovery.ts | 373 ++++++++++
src/browser/ElectronFileScope.ts | 56 ++
src/browser/PngVisualDiff.ts | 222 ++++++
src/browser/SensitiveTextCapture.ts | 35 +
src/browser/WebSourceMapFetcher.ts | 445 ++++++++++++
src/catalogIdentity.ts | 8 +
src/cli.ts | 4 +
src/cliBrowserAdvancedCommands.ts | 220 ++++++
src/cliBrowserCommands.ts | 197 +++++
src/cliElectronCommands.ts | 141 ++++
src/cliPolicyCommands.ts | 1 +
src/config.ts | 55 ++
src/contracts/browserToolContracts.ts | 330 ++++++++-
src/contracts/electronToolContracts.ts | 84 +++
src/contracts/toolContractTypes.ts | 1 +
src/contracts/toolContracts.ts | 2 +
src/domain/browserCompleteness.ts | 142 ++++
src/domain/browserObservation.ts | 269 ++++++-
src/domain/browserSession.ts | 74 ++
src/domain/electronObservation.ts | 194 +++++
src/domain/errors.ts | 15 +-
src/domain/jsonShape.ts | 151 ++++
src/domain/permissionPolicy.ts | 1 +
src/domain/webBundleAnalysis.ts | 228 ++++++
src/domain/webBundleAnalyzer.ts | 640 +++++++++++++++++
src/domain/webCaptureDiff.ts | 286 ++++++++
src/domain/webContentArtifact.ts | 56 ++
src/domain/webInventory.ts | 120 ++++
src/domain/webMcpDiscovery.ts | 80 +++
src/domain/webScreenshot.ts | 142 ++++
src/generatedPackageMetadata.ts | 4 +-
src/main.ts | 7 +
src/server/createServer.ts | 10 +
src/server/registerBrowserTools.ts | 145 +++-
src/server/registerElectronTools.ts | 90 +++
src/server/registerSessionStatusTool.ts | 1 +
src/server/registerSessionTools.ts | 3 +
tests/browserCli.test.ts | 148 +++-
tests/browserMcp.test.ts | 154 +++-
tests/browserObservation.test.ts | 53 ++
tests/cdpBrowserProvider.test.ts | 675 +++++++++++++++++-
tests/cdpCaptureCompleteness.test.ts | 56 ++
tests/cdpCaptureDocuments.test.ts | 62 ++
tests/cdpElectronProvider.test.ts | 211 ++++++
tests/cdpSafeMetadata.test.ts | 99 +++
tests/config.test.ts | 28 +
tests/contractSnapshot.test.ts | 17 +-
tests/electronCli.test.ts | 108 +++
tests/electronFileScope.test.ts | 57 ++
tests/electronMcp.test.ts | 131 ++++
tests/enhancedTools.test.ts | 12 +-
tests/fixtures/fakeCdpBrowser.ts | 384 +++++++++-
tests/integration/serverIntegration.test.ts | 14 +-
tests/jsonShape.test.ts | 66 ++
tests/pngVisualDiff.test.ts | 95 +++
tests/promptMcp.test.ts | 2 +-
tests/readmeConsistency.test.ts | 6 +-
tests/runtime.test.ts | 6 +-
tests/sensitiveTextCapture.test.ts | 27 +
tests/serverIdentity.test.ts | 10 +-
tests/sessionMcp.test.ts | 2 +-
tests/setupSkill.test.ts | 2 +-
tests/toolContracts.test.ts | 17 +-
tests/webBundleAnalyzer.test.ts | 267 +++++++
tests/webCaptureDiff.test.ts | 151 ++++
tests/webInventory.test.ts | 154 ++++
tests/webSourceMapFetcher.test.ts | 264 +++++++
106 files changed, 11893 insertions(+), 404 deletions(-)
create mode 100644 docs/electron-observation.md
create mode 100644 scripts/fixtures/browser-verifier-site.mjs
create mode 100644 src/application/ElectronEvidence.ts
create mode 100644 src/application/ElectronObservationPort.ts
create mode 100644 src/application/ElectronObservationService.ts
create mode 100644 src/browser/CdpCaptureCompleteness.ts
create mode 100644 src/browser/CdpElectronInspection.ts
create mode 100644 src/browser/CdpElectronProvider.ts
create mode 100644 src/browser/CdpObservationSession.ts
create mode 100644 src/browser/CdpSafeMetadata.ts
create mode 100644 src/browser/CdpScreenshot.ts
create mode 100644 src/browser/CdpWebMcpDiscovery.ts
create mode 100644 src/browser/ElectronFileScope.ts
create mode 100644 src/browser/PngVisualDiff.ts
create mode 100644 src/browser/SensitiveTextCapture.ts
create mode 100644 src/browser/WebSourceMapFetcher.ts
create mode 100644 src/cliBrowserAdvancedCommands.ts
create mode 100644 src/cliElectronCommands.ts
create mode 100644 src/contracts/electronToolContracts.ts
create mode 100644 src/domain/browserCompleteness.ts
create mode 100644 src/domain/browserSession.ts
create mode 100644 src/domain/electronObservation.ts
create mode 100644 src/domain/jsonShape.ts
create mode 100644 src/domain/webBundleAnalysis.ts
create mode 100644 src/domain/webBundleAnalyzer.ts
create mode 100644 src/domain/webCaptureDiff.ts
create mode 100644 src/domain/webContentArtifact.ts
create mode 100644 src/domain/webInventory.ts
create mode 100644 src/domain/webMcpDiscovery.ts
create mode 100644 src/domain/webScreenshot.ts
create mode 100644 src/server/registerElectronTools.ts
create mode 100644 tests/cdpCaptureCompleteness.test.ts
create mode 100644 tests/cdpElectronProvider.test.ts
create mode 100644 tests/cdpSafeMetadata.test.ts
create mode 100644 tests/electronCli.test.ts
create mode 100644 tests/electronFileScope.test.ts
create mode 100644 tests/electronMcp.test.ts
create mode 100644 tests/jsonShape.test.ts
create mode 100644 tests/pngVisualDiff.test.ts
create mode 100644 tests/sensitiveTextCapture.test.ts
create mode 100644 tests/webBundleAnalyzer.test.ts
create mode 100644 tests/webCaptureDiff.test.ts
create mode 100644 tests/webInventory.test.ts
create mode 100644 tests/webSourceMapFetcher.test.ts
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index ac09b405e..cb1ae8d8d 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, 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.
+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, 8 browser, 2 Electron, and 18 session tools (78 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 70 tools:
+After npm registry propagation, verify the published CLI and connect a beta.3 MCP client to the published server to confirm all 78 tools:
```bash
npx -y rea-agents --help
diff --git a/README.md b/README.md
index 08f341812..9175d6263 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)
-[](#70-tools-for-investigation)
+[](#78-tools-for-investigation)
[](https://nodejs.org/)
[](LICENSE)
-[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)
+[Quick start](#quick-start) · [Current status](#current-status) · [Investigation model](#the-investigation-model) · [78 tools](#78-tools-for-investigation) · [Roadmap](#roadmap) · [How it works](#how-it-works)
@@ -30,7 +30,7 @@
See a feature in an app that you want in your own product? Give the app to your agent—even without its source code. With REA, the agent can investigate the feature, explain how it works, show its evidence, and build a version adapted to your stack and requirements.
-REA gives agents one consistent way to investigate software. Today that includes deep native analysis through Hopper, complete function dossiers, reproducible Evidence v2 records, and controlled process capture. The longer-term toolkit extends the same agent workflow to packaged apps, JavaScript bundles, websites, APIs, protocols, mobile artifacts, firmware, runtime behavior, and differences between versions.
+REA gives agents one consistent way to investigate software. Today that includes deep native analysis through Hopper, complete function dossiers, reproducible Evidence v2 records, controlled process capture, passive website and Electron observation, and bounded JavaScript/source-map reconstruction. The longer-term toolkit extends the same agent workflow to APIs, protocols, mobile artifacts, firmware, richer runtime behavior, and differences between versions.
Reverse engineering normally makes the operator choose a tool, learn its API, move evidence between programs, and decide what to inspect next. REA gives that work to the agent through commands, skills, structured results, and repeatable investigation workflows.
@@ -294,16 +294,17 @@ 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.
-## 70 tools for investigation
+## 78 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 |
-| 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 |
+| 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 | 8 | exact-origin CDP capture, bundle and source-map analysis, WebMCP discovery, session timelines, capture diff, and visual evidence |
+| Electron observation | 2 | canonical-root-confined file-page discovery and passive DOM, resource, and optionally approved script-source 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.
@@ -312,7 +313,8 @@ 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.
+- Attach to a user-owned Chrome-family browser over a configured loopback CDP endpoint; capture exact-origin web structure, safe metadata, approved value-free payload shapes, bundle/source-map evidence, WebMCP declarations, user-action timelines, capture diffs, and explicitly approved screenshots without navigation or JavaScript evaluation.
+- Inspect Electron `file://` renderer pages through a separate canonical-root permission boundary without invoking Electron APIs; script contents remain separately approved and byte bounded.
- 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.
@@ -346,14 +348,14 @@ 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.
+All eight browser tools expose the same Evidence v2 contracts over CLI and MCP. Inspection is passive: REA does not evaluate page JavaScript, navigate, click, close the page, or close the browser. Query values, credentials, cookies, authorization headers, storage values, and raw JSON or WebSocket values are never retained. Separately approved captures can retain bounded redacted console primitives, value-free JSON/WebSocket shapes, script sources, accessibility text, or screenshot pixels. 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** — extend the shipped passive CDP observation with approved interaction, screenshots, Electron IPC, route discovery, controlled replay, and visual or structural differences.
+2. **Web and Electron investigation** — extend the shipped passive CDP, bundle, visual-diff, and file-page observation with approved interaction, controlled replay, Electron IPC observation, semantic UI differences, and deeper JavaScript reconstruction.
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.
diff --git a/README_ar.md b/README_ar.md
index 097053d4c..eca8b8011 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)
-[](#منصة-من-70-أداة)
+[](#منصة-من-78-أداة)
[](https://nodejs.org/)
[](LICENSE)
-[البدء السريع](#البدء-السريع) · [من الملف التنفيذي إلى السلوك](#من-الملف-التنفيذي-إلى-السلوك) · [70 أداة](#منصة-من-70-أداة) · [كيف يعمل](#كيف-يعمل) · [الأسئلة الشائعة](#الأسئلة-الشائعة)
+[البدء السريع](#البدء-السريع) · [من الملف التنفيذي إلى السلوك](#من-الملف-التنفيذي-إلى-السلوك) · [78 أداة](#منصة-من-78-أداة) · [كيف يعمل](#كيف-يعمل) · [الأسئلة الشائعة](#الأسئلة-الشائعة)
@@ -155,7 +155,7 @@ rea uninstall --purge-data
افحص التحقق من الإدخال، والتشفير، والصلاحيات، والتخزين، ومسارات الأخطاء من دون رفع الملف التنفيذي إلى خدمة بعيدة.
-## منصة من 70 أداة
+## منصة من 78 أداة
| عائلة الأدوات | العدد | أمثلة |
| --------------------- | ----: | ---------------------------------------------------------------------------------------- |
@@ -163,7 +163,8 @@ rea uninstall --purge-data
| التحليل المركب | 10 | النظرة العامة، وفك الترجمة الدفعي، ومخططات الاستدعاء، والمراجع، واكتشاف الأنواع |
| أدوات macOS الأصلية | 5 | بيانات Mach-O والتوقيعات وملفات plist والمعماريات وفك رموز Swift دون تشغيل Hopper |
| رسم القطع الأثرية | 2 | جرد حتمي للدلائل وZIP/APK/IPA وASAR واستخراج معاملاتي محدد صراحة |
-| مراقبة المتصفح | 2 | اكتشاف صفحات CDP ضمن أصول دقيقة وفحص سلبي لـ DOM وإتاحة الوصول والبرامج والشبكة والتخزين |
+| مراقبة المتصفح | 8 | التقاط CDP محدود الأصل وتحليل الحزم وخرائط المصدر واكتشاف WebMCP والفروق والأدلة المرئية |
+| مراقبة Electron | 2 | اكتشاف صفحات الملفات ضمن جذور canonical وفحص DOM والموارد والمصادر المعتمدة |
| جلسة الملف التنفيذي | 18 | فتح الأهداف وحزم الأدلة ومقارنة العمليات والقطع والدوال وسجل المجهولات المتبقية |
## استخدام REA مع وكلاء برمجة آخرين
diff --git a/README_ja.md b/README_ja.md
index b7e37cee4..bbfb1f5e0 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)
-[](#70-ツールのワークベンチ)
+[](#78-ツールのワークベンチ)
[](https://nodejs.org/)
[](LICENSE)
-[クイックスタート](#クイックスタート) · [バイナリから動作へ](#バイナリから動作へ) · [70 ツール](#70-ツールのワークベンチ) · [仕組み](#仕組み) · [FAQ](#faq)
+[クイックスタート](#クイックスタート) · [バイナリから動作へ](#バイナリから動作へ) · [78 ツール](#78-ツールのワークベンチ) · [仕組み](#仕組み) · [FAQ](#faq)
@@ -145,7 +145,7 @@ REA は手順 1〜5 のバイナリ解析を処理し、手順 6 はエージェ
- Swift / Objective-C のメタデータを解析する。
- Hopper に名前、コメント、ブックマークを残し、人間とエージェントの調査を共有する。
-## 70 ツールのワークベンチ
+## 78 ツールのワークベンチ
| ツール群 | 数 | 例 |
| ---------------------- | --: | ------------------------------------------------------------------------------------------------------------------- |
@@ -153,7 +153,8 @@ 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、アクセシビリティ、スクリプト、通信、保存領域の調査 |
+| ブラウザ観察 | 8 | origin 限定 CDP 取得、bundle/source map 解析、WebMCP 検出、セッション、capture diff、視覚証拠 |
+| Electron 観察 | 2 | canonical ファイルルート内のページ検出と受動的 DOM、リソース、承認済みスクリプトソース調査 |
| バイナリセッション | 18 | `open_binary`、`binary_session`、証拠バンドル、プロセス/成果物/関数比較、残余未知レジストリ |
## 他のコーディングエージェントで使う
diff --git a/README_ko.md b/README_ko.md
index a7e0c7e46..606fe9b81 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)
-[](#70개-도구로-구성된-워크벤치)
+[](#78개-도구로-구성된-워크벤치)
[](https://nodejs.org/)
[](LICENSE)
-[빠른 시작](#빠른-시작) · [바이너리에서 동작까지](#바이너리에서-동작까지) · [70개 도구](#70개-도구로-구성된-워크벤치) · [작동 방식](#작동-방식) · [FAQ](#faq)
+[빠른 시작](#빠른-시작) · [바이너리에서 동작까지](#바이너리에서-동작까지) · [78개 도구](#78개-도구로-구성된-워크벤치) · [작동 방식](#작동-방식) · [FAQ](#faq)
@@ -145,7 +145,7 @@ REA는 1–5단계의 바이너리 분석을 처리합니다. 6단계는 에이
- Swift 및 Objective-C 메타데이터를 분석합니다.
- Hopper에 이름, 주석, 북마크를 남겨 사람과 에이전트의 분석을 연결합니다.
-## 70개 도구로 구성된 워크벤치
+## 78개 도구로 구성된 워크벤치
| 도구 그룹 | 수 | 예시 |
| ------------------- | --: | -------------------------------------------------------------------------------------------------------------------- |
@@ -153,7 +153,8 @@ 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, 접근성, 스크립트, 네트워크, 콘솔 및 저장소 조사 |
+| 브라우저 관찰 | 8 | origin 제한 CDP 캡처, bundle/source map 분석, WebMCP 검색, 세션 타임라인, capture diff 및 시각 증거 |
+| Electron 관찰 | 2 | canonical 파일 루트 내 페이지 검색과 수동 DOM, 리소스 및 별도 승인된 스크립트 소스 조사 |
| 바이너리 세션 | 18 | `open_binary`, `binary_session`, 증거 번들, 프로세스·아티팩트·함수 비교, 잔여 미지수 레지스트리 |
## 다른 코딩 에이전트에서 사용하기
diff --git a/README_zh.md b/README_zh.md
index 4bdc6cd9c..5ea0536cf 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)
-[](#70-个工具组成的工作台)
+[](#78-个工具组成的工作台)
[](https://nodejs.org/)
[](LICENSE)
-[快速开始](#快速开始) · [从二进制到行为](#从二进制到行为) · [70 个工具](#70-个工具组成的工作台) · [工作原理](#工作原理) · [常见问题](#常见问题)
+[快速开始](#快速开始) · [从二进制到行为](#从二进制到行为) · [78 个工具](#78-个工具组成的工作台) · [工作原理](#工作原理) · [常见问题](#常见问题)
@@ -145,7 +145,7 @@ REA 负责第 1–5 步中的二进制分析。第 6 步由智能体使用其常
- 分析 Swift 和 Objective-C 元数据。
- 在 Hopper 中留下名称、注释与书签,使人与智能体的分析互相增强。
-## 70 个工具组成的工作台
+## 78 个工具组成的工作台
| 工具类别 | 数量 | 示例 |
| -------------- | ---: | -------------------------------------------------------------------------------------------------------------------- |
@@ -153,7 +153,8 @@ 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、无障碍树、脚本、网络、控制台与存储检查 |
+| 浏览器观察 | 8 | 精确来源 CDP 抓取、bundle/source map 分析、WebMCP 发现、会话时间线、capture diff 与视觉证据 |
+| Electron 观察 | 2 | 限定 canonical 文件根的页面发现,以及被动 DOM、资源与另行批准的脚本源码检查 |
| 二进制会话 | 18 | `open_binary`、`binary_session`、证据包、进程、制品与函数比较、残余未知项注册表 |
## 与其他编程智能体一起使用
diff --git a/docs/architecture.mermaid b/docs/architecture.mermaid
index 60d7b68d5..26e608db1 100644
--- a/docs/architecture.mermaid
+++ b/docs/architecture.mermaid
@@ -25,7 +25,7 @@ graph TD
end
subgraph "Contracts Layer"
- CONTRACTS["src/contracts/
Caller-visible tool schemas
70 analysis, browser, and session tools"]
+ CONTRACTS["src/contracts/
Caller-visible tool schemas
78 analysis, browser, Electron, and session tools"]
end
subgraph "Domain Layer"
diff --git a/docs/browser-observation.md b/docs/browser-observation.md
index 1728d61d3..39fdd989c 100644
--- a/docs/browser-observation.md
+++ b/docs/browser-observation.md
@@ -5,10 +5,18 @@ REA can attach to a user-owned Chrome-family browser through the Chrome DevTools
## 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.
+- `inspect_web_page` / `rea inspect-web-page` captures bounded DOM structure, accessibility nodes, scripts, resources, safe response/DOM metadata, attach-window network and console metadata, WebSocket frame sizes, workers, quota, and optionally storage key names or script sources.
+- `analyze_web_bundle` / `rea analyze-web-bundle` parses approved script artifacts without execution and derives chunk edges, route and endpoint candidates, vendor fingerprints, static WebMCP declarations, and optionally approved source-map/original-source evidence.
+- `observe_web_session` / `rea observe-web-session` arms a bounded window for an external user action and records ordered reload, SPA navigation, redirect, failure, lifecycle, and target-termination metadata.
+- `discover_webmcp_tools` / `rea discover-webmcp-tools` uses the experimental CDP WebMCP domain to inventory page registrations. REA never exposes `WebMCP.invokeTool`.
+- `compare_web_captures` / `rea compare-web-captures` compares stable DOM, script, resource, network, metadata, and optional WebMCP identities without treating incomplete absence as equivalence.
+- `capture_web_screenshot` / `rea capture-web-screenshot` returns an explicitly approved, bounded, content-addressed visible-viewport PNG.
+- `compare_web_screenshots` / `rea compare-web-screenshots` performs bounded local PNG pixel comparison without OCR or external services.
+- Every surface has equivalent CLI and MCP contracts and returns 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.
+Electron `file://` pages use a separate provider, permission capability, and root model; see [electron-observation.md](electron-observation.md).
+
## Start a browser
Start a separate browser profile with an explicit debugging port. The exact executable name varies by platform and installation:
@@ -60,17 +68,39 @@ rea inspect-web-page http://127.0.0.1:9222 TARGET_ID \
--json
```
-Script content and storage key names require separate opt-ins:
+Static bundle analysis and a user-driven observation window are separate operations:
+
+```bash
+rea analyze-web-bundle http://127.0.0.1:9222 TARGET_ID \
+ --approved --source-capture-approved --json
+rea observe-web-session http://127.0.0.1:9222 TARGET_ID \
+ --approved --observation-ms 10000 --json
+rea discover-webmcp-tools http://127.0.0.1:9222 TARGET_ID \
+ --approved --json
+```
+
+Accessibility names/descriptions, console primitive text, JSON body shapes, WebSocket shapes, script content, and storage key names require separate opt-ins. Console/body/WebSocket capture additionally requires its matching approval flag:
```bash
rea inspect-web-page http://127.0.0.1:9222 TARGET_ID \
--approved \
+ --include-accessibility-text \
+ --include-console-text --console-text-approved \
+ --include-json-body-shapes --json-body-schema-approved \
+ --include-websocket-shapes --websocket-shape-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.
+Accessibility text and script content may contain application secrets and become part of the returned Evidence. Accessibility and console text have independent per-field and aggregate UTF-8 byte limits; credential-shaped console substrings are redacted. JSON and WebSocket captures retain paths, types, counts, and truncation only, never values or examples. Storage values remain redacted even when key-name capture is approved.
+
+Screenshot pixels require both `--approved` and `--screenshot-approved`:
+
+```bash
+rea capture-web-screenshot http://127.0.0.1:9222 TARGET_ID \
+ --approved --screenshot-approved --json
+```
## MCP input
@@ -81,6 +111,13 @@ Script content may contain application secrets and becomes part of the returned
"target_id": "TARGET_ID_FROM_LIST_BROWSER_TARGETS",
"approved": true,
"observation_ms": 500,
+ "include_accessibility_text": false,
+ "include_console_text": false,
+ "console_text_approved": false,
+ "include_json_body_shapes": false,
+ "json_body_schema_approved": false,
+ "include_websocket_shapes": false,
+ "websocket_shape_approved": false,
"include_script_sources": false,
"include_storage_keys": false
}
@@ -96,11 +133,13 @@ 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.
+- Accessibility structure and roles are retained by default, but names and descriptions require `include_accessibility_text: true` and remain byte-bounded.
+- Network observations retain method, status, MIME type, size, type, initiator stack location, and redacted URLs. Headers are discarded after an allowlisted projection of length/encoding, structured CSP/Link/policy fields, and untrusted agent hints. Cookies and authorization headers are never retained.
+- Request/response bodies are not requested or parsed by default. With independent approval, only allowed-origin JSON media types are read within per-body and aggregate budgets, converted immediately to value-free property paths/types, and discarded. `Network.getResponseBody` is never sent without that approval.
+- Console observations with an approved stack source retain call type, argument types, timestamp, and redacted source location. With independent approval, only already-delivered primitive values are retained after credential redaction and byte bounds; objects, getters, and remote properties are never expanded.
+- WebSocket observations retain direction, opcode, and payload byte length. With independent approval, bounded text frames are classified as text or value-free JSON shape; binary bytes, hashes, prefixes, and raw frames are never retained.
- 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.
+- Script metadata is included only when CDP supplies a URL on an allowed origin. Stable keys exclude transient CDP script IDs, and exact transient raw URLs are used only during script/resource reconciliation. URL-less scripts are excluded because their origin cannot be established. Source content is omitted unless explicitly requested and becomes a self-verifying `rea://web-content/sha256/...` artifact 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.
@@ -108,14 +147,14 @@ Cross-origin frames, resources, scripts, events, and workers are excluded unless
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.
+Every result distinguishes `complete_within_window`, `policy_filtered`, `attach_limited`, and `truncated` coverage. It names affected sections and reports sparse excluded-item and per-event-type dropped 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.
+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 not fetched by inspection. Bundle analysis can fetch them only after separate approval, with exact-origin redirect checks, no credentials/cookies/referrer, per-map and aggregate byte limits, a total map-count limit, v3 validation, and bounded generated/original mappings. Source-map results report requested, processed, and dropped counts rather than hiding budget truncation.
## 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.
+The browser provider deliberately does not expose generic CDP commands, `Runtime.evaluate`, WebMCP invocation, navigation, input, downloads, page closure, or browser closure. Screenshot capture is the sole pixel surface and requires separate literal approval. 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/electron-observation.md b/docs/electron-observation.md
new file mode 100644
index 000000000..1327de089
--- /dev/null
+++ b/docs/electron-observation.md
@@ -0,0 +1,35 @@
+# Electron file-page observation
+
+REA can attach to a user-owned Electron/Chromium CDP endpoint and inspect existing `file://` renderer pages without evaluating JavaScript or invoking Electron APIs. Electron observation is separate from website observation because filesystem roots, not HTTP origins, define its authority.
+
+## Configure authority
+
+The capability is disabled by default:
+
+```bash
+export REA_ELECTRON_OBSERVE_ENABLED=true
+export REA_ELECTRON_CDP_ENDPOINTS_JSON='["http://127.0.0.1:9223"]'
+export REA_ELECTRON_FILE_ROOTS_JSON='["/Applications/Example.app/Contents/Resources"]'
+```
+
+Endpoints accept only explicit-port loopback HTTP URLs. Roots are canonicalized by the shared permission authority. Each target, frame, script, and resource is independently converted from a hostless `file://` URL to a real path and checked after symlink resolution. UNC hosts, percent-encoded path separators, nonexistent paths, and root escapes are rejected.
+
+## Workflow
+
+```bash
+rea list-electron-targets http://127.0.0.1:9223 --approved --json
+rea inspect-electron-page http://127.0.0.1:9223 TARGET_ID \
+ --approved --observation-ms 100 --json
+```
+
+Script content is excluded by default. Capturing it requires both flags and remains subject to per-script and aggregate byte budgets:
+
+```bash
+rea inspect-electron-page http://127.0.0.1:9223 TARGET_ID \
+ --approved \
+ --include-script-sources \
+ --source-capture-approved \
+ --json
+```
+
+The normalized result contains canonical local paths, bounded frame and DOM structure, resource metadata, stable script/resource identities, explicit completeness, and content-addressed approved source artifacts. It does not retain DOM values, execute renderer code, navigate, click, invoke Electron IPC, close a target, or terminate the application.
diff --git a/docs/mcp-prompts.md b/docs/mcp-prompts.md
index ce9d44a78..f41fb90aa 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 70 tools; they do not add, remove, or
+`prompts` capability. They complement the 78 tools; they do not add, remove, or
invoke tools by themselves.
## Prompt inventory
diff --git a/package-lock.json b/package-lock.json
index 611098065..049e1ff80 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -13,6 +13,7 @@
"@babel/parser": "8.0.4",
"@babel/types": "8.0.4",
"@electron/asar": "4.2.0",
+ "@jridgewell/trace-mapping": "0.3.31",
"@modelcontextprotocol/server": "2.0.0-beta.4",
"@xterm/addon-serialize": "0.14.0",
"@xterm/headless": "6.0.0",
@@ -221,7 +222,6 @@
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=6.0.0"
@@ -231,14 +231,12 @@
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
"integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
- "dev": true,
"license": "MIT"
},
"node_modules/@jridgewell/trace-mapping": {
"version": "0.3.31",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
- "dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/resolve-uri": "^3.1.0",
diff --git a/package.json b/package.json
index bb6383325..e3a3148a4 100644
--- a/package.json
+++ b/package.json
@@ -92,6 +92,7 @@
"@babel/parser": "8.0.4",
"@babel/types": "8.0.4",
"@electron/asar": "4.2.0",
+ "@jridgewell/trace-mapping": "0.3.31",
"@modelcontextprotocol/server": "2.0.0-beta.4",
"@xterm/addon-serialize": "0.14.0",
"@xterm/headless": "6.0.0",
diff --git a/scripts/fixtures/browser-verifier-site.mjs b/scripts/fixtures/browser-verifier-site.mjs
new file mode 100644
index 000000000..5c8dd78bb
--- /dev/null
+++ b/scripts/fixtures/browser-verifier-site.mjs
@@ -0,0 +1,120 @@
+import { createServer } from "node:http";
+
+import { WebSocketServer } from "ws";
+
+/** Start the local HTTP/WS application used by real-browser verification. */
+export async function startBrowserVerifierSite() {
+ let port = 0;
+ let sessionGeneration = 0;
+ const server = createServer((request, response) => {
+ if (request.url === "/app.js.map") {
+ response.setHeader("content-type", "application/source-map+json");
+ response.end(sourceMap());
+ return;
+ }
+ if (request.url === "/session-generation") {
+ response.setHeader("content-type", "application/json");
+ response.end(JSON.stringify({ generation: sessionGeneration }));
+ return;
+ }
+ if (request.url?.startsWith("/app.js") === true) {
+ response.setHeader("content-type", "text/javascript");
+ response.end(browserScript(port));
+ return;
+ }
+ if (request.url?.startsWith("/api") === true) {
+ response.setHeader("content-type", "application/json");
+ response.setHeader(
+ "content-security-policy",
+ "default-src 'self'; connect-src 'self' ws:",
+ );
+ response.setHeader(
+ "link",
+ '; rel="service-desc"; type="application/json"',
+ );
+ response.setHeader("permissions-policy", "geolocation=(), camera=()");
+ 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)}`,
+ triggerSessionNavigation() {
+ sessionGeneration += 1;
+ },
+ 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),
+ ),
+ );
+ },
+ };
+}
+
+const browserScript = (port) => `
+ export const reaSourceMarker = "approved-source-marker";
+ export const verifiedRoute = { path: "/verified-route" };
+ 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", "authorization=Bearer console-secret-value");
+ fetch("/api?token=network-secret-value", {
+ method: "POST",
+ headers: {
+ Authorization: "Bearer request-secret-value",
+ "Content-Type": "application/json"
+ },
+ body: JSON.stringify({ token: "request-body-secret-value", active: true })
+ });
+ const socket = new WebSocket("ws://127.0.0.1:${String(port)}/live?token=websocket-url-secret");
+ socket.addEventListener("open", () => socket.send(JSON.stringify({ token: "websocket-secret-value" })));
+ socket.addEventListener("message", () => socket.close());
+ };
+ observe();
+ setInterval(observe, 150);
+ let observedGeneration = 0;
+ setInterval(async () => {
+ const response = await fetch("/session-generation");
+ const { generation } = await response.json();
+ if (generation <= observedGeneration) return;
+ observedGeneration = generation;
+ history.pushState({}, "", "/app/session-" + String(generation));
+ }, 100);
+ //# sourceMappingURL=/app.js.map
+`;
+
+const sourceMap = () =>
+ JSON.stringify({
+ version: 3,
+ file: "app.js",
+ names: ["reaSourceMarker"],
+ sources: ["../src/main.ts"],
+ sourcesContent: [
+ "import './dependency.ts';\nexport const reaSourceMarker = 'approved-source-marker';",
+ ],
+ mappings: "AAAAA",
+ });
diff --git a/scripts/rea.mjs b/scripts/rea.mjs
index 695fbc79f..6d7433910 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 70-tool stdio server.
+// such as `mcp add`, while only dist/main.js may serve the 78-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 1f267ed9a..4603ea416 100644
--- a/scripts/verify-package.mjs
+++ b/scripts/verify-package.mjs
@@ -345,17 +345,22 @@ try {
);
const planned = json(plannedExecution.stdout);
if (supportedSetupHost) {
+ const plannedClaudeConfig = await readFile(claudeConfig, "utf8");
+ const plannedCursorConfig = await readFile(cursorConfig, "utf8");
+ const plannedSkill = await readFile(skillPath, "utf8");
if (
planned.status !== "needs_confirmation" ||
plannedExecution.status !== 1 ||
planned.appliedActions.length !== 0 ||
!planned.plannedActions.some(({ kind }) => kind === "configure_client") ||
!planned.plannedActions.some(({ kind }) => kind === "install_skill") ||
- (await readFile(claudeConfig, "utf8")) !== '{"existing":true}\n' ||
- (await readFile(cursorConfig, "utf8")) !== '{"existing":true}\n' ||
- (await readFile(skillPath, "utf8")) !== "stale managed skill\n"
+ plannedClaudeConfig !== '{"existing":true}\n' ||
+ plannedCursorConfig !== '{"existing":true}\n' ||
+ plannedSkill !== "stale managed skill\n"
)
- throw new Error("packaged setup plan mutated files before approval");
+ throw new Error(
+ `packaged setup plan was not read-only: ${JSON.stringify({ status: planned.status, exitCode: plannedExecution.status, plannedKinds: planned.plannedActions.map(({ kind }) => kind), appliedKinds: planned.appliedActions.map(({ kind }) => kind), claudeConfig: plannedClaudeConfig, cursorConfig: plannedCursorConfig, skill: plannedSkill })}`,
+ );
}
const firstExecution = await runWithStatus(
cli,
diff --git a/scripts/verify-published-package.mjs b/scripts/verify-published-package.mjs
index 7b6e0da78..cc9dc7847 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 !== 70)
+ if (tools.tools.length !== 78)
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: 70 })}\n`,
+ `${JSON.stringify({ package: "rea-agents", version, mcpTools: 78 })}\n`,
);
diff --git a/scripts/verify-real-browser.mjs b/scripts/verify-real-browser.mjs
index 835c2141c..d2cf3c221 100644
--- a/scripts/verify-real-browser.mjs
+++ b/scripts/verify-real-browser.mjs
@@ -2,28 +2,34 @@
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";
+import { analyzeWebBundleInputSchema } from "../dist/domain/webBundleAnalysis.js";
+import { observeWebSessionInputSchema } from "../dist/domain/browserSession.js";
+import { compareWebCapturesInputSchema } from "../dist/domain/webCaptureDiff.js";
+import {
+ captureWebScreenshotInputSchema,
+ compareWebScreenshotsInputSchema,
+} from "../dist/domain/webScreenshot.js";
+import { startBrowserVerifierSite } from "./fixtures/browser-verifier-site.mjs";
const SECRET_VALUES = [
"network-secret-value",
"console-secret-value",
"storage-secret-value",
"websocket-secret-value",
+ "ax-private-label-value",
];
const executable = await browserExecutable();
const profile = await mkdtemp(join(tmpdir(), "rea-real-browser-"));
-const site = await startSite();
+const site = await startBrowserVerifierSite();
let browser;
try {
browser = spawn(
@@ -77,19 +83,113 @@ try {
approved: true,
target_id: target,
observation_ms: 200,
+ include_accessibility_text: true,
include_script_sources: true,
+ include_console_text: true,
+ console_text_approved: true,
+ include_json_body_shapes: true,
+ json_body_schema_approved: true,
+ include_websocket_shapes: true,
+ websocket_shape_approved: true,
}),
);
if (!withSource.ok) throw withSource.error;
const source = withSource.value.scripts.items.find(
(script) =>
script.source.included &&
- script.source.content.includes("reaSourceMarker"),
+ script.source.artifact.text.includes("reaSourceMarker"),
);
if (source === undefined)
throw new Error(
"Real Chrome did not return explicitly approved script source",
);
+ if (
+ !withSource.value.accessibility.nodes.some((node) =>
+ node.name?.includes("ax-private-label-value"),
+ )
+ )
+ throw new Error(
+ "Real Chrome did not return independently approved accessibility text",
+ );
+ assertSensitiveShapes(withSource.value);
+
+ const bundle = await provider.analyzeBundle(
+ analyzeWebBundleInputSchema.parse({
+ cdp_endpoint: endpoint,
+ allowed_origins: [site.origin],
+ approved: true,
+ target_id: target,
+ observation_ms: 200,
+ source_capture_approved: true,
+ fetch_source_maps: true,
+ source_map_fetch_approved: true,
+ }),
+ );
+ if (!bundle.ok) throw bundle.error;
+ assertBundleAnalysis(bundle.value);
+
+ const captureDiff = await provider.compareCaptures(
+ compareWebCapturesInputSchema.parse({
+ before: { inspection: observed.value },
+ after: { inspection: withSource.value },
+ }),
+ );
+ if (!captureDiff.ok) throw captureDiff.error;
+ if (
+ captureDiff.value.dimensions.dom_structure.status !== "unchanged" ||
+ captureDiff.value.dimensions.scripts.status !== "unchanged"
+ )
+ throw new Error("Real Chrome stable capture identities did not reconcile");
+
+ const screenshot = await provider.captureScreenshot(
+ captureWebScreenshotInputSchema.parse({
+ cdp_endpoint: endpoint,
+ allowed_origins: [site.origin],
+ approved: true,
+ screenshot_approved: true,
+ target_id: target,
+ }),
+ );
+ if (!screenshot.ok) throw screenshot.error;
+ if (
+ screenshot.value.viewport.width < 1 ||
+ screenshot.value.viewport.height < 1 ||
+ screenshot.value.artifact.bytes < 1
+ )
+ throw new Error("Real Chrome screenshot artifact was empty");
+ const screenshotDiff = await provider.compareScreenshots(
+ compareWebScreenshotsInputSchema.parse({
+ before: screenshot.value.artifact,
+ after: screenshot.value.artifact,
+ }),
+ );
+ if (!screenshotDiff.ok) throw screenshotDiff.error;
+ if (
+ screenshotDiff.value.status !== "identical" ||
+ screenshotDiff.value.changed_pixels !== 0
+ )
+ throw new Error("Real Chrome PNG artifact did not compare identically");
+
+ const sessionPromise = provider.observeSession(
+ observeWebSessionInputSchema.parse({
+ cdp_endpoint: endpoint,
+ allowed_origins: [site.origin],
+ approved: true,
+ target_id: target,
+ observation_ms: 1_500,
+ }),
+ );
+ await delay(250);
+ site.triggerSessionNavigation();
+ const session = await sessionPromise;
+ if (!session.ok) throw session.error;
+ if (
+ !session.value.timeline.some(
+ ({ type }) => type === "same_document_navigation",
+ ) ||
+ !session.value.target.final_url?.includes("/app/session-1")
+ )
+ throw new Error("Real Chrome same-origin SPA timeline was missing");
process.stdout.write(
`${JSON.stringify({
@@ -102,6 +202,10 @@ try {
networkRequests: observed.value.network.requests.length,
consoleEvents: observed.value.console.events.length,
websocketEvents: observed.value.network.websocket_events.length,
+ bundleScripts: bundle.value.capture.scripts_analyzed,
+ sourceMaps: bundle.value.observations.source_maps.processed,
+ sessionEvents: session.value.timeline.length,
+ screenshotBytes: screenshot.value.artifact.bytes,
verified: true,
})}\n`,
);
@@ -178,6 +282,13 @@ function assertObservation(result, origin) {
);
if (result.accessibility.nodes.length < 1)
throw new Error("Real Chrome accessibility observation was empty");
+ if (
+ result.accessibility.text_capture.status !== "not_approved" ||
+ result.accessibility.nodes.some(
+ (node) => node.name !== null || node.description !== null,
+ )
+ )
+ throw new Error("Accessibility text was retained without approval");
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")))
@@ -186,86 +297,121 @@ function assertObservation(result, origin) {
throw new Error(
"Real Chrome attach-window network observation was missing",
);
+ const initiatedRequest = result.network.requests.find((request) =>
+ request.url.includes("/api"),
+ );
+ if (
+ !initiatedRequest?.initiator.url?.includes("/app.js") ||
+ initiatedRequest.initiator.line === null ||
+ initiatedRequest.initiator.column === null
+ )
+ throw new Error("Real Chrome script initiator stack was not normalized");
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.console.events.some(
+ (event) => event.text_capture.status !== "not_approved",
+ ) ||
+ result.network.requests.some(
+ (request) => request.body_shapes.status !== "not_approved",
+ ) ||
+ result.network.websocket_events.some(
+ (event) => event.payload_shape !== null,
+ )
+ )
+ throw new Error(
+ "Sensitive text or payload shapes were retained without approval",
+ );
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");
+ if (
+ !result.metadata.responses.some(({ csp }) =>
+ csp.directives.some(({ name }) => name === "default-src"),
+ ) ||
+ !result.metadata.agent_hints.some(
+ ({ declaration }) => declaration === "service-desc",
+ )
+ )
+ throw new Error("Real Chrome safe response metadata 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
',
+function assertBundleAnalysis(result) {
+ if (
+ result.capture.scripts_analyzed < 1 ||
+ !result.observations.routes.some(({ value }) =>
+ value.includes("/verified-route"),
+ ) ||
+ !result.observations.endpoints.some(({ value }) => value.includes("/api"))
+ )
+ throw new Error("Real Chrome static bundle findings were missing");
+ if (
+ result.observations.source_maps.status !== "included" ||
+ !result.observations.source_maps.items.some(
+ ({ status, original_sources, original_module_edges, mappings }) =>
+ status === "included" &&
+ original_sources.some(({ source }) =>
+ source.includes("/src/main.ts"),
+ ) &&
+ original_module_edges.some(
+ ({ specifier }) => specifier === "./dependency.ts",
+ ) &&
+ mappings.length > 0,
+ )
+ )
+ throw new Error(
+ "Real Chrome approved source-map reconstruction was missing",
);
- });
- 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 assertSensitiveShapes(result) {
+ const request = result.network.requests.find((item) =>
+ item.url.includes("/api"),
+ );
+ const requestPaths = request?.body_shapes.request?.properties.map(
+ ({ path }) => path,
+ );
+ const responsePaths = request?.body_shapes.response?.properties.map(
+ ({ path }) => path,
+ );
+ if (!requestPaths?.includes("/token") || !responsePaths?.includes("/secret"))
+ throw new Error("Real Chrome JSON request/response shapes were missing");
+ const consoleText = result.console.events.flatMap(
+ (event) => event.text_capture.values,
+ );
+ if (
+ !consoleText.some(({ text }) => text.includes("[REDACTED]")) ||
+ consoleText.some(({ text }) => text.includes("console-secret-value"))
+ )
+ throw new Error(
+ "Real Chrome approved console text was not safely redacted",
+ );
+ if (
+ !result.network.websocket_events.some(
+ (event) =>
+ event.payload_shape?.format === "json" &&
+ event.payload_shape.json_shape?.properties.some(
+ ({ path }) => path === "/token",
+ ),
+ )
+ )
+ throw new Error("Real Chrome WebSocket JSON shape was missing");
+ const serialized = JSON.stringify(result);
+ for (const secret of [
+ "request-body-secret-value",
+ "response-secret-value",
+ "websocket-secret-value",
+ "console-secret-value",
+ ])
+ if (serialized.includes(secret))
+ throw new Error(`Approved shape capture retained raw value: ${secret}`);
}
function delay(milliseconds) {
diff --git a/scripts/verify-real-hopper.mjs b/scripts/verify-real-hopper.mjs
index 2914f11a3..80f249f78 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 70 tools");
+ throw new Error("The real server did not expose the intended 78 tools");
}
const options = { timeout };
diff --git a/skills/rea-analysis/SKILL.md b/skills/rea-analysis/SKILL.md
index 4902a925d..5a9caf4a7 100644
--- a/skills/rea-analysis/SKILL.md
+++ b/skills/rea-analysis/SKILL.md
@@ -2,16 +2,18 @@
name: rea-analysis
description: Reverse engineer apps and websites with REA. Explore how features work, then build a version tailored to your project.
metadata:
- version: "13"
- tool_count: 70
+ version: "14"
+ tool_count: 78
---
# 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
+For a website already open in a user-owned Chrome-family browser, start with
+`list_browser_targets` and `inspect_web_page` instead of opening a binary. Use
+`analyze_web_bundle`, `observe_web_session`, `discover_webmcp_tools`, capture
+comparison, or screenshot tools only for the corresponding investigation. 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
@@ -19,11 +21,19 @@ first call. Browser observation is disabled unless the operator configured
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.
+network. Query values, credentials, cookies, authorization headers, storage
+values, and raw WebSocket or JSON values are deliberately absent. Accessibility
+text, bounded redacted console primitives, value-free JSON/WebSocket shapes,
+script sources, storage key names, source-map fetches, and screenshot pixels
+each require their documented independent opt-in or approval. Treat truncation,
+policy filtering, and attach-window coverage as explicit limitations, and cite
+the returned Evidence v2 IDs. WebMCP declarations are page-declared untrusted;
+REA inventories them but never invokes them.
+
+Electron `file://` pages use `list_electron_targets` and
+`inspect_electron_page` with a separate loopback endpoint and canonical
+filesystem-root authority. Never claim that Electron inspection invoked IPC,
+evaluated renderer JavaScript, navigated, or escaped an approved root.
## Understand the request
diff --git a/src/application/BrowserEvidence.ts b/src/application/BrowserEvidence.ts
index edba27982..2e7306467 100644
--- a/src/application/BrowserEvidence.ts
+++ b/src/application/BrowserEvidence.ts
@@ -11,29 +11,73 @@ import type {
ListBrowserTargetsInput,
WebPageInspection,
} from "../domain/browserObservation.js";
+import type {
+ AnalyzeWebBundleInput,
+ WebBundleAnalysis,
+} from "../domain/webBundleAnalysis.js";
+import type {
+ ObserveWebSessionInput,
+ WebObservationSession,
+} from "../domain/browserSession.js";
+import type {
+ DiscoverWebMcpToolsInput,
+ WebMcpDiscovery,
+} from "../domain/webMcpDiscovery.js";
+import type {
+ CompareWebCapturesInput,
+ WebCaptureDiff,
+} from "../domain/webCaptureDiff.js";
+import type {
+ CaptureWebScreenshotInput,
+ CompareWebScreenshotsInput,
+ WebScreenshot,
+ WebScreenshotDiff,
+} from "../domain/webScreenshot.js";
-type BrowserEvidenceInput = ListBrowserTargetsInput | InspectWebPageInput;
-type BrowserEvidenceResult = BrowserTargetList | WebPageInspection;
+type BrowserEvidenceInput =
+ | ListBrowserTargetsInput
+ | InspectWebPageInput
+ | AnalyzeWebBundleInput
+ | ObserveWebSessionInput
+ | DiscoverWebMcpToolsInput
+ | CompareWebCapturesInput
+ | CaptureWebScreenshotInput
+ | CompareWebScreenshotsInput;
+type BrowserEvidenceResult =
+ | BrowserTargetList
+ | WebPageInspection
+ | WebBundleAnalysis
+ | WebObservationSession
+ | WebMcpDiscovery
+ | WebCaptureDiff
+ | WebScreenshot
+ | WebScreenshotDiff;
+type BrowserEvidenceOperation =
+ | "list_browser_targets"
+ | "inspect_web_page"
+ | "analyze_web_bundle"
+ | "observe_web_session"
+ | "discover_webmcp_tools"
+ | "compare_web_captures"
+ | "capture_web_screenshot"
+ | "compare_web_screenshots";
/** Create Evidence v2 for a policy-scoped external browser observation. */
export const createBrowserEvidence = (
- operation: "list_browser_targets" | "inspect_web_page",
+ operation: BrowserEvidenceOperation,
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",
+ predicateType: browserPredicate(operation),
operation,
parameters: browserParameters(input),
result: jsonValueSchema.parse(result),
confidence: "observed",
authority: "external-service",
environment:
- "target" in result
+ "browser" in result
? {
id: `${result.browser.product}@${result.browser.revision}`,
platform: process.platform,
@@ -46,16 +90,92 @@ export const createBrowserEvidence = (
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 }),
-});
+): EvidenceObservation["parameters"] => {
+ if (!("cdp_endpoint" in input)) {
+ if ("max_changes" in input)
+ return {
+ before_target_id: input.before.inspection.target.target_id,
+ before_capture_ended_at:
+ input.before.inspection.capture_window.ended_at,
+ after_target_id: input.after.inspection.target.target_id,
+ after_capture_ended_at: input.after.inspection.capture_window.ended_at,
+ max_changes: input.max_changes,
+ };
+ return {
+ before_artifact_uri: input.before.uri,
+ after_artifact_uri: input.after.uri,
+ channel_threshold: input.channel_threshold,
+ maximum_pixels: input.maximum_pixels,
+ };
+ }
+ const scope = {
+ cdp_endpoint: input.cdp_endpoint,
+ allowed_origins: input.allowed_origins,
+ };
+ if (!("target_id" in input))
+ return { ...scope, offset: input.offset, limit: input.limit };
+ if ("screenshot_approved" in input)
+ return {
+ ...scope,
+ target_id: input.target_id,
+ maximum_image_bytes: input.maximum_image_bytes,
+ };
+ if ("max_tools" in input)
+ return {
+ ...scope,
+ target_id: input.target_id,
+ observation_ms: input.observation_ms,
+ max_tools: input.max_tools,
+ max_schema_bytes: input.max_schema_bytes,
+ max_schema_nodes: input.max_schema_nodes,
+ max_schema_depth: input.max_schema_depth,
+ };
+ if (!("include_accessibility_text" in input))
+ return {
+ ...scope,
+ target_id: input.target_id,
+ observation_ms: input.observation_ms,
+ max_timeline_events: input.max_timeline_events,
+ };
+ return {
+ ...scope,
+ target_id: input.target_id,
+ observation_ms: input.observation_ms,
+ include_accessibility_text: input.include_accessibility_text,
+ include_console_text: input.include_console_text,
+ include_json_body_shapes: input.include_json_body_shapes,
+ include_websocket_shapes: input.include_websocket_shapes,
+ include_script_sources: input.include_script_sources,
+ include_storage_keys: input.include_storage_keys,
+ limits: input.limits,
+ ...(input.include_script_sources && "source_capture_approved" in input
+ ? {
+ source_capture_approved: input.source_capture_approved,
+ fetch_source_maps: input.fetch_source_maps,
+ source_map_fetch_approved: input.source_map_fetch_approved,
+ analysis_limits: input.analysis_limits,
+ }
+ : {}),
+ };
+};
+
+const browserPredicate = (operation: BrowserEvidenceOperation): string => {
+ switch (operation) {
+ case "list_browser_targets":
+ return "rea.browser-target-list/v1";
+ case "inspect_web_page":
+ return "rea.web-page-inspection/v2";
+ case "analyze_web_bundle":
+ return "rea.web-bundle-analysis/v1";
+ case "observe_web_session":
+ return "rea.web-observation-session/v1";
+ case "discover_webmcp_tools":
+ return "rea.webmcp-discovery/v1";
+ case "compare_web_captures":
+ return "rea.web-capture-diff/v1";
+ case "capture_web_screenshot":
+ return "rea.web-screenshot/v1";
+ case "compare_web_screenshots":
+ return "rea.web-screenshot-diff/v1";
+ }
+};
diff --git a/src/application/BrowserObservationPort.ts b/src/application/BrowserObservationPort.ts
index f9e3cb45a..d966785ab 100644
--- a/src/application/BrowserObservationPort.ts
+++ b/src/application/BrowserObservationPort.ts
@@ -6,6 +6,28 @@ import type {
WebPageInspection,
} from "../domain/browserObservation.js";
import type { Result } from "../domain/result.js";
+import type {
+ AnalyzeWebBundleInput,
+ WebBundleAnalysis,
+} from "../domain/webBundleAnalysis.js";
+import type {
+ ObserveWebSessionInput,
+ WebObservationSession,
+} from "../domain/browserSession.js";
+import type {
+ DiscoverWebMcpToolsInput,
+ WebMcpDiscovery,
+} from "../domain/webMcpDiscovery.js";
+import type {
+ CompareWebCapturesInput,
+ WebCaptureDiff,
+} from "../domain/webCaptureDiff.js";
+import type {
+ CaptureWebScreenshotInput,
+ CompareWebScreenshotsInput,
+ WebScreenshot,
+ WebScreenshotDiff,
+} from "../domain/webScreenshot.js";
import type { ProviderIdentity } from "./AnalysisProvider.js";
import type { ExecutionOptions } from "./AnalysisProvider.js";
@@ -20,4 +42,26 @@ export interface BrowserObservationPort {
input: InspectWebPageInput,
options?: ExecutionOptions,
): Promise>;
+ analyzeBundle(
+ input: AnalyzeWebBundleInput,
+ options?: ExecutionOptions,
+ ): Promise>;
+ observeSession(
+ input: ObserveWebSessionInput,
+ options?: ExecutionOptions,
+ ): Promise>;
+ discoverWebMcpTools(
+ input: DiscoverWebMcpToolsInput,
+ options?: ExecutionOptions,
+ ): Promise>;
+ compareCaptures(
+ input: CompareWebCapturesInput,
+ ): Promise>;
+ captureScreenshot(
+ input: CaptureWebScreenshotInput,
+ options?: ExecutionOptions,
+ ): Promise>;
+ compareScreenshots(
+ input: CompareWebScreenshotsInput,
+ ): Promise>;
}
diff --git a/src/application/BrowserObservationService.ts b/src/application/BrowserObservationService.ts
index 859a33168..6ad7c1f58 100644
--- a/src/application/BrowserObservationService.ts
+++ b/src/application/BrowserObservationService.ts
@@ -3,6 +3,14 @@ import type {
InspectWebPageInput,
ListBrowserTargetsInput,
} from "../domain/browserObservation.js";
+import type { AnalyzeWebBundleInput } from "../domain/webBundleAnalysis.js";
+import type { ObserveWebSessionInput } from "../domain/browserSession.js";
+import type { DiscoverWebMcpToolsInput } from "../domain/webMcpDiscovery.js";
+import type { CompareWebCapturesInput } from "../domain/webCaptureDiff.js";
+import type {
+ CaptureWebScreenshotInput,
+ CompareWebScreenshotsInput,
+} from "../domain/webScreenshot.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisProtocolError,
@@ -69,11 +77,154 @@ export const inspectWebPage = async (
: result;
};
+/** Capture approved sources and derive bounded static web-bundle evidence. */
+export const analyzeWebBundle = async (
+ browser: BrowserObservationPort | undefined,
+ authority: PermissionAuthority | undefined,
+ input: AnalyzeWebBundleInput,
+ options: ExecutionOptions = {},
+): Promise> => {
+ const ready = await prepare(browser, authority, input, "analyze_web_bundle");
+ if (!ready.ok) return ready;
+ const analyzed = await ready.value.analyzeBundle(input, options);
+ if (!analyzed.ok) return analyzed;
+ return ok(
+ createBrowserEvidence(
+ "analyze_web_bundle",
+ input,
+ analyzed.value,
+ ready.value.identity(),
+ ),
+ );
+};
+
+/** Observe navigation caused by external user actions during one armed window. */
+export const observeWebSession = async (
+ browser: BrowserObservationPort | undefined,
+ authority: PermissionAuthority | undefined,
+ input: ObserveWebSessionInput,
+ options: ExecutionOptions = {},
+): Promise> => {
+ const ready = await prepare(browser, authority, input, "observe_web_session");
+ if (!ready.ok) return ready;
+ const observed = await ready.value.observeSession(input, options);
+ return observed.ok
+ ? ok(
+ createBrowserEvidence(
+ "observe_web_session",
+ input,
+ observed.value,
+ ready.value.identity(),
+ ),
+ )
+ : observed;
+};
+
+/** Discover WebMCP declarations without exposing an invocation surface. */
+export const discoverWebMcpTools = async (
+ browser: BrowserObservationPort | undefined,
+ authority: PermissionAuthority | undefined,
+ input: DiscoverWebMcpToolsInput,
+ options: ExecutionOptions = {},
+): Promise> => {
+ const ready = await prepare(
+ browser,
+ authority,
+ input,
+ "discover_webmcp_tools",
+ );
+ if (!ready.ok) return ready;
+ const discovered = await ready.value.discoverWebMcpTools(input, options);
+ return discovered.ok
+ ? ok(
+ createBrowserEvidence(
+ "discover_webmcp_tools",
+ input,
+ discovered.value,
+ ready.value.identity(),
+ ),
+ )
+ : discovered;
+};
+
+/** Compare two already-normalized web captures without external access. */
+export const compareWebCaptureEvidence = async (
+ browser: BrowserObservationPort | undefined,
+ input: CompareWebCapturesInput,
+): Promise> => {
+ const ready = requireBrowser(browser, "compare_web_captures");
+ if (!ready.ok) return ready;
+ const compared = await ready.value.compareCaptures(input);
+ return compared.ok
+ ? ok(
+ createBrowserEvidence(
+ "compare_web_captures",
+ input,
+ compared.value,
+ ready.value.identity(),
+ ),
+ )
+ : compared;
+};
+
+/** Capture one explicitly approved visible-viewport screenshot. */
+export const captureWebScreenshot = async (
+ browser: BrowserObservationPort | undefined,
+ authority: PermissionAuthority | undefined,
+ input: CaptureWebScreenshotInput,
+ options: ExecutionOptions = {},
+): Promise> => {
+ const ready = await prepare(
+ browser,
+ authority,
+ input,
+ "capture_web_screenshot",
+ );
+ if (!ready.ok) return ready;
+ const captured = await ready.value.captureScreenshot(input, options);
+ return captured.ok
+ ? ok(
+ createBrowserEvidence(
+ "capture_web_screenshot",
+ input,
+ captured.value,
+ ready.value.identity(),
+ ),
+ )
+ : captured;
+};
+
+/** Compare two self-verifying PNG artifacts without external access. */
+export const compareWebScreenshotEvidence = async (
+ browser: BrowserObservationPort | undefined,
+ input: CompareWebScreenshotsInput,
+): Promise> => {
+ const ready = requireBrowser(browser, "compare_web_screenshots");
+ if (!ready.ok) return ready;
+ const compared = await ready.value.compareScreenshots(input);
+ return compared.ok
+ ? ok(
+ createBrowserEvidence(
+ "compare_web_screenshots",
+ input,
+ compared.value,
+ ready.value.identity(),
+ ),
+ )
+ : compared;
+};
+
const prepare = async (
browser: BrowserObservationPort | undefined,
authority: PermissionAuthority | undefined,
input: ScopedBrowserInput,
- operation: "list_browser_targets" | "inspect_web_page",
+ operation:
+ | "list_browser_targets"
+ | "inspect_web_page"
+ | "analyze_web_bundle"
+ | "observe_web_session"
+ | "discover_webmcp_tools"
+ | "capture_web_screenshot",
): Promise> => {
if (authority === undefined)
return err(
@@ -115,6 +266,20 @@ const prepare = async (
: ok(browser);
};
+const requireBrowser = (
+ browser: BrowserObservationPort | undefined,
+ operation: string,
+): Result =>
+ browser === undefined
+ ? err(
+ new AnalysisCapabilityUnavailableError(
+ "rea-cdp-browser",
+ operation,
+ "browser comparison provider is not configured",
+ ),
+ )
+ : ok(browser);
+
const browserNetworkScope = (
allowedOrigins: readonly string[],
): "loopback" | "external" =>
diff --git a/src/application/CapabilityInventory.ts b/src/application/CapabilityInventory.ts
index 95e637665..213edefb8 100644
--- a/src/application/CapabilityInventory.ts
+++ b/src/application/CapabilityInventory.ts
@@ -55,6 +55,7 @@ export const buildCapabilityInventory = (
readonly processCaptureEnabled: boolean;
readonly evidenceFileRoots: number;
readonly browserObservationEnabled?: boolean;
+ readonly electronObservationEnabled?: boolean;
},
) => {
const status = statusSchema.parse(sessionStatus);
@@ -99,6 +100,7 @@ const availabilityFor = (
readonly processCaptureEnabled: boolean;
readonly evidenceFileRoots: number;
readonly browserObservationEnabled?: boolean;
+ readonly electronObservationEnabled?: boolean;
},
): {
readonly reason: ToolAvailabilityReason;
@@ -123,6 +125,14 @@ const availabilityFor = (
remediation:
"Enable browser observation and configure exact CDP endpoint and page origins.",
};
+ if (kind === "electron-provider")
+ return policy.electronObservationEnabled === true
+ ? { reason: "available", remediation: null }
+ : {
+ reason: "policy_disabled",
+ remediation:
+ "Enable Electron observation and configure a loopback CDP endpoint and canonical file roots.",
+ };
if (kind === "session") return { reason: "available", remediation: null };
if (!targetOpen)
return {
diff --git a/src/application/ElectronEvidence.ts b/src/application/ElectronEvidence.ts
new file mode 100644
index 000000000..7bc33d683
--- /dev/null
+++ b/src/application/ElectronEvidence.ts
@@ -0,0 +1,60 @@
+import type { ProviderIdentity } from "./AnalysisProvider.js";
+import {
+ createEvidence,
+ type Evidence,
+ type EvidenceObservation,
+} from "../domain/evidence.js";
+import { jsonValueSchema } from "../domain/jsonValue.js";
+import type {
+ ElectronPageInspection,
+ ElectronTargetList,
+ InspectElectronPageInput,
+ ListElectronTargetsInput,
+} from "../domain/electronObservation.js";
+
+type ElectronOperation = "list_electron_targets" | "inspect_electron_page";
+
+/** Create Evidence v2 for one root-confined Electron observation. */
+export const createElectronEvidence = (
+ operation: ElectronOperation,
+ input: ListElectronTargetsInput | InspectElectronPageInput,
+ result: ElectronTargetList | ElectronPageInspection,
+ provider: ProviderIdentity,
+): Evidence =>
+ createEvidence(undefined, provider, {
+ predicateType:
+ operation === "list_electron_targets"
+ ? "rea.electron-target-list/v1"
+ : "rea.electron-page-inspection/v1",
+ operation,
+ parameters: parameters(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 parameters = (
+ input: ListElectronTargetsInput | InspectElectronPageInput,
+): EvidenceObservation["parameters"] => ({
+ cdp_endpoint: input.cdp_endpoint,
+ allowed_file_roots: input.allowed_file_roots,
+ ...("target_id" in input
+ ? {
+ target_id: input.target_id,
+ observation_ms: input.observation_ms,
+ include_script_sources: input.include_script_sources,
+ source_capture_approved: input.source_capture_approved,
+ limits: input.limits,
+ }
+ : { offset: input.offset, limit: input.limit }),
+});
diff --git a/src/application/ElectronObservationPort.ts b/src/application/ElectronObservationPort.ts
new file mode 100644
index 000000000..3b882cae9
--- /dev/null
+++ b/src/application/ElectronObservationPort.ts
@@ -0,0 +1,22 @@
+import type { ExecutionOptions, ProviderIdentity } from "./AnalysisProvider.js";
+import type { AnalysisError } from "../domain/errors.js";
+import type {
+ ElectronPageInspection,
+ ElectronTargetList,
+ InspectElectronPageInput,
+ ListElectronTargetsInput,
+} from "../domain/electronObservation.js";
+import type { Result } from "../domain/result.js";
+
+/** Provider-neutral boundary for root-confined Electron file-page observation. */
+export interface ElectronObservationPort {
+ identity(): ProviderIdentity;
+ listTargets(
+ input: ListElectronTargetsInput,
+ options?: ExecutionOptions,
+ ): Promise>;
+ inspectPage(
+ input: InspectElectronPageInput,
+ options?: ExecutionOptions,
+ ): Promise>;
+}
diff --git a/src/application/ElectronObservationService.ts b/src/application/ElectronObservationService.ts
new file mode 100644
index 000000000..6b007cb0e
--- /dev/null
+++ b/src/application/ElectronObservationService.ts
@@ -0,0 +1,116 @@
+import type { ExecutionOptions } from "./AnalysisProvider.js";
+import type { ElectronObservationPort } from "./ElectronObservationPort.js";
+import type { PermissionAuthority } from "./PermissionAuthority.js";
+import type { Evidence } from "../domain/evidence.js";
+import type {
+ InspectElectronPageInput,
+ ListElectronTargetsInput,
+} from "../domain/electronObservation.js";
+import {
+ AnalysisCapabilityUnavailableError,
+ AnalysisProtocolError,
+ PermissionRequiredError,
+ type AnalysisError,
+} from "../domain/errors.js";
+import { err, ok, type Result } from "../domain/result.js";
+import { createElectronEvidence } from "./ElectronEvidence.js";
+
+/** Authorize and list root-confined Electron page targets. */
+export const listElectronTargets = async (
+ provider: ElectronObservationPort | undefined,
+ authority: PermissionAuthority | undefined,
+ input: ListElectronTargetsInput,
+ options: ExecutionOptions = {},
+): Promise> => {
+ const ready = await prepare(
+ provider,
+ authority,
+ input,
+ "list_electron_targets",
+ );
+ if (!ready.ok) return ready;
+ const result = await ready.value.listTargets(input, options);
+ return result.ok
+ ? ok(
+ createElectronEvidence(
+ "list_electron_targets",
+ input,
+ result.value,
+ ready.value.identity(),
+ ),
+ )
+ : result;
+};
+
+/** Authorize and inspect one root-confined Electron page. */
+export const inspectElectronPage = async (
+ provider: ElectronObservationPort | undefined,
+ authority: PermissionAuthority | undefined,
+ input: InspectElectronPageInput,
+ options: ExecutionOptions = {},
+): Promise> => {
+ const ready = await prepare(
+ provider,
+ authority,
+ input,
+ "inspect_electron_page",
+ );
+ if (!ready.ok) return ready;
+ const result = await ready.value.inspectPage(input, options);
+ return result.ok
+ ? ok(
+ createElectronEvidence(
+ "inspect_electron_page",
+ input,
+ result.value,
+ ready.value.identity(),
+ ),
+ )
+ : result;
+};
+
+const prepare = async (
+ provider: ElectronObservationPort | undefined,
+ authority: PermissionAuthority | undefined,
+ input: ListElectronTargetsInput | InspectElectronPageInput,
+ operation: "list_electron_targets" | "inspect_electron_page",
+): Promise> => {
+ if (authority === undefined)
+ return err(
+ new AnalysisCapabilityUnavailableError(
+ "rea-cdp-electron",
+ operation,
+ "Electron observation permission policy is not configured",
+ ),
+ );
+ const authorized = await authority.authorize(
+ {
+ capability: "electron_observe",
+ roots: input.allowed_file_roots,
+ executables: [],
+ environment_names: [],
+ origins: [input.cdp_endpoint],
+ network: "loopback",
+ mount: false,
+ operation_identity: `${operation}:${"target_id" in input ? 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 provider === undefined
+ ? err(
+ new AnalysisCapabilityUnavailableError(
+ "rea-cdp-electron",
+ operation,
+ "Electron observation provider is not configured",
+ ),
+ )
+ : ok(provider);
+};
diff --git a/src/application/ProjectPermissionStore.ts b/src/application/ProjectPermissionStore.ts
index 2c52c77dd..7d4d4b90a 100644
--- a/src/application/ProjectPermissionStore.ts
+++ b/src/application/ProjectPermissionStore.ts
@@ -23,6 +23,7 @@ const grantSchema = z.object({
capability: z.enum([
"process_capture",
"browser_observe",
+ "electron_observe",
"evidence_read",
"evidence_write",
"investigation_input",
diff --git a/src/browser/CdpBrowserProvider.ts b/src/browser/CdpBrowserProvider.ts
index 67914d98b..b49202f0c 100644
--- a/src/browser/CdpBrowserProvider.ts
+++ b/src/browser/CdpBrowserProvider.ts
@@ -10,10 +10,41 @@ import {
type ListBrowserTargetsInput,
type WebPageInspection,
} from "../domain/browserObservation.js";
+import { analyzeCapturedWebBundle } from "../domain/webBundleAnalyzer.js";
+import {
+ webBundleAnalysisSchema,
+ type AnalyzeWebBundleInput,
+ type WebBundleAnalysis,
+} from "../domain/webBundleAnalysis.js";
+import {
+ webObservationSessionSchema,
+ type ObserveWebSessionInput,
+ type WebObservationSession,
+} from "../domain/browserSession.js";
+import {
+ webMcpDiscoverySchema,
+ type DiscoverWebMcpToolsInput,
+ type WebMcpDiscovery,
+} from "../domain/webMcpDiscovery.js";
+import {
+ compareWebCaptures,
+ webCaptureDiffSchema,
+ type CompareWebCapturesInput,
+ type WebCaptureDiff,
+} from "../domain/webCaptureDiff.js";
+import {
+ webScreenshotDiffSchema,
+ webScreenshotSchema,
+ type CaptureWebScreenshotInput,
+ type CompareWebScreenshotsInput,
+ type WebScreenshot,
+ type WebScreenshotDiff,
+} from "../domain/webScreenshot.js";
import {
AnalysisError,
BrowserObservationError,
ProviderAdapterError,
+ type BrowserObservationOperation,
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import { CdpConnection } from "./CdpConnection.js";
@@ -22,12 +53,17 @@ import {
type CdpEndpointDiscovery,
type CdpEndpointTarget,
} from "./CdpEndpoint.js";
-import { capturePage } from "./CdpPageCapture.js";
+import { capturePage, type CapturedPage } from "./CdpPageCapture.js";
+import { fetchWebSourceMaps } from "./WebSourceMapFetcher.js";
+import { observeCdpSession } from "./CdpObservationSession.js";
+import { discoverWebMcp } from "./CdpWebMcpDiscovery.js";
+import { captureCdpScreenshot } from "./CdpScreenshot.js";
+import { comparePngScreenshots } from "./PngVisualDiff.js";
const IDENTITY: ProviderIdentity = {
id: "rea-cdp-browser",
name: "REA Chrome DevTools Protocol observation provider",
- version: "1",
+ version: "2",
};
/** Passive, origin-scoped browser observation through a user-owned CDP endpoint. */
@@ -81,6 +117,41 @@ export class CdpBrowserProvider implements BrowserObservationPort {
input: InspectWebPageInput,
options: ExecutionOptions = {},
): Promise> {
+ try {
+ const captured = await this.#capture(input, options);
+ return ok(webPageInspectionSchema.parse(captured.inspection));
+ } catch (cause: unknown) {
+ return err(providerError(cause, "inspect_web_page"));
+ }
+ }
+
+ async analyzeBundle(
+ input: AnalyzeWebBundleInput,
+ options: ExecutionOptions = {},
+ ): Promise> {
+ try {
+ const captured = await this.#capture(input, options);
+ const sourceMaps = input.fetch_source_maps
+ ? await fetchWebSourceMaps(
+ captured.sourceMapRequests,
+ input,
+ options.signal,
+ )
+ : undefined;
+ return ok(
+ webBundleAnalysisSchema.parse(
+ analyzeCapturedWebBundle(captured.inspection, input, sourceMaps),
+ ),
+ );
+ } catch (cause: unknown) {
+ return err(providerError(cause, "analyze_web_bundle"));
+ }
+ }
+
+ async observeSession(
+ input: ObserveWebSessionInput,
+ options: ExecutionOptions = {},
+ ): Promise> {
let connection: CdpConnection | undefined;
let sessionId: string | undefined;
try {
@@ -101,7 +172,177 @@ export class CdpBrowserProvider implements BrowserObservationPort {
options.signal,
);
sessionId = attachedSessionId(attached);
- const result = await capturePage({
+ return ok(
+ webObservationSessionSchema.parse(
+ await observeCdpSession({
+ connection,
+ sessionId,
+ discovery,
+ target,
+ input,
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
+ ...(options.progress === undefined
+ ? {}
+ : { progress: options.progress }),
+ }),
+ ),
+ );
+ } catch (cause: unknown) {
+ return err(providerError(cause, "observe_web_session"));
+ } finally {
+ if (connection !== undefined) {
+ if (sessionId !== undefined)
+ await bestEffortCleanup(connection, sessionId);
+ await connection.close();
+ }
+ }
+ }
+
+ async discoverWebMcpTools(
+ input: DiscoverWebMcpToolsInput,
+ 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);
+ return ok(
+ webMcpDiscoverySchema.parse(
+ await discoverWebMcp({
+ connection,
+ sessionId,
+ discovery,
+ target,
+ input,
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
+ ...(options.progress === undefined
+ ? {}
+ : { progress: options.progress }),
+ }),
+ ),
+ );
+ } catch (cause: unknown) {
+ return err(providerError(cause, "discover_webmcp_tools"));
+ } finally {
+ if (connection !== undefined) {
+ if (sessionId !== undefined)
+ await bestEffortCleanup(connection, sessionId);
+ await connection.close();
+ }
+ }
+ }
+
+ async compareCaptures(
+ input: CompareWebCapturesInput,
+ ): Promise> {
+ try {
+ return ok(webCaptureDiffSchema.parse(compareWebCaptures(input)));
+ } catch (cause: unknown) {
+ return err(providerError(cause, "compare_web_captures"));
+ }
+ }
+
+ async captureScreenshot(
+ input: CaptureWebScreenshotInput,
+ 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);
+ return ok(
+ webScreenshotSchema.parse(
+ await captureCdpScreenshot({
+ connection,
+ sessionId,
+ discovery,
+ target,
+ input,
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
+ ...(options.progress === undefined
+ ? {}
+ : { progress: options.progress }),
+ }),
+ ),
+ );
+ } catch (cause: unknown) {
+ return err(providerError(cause, "capture_web_screenshot"));
+ } finally {
+ if (connection !== undefined) {
+ if (sessionId !== undefined)
+ await bestEffortCleanup(connection, sessionId);
+ await connection.close();
+ }
+ }
+ }
+
+ async compareScreenshots(
+ input: CompareWebScreenshotsInput,
+ ): Promise> {
+ try {
+ return ok(webScreenshotDiffSchema.parse(comparePngScreenshots(input)));
+ } catch (cause: unknown) {
+ return err(providerError(cause, "compare_web_screenshots"));
+ }
+ }
+
+ async #capture(
+ 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);
+ return await capturePage({
connection,
sessionId,
discovery,
@@ -112,9 +353,6 @@ export class CdpBrowserProvider implements BrowserObservationPort {
? {}
: { 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)
@@ -172,7 +410,7 @@ const selectTargets = (
const authorizeTarget = (
discovery: CdpEndpointDiscovery,
- input: InspectWebPageInput,
+ input: Pick,
): CdpEndpointTarget => {
const target = discovery.targets.find(
(candidate) => candidate.id === input.target_id,
@@ -222,8 +460,10 @@ const bestEffortCleanup = async (
const providerError = (
cause: unknown,
- operation: "list_browser_targets" | "inspect_web_page",
+ operation: BrowserObservationOperation,
): AnalysisError =>
- cause instanceof AnalysisError
- ? cause
- : new ProviderAdapterError(IDENTITY.id, operation, { cause });
+ cause instanceof BrowserObservationError && cause.operation !== operation
+ ? new BrowserObservationError(operation, cause.reason, { cause })
+ : cause instanceof AnalysisError
+ ? cause
+ : new ProviderAdapterError(IDENTITY.id, operation, { cause });
diff --git a/src/browser/CdpCaptureCompleteness.ts b/src/browser/CdpCaptureCompleteness.ts
new file mode 100644
index 000000000..48e66e311
--- /dev/null
+++ b/src/browser/CdpCaptureCompleteness.ts
@@ -0,0 +1,119 @@
+import {
+ classifyBrowserCompleteness,
+ type BrowserCompleteness,
+ type BrowserDroppedEventKind,
+ type BrowserDroppedEvents,
+ type BrowserExclusion,
+ type BrowserExclusionReason,
+ type BrowserSection,
+} from "../domain/browserCompleteness.js";
+
+const EVENT_SECTIONS: Readonly<
+ Record
+> = {
+ scripts: "scripts",
+ network_requests: "network_requests",
+ console_events: "console_events",
+ websocket_connections: "websocket_connections",
+ websocket_frames: "websocket_frames",
+ webmcp_tools: "webmcp_tools",
+ timeline_events: "timeline",
+};
+
+const POLICY_REASONS = new Set([
+ "disallowed_origin",
+ "unsupported_url",
+ "unattributed_origin",
+ "not_approved",
+ "out_of_target_scope",
+]);
+
+/** Mutable adapter ledger projected into immutable, canonical completeness v2. */
+export class CdpCaptureCompleteness {
+ readonly #initialAttachLimited: readonly BrowserSection[];
+ readonly #policyFiltered = new Set();
+ readonly #attachLimited = new Set();
+ readonly #truncated = new Set();
+ readonly #unavailable = new Set();
+ readonly #excluded = new Map();
+ readonly #dropped: Omit = emptyDropped();
+
+ constructor(initialAttachLimited: readonly BrowserSection[] = []) {
+ this.#initialAttachLimited = [...initialAttachLimited];
+ this.reset();
+ }
+
+ reset(): void {
+ this.#policyFiltered.clear();
+ this.#attachLimited.clear();
+ this.#truncated.clear();
+ this.#unavailable.clear();
+ this.#excluded.clear();
+ Object.assign(this.#dropped, emptyDropped());
+ for (const section of this.#initialAttachLimited)
+ this.#attachLimited.add(section);
+ }
+
+ exclude(
+ section: BrowserSection,
+ reason: BrowserExclusionReason,
+ count: number | null = 1,
+ ): void {
+ if (POLICY_REASONS.has(reason)) this.#policyFiltered.add(section);
+ if (
+ reason === "provider_unavailable" ||
+ reason === "invalid_protocol_value"
+ )
+ this.#unavailable.add(section);
+ const key = `${section}\0${reason}`;
+ const existing = this.#excluded.get(key);
+ const combined =
+ count === null || existing?.count === null
+ ? null
+ : (existing?.count ?? 0) + count;
+ this.#excluded.set(key, { section, reason, count: combined });
+ }
+
+ attachLimited(section: BrowserSection): void {
+ this.#attachLimited.add(section);
+ }
+
+ unavailable(section: BrowserSection): void {
+ this.#unavailable.add(section);
+ this.exclude(section, "provider_unavailable", null);
+ }
+
+ truncate(section: BrowserSection): void {
+ this.#truncated.add(section);
+ }
+
+ drop(kind: BrowserDroppedEventKind, count = 1): void {
+ this.#dropped[kind] += count;
+ this.#truncated.add(EVENT_SECTIONS[kind]);
+ }
+
+ get droppedTotal(): number {
+ return Object.values(this.#dropped).reduce((sum, count) => sum + count, 0);
+ }
+
+ snapshot(): BrowserCompleteness {
+ return classifyBrowserCompleteness({
+ policyFilteredSections: this.#policyFiltered,
+ attachLimitedSections: this.#attachLimited,
+ truncatedSections: this.#truncated,
+ unavailableSections: this.#unavailable,
+ excluded: [...this.#excluded.values()],
+ droppedEvents: this.#dropped,
+ });
+ }
+}
+
+const emptyDropped = (): Omit => ({
+ scripts: 0,
+ network_requests: 0,
+ console_events: 0,
+ websocket_connections: 0,
+ websocket_frames: 0,
+ webmcp_tools: 0,
+ timeline_events: 0,
+});
diff --git a/src/browser/CdpCaptureDocuments.ts b/src/browser/CdpCaptureDocuments.ts
index b716dbf17..5f7173f74 100644
--- a/src/browser/CdpCaptureDocuments.ts
+++ b/src/browser/CdpCaptureDocuments.ts
@@ -5,6 +5,7 @@ import type {
import {
allowedSanitizedUrl,
boundedText,
+ isHttpUrl,
numberValue,
recordValue,
recordsValue,
@@ -12,12 +13,19 @@ import {
stringValue,
type UnknownRecord,
} from "./CdpCaptureValues.js";
+import type { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
+
+export type CapturedResource = Omit<
+ WebPageInspection["resources"][number],
+ "resource_key"
+> & { readonly rawUrl: string };
/** Normalize allowed frames while retaining a bounded prefix and total count. */
export const captureFrames = (
result: unknown,
allowedOrigins: ReadonlySet,
maximum: number,
+ completeness?: CdpCaptureCompleteness,
): {
readonly total: number;
readonly items: WebPageInspection["frames"];
@@ -30,14 +38,17 @@ export const captureFrames = (
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
- )
+ if (frame === undefined || frameId === undefined || frameId.length > 256) {
+ completeness?.exclude("frames", "invalid_protocol_value");
continue;
+ }
+ if (sanitized === undefined || sanitized.origin === null) {
+ completeness?.exclude(
+ "frames",
+ exclusionReasonForUrl(stringValue(frame.url)),
+ );
+ continue;
+ }
total += 1;
if (items.length >= maximum) continue;
items.push({
@@ -62,22 +73,30 @@ export const captureResources = (
result: unknown,
allowedOrigins: ReadonlySet,
maximum: number,
+ completeness?: CdpCaptureCompleteness,
): {
readonly total: number;
- readonly items: WebPageInspection["resources"];
+ readonly items: readonly CapturedResource[];
} => {
const root = recordValue(requiredRecord(result).frameTree);
if (root === undefined) return { total: 0, items: [] };
- const items: WebPageInspection["resources"] = [];
+ const items: CapturedResource[] = [];
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;
+ if (url === undefined || url.origin === null) {
+ completeness?.exclude(
+ "resources",
+ exclusionReasonForUrl(stringValue(resource.url)),
+ );
+ continue;
+ }
total += 1;
if (items.length >= maximum) continue;
const contentSize = numberValue(resource.contentSize);
items.push({
+ rawUrl: stringValue(resource.url) ?? "",
url: url.url,
origin: url.origin,
type: (stringValue(resource.type) ?? "Other").slice(0, 100),
@@ -110,20 +129,29 @@ export const captureDom = (
result: unknown,
allowedOrigins: ReadonlySet,
input: InspectWebPageInput,
+ completeness?: CdpCaptureCompleteness,
): {
readonly total: number;
readonly nodes: WebPageInspection["dom"]["nodes"];
+ readonly urls: WebPageInspection["metadata"]["dom_urls"];
+ readonly agentHints: WebPageInspection["metadata"]["agent_hints"];
+ readonly excludedUrls: number;
} => {
const root = requiredRecord(result);
const strings = Array.isArray(root.strings)
? root.strings.map((value) => stringValue(value) ?? "")
: [];
const nodes: WebPageInspection["dom"]["nodes"] = [];
+ const urls: WebPageInspection["metadata"]["dom_urls"] = [];
+ const agentHints: WebPageInspection["metadata"]["agent_hints"] = [];
+ let excludedUrls = 0;
let total = 0;
for (const document of recordsValue(root.documents)) {
const documentUrl = indexedString(strings, document.documentURL);
- if (allowedSanitizedUrl(documentUrl, allowedOrigins) === undefined)
+ if (allowedSanitizedUrl(documentUrl, allowedOrigins) === undefined) {
+ completeness?.exclude("dom", exclusionReasonForUrl(documentUrl));
continue;
+ }
const documentNodes = recordValue(document.nodes);
if (documentNodes === undefined) continue;
const nodeTypes = numberArray(documentNodes.nodeType);
@@ -142,42 +170,129 @@ export const captureDom = (
) {
const attributeIndexes = numberArray(attributes[index]);
const parent = Math.trunc(parents[index] ?? -1);
+ const nodeIndex = nodes.length;
+ const nodeName = indexedString(strings, nodeNames[index]).slice(0, 256);
nodes.push({
- index: nodes.length,
+ index: nodeIndex,
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_name: nodeName,
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),
});
+ const metadata = domMetadata(
+ strings,
+ attributeIndexes,
+ documentUrl,
+ nodeIndex,
+ nodeName,
+ allowedOrigins,
+ );
+ for (const url of metadata.urls) {
+ if (urls.length >= input.limits.max_resources) {
+ completeness?.truncate("metadata");
+ continue;
+ }
+ urls.push(url);
+ if (url.destination_scope !== "approved") {
+ excludedUrls += 1;
+ completeness?.exclude(
+ "metadata",
+ url.destination_scope === "outside_policy"
+ ? "disallowed_origin"
+ : "unsupported_url",
+ );
+ }
+ }
+ agentHints.push(...metadata.agentHints);
}
}
- return { total, nodes };
+ return {
+ total,
+ nodes,
+ urls,
+ agentHints: agentHints.slice(0, input.limits.max_resources),
+ excludedUrls,
+ };
};
export const captureAccessibility = (
results: readonly unknown[],
maximum: number,
+ options: {
+ readonly includeText: boolean;
+ readonly maximumFieldBytes: number;
+ readonly maximumTotalBytes: number;
+ readonly unavailable?: boolean;
+ },
): {
readonly total: number;
readonly nodes: WebPageInspection["accessibility"]["nodes"];
+ readonly textCapture: WebPageInspection["accessibility"]["text_capture"];
} => {
const all = results.flatMap((result) =>
recordsValue(requiredRecord(result).nodes),
);
- return {
- total: all.length,
- nodes: all.slice(0, maximum).map((node) => ({
+ let retainedBytes = 0;
+ let excludedFields = 0;
+ let truncatedFields = 0;
+ const nodes = all.slice(0, maximum).map((node) => {
+ const captureText = (value: unknown): string | null => {
+ const raw = stringValue(recordValue(value)?.value);
+ if (raw === undefined) return null;
+ if (!options.includeText) {
+ excludedFields += 1;
+ return null;
+ }
+ const available = Math.max(0, options.maximumTotalBytes - retainedBytes);
+ const captured = boundedUtf8(
+ raw,
+ Math.min(options.maximumFieldBytes, available),
+ );
+ retainedBytes += captured.bytes;
+ if (captured.truncated) {
+ truncatedFields += 1;
+ if (captured.text === "" && raw !== "") {
+ excludedFields += 1;
+ return null;
+ }
+ }
+ return captured.text;
+ };
+ return {
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),
+ name: captureText(node.name),
+ description: captureText(node.description),
ignored: node.ignored === true,
- })),
+ };
+ });
+ for (const node of all.slice(maximum)) {
+ for (const value of [node.name, node.description]) {
+ if (stringValue(recordValue(value)?.value) === undefined) continue;
+ excludedFields += 1;
+ if (options.includeText) truncatedFields += 1;
+ }
+ }
+ return {
+ total: all.length,
+ nodes,
+ textCapture: {
+ status: options.unavailable
+ ? "unavailable"
+ : !options.includeText
+ ? "not_approved"
+ : truncatedFields > 0
+ ? "truncated"
+ : "included",
+ retained_bytes: retainedBytes,
+ excluded_fields: excludedFields,
+ truncated_fields: truncatedFields,
+ },
};
};
@@ -196,3 +311,112 @@ const numberArray = (value: unknown): readonly number[] =>
return number === undefined ? [] : [number];
})
: [];
+
+const domMetadata = (
+ strings: readonly string[],
+ attributes: readonly number[],
+ documentUrl: string,
+ nodeIndex: number,
+ nodeName: string,
+ allowedOrigins: ReadonlySet,
+): {
+ readonly urls: WebPageInspection["metadata"]["dom_urls"];
+ readonly agentHints: WebPageInspection["metadata"]["agent_hints"];
+} => {
+ const pairs = new Map();
+ for (let index = 0; index + 1 < attributes.length; index += 2) {
+ const name = indexedString(strings, attributes[index]).toLowerCase();
+ const value = indexedString(strings, attributes[index + 1]);
+ pairs.set(name, value);
+ }
+ const urls: WebPageInspection["metadata"]["dom_urls"] = [];
+ for (const attribute of domUrlAttributes) {
+ const value = pairs.get(attribute);
+ if (value === undefined) continue;
+ const destination = domDestination(value, documentUrl, allowedOrigins);
+ urls.push({
+ node_index: nodeIndex,
+ attribute,
+ url: destination.url,
+ destination_scope: destination.scope,
+ });
+ }
+ const rel = (pairs.get("rel") ?? "")
+ .toLowerCase()
+ .split(/\s+/u)
+ .filter((value) => agentRelValues.includes(value));
+ const href = urls.find(({ attribute }) => attribute === "href")?.url ?? null;
+ const agentHints =
+ nodeName.toLowerCase() === "link" && rel.length > 0
+ ? rel.map((declaration) => ({
+ mechanism: "dom_link_rel" as const,
+ declaration,
+ url: href,
+ trust: "page-declared-untrusted" as const,
+ }))
+ : [];
+ return { urls, agentHints };
+};
+
+const domDestination = (
+ value: string,
+ documentUrl: string,
+ allowedOrigins: ReadonlySet,
+): {
+ readonly url: string | null;
+ readonly scope: "approved" | "outside_policy" | "unsupported";
+} => {
+ try {
+ const parsed = new URL(value, documentUrl);
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
+ return { url: null, scope: "unsupported" };
+ if (!allowedOrigins.has(parsed.origin))
+ return { url: null, scope: "outside_policy" };
+ return {
+ url: allowedSanitizedUrl(parsed.href, allowedOrigins)?.url ?? null,
+ scope: "approved",
+ };
+ } catch {
+ return { url: null, scope: "unsupported" };
+ }
+};
+
+const boundedUtf8 = (
+ value: string,
+ maximumBytes: number,
+): {
+ readonly text: string;
+ readonly bytes: number;
+ readonly truncated: boolean;
+} => {
+ const total = Buffer.byteLength(value);
+ if (total <= maximumBytes)
+ return { text: value, bytes: total, truncated: false };
+ let text = "";
+ let bytes = 0;
+ for (const character of value) {
+ const characterBytes = Buffer.byteLength(character);
+ if (bytes + characterBytes > maximumBytes) break;
+ text += character;
+ bytes += characterBytes;
+ }
+ return { text, bytes, truncated: true };
+};
+
+const exclusionReasonForUrl = (
+ value: string | undefined,
+): "disallowed_origin" | "unsupported_url" | "unattributed_origin" =>
+ value === undefined || value === ""
+ ? "unattributed_origin"
+ : isHttpUrl(value)
+ ? "disallowed_origin"
+ : "unsupported_url";
+
+const domUrlAttributes = [
+ "href",
+ "src",
+ "action",
+ "formaction",
+ "poster",
+] as const;
+const agentRelValues = ["mcp", "model-context", "ai-plugin", "service-desc"];
diff --git a/src/browser/CdpCaptureEvents.ts b/src/browser/CdpCaptureEvents.ts
index 2a254af03..67e45974f 100644
--- a/src/browser/CdpCaptureEvents.ts
+++ b/src/browser/CdpCaptureEvents.ts
@@ -2,7 +2,11 @@ import type {
InspectWebPageInput,
WebPageInspection,
} from "../domain/browserObservation.js";
+import { inferJsonShape, type JsonShape } from "../domain/jsonShape.js";
import type { CdpEvent } from "./CdpConnection.js";
+import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
+import { safeResponseMetadata } from "./CdpSafeMetadata.js";
+import { boundedSensitiveText } from "./SensitiveTextCapture.js";
import {
allowedSanitizedUrl,
boundedText,
@@ -16,6 +20,7 @@ import {
export interface CapturedScript {
readonly scriptId: string;
+ readonly rawUrl: string;
readonly url: string;
readonly origin: string | null;
readonly hash: string;
@@ -23,6 +28,7 @@ export interface CapturedScript {
readonly isModule: boolean;
readonly language: string | null;
readonly sourceMapUrl: string | null;
+ readonly sourceMapRawUrl: string | null;
}
type NetworkState = WebPageInspection["network"]["requests"][number];
@@ -34,10 +40,21 @@ export class CdpCaptureEvents {
readonly allowedWebSockets = new Set();
readonly console: WebPageInspection["console"]["events"] = [];
readonly websockets: WebPageInspection["network"]["websocket_events"] = [];
- dropped = 0;
+ readonly responseMetadata: WebPageInspection["metadata"]["responses"] = [];
+ readonly agentHints: WebPageInspection["metadata"]["agent_hints"] = [];
+ readonly completeness = new CdpCaptureCompleteness([
+ "network_requests",
+ "console_events",
+ "websocket_connections",
+ "websocket_frames",
+ "metadata",
+ ]);
originViolation = false;
navigationDuringCapture = false;
#mainFrameId: string | undefined;
+ #consoleTextBytes = 0;
+ #jsonBodyBytes = 0;
+ #websocketShapeBytes = 0;
constructor(
private readonly input: InspectWebPageInput,
@@ -48,12 +65,23 @@ export class CdpCaptureEvents {
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;
+ this.responseMetadata.length = 0;
+ this.agentHints.length = 0;
+ this.#consoleTextBytes = 0;
+ this.#jsonBodyBytes = 0;
+ this.#websocketShapeBytes = 0;
+ this.completeness.reset();
+ if (!this.input.include_console_text)
+ this.completeness.exclude("console_text", "not_approved", null);
+ if (!this.input.include_json_body_shapes)
+ this.completeness.exclude("json_body_shapes", "not_approved", null);
+ if (!this.input.include_websocket_shapes)
+ this.completeness.exclude("websocket_shapes", "not_approved", null);
}
beginFinalCapture(frameId: string): void {
@@ -99,21 +127,25 @@ export class CdpCaptureEvents {
const scriptId = stringValue(params.scriptId);
const rawUrl = stringValue(params.url) ?? "";
const sanitized = allowedSanitizedUrl(rawUrl, this.allowedOrigins);
- if (
- scriptId === undefined ||
- scriptId.length > 256 ||
- sanitized === undefined
- )
+ if (scriptId === undefined || scriptId.length > 256) {
+ this.completeness.exclude("scripts", "invalid_protocol_value");
return;
+ }
+ if (sanitized === undefined) {
+ this.completeness.exclude("scripts", exclusionReasonForUrl(rawUrl));
+ return;
+ }
if (
this.scripts.size >= this.input.limits.max_scripts &&
!this.scripts.has(scriptId)
) {
- this.dropped += 1;
+ this.completeness.drop("scripts");
return;
}
+ const sourceMap = this.#sourceMap(params.sourceMapURL);
this.scripts.set(scriptId, {
scriptId,
+ rawUrl,
url: sanitized.url,
origin: sanitized.origin,
hash: (stringValue(params.hash) ?? "").slice(0, 512),
@@ -126,21 +158,43 @@ export class CdpCaptureEvents {
),
isModule: params.isModule === true,
language: boundedText(params.scriptLanguage, 100),
- sourceMapUrl: this.#sourceMap(params.sourceMapURL),
+ sourceMapUrl: sourceMap.sanitized,
+ sourceMapRawUrl: sourceMap.raw,
});
}
- #sourceMap(value: unknown): string | null {
- const sanitized = allowedSanitizedUrl(value, this.allowedOrigins);
- return sanitized?.url ?? null;
+ #sourceMap(value: unknown): {
+ readonly sanitized: string | null;
+ readonly raw: string | null;
+ } {
+ const rawUrl = stringValue(value);
+ if (rawUrl === undefined || rawUrl === "")
+ return { sanitized: null, raw: null };
+ const sanitized = allowedSanitizedUrl(rawUrl, this.allowedOrigins);
+ if (sanitized !== undefined)
+ return { sanitized: sanitized.url, raw: rawUrl };
+ this.completeness.exclude("source_maps", exclusionReasonForUrl(rawUrl));
+ return { sanitized: null, raw: 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) return;
- if (request === undefined || sanitized === undefined) {
+ if (requestId === undefined || requestId.length > 256) {
+ this.completeness.exclude("network_requests", "invalid_protocol_value");
+ return;
+ }
+ if (request === undefined) {
+ this.completeness.exclude("network_requests", "invalid_protocol_value");
+ this.network.delete(requestId);
+ return;
+ }
+ const sanitized = allowedSanitizedUrl(request.url, this.allowedOrigins);
+ if (sanitized === undefined) {
+ this.completeness.exclude(
+ "network_requests",
+ exclusionReasonForUrl(stringValue(request.url)),
+ );
this.network.delete(requestId);
return;
}
@@ -148,14 +202,21 @@ export class CdpCaptureEvents {
this.network.size >= this.input.limits.max_network_events &&
!this.network.has(requestId)
) {
- this.dropped += 1;
+ this.completeness.drop("network_requests");
return;
}
const initiator = recordValue(params.initiator);
+ const initiatorFrame = initiatorLocation(initiator);
+ const rawInitiatorUrl = stringValue(initiatorFrame?.url);
const initiatorUrl = allowedSanitizedUrl(
- firstCallFrame(initiator)?.url,
+ rawInitiatorUrl,
this.allowedOrigins,
);
+ if (rawInitiatorUrl !== undefined && initiatorUrl === undefined)
+ this.completeness.exclude(
+ "network_initiators",
+ exclusionReasonForUrl(rawInitiatorUrl),
+ );
this.network.set(requestId, {
request_id: requestId,
url: sanitized.url,
@@ -168,20 +229,30 @@ export class CdpCaptureEvents {
initiator: {
type: (stringValue(initiator?.type) ?? "other").slice(0, 100),
url: initiatorUrl?.url ?? null,
- line: integerOrNull(firstCallFrame(initiator)?.lineNumber),
- column: integerOrNull(firstCallFrame(initiator)?.columnNumber),
+ line: integerOrNull(initiatorFrame?.lineNumber),
+ column: integerOrNull(initiatorFrame?.columnNumber),
},
+ body_shapes: this.#requestBodyShape(request),
});
}
#response(params: UnknownRecord): void {
const requestId = stringValue(params.requestId);
- if (requestId === undefined || requestId.length > 256) return;
+ if (requestId === undefined || requestId.length > 256) {
+ this.completeness.exclude("network_requests", "invalid_protocol_value");
+ return;
+ }
const current = this.network.get(requestId);
const response = recordValue(params.response);
- const sanitized = allowedSanitizedUrl(response?.url, this.allowedOrigins);
if (current === undefined) return;
+ const sanitized = allowedSanitizedUrl(response?.url, this.allowedOrigins);
if (response === undefined || sanitized === undefined) {
+ this.completeness.exclude(
+ "network_requests",
+ response === undefined
+ ? "invalid_protocol_value"
+ : exclusionReasonForUrl(stringValue(response.url)),
+ );
this.network.delete(requestId);
return;
}
@@ -190,6 +261,18 @@ export class CdpCaptureEvents {
status: numberValue(response.status) ?? null,
mime_type: boundedText(response.mimeType, 256),
});
+ if (this.responseMetadata.length >= this.input.limits.max_network_events) {
+ this.completeness.truncate("metadata");
+ return;
+ }
+ const metadata = safeResponseMetadata(
+ requestId,
+ sanitized.url,
+ response,
+ this.allowedOrigins,
+ );
+ this.responseMetadata.push(metadata.response);
+ this.agentHints.push(...metadata.agentHints);
}
#finished(params: UnknownRecord): void {
@@ -208,23 +291,35 @@ export class CdpCaptureEvents {
#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;
+ if (frame === undefined) {
+ this.completeness.exclude("console_events", "unattributed_origin");
return;
}
+ const source = allowedSanitizedUrl(frame.url, this.allowedOrigins);
+ if (source === undefined) {
+ this.completeness.exclude(
+ "console_events",
+ exclusionReasonForUrl(stringValue(frame.url)),
+ );
+ return;
+ }
+ if (this.console.length >= this.input.limits.max_console_events) {
+ this.completeness.drop("console_events");
+ return;
+ }
+ const arguments_ = recordsValue(params.args);
this.console.push({
type: (stringValue(params.type) ?? "unknown").slice(0, 100),
timestamp: numberValue(params.timestamp) ?? 0,
- argument_types: recordsValue(params.args)
+ argument_types: arguments_
.map((argument) =>
(stringValue(argument.type) ?? "unknown").slice(0, 100),
)
.slice(0, 100),
- url: source?.url ?? null,
- line: integerOrNull(frame?.lineNumber),
- column: integerOrNull(frame?.columnNumber),
+ url: source.url,
+ line: integerOrNull(frame.lineNumber),
+ column: integerOrNull(frame.columnNumber),
+ text_capture: this.#consoleText(arguments_),
});
}
@@ -237,48 +332,243 @@ export class CdpCaptureEvents {
)
return;
if (this.websockets.length >= this.input.limits.max_websocket_events) {
- this.dropped += 1;
+ this.completeness.drop("websocket_frames");
return;
}
const response = recordValue(params.response);
const payload = stringValue(response?.payloadData) ?? "";
const opcode = Math.max(0, Math.trunc(numberValue(response?.opcode) ?? 0));
+ const decoded = opcode === 1 ? undefined : decodeBase64(payload);
+ if (opcode !== 1 && decoded === undefined)
+ this.completeness.exclude("websocket_frames", "invalid_protocol_value");
this.websockets.push({
request_id: requestId,
direction,
opcode,
payload_bytes:
- opcode === 1
- ? Buffer.byteLength(payload)
- : Buffer.from(payload, "base64").byteLength,
+ opcode === 1 ? Buffer.byteLength(payload) : (decoded?.byteLength ?? 0),
+ payload_shape: this.#websocketShape(payload, opcode),
});
}
+ responseBodyRequestIds(): readonly string[] {
+ if (!this.input.include_json_body_shapes) return [];
+ return [...this.network.values()]
+ .filter((request) => isJsonMediaType(request.mime_type))
+ .map((request) => request.request_id);
+ }
+
+ responseBodyUnavailable(requestId: string): void {
+ this.#updateResponseShape(requestId, null, false);
+ this.completeness.unavailable("json_body_shapes");
+ }
+
+ ingestResponseBody(requestId: string, value: unknown): void {
+ const result = recordValue(value);
+ const body = stringValue(result?.body);
+ if (body === undefined) {
+ this.#invalidResponseBody(requestId);
+ return;
+ }
+ const decoded =
+ result?.base64Encoded === true
+ ? decodeBase64(body)?.toString("utf8")
+ : body;
+ if (decoded === undefined) {
+ this.#invalidResponseBody(requestId);
+ return;
+ }
+ const inferred = this.#inferBodyShape(decoded);
+ this.#updateResponseShape(requestId, inferred.shape, inferred.truncated);
+ }
+
+ #invalidResponseBody(requestId: string): void {
+ this.#updateResponseShape(requestId, null, false);
+ this.completeness.exclude("json_body_shapes", "invalid_protocol_value");
+ }
+
+ #requestBodyShape(request: UnknownRecord): NetworkState["body_shapes"] {
+ if (!this.input.include_json_body_shapes)
+ return { status: "not_approved", request: null, response: null };
+ const body = stringValue(request.postData);
+ if (!isJsonContentType(recordValue(request.headers)) || body === undefined)
+ return { status: "unavailable", request: null, response: null };
+ const inferred = this.#inferBodyShape(body);
+ return {
+ status: inferred.truncated
+ ? "truncated"
+ : inferred.shape === null
+ ? "unavailable"
+ : "included",
+ request: inferred.shape,
+ response: null,
+ };
+ }
+
+ #inferBodyShape(text: string): {
+ readonly shape: JsonShape | null;
+ readonly truncated: boolean;
+ } {
+ const bytes = Buffer.byteLength(text);
+ const remaining =
+ this.input.limits.max_total_json_body_bytes - this.#jsonBodyBytes;
+ if (bytes > this.input.limits.max_json_body_bytes || bytes > remaining) {
+ this.completeness.truncate("json_body_shapes");
+ return { shape: null, truncated: true };
+ }
+ this.#jsonBodyBytes += bytes;
+ const shape = inferJsonShape(text, {
+ maximumBytes: this.input.limits.max_json_body_bytes,
+ maximumNodes: this.input.limits.max_json_shape_nodes,
+ maximumDepth: this.input.limits.max_json_shape_depth,
+ });
+ if (shape?.truncated === true)
+ this.completeness.truncate("json_body_shapes");
+ return { shape, truncated: shape?.truncated === true };
+ }
+
+ #updateResponseShape(
+ requestId: string,
+ response: JsonShape | null,
+ truncated: boolean,
+ ): void {
+ const current = this.network.get(requestId);
+ if (current === undefined) return;
+ const request = current.body_shapes.request;
+ const status =
+ truncated || current.body_shapes.status === "truncated"
+ ? "truncated"
+ : response !== null
+ ? "included"
+ : request !== null
+ ? "partial"
+ : "unavailable";
+ this.network.set(requestId, {
+ ...current,
+ body_shapes: { status, request, response },
+ });
+ }
+
+ #consoleText(
+ arguments_: readonly UnknownRecord[],
+ ): WebPageInspection["console"]["events"][number]["text_capture"] {
+ if (!this.input.include_console_text)
+ return {
+ status: "not_approved",
+ values: [],
+ retained_bytes: 0,
+ truncated_values: 0,
+ };
+ const values: WebPageInspection["console"]["events"][number]["text_capture"]["values"] =
+ [];
+ let retainedBytes = 0;
+ let truncatedValues = 0;
+ for (const [argumentIndex, argument] of arguments_.entries()) {
+ const primitive = consolePrimitive(argument);
+ if (primitive === undefined) continue;
+ const remaining =
+ this.input.limits.max_total_console_text_bytes - this.#consoleTextBytes;
+ if (remaining <= 0) {
+ truncatedValues += 1;
+ continue;
+ }
+ const bounded = boundedSensitiveText(
+ primitive.text,
+ Math.min(this.input.limits.max_console_text_field_bytes, remaining),
+ );
+ values.push({
+ argument_index: argumentIndex,
+ type: primitive.type,
+ text: bounded.text,
+ });
+ retainedBytes += bounded.bytes;
+ this.#consoleTextBytes += bounded.bytes;
+ if (bounded.truncated) truncatedValues += 1;
+ }
+ if (truncatedValues > 0) this.completeness.truncate("console_text");
+ return {
+ status: truncatedValues > 0 ? "truncated" : "included",
+ values,
+ retained_bytes: retainedBytes,
+ truncated_values: truncatedValues,
+ };
+ }
+
+ #websocketShape(
+ payload: string,
+ opcode: number,
+ ): WebPageInspection["network"]["websocket_events"][number]["payload_shape"] {
+ if (!this.input.include_websocket_shapes) return null;
+ if (opcode !== 1)
+ return { format: "binary", json_shape: null, truncated: false };
+ const bytes = Buffer.byteLength(payload);
+ const remaining =
+ this.input.limits.max_total_websocket_shape_bytes -
+ this.#websocketShapeBytes;
+ if (
+ bytes > this.input.limits.max_websocket_shape_bytes ||
+ bytes > remaining
+ ) {
+ this.completeness.truncate("websocket_shapes");
+ return { format: "text", json_shape: null, truncated: true };
+ }
+ this.#websocketShapeBytes += bytes;
+ const shape = inferJsonShape(payload, {
+ maximumBytes: this.input.limits.max_websocket_shape_bytes,
+ maximumNodes: this.input.limits.max_json_shape_nodes,
+ maximumDepth: this.input.limits.max_json_shape_depth,
+ });
+ if (shape?.truncated === true)
+ this.completeness.truncate("websocket_shapes");
+ return {
+ format: shape === null ? "text" : "json",
+ json_shape: shape,
+ truncated: shape?.truncated === true,
+ };
+ }
+
#websocketCreated(params: UnknownRecord): void {
const requestId = stringValue(params.requestId);
const rawUrl = stringValue(params.url);
- if (
- requestId === undefined ||
- requestId.length > 256 ||
- rawUrl === undefined
- )
+ if (requestId === undefined || requestId.length > 256) {
+ this.completeness.exclude(
+ "websocket_connections",
+ "invalid_protocol_value",
+ );
return;
+ }
+ if (rawUrl === undefined) {
+ this.completeness.exclude(
+ "websocket_connections",
+ "invalid_protocol_value",
+ );
+ return;
+ }
let parsed: URL;
try {
parsed = new URL(rawUrl);
} catch {
+ this.completeness.exclude("websocket_connections", "unsupported_url");
return;
}
if (parsed.protocol === "ws:") parsed.protocol = "http:";
else if (parsed.protocol === "wss:") parsed.protocol = "https:";
- else return;
+ else {
+ this.completeness.exclude("websocket_connections", "unsupported_url");
+ return;
+ }
+ if (!this.allowedOrigins.has(parsed.origin)) {
+ this.completeness.exclude("websocket_connections", "disallowed_origin");
+ 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;
+ !this.allowedWebSockets.has(requestId) &&
+ this.allowedWebSockets.size >= this.input.limits.max_websocket_events
+ ) {
+ this.completeness.drop("websocket_connections");
+ return;
+ }
+ this.allowedWebSockets.add(requestId);
}
#frameNavigated(params: UnknownRecord): void {
@@ -296,12 +586,85 @@ export class CdpCaptureEvents {
const firstCallFrame = (
value: UnknownRecord | undefined,
+): UnknownRecord | undefined => recordsValue(value?.callFrames)[0];
+
+const initiatorLocation = (
+ initiator: UnknownRecord | undefined,
): UnknownRecord | undefined => {
- const callFrames = recordsValue(value?.callFrames);
- return callFrames[0];
+ let stack = recordValue(initiator?.stack);
+ for (let depth = 0; depth < 32 && stack !== undefined; depth += 1) {
+ const frame = firstCallFrame(stack);
+ if (frame !== undefined) return frame;
+ stack = recordValue(stack.parent);
+ }
+ return stringValue(initiator?.url) === undefined ? undefined : initiator;
};
+const exclusionReasonForUrl = (
+ value: string | undefined,
+): "disallowed_origin" | "unsupported_url" | "unattributed_origin" =>
+ value === undefined || value === ""
+ ? "unattributed_origin"
+ : isHttpUrl(value)
+ ? "disallowed_origin"
+ : "unsupported_url";
+
const integerOrNull = (value: unknown): number | null => {
const number = numberValue(value);
return number === undefined ? null : Math.max(0, Math.trunc(number));
};
+
+const isJsonContentType = (headers: UnknownRecord | undefined): boolean => {
+ if (headers === undefined) return false;
+ for (const [name, value] of Object.entries(headers))
+ if (
+ name.toLowerCase() === "content-type" &&
+ isJsonMediaType(stringValue(value))
+ )
+ return true;
+ return false;
+};
+
+const isJsonMediaType = (value: string | null | undefined): boolean => {
+ const mediaType = value?.split(";", 1)[0]?.trim().toLowerCase();
+ return (
+ mediaType === "application/json" || mediaType?.endsWith("+json") === true
+ );
+};
+
+const consolePrimitive = (
+ value: UnknownRecord,
+): { readonly type: string; readonly text: string } | undefined => {
+ const type = stringValue(value.type);
+ switch (type) {
+ case "string":
+ return typeof value.value === "string"
+ ? { type, text: value.value }
+ : undefined;
+ case "boolean":
+ return typeof value.value === "boolean"
+ ? { type, text: String(value.value) }
+ : undefined;
+ case "number":
+ return typeof value.value === "number"
+ ? { type, text: String(value.value) }
+ : typeof value.unserializableValue === "string"
+ ? { type, text: value.unserializableValue }
+ : undefined;
+ case "bigint":
+ return typeof value.unserializableValue === "string"
+ ? { type, text: value.unserializableValue }
+ : undefined;
+ case "undefined":
+ return { type, text: "undefined" };
+ default:
+ return undefined;
+ }
+};
+
+const BASE64 = /^(?:[A-Za-z\d+/]{4})*(?:[A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/u;
+
+const decodeBase64 = (value: string): Buffer | undefined =>
+ value.length % 4 === 0 && BASE64.test(value)
+ ? Buffer.from(value, "base64")
+ : undefined;
diff --git a/src/browser/CdpCaptureValues.ts b/src/browser/CdpCaptureValues.ts
index 439786cff..ffa601fc8 100644
--- a/src/browser/CdpCaptureValues.ts
+++ b/src/browser/CdpCaptureValues.ts
@@ -1,10 +1,9 @@
-import { createHash } from "node:crypto";
-
import {
AnalysisCancelledError,
BrowserObservationError,
} from "../domain/errors.js";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
+import { createWebTextArtifact } from "../domain/webContentArtifact.js";
export type UnknownRecord = Readonly>;
@@ -64,11 +63,9 @@ export const allowedSanitizedUrl = (
export const sourceResult = (
source: string,
-): { included: true; sha256: string; bytes: number; content: string } => ({
+): { included: true; artifact: ReturnType } => ({
included: true,
- sha256: createHash("sha256").update(source).digest("hex"),
- bytes: Buffer.byteLength(source),
- content: source,
+ artifact: createWebTextArtifact(source, "text/javascript"),
});
export const sourceExcluded = (
diff --git a/src/browser/CdpElectronInspection.ts b/src/browser/CdpElectronInspection.ts
new file mode 100644
index 000000000..9aa0e7172
--- /dev/null
+++ b/src/browser/CdpElectronInspection.ts
@@ -0,0 +1,481 @@
+import { createHash } from "node:crypto";
+
+import canonicalize from "canonicalize";
+
+import type { ProgressReporter } from "../application/ProgressReporter.js";
+import type {
+ ElectronPageInspection,
+ InspectElectronPageInput,
+} from "../domain/electronObservation.js";
+import { BrowserObservationError } from "../domain/errors.js";
+import { createWebTextArtifact } from "../domain/webContentArtifact.js";
+import type { CdpConnection, CdpEvent } from "./CdpConnection.js";
+import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
+import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
+import {
+ boundedText,
+ delayWithCancellation,
+ numberValue,
+ recordValue,
+ recordsValue,
+ requiredRecord,
+ stringValue,
+ type UnknownRecord,
+} from "./CdpCaptureValues.js";
+import {
+ authorizedElectronFile,
+ canonicalElectronRoots,
+} from "./ElectronFileScope.js";
+
+interface ElectronContext {
+ readonly connection: CdpConnection;
+ readonly sessionId: string;
+ readonly discovery: CdpEndpointDiscovery;
+ readonly target: CdpEndpointTarget;
+ readonly input: InspectElectronPageInput;
+ readonly signal?: AbortSignal;
+ readonly progress?: ProgressReporter;
+}
+
+interface ScriptDraft {
+ readonly scriptId: string;
+ readonly rawUrl: string;
+ readonly hash: string;
+ readonly length: number;
+ readonly isModule: boolean;
+ readonly language: string | null;
+}
+
+/** Passively inspect one root-confined Electron file page. */
+export const inspectCdpElectronPage = async (
+ context: ElectronContext,
+): Promise => {
+ const roots = await canonicalElectronRoots(context.input.allowed_file_roots);
+ const completeness = new CdpCaptureCompleteness();
+ const scripts: ScriptDraft[] = [];
+ let mainFrameId: string | undefined;
+ let navigationDuringCapture = false;
+ const removeListener = context.connection.onEvent((event) => {
+ if (event.sessionId !== context.sessionId) return;
+ ingestScript(event, scripts, completeness);
+ if (mainFrameId !== undefined && navigatedFrameId(event) === mainFrameId)
+ navigationDuringCapture = true;
+ });
+ const startedAt = new Date().toISOString();
+ try {
+ await report(context.progress, 1, "Authorizing Electron file frames");
+ await context.connection.send(
+ "Page.enable",
+ {},
+ context.sessionId,
+ context.signal,
+ );
+ const before = await context.connection.send(
+ "Page.getFrameTree",
+ {},
+ context.sessionId,
+ context.signal,
+ );
+ const frames = await captureFrames(
+ before,
+ roots,
+ context.input.limits.max_frames,
+ completeness,
+ );
+ const main = frames[0];
+ if (main === undefined)
+ throw new BrowserObservationError(
+ "inspect_web_page",
+ "target_not_allowed",
+ );
+ mainFrameId = main.frame_id;
+ await context.connection.send(
+ "Debugger.enable",
+ { maxScriptsCacheSize: 4 * 1_024 * 1_024 },
+ context.sessionId,
+ context.signal,
+ );
+ await delayWithCancellation(context.input.observation_ms, context.signal);
+ await report(context.progress, 2, "Capturing Electron structure");
+ const resources = await captureResources(context, roots, completeness);
+ const dom = await captureDom(context, roots, completeness);
+ const normalizedScripts = await captureScripts(
+ context,
+ roots,
+ scripts,
+ completeness,
+ );
+ const after = await context.connection.send(
+ "Page.getFrameTree",
+ {},
+ context.sessionId,
+ context.signal,
+ );
+ const afterMain = await mainFilePath(after, roots);
+ if (afterMain === undefined)
+ throw new BrowserObservationError(
+ "inspect_web_page",
+ "target_not_allowed",
+ );
+ if (navigationDuringCapture || afterMain !== main.file_path)
+ throw new BrowserObservationError("inspect_web_page", "target_changed");
+ await report(context.progress, 3, "Electron inspection complete");
+ return {
+ schema_version: 1,
+ browser: context.discovery.version,
+ target: {
+ target_id: context.target.id,
+ type: context.target.type,
+ title: context.target.title.slice(0, 16_384),
+ file_path: main.file_path,
+ attached: context.target.attached,
+ },
+ capture_window: {
+ started_at: startedAt,
+ ended_at: new Date().toISOString(),
+ observation_ms: context.input.observation_ms,
+ },
+ completeness: completeness.snapshot(),
+ frames,
+ dom,
+ scripts: normalizedScripts,
+ resources,
+ limitations: [
+ "Only canonical file paths contained by an approved root are retained.",
+ "REA does not evaluate renderer JavaScript, invoke Electron APIs, navigate, click, or close the page.",
+ "Script contents require separate source-capture approval and remain byte bounded.",
+ ],
+ };
+ } finally {
+ removeListener();
+ }
+};
+
+const navigatedFrameId = (event: CdpEvent): string | undefined => {
+ const params = recordValue(event.params);
+ if (params === undefined) return undefined;
+ if (event.method === "Page.frameNavigated")
+ return stringValue(recordValue(params.frame)?.id);
+ if (event.method === "Page.navigatedWithinDocument")
+ return stringValue(params.frameId);
+ return undefined;
+};
+
+const ingestScript = (
+ event: CdpEvent,
+ scripts: ScriptDraft[],
+ completeness: CdpCaptureCompleteness,
+): void => {
+ if (event.method !== "Debugger.scriptParsed") return;
+ const value = recordValue(event.params);
+ const scriptId = stringValue(value?.scriptId);
+ const rawUrl = stringValue(value?.url);
+ if (scriptId === undefined || scriptId.length > 256) {
+ completeness.exclude("scripts", "invalid_protocol_value");
+ return;
+ }
+ if (rawUrl === undefined || rawUrl === "") {
+ completeness.exclude("scripts", "unattributed_origin");
+ return;
+ }
+ if (scripts.length >= 2_000) {
+ completeness.drop("scripts");
+ return;
+ }
+ scripts.push({
+ scriptId,
+ rawUrl,
+ hash: (stringValue(value?.hash) ?? "").slice(0, 512),
+ length: nonnegativeInteger(value?.length),
+ isModule: value?.isModule === true,
+ language: boundedText(value?.scriptLanguage, 100),
+ });
+};
+
+const captureFrames = async (
+ result: unknown,
+ roots: readonly string[],
+ maximum: number,
+ completeness: CdpCaptureCompleteness,
+): Promise => {
+ const frameTree = recordValue(requiredRecord(result).frameTree);
+ if (frameTree === undefined)
+ throw new BrowserObservationError("inspect_web_page", "protocol_error");
+ const pending: Array<{
+ readonly tree: UnknownRecord;
+ readonly parent: string | null;
+ }> = [{ tree: frameTree, parent: null }];
+ const frames: ElectronPageInspection["frames"] = [];
+ while (pending.length > 0) {
+ const current = pending.shift();
+ if (current === undefined) break;
+ const frame = recordValue(current.tree.frame);
+ const frameId = stringValue(frame?.id);
+ const path = await authorizedElectronFile(
+ stringValue(frame?.url) ?? "",
+ roots,
+ );
+ if (frameId === undefined || path === undefined) {
+ completeness.exclude("frames", "out_of_target_scope");
+ continue;
+ }
+ if (frames.length >= maximum) {
+ completeness.truncate("frames");
+ continue;
+ }
+ frames.push({
+ frame_id: frameId.slice(0, 256),
+ parent_frame_id: current.parent,
+ file_path: path,
+ });
+ for (const child of recordsValue(current.tree.childFrames))
+ pending.push({ tree: child, parent: frameId.slice(0, 256) });
+ }
+ return frames;
+};
+
+const captureResources = async (
+ context: ElectronContext,
+ roots: readonly string[],
+ completeness: CdpCaptureCompleteness,
+): Promise => {
+ const result = await context.connection.send(
+ "Page.getResourceTree",
+ {},
+ context.sessionId,
+ context.signal,
+ );
+ const root = recordValue(requiredRecord(result).frameTree);
+ if (root === undefined)
+ throw new BrowserObservationError("inspect_web_page", "protocol_error");
+ const pending = [root];
+ const resources: ElectronPageInspection["resources"] = [];
+ const seen = new Set();
+ while (pending.length > 0) {
+ const tree = pending.shift();
+ if (tree === undefined) break;
+ for (const resource of recordsValue(tree.resources)) {
+ const path = await authorizedElectronFile(
+ stringValue(resource.url) ?? "",
+ roots,
+ );
+ if (path === undefined) {
+ completeness.exclude("resources", "out_of_target_scope");
+ continue;
+ }
+ const item = {
+ file_path: path,
+ type: (stringValue(resource.type) ?? "Other").slice(0, 100),
+ mime_type: (stringValue(resource.mimeType) ?? "").slice(0, 256),
+ content_size:
+ numberValue(resource.contentSize) === undefined
+ ? null
+ : Math.max(0, numberValue(resource.contentSize) ?? 0),
+ };
+ const resourceKey = `electron_resource_${digest(item)}`;
+ if (seen.has(resourceKey)) continue;
+ seen.add(resourceKey);
+ if (resources.length >= context.input.limits.max_resources) {
+ completeness.truncate("resources");
+ continue;
+ }
+ resources.push({
+ resource_key: resourceKey,
+ ...item,
+ });
+ }
+ pending.push(...recordsValue(tree.childFrames));
+ }
+ return resources.sort((left, right) =>
+ left.resource_key.localeCompare(right.resource_key),
+ );
+};
+
+const captureDom = async (
+ context: ElectronContext,
+ roots: readonly string[],
+ completeness: CdpCaptureCompleteness,
+): Promise => {
+ const result = requiredRecord(
+ await context.connection.send(
+ "DOMSnapshot.captureSnapshot",
+ { computedStyles: [], includePaintOrder: false, includeDOMRects: false },
+ context.sessionId,
+ context.signal,
+ ),
+ );
+ const strings = Array.isArray(result.strings)
+ ? result.strings.map((value) => (typeof value === "string" ? value : ""))
+ : [];
+ const nodes: ElectronPageInspection["dom"]["nodes"] = [];
+ let total = 0;
+ for (const document of recordsValue(result.documents)) {
+ const documentUrl = stringAt(strings, document.documentURL);
+ if ((await authorizedElectronFile(documentUrl, roots)) === undefined) {
+ completeness.exclude("dom", "out_of_target_scope");
+ continue;
+ }
+ const nodeData = recordValue(document.nodes);
+ const nodeTypes = arrayValue(nodeData?.nodeType);
+ const nodeNames = arrayValue(nodeData?.nodeName);
+ const nodeValues = arrayValue(nodeData?.nodeValue);
+ const parents = arrayValue(nodeData?.parentIndex);
+ const attributes = arrayValue(nodeData?.attributes);
+ const baseIndex = nodes.length;
+ total += nodeTypes.length;
+ for (let index = 0; index < nodeTypes.length; index += 1) {
+ if (nodes.length >= context.input.limits.max_dom_nodes) continue;
+ const attributeIndexes = arrayValue(attributes[index]);
+ const parent = integer(parents[index], -1);
+ nodes.push({
+ index: nodes.length,
+ parent_index: parent < 0 ? -1 : baseIndex + parent,
+ node_type: integer(nodeTypes[index], 0),
+ node_name: stringAt(strings, nodeNames[index]).slice(0, 1_024),
+ node_value_length: Buffer.byteLength(
+ stringAt(strings, nodeValues[index]),
+ ),
+ attribute_names: attributeIndexes
+ .filter((_value, attributeIndex) => attributeIndex % 2 === 0)
+ .map((value) => stringAt(strings, value).slice(0, 1_024))
+ .slice(0, 256),
+ });
+ }
+ }
+ if (total > nodes.length) completeness.truncate("dom");
+ return { total_nodes: total, nodes };
+};
+
+const captureScripts = async (
+ context: ElectronContext,
+ roots: readonly string[],
+ scripts: readonly ScriptDraft[],
+ completeness: CdpCaptureCompleteness,
+): Promise => {
+ let total = 0;
+ let sourceBytes = 0;
+ const items: ElectronPageInspection["scripts"]["items"] = [];
+ const seen = new Set();
+ for (const script of scripts) {
+ const path = await authorizedElectronFile(script.rawUrl, roots);
+ if (path === undefined) {
+ completeness.exclude("scripts", "out_of_target_scope");
+ continue;
+ }
+ const identity = {
+ file_path: path,
+ cdp_hash: script.hash,
+ length: script.length,
+ is_module: script.isModule,
+ language: script.language,
+ };
+ const scriptKey = `electron_script_${digest(identity)}`;
+ if (seen.has(scriptKey)) continue;
+ seen.add(scriptKey);
+ total += 1;
+ if (items.length >= context.input.limits.max_scripts) {
+ completeness.drop("scripts");
+ continue;
+ }
+ let source: ElectronPageInspection["scripts"]["items"][number]["source"] = {
+ included: false,
+ reason: "source capture was not approved",
+ };
+ if (context.input.include_script_sources) {
+ if (
+ script.length > context.input.limits.max_script_source_bytes ||
+ sourceBytes + script.length >
+ context.input.limits.max_total_script_source_bytes
+ ) {
+ source = {
+ included: false,
+ reason: "script source byte limit reached",
+ };
+ completeness.truncate("script_sources");
+ } else {
+ const result = requiredRecord(
+ await context.connection.send(
+ "Debugger.getScriptSource",
+ { scriptId: script.scriptId },
+ context.sessionId,
+ context.signal,
+ ),
+ );
+ const text = stringValue(result.scriptSource) ?? "";
+ const bytes = Buffer.byteLength(text);
+ if (
+ bytes > context.input.limits.max_script_source_bytes ||
+ sourceBytes + bytes >
+ context.input.limits.max_total_script_source_bytes
+ ) {
+ source = {
+ included: false,
+ reason: "script source byte limit reached",
+ };
+ completeness.truncate("script_sources");
+ } else {
+ source = {
+ included: true,
+ artifact: createWebTextArtifact(text, "text/javascript"),
+ };
+ sourceBytes += bytes;
+ }
+ }
+ }
+ items.push({
+ script_key: scriptKey,
+ ...identity,
+ source,
+ });
+ }
+ if (!context.input.include_script_sources)
+ completeness.exclude("script_sources", "not_approved", total);
+ return {
+ total,
+ items: items.sort((left, right) =>
+ left.script_key.localeCompare(right.script_key),
+ ),
+ };
+};
+
+const mainFilePath = async (
+ result: unknown,
+ roots: readonly string[],
+): Promise => {
+ const frameTree = recordValue(requiredRecord(result).frameTree);
+ const frame = recordValue(frameTree?.frame);
+ return await authorizedElectronFile(stringValue(frame?.url) ?? "", roots);
+};
+
+const arrayValue = (value: unknown): readonly unknown[] =>
+ Array.isArray(value) ? value : [];
+
+const stringAt = (strings: readonly string[], value: unknown): string =>
+ strings[integer(value, -1)] ?? "";
+
+const integer = (value: unknown, fallback: number): number => {
+ const number = numberValue(value);
+ return number === undefined ? fallback : Math.trunc(number);
+};
+
+const nonnegativeInteger = (value: unknown): number =>
+ Math.max(0, integer(value, 0));
+
+const digest = (value: unknown): string => {
+ const encoded = canonicalize(value);
+ if (encoded === undefined) throw new TypeError("Expected canonical JSON");
+ return createHash("sha256").update(encoded).digest("hex");
+};
+
+const report = async (
+ progress: ProgressReporter | undefined,
+ completed: number,
+ message: string,
+): Promise =>
+ await progress?.report({
+ phase: "browser_observation",
+ completed,
+ total: 3,
+ message,
+ ...(completed === 3 ? { terminal: true } : {}),
+ });
diff --git a/src/browser/CdpElectronProvider.ts b/src/browser/CdpElectronProvider.ts
new file mode 100644
index 000000000..d779ca5b5
--- /dev/null
+++ b/src/browser/CdpElectronProvider.ts
@@ -0,0 +1,223 @@
+import type {
+ ExecutionOptions,
+ ProviderIdentity,
+} from "../application/AnalysisProvider.js";
+import type { ElectronObservationPort } from "../application/ElectronObservationPort.js";
+import {
+ electronPageInspectionSchema,
+ electronTargetListSchema,
+ type ElectronPageInspection,
+ type ElectronTargetList,
+ type InspectElectronPageInput,
+ type ListElectronTargetsInput,
+} from "../domain/electronObservation.js";
+import {
+ AnalysisError,
+ BrowserObservationError,
+ ProviderAdapterError,
+ type BrowserObservationOperation,
+} from "../domain/errors.js";
+import { err, ok, type Result } from "../domain/result.js";
+import { CdpConnection } from "./CdpConnection.js";
+import { discoverCdpEndpoint, type CdpEndpointTarget } from "./CdpEndpoint.js";
+import { inspectCdpElectronPage } from "./CdpElectronInspection.js";
+import {
+ authorizedElectronFile,
+ canonicalElectronRoots,
+} from "./ElectronFileScope.js";
+
+const IDENTITY: ProviderIdentity = {
+ id: "rea-cdp-electron",
+ name: "REA Electron file-page CDP observation provider",
+ version: "1",
+};
+
+/** Passive Electron provider with canonical file-root confinement. */
+export class CdpElectronProvider implements ElectronObservationPort {
+ identity(): ProviderIdentity {
+ return IDENTITY;
+ }
+
+ async listTargets(
+ input: ListElectronTargetsInput,
+ options: ExecutionOptions = {},
+ ): Promise> {
+ try {
+ const roots = await canonicalElectronRoots(input.allowed_file_roots);
+ const discovery = await discoverCdpEndpoint(
+ input.cdp_endpoint,
+ "list_browser_targets",
+ options.signal,
+ );
+ const allowed = [];
+ let outsideRoot = 0;
+ let unsupportedUrl = 0;
+ let nonPage = 0;
+ for (const target of discovery.targets) {
+ if (target.type !== "page") {
+ nonPage += 1;
+ continue;
+ }
+ const path = await authorizedElectronFile(target.url, roots);
+ if (path === undefined) {
+ if (isFileUrl(target.url)) outsideRoot += 1;
+ else unsupportedUrl += 1;
+ continue;
+ }
+ allowed.push({
+ target_id: target.id,
+ type: target.type,
+ title: target.title.slice(0, 16_384),
+ file_path: path,
+ attached: target.attached,
+ });
+ }
+ allowed.sort((left, right) =>
+ left.target_id.localeCompare(right.target_id),
+ );
+ const items = allowed.slice(input.offset, input.offset + input.limit);
+ const next = input.offset + items.length;
+ return ok(
+ electronTargetListSchema.parse({
+ schema_version: 1,
+ browser: discovery.version,
+ targets: {
+ items,
+ offset: input.offset,
+ limit: input.limit,
+ total: allowed.length,
+ next_offset: next < allowed.length ? next : null,
+ has_more: next < allowed.length,
+ },
+ excluded: {
+ outside_root: outsideRoot,
+ unsupported_url: unsupportedUrl,
+ non_page: nonPage,
+ },
+ limitations: [
+ "Only page targets whose canonical file path is contained by an approved root are listed.",
+ ],
+ }),
+ );
+ } catch (cause: unknown) {
+ return err(providerError(cause, "list_electron_targets"));
+ }
+ }
+
+ async inspectPage(
+ input: InspectElectronPageInput,
+ options: ExecutionOptions = {},
+ ): Promise> {
+ let connection: CdpConnection | undefined;
+ let sessionId: string | undefined;
+ try {
+ const roots = await canonicalElectronRoots(input.allowed_file_roots);
+ const discovery = await discoverCdpEndpoint(
+ input.cdp_endpoint,
+ "inspect_web_page",
+ options.signal,
+ );
+ const target = await authorizeTarget(
+ discovery.targets,
+ input.target_id,
+ roots,
+ );
+ 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);
+ return ok(
+ electronPageInspectionSchema.parse(
+ await inspectCdpElectronPage({
+ connection,
+ sessionId,
+ discovery,
+ target,
+ input,
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
+ ...(options.progress === undefined
+ ? {}
+ : { progress: options.progress }),
+ }),
+ ),
+ );
+ } catch (cause: unknown) {
+ return err(providerError(cause, "inspect_electron_page"));
+ } finally {
+ if (connection !== undefined) {
+ if (sessionId !== undefined) await cleanup(connection, sessionId);
+ await connection.close();
+ }
+ }
+ }
+}
+
+const authorizeTarget = async (
+ targets: readonly CdpEndpointTarget[],
+ targetId: string,
+ roots: readonly string[],
+): Promise => {
+ const target = targets.find(({ id }) => id === targetId);
+ if (target === undefined)
+ throw new BrowserObservationError("inspect_web_page", "target_not_found");
+ if (
+ target.type !== "page" ||
+ (await authorizedElectronFile(target.url, roots)) === undefined
+ )
+ 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) ||
+ typeof value.sessionId !== "string" ||
+ value.sessionId.length > 256
+ )
+ throw new BrowserObservationError("inspect_web_page", "protocol_error");
+ return value.sessionId;
+};
+
+const cleanup = async (
+ connection: CdpConnection,
+ sessionId: string,
+): Promise => {
+ for (const method of ["Debugger.disable", "Page.disable"])
+ try {
+ await connection.send(method, {}, sessionId);
+ } catch {
+ // Detach remains the final non-destructive cleanup boundary.
+ }
+ try {
+ await connection.send("Target.detachFromTarget", { sessionId });
+ } catch {
+ // Closing REA's socket never closes the Electron target.
+ }
+};
+
+const isFileUrl = (value: string): boolean => {
+ try {
+ return new URL(value).protocol === "file:";
+ } catch {
+ return false;
+ }
+};
+
+const providerError = (
+ cause: unknown,
+ operation: BrowserObservationOperation,
+): AnalysisError =>
+ cause instanceof BrowserObservationError && cause.operation !== operation
+ ? new BrowserObservationError(operation, cause.reason, { cause })
+ : cause instanceof AnalysisError
+ ? cause
+ : new ProviderAdapterError(IDENTITY.id, operation, { cause });
diff --git a/src/browser/CdpEndpoint.ts b/src/browser/CdpEndpoint.ts
index d63a5e32b..b09c9d1ca 100644
--- a/src/browser/CdpEndpoint.ts
+++ b/src/browser/CdpEndpoint.ts
@@ -7,6 +7,7 @@ import {
AnalysisError,
AnalysisTimeoutError,
BrowserObservationError,
+ type BrowserObservationOperation,
} from "../domain/errors.js";
const HTTP_TIMEOUT_MS = 5_000;
@@ -45,12 +46,10 @@ export interface CdpEndpointDiscovery {
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,
+ operation: BrowserObservationOperation,
signal?: AbortSignal,
): Promise => {
const versionInput = await readJson(
@@ -95,7 +94,7 @@ export const discoverCdpEndpoint = async (
const parseEndpointValue =