Skip to content

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Browser Context Bridge

Browser Context Bridge 是一个最小权限的 Chrome 扩展和本地 Broker,用来让本机 Agent 安全读取浏览器侧上下文。

它只解决两件事:

  • 把浏览器里的登录态、Cookie、Storage 等上下文交给可信的本机 Agent 使用
  • 在用户明确配置后,提供有限的请求摘要读取能力

默认情况下,它不会拦截、阻断、改写、重放或检查任何浏览器请求。

为什么需要它

Agent 经常需要使用浏览器里的登录态来处理已经登录的 Web 产品。危险的做法是让浏览器扩展在后台静默观察所有网页,或者把浏览器数据发到不明确的远端服务。

Browser Context Bridge 反过来做:

  • 没有内置云端后端
  • 没有隐藏遥测
  • 默认不做请求拦截
  • 默认不改写请求
  • 不做大范围浏览器数据采集
  • 扩展不会引入额外的远端网络目标

扩展只应该和明确配置的本机或可信端点通信。

当前状态

这个仓库是 Chrome 扩展和本机 Broker 的 source of truth。

安装

当前适配版本:

组件 版本
Chrome 扩展 0.4.4
Broker npm 包 browser-context-bridge-broker@0.1.4

扩展通过本机 connect page 连接用户级 Broker。Broker 会生成 pairing token,扩展收到带 token 的本地 WebSocket URL 后才连接:

ws://127.0.0.1:37181/extension?pairingToken=...

本机 Agent 通过同一端口上的 HTTP API 访问 Broker。

工作方式

Browser Context Bridge architecture

Agent 不直接连接 Chrome。它连接本机 Broker,Broker 把允许的命令转发给已安装的 Chrome 扩展,扩展再通过 Chrome Extension API 读取被请求的浏览器上下文。

本机安全门

这条链路有两道浏览器侧安全门:

  1. 新安装用户必须在扩展 popup 里打开 Enable local bridge。默认关闭时,扩展不会连接 Broker,也不会记录请求摘要。升级自老扩展的用户在过渡期会保留 legacy enabled,避免自动更新时中断。
  2. Broker 支持带当前 pairing token 的 /extension WebSocket。pairing URL 由 GET /api/browser-context-bridge/pairing 生成;如果 Broker 配了 bearer token,这个 pairing endpoint 也必须带 Authorization: Bearer <token>

本机 Agent 侧还应该自己做 token/capability 授权。Broker 的 bearer token 保护 Broker HTTP API;上层服务如果再暴露自己的 localhost API,也要单独保护。

发布兼容策略

Chrome Web Store 审核期间,Broker 默认处于过渡兼容模式:它接受新扩展的 paired URL,也接受老扩展 0.4.3 的无 token /extension 连接。这样可以先发布 Broker 和上层 Agent runtime,不必等待扩展审核完成。

推荐发布顺序:

  1. 先发布 Broker npm 包和上层 runtime。老扩展仍可连接新 Broker。
  2. 等 Chrome Web Store 审核通过后发布扩展。
  3. 确认主要用户已更新到新扩展后,再用 strict pairing 关闭老入口:
BROWSER_CONTEXT_BRIDGE_STRICT_PAIRING=1 bunx browser-context-bridge-broker

也可以用 CLI 参数:

bunx browser-context-bridge-broker --strict-pairing

Agent 接入方式

Agent 可以用两种方式接入:

  • 使用 browser-context-bridge-broker/core,适合 JavaScript 或 TypeScript runtime。
  • 直接请求 Broker HTTP API,适合已经有自己的服务发现、重试和 HTTP 封装的 Agent runtime。

core client 覆盖的能力应该和直接 HTTP API 保持一致。它只是协议封装,不是另一条能力路径。

查询 Broker 状态:

curl http://127.0.0.1:37181/api/browser-context-bridge/status

发送浏览器上下文命令:

curl -X POST http://127.0.0.1:37181/api/browser-context-bridge/command \
  -H 'content-type: application/json' \
  -d '{
    "method": "browserContext.cookies.getAll",
    "params": [{ "url": "https://example.com" }],
    "timeoutMs": 5000
  }'

如果 Broker 启动时设置了 BROWSER_CONTEXT_BRIDGE_BROKER_TOKEN,直接 HTTP 调用也必须带上 Authorization: Bearer <token>

获取扩展 pairing relay URL:

curl http://127.0.0.1:37181/api/browser-context-bridge/pairing \
  -H "Authorization: Bearer $BROWSER_CONTEXT_BRIDGE_BROKER_TOKEN"

Broker 生命周期

Broker 是一个本机长驻进程,但这个 npm 包不会自动安装系统后台服务。只安装 Chrome 扩展也不会启动 Broker。

有三种常见运行方式:

  • 手动前台运行:执行 bunx browser-context-bridge-broker,进程活着时 Broker 可用。
  • Agent 托管:Agent 先探测 GET /api/browser-context-bridge/status,如果没有 Broker,就拿用户级锁,再在 127.0.0.1:37181 启动一个共享 Broker。
  • OS 服务托管:如果希望它在终端退出、登录会话变化或机器重启后继续可用,可以用 launchdsystemd 或其他本机服务管理器包装同一个 CLI。

browser-context-bridge-broker/core 只通过 HTTP 访问 Broker,不会启动、杀掉或守护 Broker 进程。

Agent runtime 的推荐实践:

  • JS/TS runtime 默认使用 browser-context-bridge-broker/core 做状态检查、能力检查和浏览器上下文命令。
  • 生命周期管理要显式:先 probe 固定状态端点,只有没有 Broker 时才启动一个共享 Broker。
  • Agent 托管启动时要用用户级锁,避免多个 Agent 同时抢占 127.0.0.1:37181
  • 启动后调用 checkCapabilities(...),如果当前 Broker 太旧,要给出清晰错误。
  • 非 JS runtime 或已经有 HTTP transport 的系统可以直接请求 HTTP API;命令集合和返回语义应与 core client 保持一致。

设计限制

  • 固定主机和端口:共享 Broker 端点是 127.0.0.1:37181
  • 固定扩展 WebSocket 路径:新扩展连接 ws://127.0.0.1:37181/extension?pairingToken=...,token 由当前 Broker pairing endpoint 下发。过渡兼容期内,Broker 默认也接受老扩展的无 token /extension 连接。
  • 每个 OS 用户共享一个 Broker:本机 Agent runtime 应复用同一个 Broker,不要为每个任务或每个 Agent 启动独立 relay。
  • 不会自动安装 daemon:Broker 必须手动启动、由 Agent 托管,或由 OS 服务管理器托管。
  • 只面向 localhost:Broker 设计用于 loopback 访问,不面向局域网或云端暴露。
  • 只接受显式命令:Broker 只接受 allowlist 中的 browserContext.* 方法。
  • 不做浏览器自动化:Broker 不打开 tab、不控制页面、不暴露 CDP、不启动 Chrome。
  • 不自动采集浏览器请求:只有本机 runtime 调用 browserContext.requests.configure 后,请求摘要能力才会开启。
  • 可选 bearer token:如果 Broker 启动时设置了 BROWSER_CONTEXT_BRIDGE_BROKER_TOKEN,所有本机 Agent client 都必须使用同一个 token。
  • 需要安装、启用并配对扩展:如果 Chrome 扩展没有安装、没有打开 Enable local bridge,或没有完成 pairing,Broker 命令会返回 not-connected 错误。升级自老扩展的用户会保留 legacy 连接能力,避免审核期间中断。

使用示例

  1. 从上面的 Chrome Web Store 链接安装扩展。
  2. 手动启动本机 Broker,或让 Agent runtime 启动并托管一个共享 Broker:
bunx browser-context-bridge-broker

可选 bearer token:

BROWSER_CONTEXT_BRIDGE_BROKER_TOKEN=local-dev-token bunx browser-context-bridge-broker
  1. 在本机 Agent runtime 中使用 broker client:
import { createBrowserContextBridgeClient } from 'browser-context-bridge-broker/core';

const bridge = createBrowserContextBridgeClient({
  token: process.env.BROWSER_CONTEXT_BRIDGE_BROKER_TOKEN,
});

const probe = await bridge.probe();
if (!probe.ok) {
  throw new Error(`Browser Context Bridge broker is not available: ${probe.reason}`);
}

if (!(await bridge.extensionConnected())) {
  throw new Error('Browser Context Bridge extension is not connected to the local broker');
}

const capabilities = await bridge.checkCapabilities([
  'browserContext.requests.getRecent',
  'browserContext.requests.prune',
]);
if (!capabilities.ok) {
  throw new Error(`Browser Context Bridge broker is missing capabilities: ${
    capabilities.missingCapabilities.join(', ')
  }`);
}

const url = 'https://example.com';
const cookies = await bridge.getCookiesForUrl(url, { timeoutMs: 5000 });
const storage = await bridge.getStorageForUrl(url, { timeoutMs: 5000 });

await bridge.configureRequests({
  enabled: true,
  methods: ['POST'],
  includeHosts: ['example.com'],
  captureBodyKeys: true,
  captureLevel: 'body-shape',
  maxEntries: 100,
});

const recentPosts = await bridge.getRecentRequests({
  hosts: ['example.com'],
  maxResults: 20,
});

console.log({ cookies, storage, recentPosts });

Broker 进程本身不读取浏览器数据。它只把本机 Agent 的显式命令转发给已安装的扩展,扩展也只通过固定 localhost Broker 返回数据。

命令

npm test
npm run build
npm run check

非目标

这个项目不是:

  • 流量代理
  • 浏览器自动化框架
  • 通用抓包工具
  • 云同步服务

English

Browser Context Bridge is a minimal Chrome extension for letting local agents use browser-side context safely.

It is designed to do only two things:

  • borrow browser cookies or session context for a trusted local agent runtime
  • expose a configurable request interception hook for future development

By default, it does not intercept, block, rewrite, replay, or inspect any browser request.

Why This Exists

Agents often need browser context to work with authenticated web products. The unsafe version of that idea is a browser extension that quietly observes everything or sends data to hidden services.

Browser Context Bridge takes the opposite approach:

  • no bundled cloud backend
  • no hidden telemetry
  • no default request interception
  • no default request mutation
  • no broad data collection workflow
  • no extra remote requests introduced by the extension

The extension should only communicate with explicitly configured local or trusted endpoints.

Request Interception Model

"Interception" here means extension developers have a place to register configurable callbacks.

It does not mean the extension changes traffic by default.

The default policy is:

interceptRequests: false

When request interception is enabled by configuration, callbacks should be explicit, auditable, and scoped by rules such as URL pattern, method, resource type, or trusted runtime identity.

Cookie And Context Borrowing

The extension can provide browser-side authentication context to a local agent bridge, so the agent can operate with the same browser login state when the user has explicitly installed and configured the extension.

This project should keep that surface small:

  • expose only the minimum required context
  • prefer local runtime handoff over remote transmission
  • avoid storing secrets unless explicitly required
  • make all sensitive flows visible in configuration

Safety Principles

This repository is intended to make the extension easy to audit.

Core principles:

  • minimal permissions
  • least-privilege host access
  • opt-in interception
  • no surprise network destinations
  • no product behavior hidden behind minified or generated code
  • clear separation between browser extension code and agent runtime code

Current Status

This repository is the source of truth for both the Browser Context Bridge Chrome extension and its localhost broker.

Install

Current compatible versions:

Component Version
Chrome extension 0.4.4
Broker npm package browser-context-bridge-broker@0.1.4

The extension always connects to the per-user local broker at ws://127.0.0.1:37181/extension. Local agents talk to the broker over HTTP on the same port.

How It Works

Browser Context Bridge architecture

The agent never talks to Chrome directly. It talks to the broker client, the broker forwards allowed commands to the installed extension, and the extension uses Chrome extension APIs to read only the requested browser context.

Agent Integration Options

Agents can use either integration style:

  • Use browser-context-bridge-broker/core as the typed client wrapper.
  • Call the broker HTTP API directly. This is useful when the agent already owns service discovery, retries, and HTTP plumbing.

The core client covers the same protocol surface as direct HTTP. It is a convenience layer for JavaScript and TypeScript runtimes, not a separate capability path:

curl http://127.0.0.1:37181/api/browser-context-bridge/status
curl -X POST http://127.0.0.1:37181/api/browser-context-bridge/command \
  -H 'content-type: application/json' \
  -d '{
    "method": "browserContext.cookies.getAll",
    "params": [{ "url": "https://example.com" }],
    "timeoutMs": 5000
  }'

If the broker was started with BROWSER_CONTEXT_BRIDGE_BROKER_TOKEN, direct HTTP callers must also send Authorization: Bearer <token>.

Broker Lifecycle

The broker is a long-running local process, but this package does not install an OS background service by itself. Installing the Chrome extension alone also does not start the broker.

There are three practical ways to run it:

  • Manual foreground process: run bunx browser-context-bridge-broker; the broker stays available while that process is alive.
  • Agent-managed process: an agent can probe GET /api/browser-context-bridge/status, acquire a per-user lock if nothing is running, then start one shared broker on 127.0.0.1:37181.
  • OS-managed service: if you want it to survive terminal exits, login sessions, or restarts, wrap the same CLI with launchd, systemd, or another local service manager.

The browser-context-bridge-broker/core client only talks to the broker over HTTP. It does not start or supervise the broker process.

Best practice for agent runtimes:

  • Use browser-context-bridge-broker/core for status, capability checks, and browser-context commands when the runtime is JavaScript or TypeScript.
  • Keep broker lifecycle management explicit: first probe the fixed status endpoint, then start one shared broker only when none is already running.
  • Protect agent-managed startup with a per-user lock so multiple agents do not race to bind 127.0.0.1:37181.
  • After startup, call checkCapabilities(...) and fail clearly if the running broker is too old for the commands the agent needs.
  • Use direct HTTP for non-JS runtimes or systems that already own their HTTP transport layer. The command set and response semantics should remain the same as the core client.

Design Constraints

  • Fixed host and port: the shared broker endpoint is 127.0.0.1:37181.
  • Fixed extension WebSocket path: new extensions connect to ws://127.0.0.1:37181/extension?pairingToken=.... During the rollout window, the broker also accepts the legacy unpaired /extension connection used by extension 0.4.3.
  • One broker per OS user: local agent runtimes should reuse the same broker instead of starting per-task or per-agent relays.
  • Not auto-installed as a daemon: the broker must be started manually, agent-managed, or wrapped by an OS service manager.
  • Localhost only: the broker is designed for loopback access, not LAN or cloud exposure.
  • Explicit commands only: the broker accepts only the allowlisted browserContext.* methods.
  • No browser automation: the broker does not open tabs, control pages, expose CDP, or start Chrome.
  • No automatic browser data capture: request capture is disabled until a local runtime calls browserContext.requests.configure.
  • Optional bearer token: if the broker is started with BROWSER_CONTEXT_BRIDGE_BROKER_TOKEN, every local agent client must use the same token.
  • Extension required: if the Chrome extension is not installed, enabled in the popup, and paired or legacy-connected with the current broker, broker commands fail with a not-connected error.

Local Safety Gates

The browser-side bridge has two explicit gates:

  1. Fresh installs require the user to enable Enable local bridge in the extension popup. When disabled, the extension does not connect to the broker or record request summaries. Updates from pre-toggle versions keep the bridge legacy-enabled during the rollout window to avoid breaking existing local runtimes.
  2. The broker supports extension WebSockets that include the current pairing token from GET /api/browser-context-bridge/pairing. If the broker is started with a bearer token, the pairing endpoint also requires Authorization: Bearer <token>.

Rollout Compatibility

While the Chrome Web Store review is pending, the broker defaults to a compatibility mode: it accepts both the new paired extension URL and the legacy unpaired /extension URL from extension 0.4.3. This lets agent runtimes and the broker npm package ship before the extension update is approved.

Recommended rollout:

  1. Publish the broker npm package and agent runtime first. Existing extension installs can still connect.
  2. Publish the Chrome extension after review approval.
  3. After most users have updated, turn on strict pairing to close the legacy path:
BROWSER_CONTEXT_BRIDGE_STRICT_PAIRING=1 bunx browser-context-bridge-broker

or:

bunx browser-context-bridge-broker --strict-pairing

Packages

  • packages/extension: Chrome Manifest V3 extension. It exposes browser cookies, storage/UA/header snapshots, and opt-in request summaries, then connects to the fixed broker WebSocket.
  • packages/broker: fixed-port localhost broker and agent-facing core client helpers.

The shared broker endpoint is fixed at 127.0.0.1:37181.

Usage Example

  1. Install the Chrome extension from the Chrome Web Store link above.
  2. Start the local broker manually, or let your agent runtime start and supervise one shared broker:
bunx browser-context-bridge-broker

Optional bearer token:

BROWSER_CONTEXT_BRIDGE_BROKER_TOKEN=local-dev-token bunx browser-context-bridge-broker
  1. Use the broker client from your local agent runtime:
import { createBrowserContextBridgeClient } from 'browser-context-bridge-broker/core';

const bridge = createBrowserContextBridgeClient({
  token: process.env.BROWSER_CONTEXT_BRIDGE_BROKER_TOKEN,
});

const probe = await bridge.probe();
if (!probe.ok) {
  throw new Error(`Browser Context Bridge broker is not available: ${probe.reason}`);
}

const status = probe.status as {
  extensionConnected?: boolean;
  extension?: { product?: string; version?: string };
};

if (!status.extensionConnected) {
  throw new Error('Browser Context Bridge extension is not connected to the local broker');
}

const capabilities = await bridge.checkCapabilities([
  'browserContext.requests.getRecent',
  'browserContext.requests.prune',
]);
if (!capabilities.ok) {
  throw new Error(`Browser Context Bridge broker is missing capabilities: ${
    capabilities.missingCapabilities.join(', ')
  }`);
}

const url = 'https://example.com';
const cookies = await bridge.getCookiesForUrl(url, { timeoutMs: 5000 });
const storage = await bridge.getStorageForUrl(url, { timeoutMs: 5000 });

await bridge.configureRequests({
  enabled: true,
  methods: ['POST'],
  includeHosts: ['example.com'],
  captureBodyKeys: true,
  captureLevel: 'body-shape',
  maxEntries: 100,
});

const recentPosts = await bridge.getRecentRequests({
  hosts: ['example.com'],
  maxResults: 20,
});

console.log({
  extension: status.extension,
  cookies,
  storage,
  recentPosts,
});

The broker process does not read browser data by itself. It only forwards explicit commands from a local agent to the installed extension, and the extension only returns data through the fixed localhost broker.

Commands

npm test
npm run build
npm run check

Non-Goals

This project is not:

  • a traffic proxy
  • a browser automation framework
  • a general-purpose packet capture tool
  • a cloud sync service
  • an analytics or telemetry collector

About

Clean private mirror of Browser Context Bridge

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages